This is a creation in Article, where the information may have evolved or changed.
GoThe language can use " := " to complete the declaration and initialization for a new variable, as shown in the following example:
i1
Equivalent to:
var1
Note that there is no variable type in the statement, no var i int = 1 .
" := " cannot re- declare a variable that has already been declared, as shown in the following example:
package mainimport"fmt"func main() { 1 2 fmt.Println(i)}
Compilation Result:
C:/GoC:/Work/go_work/Hello.go# command-line-arguments.\Hello.go:8::=
The reason for the error is that the variable is declared repeatedly.
But when you use " := " to assign values to multiple variables, if at least one new variable is introduced, compilation is possible, as shown in the following example:
package mainimport"fmt"func main() { 1 2false fmt.Println(i, err)}
Compile execution:
C:/GoC:/Work/go_work/Hello.go2false
Note that at this time, the "" variable is not re i -declared, only the "" "variable that was previously declared is i assigned a value.
" := " can only be used in the body of a function. One important use of this is to initialize the "," " if for and" switch "statements so that the variable becomes a" temporary variable ", that is, the scope of the variable is limited to this statement. As shown in the following example:
package mainimport"fmt"func main() { for 35; j++ { fmt.Println(j) } fmt.Println(j)}
Compilation Result:
C:/GoC:/Work/go_work/Hello.go# command-line-arguments.\Hello.go:11:undefined: j
The j declaration scope of "" is limited for to the statement, so compiling the second print statement will make an error.
Resources:
(1) Short variable declarations;
(2) Assignment operator in Go language.