本文主要研究一下golang中的零值
初始化时没有赋值的变量的默认值如下:
package main import ( "encoding/json" "fmt" ) // https://golang.google.cn/ref/spec#The_zero_value type Demo struct { Name string Ptr *string } type DemoFunc func() string type DemoInterface interface { Hello() string } func main() { var demo Demo fmt.Println("demo.Name=", demo.Name) // {"Name":"","Ptr":null} printJson(demo) var demoPtr *Demo // null printJson(demoPtr) // panic: runtime error: invalid memory address or nil pointer dereference // [signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x10a7167] // fmt.Println(demoPtr.Name) var demoFunc DemoFunc // could not marshal object printJson(demoFunc) // panic: runtime error: invalid memory address or nil pointer dereference // fmt.Println(demoFunc()) var demoInterface DemoInterface // null printJson(demoInterface) // panic: runtime error: invalid memory address or nil pointer dereference // fmt.Println(demoInterface.Hello()) var s []Demo // [] fmt.Println("[]Demo=", s) // null printJson(s) for _, e := range s { fmt.Println(e) } var sp []*Demo // [] fmt.Println("[]*Demo=", sp) // null printJson(sp) for _, e := range sp { fmt.Println(e) } var c chan bool // <nil> fmt.Println(c) var m map[string]int // map[] fmt.Println("map[string]int=", m) // 0 fmt.Println(m["abc"]) // null printJson(m) for k, e := range m { fmt.Println(k) fmt.Println(e) } } func printJson(data interface{}) { jsonBytes, err := json.Marshal(data) if err != nil { fmt.Println("could not marshal object") return } fmt.Println(string(jsonBytes)) }
panic: runtime error: invalid memory address or nil pointer dereference