Senior
Go does not have inheritance like Java. How would you explain to a junior with a Java background code reuse in Go and why it might be better?
sobes.tech AI
Answer from AI
In Go, there is no classical inheritance like in Java, where one class extends another. Instead, Go uses composition and interfaces for code reuse.
Composition is when one struct contains another as a field, thereby "embedding" its functionality. This allows building complex types from simple ones, avoiding rigid hierarchies.
Interfaces in Go describe behavior (a set of methods), not structure. Any type that implements the methods of an interface automatically satisfies that interface, without explicit declaration.
Why is this better:
- Flexibility: you can combine different behaviors without complex hierarchies.
- Simplicity: fewer relationships between types, easier to understand and test.
- No issues with multiple inheritance: Java prohibits it, but in Go, composition naturally solves this problem.
Example of composition:
package main
import "fmt"
type Logger struct {}
func (l Logger) Log(msg string) {
fmt.Println("Log:", msg)
}
type Service struct {
Logger // embedding Logger
}
func (s Service) DoWork() {
s.Log("Starting work")
// ...
s.Log("Work completed")
}
func main() {
svc := Service{}
svc.DoWork()
}
Here, Service does not inherit from Logger, but simply includes it, gaining access to the Log method. This approach is simpler and more explicit than inheritance.