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

go语言接口查询

2018-01-29 20:49 399 查看
一句话总结:如果接口A实现了接口B中所有方法,那么A可以转化为B接口。

package options


type IPeople interface {

GetName() string

}


type IPeople2 interface {

GetName() string

GetAge() int

}


package main


import (

"fmt"

"options"

)


type person struct {

name string

}


func (p *person) GetName() string {

return p.name

}


type person2 struct {

name string

age  int

}


func (p *person2) GetName() string {

return p.name

}

func (p *person2) GetAge() int {

return p.age

}

func main() {

//p不可以转化为options.IPeople2接口,没有实现options.IPeople2接口中的GetAge()

var p options.IPeople = &person{"jack"}

if p2, ok := p.(options.IPeople2); ok {

fmt.Println(p2.GetName(), p2.GetAge())

} else <
dccf
span style="color:#000000;">{

fmt.Println("p不是Ipeople2接口类型")

}


//p2可以转化为options.IPeople接口,因为实现了options.IPeople接口的所有方法

var p2 options.IPeople2 = &person2{"mary", 23}

if p, ok := p2.(options.IPeople); ok {

fmt.Println(p.GetName())

}



var pp options.IPeople = &person{"alen"}

if pp2, ok := pp.(*person); ok {

fmt.Println(pp2.GetName()) //pp接口指向的对象实例是否是*person类型,*不能忘

}

switch pp.(type) {
case options.IPeople:
fmt.Println("options.IPeople") //判断接口的类型
case options.IPeople2:
fmt.Println("options.IPeople2")
default:
fmt.Println("can't found")
}
var ii interface{} = 43 //默认int类型
switch ii.(type) {
case int:
fmt.Println("int")
default:
fmt.Println("can't found")
}

}


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  go 接口查询