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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大