The greatest glory in living lies not in never falling, but in rising every time we fall.

—— Nelson Mandela

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)

    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
Is m a nil?  true
m[1] is  false
panic: assignment to entry in nil map
goroutine 1 [running]:

m := make(map[int]bool)