In Go, you declare and initialize a variable using the var
keyword followed by the variable name, its type, and an optional initialization value.
Here's an example of declaring and initializing a variable in Go:
var age int // Declaration of a variable of type int
age = 25 // Initialization
fmt.Println(age) // Output: 25
You can also declare and initialize a variable in a single line using the short variable declaration :=
like this:
age := 25 // Declaration and initialization in a single line
fmt.Println(age) // Output: 25
Note that the variable's type is automatically inferred from the value assigned to it when using the :=
short variable declaration.