• 【go语言基础】go类型断言 type switch + case,t := x.(type)


    有这么一个场景,当你在和用户对接的时候,调取第三方接口,但是第三方接口的时常变化的,比如从string类型变为int,这个时候你需要再去判断类型,获取第三方接口的参数。比较麻烦。

    针对这一场景,go中对switch进行了升级。a是一个未知类型的变量,switch b := a.(type) 用这个方式来赋值,b + case进行判断就是有确定类型的变量。

    未知类型比如类似于java的Object,interface{},通过case之后,变成确定的数据类型的值。

    先看下例子:

    a是任意类型,因为传入值的类型是不确定的。所以我们赋值a为任意类型。

    case是需要的类型,如果需要的是string类型,那么将string类型给b,如果需要int类型,那么将int类型给b,其实b拥有a的类型,需要什么类型,那么就case什么类型。

    1. func test() {
    2. // a是任意类型,这个可以当做传入的参数,根据传入的参数来进行判断。
    3. var a any
    4. switch b := a.(type) {
    5. case string:
    6. fmt.Printf("type of b is %T\n", b)
    7. fmt.Printf("value of b is %v\n", b)
    8. case int:
    9. fmt.Printf("type of b is %T\n", b)
    10. fmt.Printf("value of b is %v\n", b)
    11. default:
    12. fmt.Printf("type of b is %T\n", b)
    13. fmt.Printf("value of b is %v\n", b)
    14. }
    15. }
    1. func test() {
    2. var a any = 1
    3. switch b := a.(type) {
    4. case string:
    5. fmt.Printf("type of b is %T\n", b)
    6. fmt.Printf("value of b is %v\n", b)
    7. case int:
    8. fmt.Printf("type of b is %T\n", b)
    9. fmt.Printf("value of b is %v\n", b)
    10. default:
    11. fmt.Printf("type of b is %T\n", b)
    12. fmt.Printf("value of b is %v\n", b)
    13. }
    14. }

    结果为:

    1. type of b is int
    2. value of b is 1

    可以看出以下类型:

  • 相关阅读:
    docker怎样安装redis
    java计算机毕业设计web网上办公自动化系统源码+mysql数据库+系统+lw文档+部署
    Linux chkconfig命令
    day4作业
    K8S(1)Pod
    一文带你梳理Python的中级知识
    Tauri | 新版2.0路线图:更强大的插件以及支持 iOS、Android 应用构建
    骑士周游算法(Java)
    HGAME-week3-web-wp
    34、Java——一个案例学会Dom4j解析技术对XML文件的增删改查
  • 原文地址:https://blog.csdn.net/Sunshineoe/article/details/133021599