您现在的位置是:网站首页> 编程资料编程资料
go语言实现接口查询_Golang_
2023-05-26
401人已围观
简介 go语言实现接口查询_Golang_
一句话总结:如果接口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 { 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") } }补充:golang中Any类型使用及空接口中类型查询
1.Any类型
GO语言中任何对象实例都满足空接口interface{},空接口可以接口任何值
var v1 interface{} = 1 var v2 interface{} = "abc" var v3 interface{} = 2.345 var v4 interface{} = make(map[..]...) ....2.1 关于空接口的类型查询方式一,使用ok
package main import "fmt" //空接口可以接受任何值 //interface { } func main() { var v1 interface{ } v1 = 6.78 //赋值一个变量v判断其类型是否为float64,是则为真,否则,为假 if v, ok := v1.(float64);ok{ fmt.Println(v, ok) }else { fmt.Println(v,ok) } }2.2 关于空接口类型查询方式二,switch语句结合 var.type()
package main import "fmt" //空接口可以接受任何值 //interface { } func main() { var v1 interface{ } v1 = "张三" switch v1.(type) { case float32: case float64: fmt.Println("this is float64 type") case string: fmt.Println("this is string type") } }以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。
您可能感兴趣的文章:
相关内容
- 如何判断Golang接口是否实现的操作_Golang_
- 浅谈golang中的&^位清空操作_Golang_
- Golang之defer 延迟调用操作_Golang_
- 解决golang sync.Wait()不执行的问题_Golang_
- golang执行命令操作 exec.Command_Golang_
- golang等待触发事件的实例_Golang_
- 浅谈golang类型断言,失败类型断言返回值问题_Golang_
- Go 修改map slice array元素值操作_Golang_
- 解决Golang map range遍历结果不稳定问题_Golang_
- 快速解决Golang Map 并发读写安全的问题_Golang_
