itang / todo.itang.me

4 stars 2 forks source link

了解Golang的nil #8

Closed itang closed 10 years ago

itang commented 10 years ago

"nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type."

nil是预先声明的标识符,用来表示指针,管道,函数,接口,Map和切片的零值(初始化值)。

看代码:

package main 

import (
  "fmt"
)

type S struct{
  Name string
}

func main () {
  var s S
  fmt.Printf("%v\n", s)
  fmt.Println("name:", s.Name) // ""

  //s = nil   // 不能赋值给结构
  //fmt.Println(s)

  var b []int 
  fmt.Println(b == nil) // true
  fmt.Println(b) // []
}