Junior — Middle
Jaka jest różnica między strukturą bez metod a interfejsem w języku programowania?
sobes.tech AI
Odpowiedź od AI
W Go struktura (struct) to konkretny typ danych, który zawiera zestaw pól (zmiennych). Opisuje, jak dane są zorganizowane, ale sama nie zawiera zachowania.
Interfejs (interface) w Go opisuje zestaw metod, które musi zaimplementować typ, aby spełniać ten interfejs. Interfejs nie zawiera danych, a jedynie sygnatury metod.
Główne różnice:
- Struktura — to konkretna implementacja z polami.
- Interfejs — abstrakcja opisująca zachowanie przez metody.
- Struktura może implementować jeden lub więcej interfejsów, jeśli posiada odpowiednie metody.
Przykład:
// Struktura bez metod
type User struct {
Name string
Age int
}
// Interfejs z metodą
type Greeter interface {
Greet() string
}
// Implementacja interfejsu
func (u User) Greet() string {
return "Hello, " + u.Name
}
Tutaj User to struktura z polami, a Greeter to interfejs opisujący zachowanie. Bez metody Greet, struktura User nie implementuje interfejsu Greeter.