To determine the data types in the Go language, this article describes three ways.
Method One: Use I. (type) combined with NULL interface (interface{})
func main() { v1 := "中国你好" v2 := 20 var v3 byte = 65 fmt.Printf("v1的数据类型为:%s\n", checkType(v1)) fmt.Printf("v2的数据类型为:%s\n", checkType(v2)) fmt.Printf("v3的数据类型为:%s\n", checkType(v3))}func checkType(i interface{}) string{ switch i.(type) { case string : return "string" case int : return "int" case byte : return "byte" } return ""}
Output:
v1的数据类型为:stringv2的数据类型为:intv3的数据类型为:byte
Note: I. (type) can only be used in switch
Method Two: Use formatted output%t in FMT
func main() { v1 := "中国你好" v2 := 20 var v3 byte = 65 fmt.Printf("v1的数据类型为:%T\n", v1) fmt.Printf("v2的数据类型为:%T\n", v2) fmt.Printf("v2的数据类型为:%T\n", v3)}
Output:
v1的数据类型为:stringv2的数据类型为:intv2的数据类型为:uint8
Description: Byte is the same type as Uint8
Method Three: Use the TypeOf function in reflect reflection
func main() { v1 := "中国你好" v2 := 20 var v3 byte = 65 fmt.Printf("v1的数据类型为:%v\n", reflect.TypeOf(v1)) fmt.Printf("v2的数据类型为:%v\n", reflect.TypeOf(v2)) fmt.Printf("v3的数据类型为:%v\n", reflect.TypeOf(v3))}
Output:
v1的数据类型为:stringv2的数据类型为:intv2的数据类型为:uint8
Judgment of data types in Go language