Type Declaration by Inference
Since Go can determine the type of a variable by its initial value, can we simplify the process of type declaration by eliminating the step of explicitly specifying the type?
package main
import "fmt"
func main() {
// var a int = 1
var a = 1 // Type is inferred
fmt.Println(a)
}
Now you don't even need to use the var
keyword to define a variable.
This way of declaring and initializing a variable can also be combined with the batch declaration method we mentioned earlier:
a, b, c := 0
// Declare variables a, b, c as integers and assign an initial value of 0
a, b, c := 0, "", true
// Declare variables a, b, c as integers, string, and boolean, respectively
Short declaration is very convenient, but be careful that :=
is not an assignment operation. It is a way to declare variables and is unique to Go, used to declare and initialize local variables inside a function. The type of the variable will be automatically inferred based on the expression.
Sometimes we write the following code:
func main() {
a := 1
println(a)
a := 2
println(a)
}
The compiler will tell you that there is an error in the code because the variable a
has been redeclared. However, if it is written in the following way:
func main() {
a := 1
if true {
a := 2
println(a) // Output: 2
}
println(a) // Output: 1
}
There is such an output because the a
with a value of 1
above and the a
with a value of 2
below are not in the same variable scope (within the same curly braces), so the compiler treats them as two different variables.
The compiler will not point out your mistake, but there will be unexpected output.
In Go, it is stipulated that:
Each statement outside a function must begin with a keyword (var
, func
, etc.).
Therefore, the short variable declaration can only be used to declare local variables, and cannot be used to declare global variables.
So what is a global variable and what is a local variable?
This involves the concept of variable lifetime, which will be explained in the next section.