go语言实现接口查询
一句话总结:如果接口A实现了接口B中所有方法,那么A可以转化为B接口。
packageoptions
typeIPeopleinterface{
GetName()string
}
typeIPeople2interface{
GetName()string
GetAge()int
}
packagemain
import(
"fmt"
"options"
)
typepersonstruct{
namestring
}
func(p*person)GetName()string{
returnp.name
}
typeperson2struct{
namestring
ageint
}
func(p*person2)GetName()string{
returnp.name
}
func(p*person2)GetAge()int{
returnp.age
}
funcmain(){
//p不可以转化为options.IPeople2接口,没有实现options.IPeople2接口中的GetAge()
varpoptions.IPeople=&person{"jack"}
ifp2,ok:=p.(options.IPeople2);ok{
fmt.Println(p2.GetName(),p2.GetAge())
}else{
fmt.Println("p不是Ipeople2接口类型")
}
//p2可以转化为options.IPeople接口,因为实现了options.IPeople接口的所有方法
varp2options.IPeople2=&person2{"mary",23}
ifp,ok:=p2.(options.IPeople);ok{
fmt.Println(p.GetName())
}
varppoptions.IPeople=&person{"alen"}
ifpp2,ok:=pp.(*person);ok{
fmt.Println(pp2.GetName())//pp接口指向的对象实例是否是*person类型,*不能忘
}
switchpp.(type){
caseoptions.IPeople:
fmt.Println("options.IPeople")//判断接口的类型
caseoptions.IPeople2:
fmt.Println("options.IPeople2")
default:
fmt.Println("can'tfound")
}
variiinterface{}=43//默认int类型
switchii.(type){
caseint:
fmt.Println("int")
default:
fmt.Println("can'tfound")
}
}
补充:golang中Any类型使用及空接口中类型查询
1.Any类型
GO语言中任何对象实例都满足空接口interface{},空接口可以接口任何值
varv1interface{}=1
varv2interface{}="abc"
varv3interface{}=2.345
varv4interface{}=make(map[..]...)
....
2.1关于空接口的类型查询方式一,使用ok
packagemain
import"fmt"
//空接口可以接受任何值
//interface{}
funcmain(){
varv1interface{}
v1=6.78
//赋值一个变量v判断其类型是否为float64,是则为真,否则,为假
ifv,ok:=v1.(float64);ok{
fmt.Println(v,ok)
}else{
fmt.Println(v,ok)
}
}
2.2关于空接口类型查询方式二,switch语句结合var.type()
packagemain
import"fmt"
//空接口可以接受任何值
//interface{}
funcmain(){
varv1interface{}
v1="张三"
switchv1.(type){
casefloat32:
casefloat64:
fmt.Println("thisisfloat64type")
casestring:
fmt.Println("thisisstringtype")
}
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持毛票票。如有错误或未考虑完全的地方,望不吝赐教。