Go-动态类型与类型断言详解(含type-switch及全部代码) 深碍√TFBOYSˉ_ 2023-01-16 06:53 85阅读 0赞 **目录** 动态类型 类型断言与type-switch 全部代码 截图 参考 -------------------- # 动态类型 # 我们知道Go不像Python,变量可以没有类型。那么如果一个**函数的参数需要兼容多个类型或是需要判断变量类型**该如何做呢? 我们可以使用接口,上一篇文章[Go-接口类型详解(定义、实现、接口继承比较等)][Go-]介绍了接口及接口的使用,知道了接口变量可以接收实现了它的类型的变量。我们就可以用接口做参数。 **结构体、接口与实现代码** type Cat struct { Name string } type Mouse struct { Name string } type Introduce interface { Intro() } func (c *Cat)Intro(){ fmt.Println("hi, i am Cat, you can call me:",c.Name) } func (m *Mouse)Intro() { fmt.Println("hi, i am Mouse, you can call me:",m.Name) } **接口参数** func selfIntro(in Introduce) { in.Intro() } **使用** tom := Cat{"Tom"} selfIntro(&tom) jerry := Mouse{"Jerry"} selfIntro(&jerry) # 类型断言与type-switch # go中有以下语法来**对变量类型判断** > value, ok = element.(T) * value 变量的值 * ok是一个bool类型 * element是interface变量 * T是断言的类型 如果element存储了T类型的数值,那么ok就是true,否则就是false **type-switch** func typeJudge(x interface{}) { switch x.(type){ case int,int8,int64,int16,int32,uint,uint8,uint16,uint32,uint64: fmt.Println("整型变量") case float32,float64: fmt.Println("浮点型变量") case []byte,[]rune,string: fmt.Println("字符串变量") default: fmt.Println("不清楚...") } } **使用** typeJudge(1) typeJudge(1.1) typeJudge("1.1") typeJudge([]byte("hi")) typeJudge([]int{1,2}) # 全部代码 # package main import "fmt" type Cat struct { Name string } type Mouse struct { Name string } type Introduce interface { Intro() } func (c *Cat)Intro(){ fmt.Println("hi, i am Cat, you can call me:",c.Name) } func (m *Mouse)Intro() { fmt.Println("hi, i am Mouse, you can call me:",m.Name) } func selfIntro(in Introduce) { in.Intro() } func typeJudge(x interface{}) { switch x.(type){ case int,int8,int64,int16,int32,uint,uint8,uint16,uint32,uint64: fmt.Println("整型变量") case float32,float64: fmt.Println("浮点型变量") case []byte,[]rune,string: fmt.Println("字符串变量") default: fmt.Println("不清楚...") } } func main() { //-----------动态类型-------------- tom := Cat{"Tom"} selfIntro(&tom) jerry := Mouse{"Jerry"} selfIntro(&jerry) //-----------类型断言与type-switch-------- typeJudge(1) typeJudge(1.1) typeJudge("1.1") typeJudge([]byte("hi")) typeJudge([]int{1,2}) } # 截图 # ![20210424205518143.PNG][] # 参考 # [Golang中的类型和类型断言][Golang] 更多Go相关内容:[Go-Golang学习总结笔记][Go-Golang] 有问题请下方评论,转载请注明出处,并附有原文链接,谢谢!如有侵权,请及时联系。如果您感觉有所收获,自愿打赏,可选择支付宝18833895206(小于),您的支持是我不断更新的动力。 [Go-]: https://blog.csdn.net/lady_killer9/article/details/115937820 [20210424205518143.PNG]: /images/20221022/276195ffbe994d3b8fa2a2ea3341c4bb.png [Golang]: https://studygolang.com/articles/20041 [Go-Golang]: https://blog.csdn.net/lady_killer9/article/details/115491317
还没有评论,来说两句吧...