跳到主要内容

避坑-3-nil判断

一 nil判断

nil在Go语言中只能被赋值给指针和接口。接口在底层的实现有两个部分,type 和 data:

  • 显式地将nil赋值给接口时:接口 == nil,此时接口的type和data都为nil。
  • 将带类型的nil赋给接口:接口 != nil
package main

import "fmt"

type Student struct {

}

func (m *Student) String() string {
return "hi"
}

// 在函数中返回 fmt.Stringer接口
func GetStringer() fmt.Stringer {
var s *Student = nil
return s
}

func main() {
if GetStringer() == nil {
fmt.Println("GetStringer() == nil")
} else {
fmt.Println("GetStringer() != nil")
}
}

上述案例输出了 !=nil,为了避免这个误判的问题,可以这样修改:

func GetStringer() fmt.Stringer {
var s *Student = nil
if s == nil {
return nil
}
return s
}