Junior — Middle
Czy struktura w Go może zaimplementować interfejs i jak to zrobić?
sobes.tech AI
Odpowiedź od AI
Tak, w Go struktura może implementować interfejs. Aby to zrobić, struktura musi mieć wszystkie metody zadeklarowane w interfejsie. W Go implementacja interfejsu nie wymaga jawnej deklaracji — jeśli struktura zawiera potrzebne metody, jest automatycznie uważana za implementującą interfejs.
Przykład:
package main
import "fmt"
type Speaker interface {
Speak() string
}
type Person struct {
Name string
}
func (p Person) Speak() string {
return "Cześć, nazywam się " + p.Name
}
func main() {
var s Speaker = Person{Name: "Ivan"}
fmt.Println(s.Speak())
}
W tym przykładzie Person implementuje interfejs Speaker, ponieważ posiada metodę Speak() z wymaganą sygnaturą.