The original
tour.golang.org/basics/8
tour.golang.org/basics/9
The translation
The var statement is used to declare a list of variables, like a list of parameters in a function, with the type last. Var statements can occur at the package or function level, as we’ll see in the following example
package main
import "fmt"
var c, python, java bool
func main() {
var i int
fmt.Println(i, c, python, java)
}
Copy the code
Variables can contain initial values when declared, one for each variable. If there is an initial value, the type can be omitted and the variable will take the initial value type.
package main
import "fmt"
var i, j int = 1, 2
func main() {
var c, python, java = true, false, "no!"
fmt.Println(i, j, c, python, java)
}
Copy the code
Inside the function, the var declaration is replaced with an implicit := short assignment statement. Outside functions, each statement begins with a keyword (var, func, etc.), so := cannot be used.
.
In Go, variables of the same name can be declared at both the package and function levels, and they will not affect each other, such as the I, J, C, Python, and Java variables in the following example. Java is declared Boolean at the package level and string at the function case3() level.
package main
import "fmt"
var c, python, java bool
var i, j = -1, -2
func case3() {
var i, j = 1, 2
k := 3
c, python, java := true, false, "No!"
fmt.Println(i, j, k, c, python, java)
}
func main() {
case3()
fmt.Println(i, j, c, python, java)
}
Copy the code
The above program will output the following result
1 2 3 true false No!
-1 -2 false false false
Copy the code
You can see that even if a variable of the same name is declared inside a function, it does not affect the execution of package-level variables.