zoukankan      html  css  js  c++  java
  • Go 类型断言

    类型断言

    作用是判断实现该接口的对象是不是某个类型
    可以通过打印空接口的值来推断空接口是什么具体类型。可以通过Printf("%T",x)进行打印,那么..有没有什么方法可以在程序运行中得到空接口的具体类型呢?
    x.(T)

    例如:data, ok := a.(string)
    x:表示类型为interface{}的变量
    T:表示断言x可能是的类型。

    示例:

    func justifyType(x interface{}) {
        switch v := x.(type) {
            case string:
                fmt.Printf("x is a string,value is %v ", v)
            case int:
                fmt.Printf("x is a int is %v ", v)
            case bool:
                fmt.Printf("x is a bool is %v ", v)
            default:
                fmt.Println("unsupport type!")
            }
    }

    这样也行。要类型断言有何用??

    func guessType(obj interface{}) string {
      tp := fmt.Sprintf("%T", obj)
      return tp
    }

  • 相关阅读:
    省常中模拟 Test4
    省常中模拟 Test3 Day1
    省常中模拟 Test3 Day2
    省常中模拟 Test1 Day1
    树型动态规划练习总结
    noip2010提高组题解
    noip2003提高组题解
    noip2009提高组题解
    noip2004提高组题解
    noip2002提高组题解
  • 原文地址:https://www.cnblogs.com/staff/p/13226492.html
Copyright © 2011-2022 走看看