# nil是什么

``````if err != nil {
// do something....
}``````

``````bool      -> false
numbers -> 0
string    -> ""

pointers -> nil
slices -> nil
maps -> nil
channels -> nil
functions -> nil
interfaces -> nil``````

``````type Person struct {
AgeYears int
Name string
Friends []Person
}

var p Person // Person{0, "", nil}``````

``````type Type int
var nil Type``````

``var nil = errors.New("hi")``

# nil有什么用

## pointers

``````var p *int
p == nil    // true
*p          // panic: invalid memory address or nil pointer dereference``````

``````type tree struct {
v int
l *tree
r *tree
}

// first solution
func (t *tree) Sum() int {
sum := t.v
if t.l != nil {
sum += t.l.Sum()
}
if t.r != nil {
sum += t.r.Sum()
}
return sum
}``````

``````if v != nil {
v.m()
}``````

``````var t *tree
sum := t.Sum()   // panic: invalid memory address or nil pointer dereference``````

``````type person struct {}
func sayHi(p *person) { fmt.Println("hi") }
func (p *person) sayHi() { fmt.Println("hi") }
var p *person
p.sayHi() // hi``````

``````func(t *tree) Sum() int {
if t == nil {
return 0
}
return t.v + t.l.Sum() + t.r.Sum()
}``````

``````func(t *tree) String() string {
if t == nil {
return ""
}
return fmt.Sprint(t.l, t.v, t.r)
}

// nil receivers are useful: Find
func (t *tree) Find(v int) bool {
if t == nil {
return false
}
return t.v == v || t.l.Find(v) || t.r.Find(v)
}``````

## slices

``````// nil slices
var s []slice
len(s)  // 0
cap(s)  // 0
for range s  // iterates zero times
s[i]  // panic: index out of range``````

slice

slice

## map

``````// nil maps
var m map[t]u
len(m)  // 0
for range m // iterates zero times
v, ok := m[i] // zero(u), false
m[i] = x // panic: assignment to entry in nil map``````

``````func NewGet(url string, headers map[string]string) (*http.Request, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}

for k, v := range headers {
}
return req, nil
}``````

``````NewGet("http://google.com", map[string]string{
"USER_AGENT": "golang/gopher",
},)``````

``NewGet("http://google.com", map[string]string{})``

``NewGet("http://google.com", nil)``

## channel

``````// nil channels
var c chan t
<- c      // blocks forever
c <- x    // blocks forever
close(c)  // panic: close of nil channel``````

``````func merge(out chan<- int, a, b <-chan int) {
for {
select {
case v := <-a:
out <- v
case v := <- b:
out <- v
}
}
}``````

``````func merge(out chan<- int, a, b <-chan int) {
for a != nil || b != nil {
select {
case v, ok := <-a:
if !ok {
a = nil
fmt.Println("a is nil")
continue
}
out <- v
case v, ok := <-b:
if !ok {
b = nil
fmt.Println("b is nil")
continue
}
out <- v
}
}
fmt.Println("close out")
close(out)
}``````

## interface

interface并不是一个指针，它的底层实现由两部分组成，一个是类型，一个值，也就是类似于：(Type, Value)。只有当类型和值都是`nil`的时候，才等于`nil`。看看下面的代码：

``````func do() error {   // error(*doError, nil)
var err *doError
return err  // nil of type *doError
}

func main() {
err := do()
fmt.Println(err == nil)
}``````

``````func do() error {
return nil
}``````

``````func do() *doError {  // nil of type *doError
return nil
}

func wrapDo() error { // error (*doError, nil)
return do()       // nil of type *doError
}

func main() {
err := wrapDo()   // error  (*doError, nil)
fmt.Println(err == nil) // false
}``````

# 总结

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

# nil是什么

``````if err != nil {
// do something....
}``````

``````bool      -> false
numbers -> 0
string    -> ""

pointers -> nil
slices -> nil
maps -> nil
channels -> nil
functions -> nil
interfaces -> nil``````

``````type Person struct {
AgeYears int
Name string
Friends []Person
}

var p Person // Person{0, "", nil}``````

``````type Type int
var nil Type``````

``var nil = errors.New("hi")``

# nil有什么用

## pointers

``````var p *int
p == nil    // true
*p          // panic: invalid memory address or nil pointer dereference``````

``````type tree struct {
v int
l *tree
r *tree
}

// first solution
func (t *tree) Sum() int {
sum := t.v
if t.l != nil {
sum += t.l.Sum()
}
if t.r != nil {
sum += t.r.Sum()
}
return sum
}``````

``````if v != nil {
v.m()
}``````

``````var t *tree
sum := t.Sum()   // panic: invalid memory address or nil pointer dereference``````

``````type person struct {}
func sayHi(p *person) { fmt.Println("hi") }
func (p *person) sayHi() { fmt.Println("hi") }
var p *person
p.sayHi() // hi``````

``````func(t *tree) Sum() int {
if t == nil {
return 0
}
return t.v + t.l.Sum() + t.r.Sum()
}``````

``````func(t *tree) String() string {
if t == nil {
return ""
}
return fmt.Sprint(t.l, t.v, t.r)
}

// nil receivers are useful: Find
func (t *tree) Find(v int) bool {
if t == nil {
return false
}
return t.v == v || t.l.Find(v) || t.r.Find(v)
}``````

## slices

``````// nil slices
var s []slice
len(s)  // 0
cap(s)  // 0
for range s  // iterates zero times
s[i]  // panic: index out of range``````

slice

slice

## map

``````// nil maps
var m map[t]u
len(m)  // 0
for range m // iterates zero times
v, ok := m[i] // zero(u), false
m[i] = x // panic: assignment to entry in nil map``````

``````func NewGet(url string, headers map[string]string) (*http.Request, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}

for k, v := range headers {
}
return req, nil
}``````

``````NewGet("http://google.com", map[string]string{
"USER_AGENT": "golang/gopher",
},)``````

``NewGet("http://google.com", map[string]string{})``

``NewGet("http://google.com", nil)``

## channel

``````// nil channels
var c chan t
<- c      // blocks forever
c <- x    // blocks forever
close(c)  // panic: close of nil channel``````

``````func merge(out chan<- int, a, b <-chan int) {
for {
select {
case v := <-a:
out <- v
case v := <- b:
out <- v
}
}
}``````

``````func merge(out chan<- int, a, b <-chan int) {
for a != nil || b != nil {
select {
case v, ok := <-a:
if !ok {
a = nil
fmt.Println("a is nil")
continue
}
out <- v
case v, ok := <-b:
if !ok {
b = nil
fmt.Println("b is nil")
continue
}
out <- v
}
}
fmt.Println("close out")
close(out)
}``````

## interface

interface并不是一个指针，它的底层实现由两部分组成，一个是类型，一个值，也就是类似于：(Type, Value)。只有当类型和值都是`nil`的时候，才等于`nil`。看看下面的代码：

``````func do() error {   // error(*doError, nil)
var err *doError
return err  // nil of type *doError
}

func main() {
err := do()
fmt.Println(err == nil)
}``````

``````func do() error {
return nil
}``````

``````func do() *doError {  // nil of type *doError
return nil
}

func wrapDo() error { // error (*doError, nil)
return do()       // nil of type *doError
}

func main() {
err := wrapDo()   // error  (*doError, nil)
fmt.Println(err == nil) // false
}``````