Go interface{}, type assertion

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

In Golang interface{} can be used to pass a variable of any type to a function, but used inside a function, the type of the variable is interface{}, also known as an empty interface type

For example, we define a function, output a string, but the argument is interface{} type

func echoString(content interface{}) {    fmt.Println(content )}

When we call echoString("输出字符串") the method, we get content an error because it's a interface{} type, not a string type.

The conversion of an interface type to a normal type is called a type assertion (run-time determination)

For the above call, you can modify the method byechoString

func echoString(content interface{}) {    result, _ := content.(string)  //通过断言实现类型转换    fmt.Println(result)}

This time there will be a potential threat, if we give the method is the int type, then we 断言 will be error, this time we need to perfect the code

func echoString(content interface{}) {    result, err := content.(string)      if err != nil {  // 断言失败        fmt.Println(err .Error())  // 输出失败原因        return    }    fmt.Println(result)}

Operations of different types of variables must be explicitly type-cast, and the result may be error-

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.