分享
  1. 首页
  2. 文章

关于Go语言中nil和interface的问题

books1958 · · 2227 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

package demo01
//关于Go语言中nil和interface的问题
//Date:2014年2月19日 20:04:25
import (
	"fmt"
)
func NilTestBase() {
	//test05()
	//fmt.Println("=====================")
	test06()
	//nilStringTest()
}
//类Student是类Person的子类
type Person struct {
}
type Student struct {
	Person
}
type IPerson interface {
	speak()
}
//为Person添加方法以实现IPerson接口
func (*Person) speak() {
	fmt.Println("I am a person")
}
//正常的返回值
func test01() Person {
	var p Person
	return p
}
//编译错误:不能将子类对象作为父类直接返回
//func test02() Person {
//	var s Student
//	return s
//}
//可以直接以interface{}形式返回
func test03() interface{} {
	var s Student
	return s
}
//如果Person实现了某个接口,则可以将Person对象作为接口类型的返回值
//但是,此时即使对象为空,将对象作为接口返回之后,接口也将不为空
func test04() IPerson {
	var p *Person = nil
	fmt.Println("in test04:", p == nil) //true
	return p
}
func test05() {
	i := test04()
	fmt.Println("in test05:", i == nil) //false
	fmt.Println("in test05:", i.(*Person) == nil) //true
}
func test06() {
	fmt.Printf("0.Type of nil:%T \n", nil)
	f := new(interface{})
	fmt.Printf("1.Type of f:%T \n", f)
	fmt.Println("2.*f==nil:", *f == nil)
	p := new(Person)
	fmt.Printf("3.Type of p:%T \n", p)
	fmt.Printf("4.Type of *p:%T \n", *p)
	ip := new(IPerson)
	fmt.Printf("5.Type of ip:%T \n", ip)
	fmt.Println("6.*ip==nil:", *ip == nil) //true
	var p1 *Person = nil
	var rip IPerson = p1
	fmt.Println("7.rip==nil:", rip == nil) //false
	fmt.Printf("8.Type of rip:%T \n", rip)
	var b *IPerson
	fmt.Println("9.b==nil:", b == nil) //true
	//output:
	/*
	0.Type of nil:<nil>
	1.Type of f:*interface {}
	2.*f==nil: true
	3.Type of p:*demo01.Person
	4.Type of *p:demo01.Person
	5.Type of ip:*demo01.IPerson
	6.*ip==nil: true
	7.rip==nil: false
	8.Type of rip:*demo01.Person
	9.b==nil: true
	*/
}
func nilStringTest() {
	var a string
	var b *string = &a
	fmt.Println("b==nil:", b == nil)
	//fmt.Println("*b==nil:", *b == nil)
}



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

本文来自:CSDN博客

感谢作者:books1958

查看原文:关于Go语言中nil和interface的问题

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

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

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏