:=
可在类型明确的地方代替 var
声明,但是函数外的每个语句都必须以关键字开始(var
, func
等等),因此 :=
结构不能在函数外使用。
没有明确初始值的变量声明会被赋予它们的 零值
- 数值类型为
0
- 布尔类型为
false
- 字符串类型为
""
输出变量类型
func main() {
v := 42 // int
f := 3.142 // float64
g := 0.867 + 0.5i // complex128
fmt.Printf("v is of type %T", v, f, g)
// output: v is of type float64%!(EXTRA float64=3.142, complex128=(0.867+0.5i))
}
for 是 Go 中的 “while”
func main() {
sum := 1
for sum < 1000 {
sum += sum
}
fmt.Println(sum)
}
同 for
一样, if
语句可以在条件表达式前执行一个简单的语句。
func pow(x, n, lim float64) float64 {
if v := math.Pow(x, n); v < lim {
return v
}
return lim
}
defer
defer 语句会将函数推迟到外层函数返回之后执行。推迟调用的函数其参数会立即求值,但直到外层函数返回前该函数都不会被调用。
推迟的函数调用会被压入一个栈中。当外层函数返回时,被推迟的函数会按照后进先出的顺序调用。
func main() {
defer fmt.Println("world")
fmt.Println("hello")
// output:
// hello
// world
}