Go-动态类型与类型断言详解(含type-switch及全部代码)

深碍√TFBOYSˉ_ 2023-01-16 06:53 175阅读 0赞

目录

动态类型

类型断言与type-switch

全部代码

截图

参考


动态类型

我们知道Go不像Python,变量可以没有类型。那么如果一个函数的参数需要兼容多个类型或是需要判断变量类型该如何做呢?

我们可以使用接口,上一篇文章Go-接口类型详解(定义、实现、接口继承比较等)介绍了接口及接口的使用,知道了接口变量可以接收实现了它的类型的变量。我们就可以用接口做参数。

结构体、接口与实现代码

  1. type Cat struct {
  2. Name string
  3. }
  4. type Mouse struct {
  5. Name string
  6. }
  7. type Introduce interface {
  8. Intro()
  9. }
  10. func (c *Cat)Intro(){
  11. fmt.Println("hi, i am Cat, you can call me:",c.Name)
  12. }
  13. func (m *Mouse)Intro() {
  14. fmt.Println("hi, i am Mouse, you can call me:",m.Name)
  15. }

接口参数

  1. func selfIntro(in Introduce) {
  2. in.Intro()
  3. }

使用

  1. tom := Cat{"Tom"}
  2. selfIntro(&tom)
  3. jerry := Mouse{"Jerry"}
  4. selfIntro(&jerry)

类型断言与type-switch

go中有以下语法来对变量类型判断

value, ok = element.(T)

  • value 变量的值
  • ok是一个bool类型
  • element是interface变量
  • T是断言的类型

如果element存储了T类型的数值,那么ok就是true,否则就是false

type-switch

  1. func typeJudge(x interface{}) {
  2. switch x.(type){
  3. case int,int8,int64,int16,int32,uint,uint8,uint16,uint32,uint64:
  4. fmt.Println("整型变量")
  5. case float32,float64:
  6. fmt.Println("浮点型变量")
  7. case []byte,[]rune,string:
  8. fmt.Println("字符串变量")
  9. default:
  10. fmt.Println("不清楚...")
  11. }
  12. }

使用

  1. typeJudge(1)
  2. typeJudge(1.1)
  3. typeJudge("1.1")
  4. typeJudge([]byte("hi"))
  5. typeJudge([]int{1,2})

全部代码

  1. package main
  2. import "fmt"
  3. type Cat struct {
  4. Name string
  5. }
  6. type Mouse struct {
  7. Name string
  8. }
  9. type Introduce interface {
  10. Intro()
  11. }
  12. func (c *Cat)Intro(){
  13. fmt.Println("hi, i am Cat, you can call me:",c.Name)
  14. }
  15. func (m *Mouse)Intro() {
  16. fmt.Println("hi, i am Mouse, you can call me:",m.Name)
  17. }
  18. func selfIntro(in Introduce) {
  19. in.Intro()
  20. }
  21. func typeJudge(x interface{}) {
  22. switch x.(type){
  23. case int,int8,int64,int16,int32,uint,uint8,uint16,uint32,uint64:
  24. fmt.Println("整型变量")
  25. case float32,float64:
  26. fmt.Println("浮点型变量")
  27. case []byte,[]rune,string:
  28. fmt.Println("字符串变量")
  29. default:
  30. fmt.Println("不清楚...")
  31. }
  32. }
  33. func main() {
  34. //-----------动态类型--------------
  35. tom := Cat{"Tom"}
  36. selfIntro(&tom)
  37. jerry := Mouse{"Jerry"}
  38. selfIntro(&jerry)
  39. //-----------类型断言与type-switch--------
  40. typeJudge(1)
  41. typeJudge(1.1)
  42. typeJudge("1.1")
  43. typeJudge([]byte("hi"))
  44. typeJudge([]int{1,2})
  45. }

截图

20210424205518143.PNG

参考

Golang中的类型和类型断言

更多Go相关内容:Go-Golang学习总结笔记

有问题请下方评论,转载请注明出处,并附有原文链接,谢谢!如有侵权,请及时联系。如果您感觉有所收获,自愿打赏,可选择支付宝18833895206(小于),您的支持是我不断更新的动力。

发表评论

表情:
评论列表 (有 0 条评论,175人围观)

还没有评论,来说两句吧...

相关阅读

    相关 golang类型转换类型断言

    类型转换在程序设计中都是不可避免的问题。当然有一些语言将这个过程给模糊了,大多数时候开发者并不需要去关注这方面的问题。但是golang中的类型匹配是很严格的,不同的类型之间通常