//普通断言 package main import ( "fmt" ) func main() { var s string s = "str" Strerface(s) } func Strerface(a interface{}) { b, ok := a.(string) //ok返回的是一个布尔值 if ok { fmt.Printf("a is string: %s, type: %T\n", b, b) } }
//结合函数和判断 package main import ( "fmt" ) func main() { var num float64 num = 10.33 showType(num) } func showType(any interface{}) { switch any.(type) { case int: fmt.Println("the type of a is int") case string: fmt.Println("the type of a is string") case float64: fmt.Println("the type of a is float") default: fmt.Println("unknown type") } }