类型断言

作用是判断实现该接口的对象是不是某个类型
可以通过打印空接口的值来推断空接口是什么具体类型。可以通过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\n", v)
        case int:
            fmt.Printf("x is a int is %v\n", v)
        case bool:
            fmt.Printf("x is a bool is %v\n", v)
        default:
            fmt.Println("unsupport type!")
        }
}

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

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

 

相关文章:

  • 2021-10-30
  • 2021-05-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-20
  • 2021-07-03
猜你喜欢
  • 2021-12-20
  • 2022-12-23
  • 2022-01-21
  • 2022-12-23
  • 2021-06-03
  • 2022-12-23
  • 2021-08-20
相关资源
相似解决方案