Junior — Middle
How can you determine that a certain structure implements a given interface?
sobes.tech AI
Answer from AI
In Go, interface implementation is checked implicitly: if a type contains all the methods declared in the interface, it automatically implements that interface.
To determine if a struct implements a given interface, you can:
- Attempt to assign an instance of the struct to a variable of the interface type — if compilation succeeds, the struct implements the interface.
- Use a static check with _var _:
var _ MyInterface = (*MyStruct)(nil)
If this code compiles without errors, it means MyStruct implements the MyInterface interface.
Example:
type MyInterface interface {
DoSomething()
}
type MyStruct struct {}
func (m *MyStruct) DoSomething() {
// implementation
}
// Check interface implementation
var _ MyInterface = (*MyStruct)(nil)
Thus, in Go, there is no need to explicitly specify interface implementation — just implement all its methods.