Go by Example: Variables
In Go, variables are explicitly declared and used by the compiler to e.g. check type-correctness of function calls.var declares 1 or more variables.
You can declare multiple variables at once.
Go will infer the type of initialized variables.Variables declared without a corresponding initialization are zero-valued. For example, the zero value for an int is 0.
The := syntax is shorthand for declaring and initializing a variable, e.g. for var f string = "short" in this case.
package main
import "fmt"
func main() {
var a string = "initial"
fmt.Println(a)
var b, c int = 1, 2
fmt.Println(b, c)
var d = true
fmt.Println(d)
var e int
fmt.Println(e)
f := "short"
fmt.Println(f)
}
译:
变量
在Go语言中,变量是明确的显示声明被编辑器所使用,来检查正确的调用函数类型。
声明 1 或者更多的变量
你可以一次声明多个变量
Go可以推断出初始化的变量类型
变量的声明没有相应的初始化为零的值,例如这个0值对于 int 来说就是 0
这个 ‘:=’ 语法是对于声明和初始化一个变量的简写 例如 对于 var f string = "short" 在这种情况 f:="short"
package main
import "fmt"
func main() {
var a string = "short"
fmt.Println(a)
var b, c int = 1, 2//可以一起声明两个变量 也可以用‘_’这个符号来占位
fmt.Println(b, c)
var d = true//这里给不给一个bool的类型都成
fmt.Println(d)
var e int//默认的初始值为0
fmt.Println(e)
f := "short"//这里的简写只能用于函数体的内部 外部还得正常声明
fmt.Println(f)
}
go run variables .go
short
1 2
true
0
short