golang中接口对象的转型
接口对象的转型有两种方式:
1. 方式一:instance,ok:=接口对象.(实际类型)
如果该接口对象是对应的实际类型,那么instance就是转型之后对象,ok的值为true
配合if...else if...使用
2. 方式二:
接口对象.(type)
配合switch...case语句使用
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | package main import ( "fmt" "math" ) type shape interface { perimeter() int area() int } type rectangle struct { a int // 长 b int // 宽 } func (r rectangle) perimeter() int { return (r.a + r.b) * 2 } func (r rectangle) area() int { return r.a * r.b } type circle struct { radios int } func (c circle) perimeter() int { return 2 * c.radios * int(math.Round(math.Pi)) } func (c circle) area() int { return int(math.Round(math.Pow(float64(c.radios), 2) * math.Pi)) } func getType(s shape) { if i, ok := s.(rectangle); ok { fmt.Printf( "长方形的长:%d,长方形的宽是:%d\n" , i.a, i.b) } else if i, ok := s.(circle); ok { fmt.Printf( "圆形的半径是:%d\n" , i.radios) } } func getType2(s shape) { switch i := s.( type ) { case rectangle: fmt.Printf( "长方形的长:%d,长方形的宽是:%d\n" , i.a, i.b) case circle: fmt.Printf( "圆形的半径是:%d\n" , i.radios) } } func getResult(s shape) { fmt.Printf( "图形的周长是:%d,图形的面积是:%d\n" , s.perimeter(), s.area()) } func main() { r := rectangle{a: 10, b: 20} getType(r) getResult(r) c := circle{radios: 5} getType2(c) getResult(c) } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)