Judgment of data types in Go language

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.