In Go, you can declare a single variable, multiple variables, or declare and initialize the variable(s) at the same time. Here’s an overview:
1. Single variable declaration:
To declare a single variable, you use the ‘var‘ keyword followed by the variable name and its type. The syntax looks like:
var variable-name variable-type
For example, to declare an integer variable named ‘x‘, you would write:
var x int
2. Multiple variable declaration:
To declare multiple variables, you can use the same ‘var‘ keyword along with parentheses ‘()‘ and list the name and type of each variable, separated by commas.
var (
variable1-name variable1-type
variable2-name variable2-type
...
)
For example, to declare an integer variable ‘x‘ and a string variable ‘s‘, you would write:
var (
x int
s string
)
3. Variable declaration and initialization:
If you want to declare and initialize a variable, you can still use the ‘var‘ keyword, but now you also assign an initial value with an equal sign ‘=‘.
var variable-name variable-type = value
For example, to declare and initialize an integer variable ‘x‘ with the value ‘10‘, you would write:
var x int = 10
Alternatively, you can use the short variable declaration operator ‘:=‘. This allows you to declare and initialize a variable without explicitly specifying the type, as Go will infer the variable’s type based on its value. The syntax looks like:
variable-name := value
For example, to declare and initialize an integer variable ‘x‘ with the value ‘10‘, you would write:
x := 10
Note: The short variable declaration operator can only be used inside a function. For package-level variables, you must use the ‘var‘ keyword.