在Go语言中,如果您声明变量时没有显式地为其赋值,Go则帮您填充一个初始值。
Go帮您自动填充初始化值就被称为零值。
这跟C/C++不同,C/C++中未明确赋初值的变量有未定义值(undefined)。
各类型的零值是什么?其并不出人意料:
换种方式说:
package main
import (
"fmt"
)
func main() {
fmt.Println("zero values for basic types:")
var zeroBool bool
fmt.Printf("bool: %v\n", zeroBool)
var zeroInt int
fmt.Printf("int: %v\n", zeroInt)
var zeroF32 float32
fmt.Printf("float32: %v\n", zeroF32)
var zeroF64 float64
fmt.Printf("float64: %v\n", zeroF64)
var zeroStr string
fmt.Printf("string: %#v\n", zeroStr)
var zeroPtr *int
fmt.Printf("pointer: %v\n", zeroPtr)
var zeroSlice []uint32
fmt.Printf("slice: %v\n", zeroSlice)
var zeroMap map[string]int
fmt.Printf("map: %#v\n", zeroMap)
var zeroInterface interface{}
fmt.Printf("interface: %v\n", zeroInterface)
var zeroChan chan bool
fmt.Printf("channel: %v\n", zeroChan)
var zeroArray [5]int
fmt.Printf("array: %v\n", zeroArray)
type struc struct {
a int
b string
}
var zeroStruct struc
fmt.Printf("struct: %#v\n", zeroStruct)
var zeroFunc func(bool)
fmt.Printf("function: %v\n", zeroFunc)
}
zero values for basic types:
bool: false
int: 0
float32: 0
float64: 0
string: ""
pointer: <nil>
slice: []
map: map[string]int(nil)
interface: <nil>
channel: <nil>
array: [0 0 0 0 0]
struct: main.struc{a:0, b:""}
function: <nil>