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.