Fork me on GitHub
随笔 - 215  文章 - 13  trackbacks - 0
<2018年10月>
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910


专注即时通讯及网游服务端编程
------------------------------------
Openresty 官方模块
Openresty 标准模块(Opm)
Openresty 三方模块
------------------------------------
本博收藏大部分文章为转载,并在文章开头给出了原文出处,如有再转,敬请保留相关信息,这是大家对原创作者劳动成果的自觉尊重!!如为您带来不便,请于本博下留言,谢谢配合。

常用链接

留言簿(1)

随笔分类

随笔档案

相册

Awesome

Blog

Book

GitHub

Link

搜索

  •  

积分与排名

  • 积分 - 204440
  • 排名 - 126

最新评论

阅读排行榜

http://studygolang.com/articles/3751

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 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

posted on 2017-05-04 10:28 思月行云 阅读(201) 评论(0)  编辑 收藏 引用 所属分类: Golang

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理