Junior — Middle
Kuidas on Go keeles objektorienteeritud struktuur rakendatud ja kuidas see erineb klassikalisest?
sobes.tech AI
Vastus AI-lt
In Go, object-oriented programming is implemented through composition and interfaces, rather than classes and inheritance, as in classical OOP.
Main differences:
- Absence of classes: In Go, there are no classes; instead, structures (
struct) are used that contain fields and methods. - Composition instead of inheritance: Instead of inheriting structures, you can include one structure within another, which allows for code reuse.
- Interfaces: Interfaces in Go define a set of methods that a structure must implement. Types automatically implement the interface if they have the required methods, without explicit declaration.
Example:
package main
import "fmt"
type Animal interface {
Speak() string
}
type Dog struct {}
func (d Dog) Speak() string {
return "Woof!"
}
type Cat struct {}
func (c Cat) Speak() string {
return "Meow!"
}
func main() {
animals := []Animal{Dog{}, Cat{}}
for _, a := range animals {
fmt.Println(a.Speak())
}
}
Thus, Go offers a simpler and more flexible object-oriented model based on interfaces and composition, without the complexities of classical inheritance.