Our world is worth fighting for

—— Mei-Ling Zhou

go 中 nil slice 和 nil map

11 Oct 2016

go 中 slice 和 map 的 默认值都是 “nil”

package main

import “fmt”

func main() { var ( s []int m map[int]bool ) if s == nil { fmt.Println(“The value of s is nil”) } if m == nil { fmt.Println(“The value of m is nil”) } }

结果:
The value of s is nil
The value of m is nil

区别是当slice 为nil 时可以进行操作,如append, 而map 却不能存key-value

package main

import "fmt"

func main() {
    var s []int
    s = append(s, 1)
    fmt.Println("Is s a nil? ", s == nil)
    fmt.Println(s)

    var m map[int]bool
    fmt.Println("Is m a nil? ", m == nil)
    fmt.Println("m[1] is ", m[1])
    m[1] = true

}

结果:

Is s a nil?  false
[1]
Is m a nil?  true
m[1] is  false
panic: assignment to entry in nil map
goroutine 1 [running]:
…
所以我们在使用map之前最后实例化一个map

m := make(map[int]bool)