Junior — Middle
Kuidas saab määrata, kas konkreetne struktuur rakendab antud liidest?
sobes.tech AI
Vastus AI-lt
In Go, the implementation of an interface 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:
- Try assigning an instance of the struct to a variable of the interface type — if compilation succeeds, it means the struct implements the interface.
- Use a static check with _var _:
var _ MyInterface = (*MyStruct)(nil)
If this code compiles without errors, it means that 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, it is not necessary to explicitly specify the implementation of an interface — it suffices to implement all its methods.