Junior — Middle
Kuidas näidata kompilaatorile, et konkreetne klass implementeerib teatud liidest?
sobes.tech AI
Vastus AI-lt
In Go, interface implementation occurs implicitly: if a type implements all the methods of an interface, it is automatically considered to implement that interface. There is no need to explicitly specify this.
Example:
package main
import "fmt"
type Speaker interface {
Speak() string
}
type Dog struct {}
func (d Dog) Speak() string {
return "Woof!"
}
func main() {
var s Speaker
d := Dog{}
s = d // Dog implements the Speaker interface
fmt.Println(s.Speak())
}
If you want to explicitly check whether a type implements an interface, you can use a compile-time check:
var _ Speaker = (*Dog)(nil) // The compiler will check if *Dog implements Speaker
Thus, in Go, interfaces are implemented automatically when the required methods are present.