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

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值