Go语言之nil详解
来源:互联网 发布:网络小说家排名 编辑:程序博客网 时间:2024/05/16 05:26
Go语言中的nil远比java中的null要难以理解和掌握。
1.普通的 struct(非指针类型)的对象不能赋值为 nil,也不能和 nil 进行判等(==),即如下代码,不能判断 *s == nil(编译错误),也不能写:var s Student = nil。
s := new(Student) //使用new创建一个 *Student 类型对象fmt.Println("s == nil", s == nil) //false//fmt.Println(*s == nil) //编译错误:cannot convert nil to type Studentfmt.Printf("%T\n", s) //*test.Studentfmt.Printf("%T\n", *s) //test.Student<pre name="code" class="plain">
type Student struct{}func (s *Student) speak() {fmt.Println("I am a student.")}type IStudent interface {speak()}
但是struct的指针对象可以赋值为 nil 或与 nil 进行判等。不过即使 *Student 类型的s3 == nil,依然可以输出s3的类型:*Student
//var s3 Student = nil //编译错误:cannot use nil as type Student in assignmentvar s3 *Student = nilfmt.Println("s3 == nil", s3 == nil) //truefmt.Printf("%T\n", s3) //*test.Student
2.接口对象和接口对象的指针都可以赋值为 nil ,或者与 nil 判等(==)。此处所说的接口可以是 interface{},也可以是自定义接口如上述代码中 IStudent. 使用 new 创建一个 *interface{} 类型的s2之后,该指针对象s2 !=nil ,但是该指针对象所指向的内容 *s2 == nil
s2 := new(interface{})fmt.Println("s2 == nil", s2 == nil) //falsefmt.Println("*s2 == nil", *s2 == nil) //truefmt.Printf("%T\n", s2) //*interface {}fmt.Printf("%T\n", *s2) //<nil>自定义的接口类似,如下。此时 s4 != nil,但 *s4 == nil ,因此调用 s4.speak()方法时会出现编译错误。
var s4 *IStudent = new(IStudent)fmt.Println("s4 == nil", s4 == nil) //falsefmt.Println("*s4 == nil", *s4 == nil) //true//s4.speak() //编译错误:s4.speak undefined (type *IStudent has no field or method speak)3.将一个指针对象赋值为 nil ,然后将该指针对象赋值给一个接口(当然,该指针类型必须实现了这个接口),此时该接口对象将不为 nil .
var s5 *Student = nilvar s5i IStudent = s5fmt.Println("s5 == nil", s5 == nil) //truefmt.Println("s5i == nil", s5i == nil) //false
为什么一个 nil 会如此复杂?还希望和大神一起沟通讨论一下~
0 0
- Go语言之nil详解
- Go语言 nil和interface详解
- 61.笔记go语言——Go语言的nil值和nil
- 关于Go语言中nil和interface的问题
- Go语言 详解reflect
- Go语言interface详解
- Go语言interface详解
- Go语言interface详解
- Go语言Channel详解
- Go语言 channel详解
- Go中nil
- Go语言之defer
- Go语言之介绍
- Go语言 时间处理详解
- Go语言interface详解(转)
- GO语言Socket编程详解
- Go语言 Go加密之DES
- Go语言 Go加密之RSA
- Ubuntu 14.04中文输入法的安装
- 迷宫问题
- Unicode字符集和多字节字符集关系
- spring+静态代理
- HDU 3395 Special Fish?费用流(虚拟边)?647★KM(加虚拟边权)
- Go语言之nil详解
- IDF实验室之万里寻踪图片里的秘密
- leetcode database 题目
- Android 异步加载图片,使用LruCache和SD卡或手机缓存,效果非常的流畅
- STL源码剖析—整体简要概述
- AsynImageLoader andriod异步加载图片类
- Vector Clock算法的理解
- database link
- CI项目架构(1)---前后台分离