您的位置:首页 > 编程语言 > Go语言

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

2014-02-19 20:06 603 查看
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)
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  go语言 struct interface