douyi2107 2016-12-02 07:56
浏览 42
已采纳

类型声明在golang中的重要性,nil值[重复]

This question already has an answer here:

I have this small golang test I cannot understand:

package main

import "fmt"

type myObj struct {
}

func nilObj() *myObj {
    return nil
}

func nilInt() interface{} {
    return nil
}

func main() {
    var obj1 interface{}
    fmt.Println(obj1 == nil)    // true
    obj1 = nilObj()
    fmt.Println(obj1 == nil)    // false

    var obj2 *myObj
    fmt.Println(obj2 == nil)    // true
    obj2 = nilObj()
    fmt.Println(obj2 == nil)    // true

    var obj3 interface{}
    fmt.Println(obj3 == nil)    // true
    obj3 = nilInt()
    fmt.Println(obj3 == nil)    // true
}

Between obj1 and obj2, only the variable declaration changes, but the result is different.

Between obj1 and obj3, the function call does not return the same type (struct pointer vs interface). I am not entirely sure I understand the result.

Any help is welcome (https://play.golang.org/p/JcjsJ-_S8I)

</div>
  • 写回答

1条回答 默认 最新

  • doukougua7873 2016-12-02 08:09
    关注

    Under the covers, interfaces are implemented as two elements, a type and a value. The value, called the interface's dynamic value, is an arbitrary concrete value and the type is that of the value. For the int value 3, an interface value contains, schematically, (int, 3).

    An interface value is nil only if the inner value and type are both unset, (nil, nil). In particular, a nil interface will always hold a nil type. If we store a nil pointer of type *int inside an interface value, the inner type will be *int regardless of the value of the pointer: (*int, nil). Such an interface value will therefore be non-nil even when the pointer inside is nil.

    https://golang.org/doc/faq#nil_error

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥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 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?