There are several ways to declare variables in go:
1. Declare with the keyword VaR
For example, var I int and then assign a value. I = 5.
2. The simplest method is to declare and assign values using the symbol: =.
For example, I: = 5 golang will default its type
Next let's look at a piece of code. First we declare a variable A, and then re-declare the variables A and B. In this function, variable A is declared twice, redeclare, And the execution result is 23.
Package main
Import (
"FMT"
)
Func main (){
A: = 1
A, B: = 2, 3
FMT. println (A, B)
}
The wonderful part is coming. Please refer to the second code
Package main
Import (
"FMT"
)
Type a struct {
I int
}
Func main (){
Testa: = & {}
Testa. I = 1
Testa. I, B: = 2, 3
FMT. println (testa. I, B)
}
We have defined a simple struct a. The member variable in a is I. i, B: = 2 and 3 new comments and assignments are made to member variables, and an error is reported during execution.
Cause: this issue was discussed on Google.
Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block with the same type, and at least one of the non-blank variables is new. as a consequence, redeclaration can only appear in a multi-variable short declaration. redeclaration does not introduce a new variable; it just assigns a new value to the original.
From the spec of go, redeclare is a value assignment instead of creating a new variable. Why is it not possible for a member variable? It can only be understood as a design problem for the moment. Here is a small pitfall, note the following when playing golang: