There are three ways to declare variables in golang
One is to use VaR keyword to declare package level or function level variables;
The second is to use the short variable declaration method, which can only declare function level variables and need to specify the variable value;
Third, the const keyword is used to declare package level or function level constants.
Var can declare package level variables, but short variables cannot. This is the biggest difference between them.
var name T // Name is the zero value of type T by default var name T = value // Specifies the type when the initial value is assigned var name = value // Infer variable types from values var name0, name1 T // Define multiple variables of the same type at the same time //Define multiple variables of different types at the same time var ( name0 T0 = value0 name 1 T1 = value1 )
2. Short statement
The short variable declaration method can only declare function level variables, and the initial value should be specified. When a variable is not declared by a scope, the variable with the same name of the previous scope will be hidden.
name := value // Declare a variable name0, name1, name2 := value0, value1, value2 // Declare multiple variables
Const is used to declare a constant. Once it is created, it cannot be assigned or modified. Const can appear where the keyword var can appear. The way to declare constant is the same as that to declare variable. The format is as follows:
const name T // The default value is zero of type T const name T = value // Assign initial value const name = value // Infer variable types from values const name1, name2 T // Define multiple variables of the same type at the same time //Define multiple variables of different types at the same time const ( name0 T0 = value0 name 1 T1 = value1 )
The above is the details of the three ways to declare golang variables. For more information about the declaration of golang variables, please pay attention to other related articles of developer!