Go语言之nil详解
2015-03-23 15:31
483 查看
Go语言中的nil远比java中的null要难以理解和掌握。
1.普通的 struct(非指针类型)的对象不能赋值为 nil,也不能和 nil 进行判等(==),即如下代码,不能判断 *s == nil(编译错误),也不能写:var s Student = nil。
但是struct的指针对象可以赋值为 nil 或与 nil 进行判等。不过即使 *Student 类型的s3 == nil,依然可以输出s3的类型:*Student
2.接口对象和接口对象的指针都可以赋值为 nil ,或者与 nil 判等(==)。此处所说的接口可以是 interface{},也可以是自定义接口如上述代码中 IStudent. 使用 new 创建一个 *interface{} 类型的s2之后,该指针对象s2 !=nil ,但是该指针对象所指向的内容 *s2 == nil
为什么一个 nil 会如此复杂?还希望和大神一起沟通讨论一下~
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 Student fmt.Printf("%T\n", s) //*test.Student fmt.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 assignment var s3 *Student = nil fmt.Println("s3 == nil", s3 == nil) //true fmt.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) //false fmt.Println("*s2 == nil", *s2 == nil) //true fmt.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) //false fmt.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 = nil var s5i IStudent = s5 fmt.Println("s5 == nil", s5 == nil) //true fmt.Println("s5i == nil", s5i == nil) //false
为什么一个 nil 会如此复杂?还希望和大神一起沟通讨论一下~
相关文章推荐
- go语言编译器详解
- golang实战使用gin+xorm搭建go语言web框架restgo详解5.4 控制器参数绑定
- Go语言interface详解
- 在go语言中安装与使用protobuf的方法详解
- golang实战使用gin+xorm搭建go语言web框架restgo详解5.5 控制器模型绑定
- [Go语言] 面向外网的Web调优详解(go1.8)
- GO语言如何手动处理TCP粘包详解
- Mac下搭建Go语言开发环境详解(步骤配图)
- Go语言之数据类型详解
- Go语言的变量、函数、Socks5代理服务器示例详解
- go语言之行--接口(interface)、反射(reflect)详解
- Go语言 详解reflect
- Go语言的JSON处理详解
- 详解go语言的array和slice 【二】
- golang实战使用gin+xorm搭建go语言web框架restgo详解5.6 控制器参数校验
- GO语言Socket编程详解
- GO语言数组和切片实例详解
- Go语言 channel详解
- Go语言 Go1.1新调度器详解
- Go语言 nil和interface详解