聊聊golang的零值

2020-12-11 10:30:27 浏览数 (1)

本文主要研究一下golang中的零值

zero value

初始化时没有赋值的变量的默认值如下:

  • false for booleans
  • 0 for numeric types
  • "" for strings
  • nil for pointers, functions, interfaces, slices, channels, and maps

访问nil实例

代码语言:javascript复制
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))
}

小结

  • 对于toJson来讲,大部分为null,func类型的会报错
  • 对于map,访问不存在的key则返回该类型的零值,另外对于零值的slice或map可以直接for range,不会报错
  • 对象指针、func、接口直接访问其属性或方法,会报panic: runtime error: invalid memory address or nil pointer dereference

doc

  • The_zero_value

0 人点赞