Go interface static and dynamic check

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

Go interface static and dynamic check

The interface of Go is the duck model, and the type does not need an explicit declaration to implement an interface, just implement all the methods of that interface and assume that the type implements that interface. In practice, most of the interface transitions are static and occur at compile time; Go also supports dynamic interface transformations, which occur at runtime.

For example, it needs to be passed *os.File to an io. The function of the reader parameter, if *os.File no interface io is implemented . Reader, the program can not be passed at compile time;

Some interface swapping occurs at run time, and an instance is encoding/json 包,其定义了一个 Marshaler接口,当JSON解析器接收的value实现该接口,就调用该value的marshaling 方法转换,反之则调用系统默认的转换器。这种转换可以通过go的type类型断言实现:

If m, OK: = val. (JSON. Marshaler); OK {xxx} else {XXX}


If str, OK: = value. (string); OK {    return str} else if str, OK: = value. ( Stringer); OK {    return str. String ()}

Sometimes we want to improve the robustness of the program or in order to prevent the interface changes and the specific implementation of the type of forgetting changes caused the program to crash, we need to run the validation of the runtime to the compile time, this can be used as follows:

var _ json. Marshaler = (*rawmessage) (nil)
This statement converts *rawmessage to JSON at compile time. Marshaler, if the interface Marshaler changes, and Rawmessage does not change, the compilation will not pass, so that we can detect the problem ahead of time, make changes, and not because of a momentary neglect to postpone the problem until the runtime to discover. The _ here is used only for type checking, not really creating a variable. However, do not misuse this method, the method is only used in the absence of static conversion, but there is a place to ensure that the program security.




Related Article

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.