dongpan2788 2016-03-14 08:56
浏览 116
已采纳

nil在golang中是什么意思?

There are many cases using nil in golang. For example:

func (u *URL) Parse(ref string) (*URL, error) {
    refurl, err := Parse(ref)
    if err != nil {
        return nil, err
    }
    return u.ResolveReference(refurl), nil
}

but we can't use it like this:

var str string //or var str int
str = nil

the golang compiler will throw a can't use nil as type string in assignment error.

Looks like nil can only be used for a pointer of struct and interface. If that is the case, then what does it mean? and when we use it to compare to the other object, how do they compare, in other words, how does golang determine one object is nil?

EDIT:For example, if an interface is nil, its type and value must be nil at the same time. How does golang do this?

  • 写回答

3条回答 默认 最新

  • doujiao1180 2016-03-14 09:21
    关注

    In Go, nil is the zero value for pointers, interfaces, maps, slices, channels and function types, representing an uninitialized value.

    nil doesn't mean some "undefined" state, it's a proper value in itself. An object in Go is nil simply if and only if it's value is nil, which it can only be if it's of one of the aforementioned types.

    An error is an interface, so nil is a valid value for one, unlike for a string. For obvious reasons a nil error represents no error.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看