What is an interface in Go? How does duck typing work? Is it possible to check the implementation of an interface at compile time?
sobes.tech AI
Answer from AI
In Go, an interface is a set of methods that a type must implement to be considered an implementation of that interface. Interfaces in Go are implemented implicitly: if a type has all the methods of an interface, it automatically implements it — this is an example of duck typing ("if it walks like a duck and quacks like a duck, it’s a duck").
Duck typing allows writing more flexible and extensible code without explicitly declaring implementation of an interface.
Checking interface implementation at compile time is possible by assigning a zero value of the interface to a variable of a specific type or using _var _ interface = (*Type)(nil). For example:
var _ io.Reader = (*MyType)(nil) // check that MyType implements io.Reader
If MyType does not implement all methods of io.Reader, the compiler will produce an error.