golang 关于nil的疑惑

Chaoxin · 2020-11-19 11:26:50 · 1085 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2020-11-19 11:26:50 的主题,其中的信息可能已经有所发展或是发生改变。

nil的底层实现在源码中为:

// nil is a predeclared identifier representing the zero value for a
// pointer, channel, func, interface, map, or slice type.
var nil Type // Type must be a pointer, channel, func, interface, map, or slice type

// Type is here for the purposes of documentation only. It is a stand-in
// for any Go type, but represents the same type for any given function
// invocation.
type Type int

在源码中好像是int类型? 我的疑惑是nil在实际使用中是有类型区分的,可以把nil转换为不同类型的nil。那nil是接口类型还是int类型? 如果接口类型他的data,type是什么内容呢?如果是int类型底层实现又是如何呢?


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1085 次点击  
加入收藏 微博
2 回复  |  直到 2020-11-20 18:49:49
focusonline
focusonline · #1 · 4年之前

nil 可以用在 指针类型和接口类型上. 其实你不必纠结这个问题, 对于这种特殊的常量, 明白意义和用法即可. 这个就相当于C里面的NULL, 你需要了解NULL是怎么定义的吗? 了解了有啥意义?

AnkoGo
AnkoGo · #2 · 4年之前

nil无类型,注意,nil无类型,网上多半是误导,(*int)nil 像这样的东西并不是nil,而是值为nil的*int类型的实例对象,nil仅仅是一种标志,标志该内存的值未初始化!仅此而已。

添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传