There are three main ways to declare variables in Golang:
First, use the var keyword to declare package-level or function-level variables;
Second, when using the short variable declaration method, you can only declare function-level variables and need to specify the variable value;
The third is to use the const keyword to declare package-level or function-level constants.
var can declare package-level variables, and short variable declaration methods are not allowed. This is the biggest difference between the two.
var name T // name defaults to zero value of type Tvar name T = value // Indicate the type when assigning the initial valuevar name = value // Infer variable type based on valuevar name0, name1 T // Define multiple variables of the same type at the same time // Define multiple variables of different types at the same timevar ( name0 T0 = value0 name 1 T1 = value1 )
2. Short statement method
The short variable declaration method can only declare function-level variables and must indicate the initial value. In variables that are not declared with scope, variables with the same name in the previous scope will be hidden.
name := value // Declare a variablename0, name1, name2 := value0, value1, value2 // Declare multiple variables
const is used to declare constants, and once created, it cannot be modified by assignment. const can appear where the keyword var can appear. The way to declare constants is the same as var declare variables, and the format is as follows:
const name T // The default value is the zero value of type Tconst name T = value // Assign initial valueconst name = value // Infer variable type based on valueconst name1, name2 T // Define multiple variables of the same type at the same time // Define multiple variables of different types at the same timeconst ( name0 T0 = value0 name 1 T1 = value1 )
The above is the detailed content of the three ways to declare Golang variables. For more information about the declaration of Golang variables, please pay attention to my other related articles!