We know that the local variable initialization method in Golang (using ": =" to create and assign values) makes it convenient to use variables. However, this is also one of the places where mistakes are easy to make. In particular, this initializer also supports the initialization of multiple variables at the same time, and more particularly, it also supports the original variable assignment and new variable creation and assignment at the same time! That is, if some of the variables do not exist and others are already declared, it is also valid to initialize some variables with: =. This is actually nothing, more convenient. However, many of the statements in go also support local pre-statements, such as in the initialization conditions of statements such as If,for,switch. In these places, when you think that you have used the original variable, the go has created a new variable that is limited to the scope of these statements!
Writing skill is too low, say for a long while you may be more confused, or directly with the code to explain it.
//This code, first declares code, and then resolves with atoi, at which point err is not declared, so the local variable is used to create the assignment ": ="
The following syntax is correct, code or the existing variable, the correct parsing has become 5
Func Test () {var code intSCODE:="5"Code,err:=StrConv. Atoi (SCODE); iferr!=nil{returnerr; } returnCode;}
If you change the function above to look like this, the result is wrong, because in the initialization statement after the IF: = actually tells go to create a new local variable under the IF statement scope!
At this point, both code and ERR are new variables, so the code outside of the parsed statement is not affected and the result is wrong!
Func Test () {
var code int
scode:="5"
If code,err:=StrConv. Atoi (SCODE); err!=nil{
return err;
}
return code;
}
Below, demonstrate with a complete code.
Package Mainimport"FMT"Import"StrConv"Func Main () {FMT. Println ("======conv func 1:") conv1 () fmt. Println ("======conv func 2:") conv2 ()}func conv1 () {code:=TenSCODE:="5"Code,err:=StrConv. Atoi (SCODE); iferr!=nil{FMT. Println ("Convert Error"Err"code=", code); } FMT. Println ("After Conv, code=", code);} Func conv2 () {code:=TenSCODE:="5" ifCode,err: =strconv. Atoi (SCODE); err!=nil{FMT. Println ("Convert Error"Err"code=", code); } FMT. Println ("After Conv, code=", code);}
The result of the code execution:
1 : After conv, code 5 2 : After conv, code Ten Program exited.
[Golang err] Golang local variable initialization: = Trap