• 2.08 Go之类型分支(switch判断空接口中变量的类型)


    2.08 Go之类型分支(switch判断空接口中变量的类型)

    type-switch

    特点:

    可以判断空接口中值得类型,做类型得断言。语法如下:

    /*
    变量 t 得到了 areaIntf 的值和类型
    */
    switch t := areaIntf.(type) {
    case *Square:
       fmt.Printf("Type Square %T with value %v\n", t, t)
    case *Circle:
       fmt.Printf("Type Circle %T with value %v\n", t, t)
    case nil:
       fmt.Printf("nil value: nothing to check?\n")
    default:
       fmt.Printf("Unexpected type %T\n", t)
    }
    /*
    所有 case 语句中列举的类型(nil 除外)都必须实现对应的接口,如果被检测类型没有在 case 语句列举的类型中,就会执行 default 语句
    如果跟随在某个 case 关键字后的条目为一个非接口类型(用一个类型名或类型字面表示),则此非接口类型必须实现了断言值 x 的(接口)类型
    */

    类型断言书写格式

    switch 接口变量.(type) {
       case 类型1:
           // 变量是类型1时的处理
       case 类型2:
           // 变量是类型2时的处理
       
       default:
           // 变量不是所有case中列举的类型时的处理
    }

    示例:使用类型分支判断基本类型

    package main

    import "fmt"

    /* 打印类型的方法--->使用类型断言 */
    func printType(v interface{}) {
       switch v.(type) {
       case int:
           fmt.Println(v, "is int!")
       case string:
           fmt.Println(v, "is string!")
       case bool:
           fmt.Println(v, "is boolean!")
       default:
           fmt.Println(v, "is unknowtype!")
      }
    }

    /* 调用函数 */
    func main() {
       printType(1024)
       printType("HelloWorld!")
       printType(false)
    }

    使用类型分支判断接口类型

    多个接口进行类型断言时,可以使用类型分支简化判断过程

    示例代码:

    package main

    import "fmt"

    /* 定义具备刷脸特性的接口 */
    type ContainCanUseFaceId interface {
       CanUseFaceId()
    }

    /* 定义具备偷窃特性的接口 */
    type ContainStolen interface {
       Stolen()
    }

    /* 定义刷脸支付类型 */
    type Alipay struct {
    }

    // 刷脸支付类型实现刷脸特性接口定义的函数
    func (a *Alipay) CanUseFaceId() {
    }

    /* 定义现金支付类型 */
    type Cash struct {
    }

    // 现金支付类型实现偷窃特性接口定义的函数
    func (c *Cash) Stolen() {
    }

    /* 定义根据接口类型进行类型断言的函数 */
    func print(payMethod interface{}) {
       switch payMethod.(type) {
       case ContainCanUseFaceId: // 这里判断的是接口的类型,所以case后+的是接口名称
           fmt.Println("支持刷脸支付!")
       case ContainStolen:
           fmt.Println("可能被偷窃!")
       default:
           fmt.Println("未知什么类型的接口!")
      }
    }

    // 调用print方法
    func main() {
       print(new(Cash))
       print(new(Alipay))
       print(new(Cash))
    }
  • 相关阅读:
    centos redis 安装 php-redis扩展安装 及使用
    mysql 大数据分页查询优化
    nginx https ssl 配置
    mysql 集群 数据同步
    linux 挂载U盘
    centos yum 没有可用软件包 nginx。
    nginx 负载均衡 反向代理
    nginx 配置
    mac 多php版本安装
    Foundation框架
  • 原文地址:https://www.cnblogs.com/JunkingBoy/p/15944291.html
Copyright © 2020-2023  润新知