Junior — Middle
How is the object-oriented structure implemented in the Go language and how does it differ from the classical one?
sobes.tech AI
Answer from AI
In Go, object-oriented structures are implemented through composition and interfaces, rather than classes and inheritance as in traditional OOP.
Main differences:
- Lack of classes: Go does not have classes; instead, it uses structures (
struct) that contain fields and methods. - Composition instead of inheritance: Instead of inheriting from structures, you can include one structure within another, allowing code reuse.
- Interfaces: Interfaces in Go define a set of methods that a structure must implement. Types automatically implement an 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 OOP model based on interfaces and composition, without the complexities of classical inheritance.