dongpan2788 2016-03-14 08:56
浏览 116


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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
  • doumu6941 2016-03-14 09:04

    nil in Go is simply the NULL pointer value of other languages.

    You can effectively use it in place of any pointer or interface (interfaces are somewhat pointers).

    You can use it as an error, because the error type is an interface.

    You can't use it as a string because in Go, a string is a value.

    nil is untyped in Go, meaning you can't do that:

    var n = nil

    Because here you lack a type for n. However, you can do

    var n *Foo = nil

    Note that nil being the zero value of pointers and interfaces, uninitialized pointers and interfaces will be nil.

  • dphfwzn8269 2019-06-14 15:11
    • For the data types like slice and pointers which "refer" to other types, "nil" indicates that the variable does not refer to an instance (equivalent of null pointer in other languages)
    • It is thee zero value of the variables of type functions, maps, interfaces, channels and structures



  • ¥15 代码已写好,求帮我指出错误,有偿!
  • ¥15 matlab+波形匹配算法
  • ¥15 转录组分析做聚类树图时癌旁组被分到了癌组
  • ¥15 大一Python字典
  • ¥15 multisim电路设计(相关搜索:设计报告)
  • ¥15 PC-lint Plus
  • ¥15 gpl24676注释
  • ¥15 php5.3内存泄露
  • ¥15 DigSilent如何复制复合模型到自己案例?
  • ¥15 求日版华为b610s-77a 官方公版固件,有偿