🔧 Inheritance in Go
Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to
Go is not an object oriented language. However, you could still get the benefit of OOP by using different approach provided by Go language. This article talks about how you can "inherit" behavior from one type to another in Go.
Embedding
In Go, to automatically implement the methods and properties of one type to another is called "embedding". Look at the following code:
type Greeter struct {
Style string
}
func (g *Greeter) Greet(name string) string {
return fmt.Sprintf("%s, %s", g.Style, name)
}
type CustomerService struct {
Greeter // embed Greeter in CustomerService
}
On the code above, type CustomerService
"embed" type Greeter into it. By doing that, instance of CustomerService
automatically has method Greet
defined on Greeter
.
c := CustomerService{}
c.Style = "Halo"
greeting := c.Greet("John") // "Halo, John"
Embedding multiple types
In OOP, you are allowed to inherit a class from only one parent. In go, you can embed multiple types.
type Greeter struct {
Style string
}
func (g *Greeter) Greet(name string) string {
return fmt.Sprintf("%s, %s", g.Style, name)
}
type Helper struct {}
func (h *Helper) Help() string {
return "I'm here to help"
}
type CustomerService struct {
Greeter
Helper
}
However, you have to make sure there is no overlapping methods between the types that you embed. Otherwise, Go will gives you "ambigous selector" error and won't compile.
type Greeter struct {}
func (g *Greeter) Greet(name string) string {
return fmt.Sprintf("%s, %s", g.Style, name)
}
type Helper struct {}
// second Greet method is defined in Helper.
// type that embed both Greeter and Helper
// wouldn't be able to call `Greet`
func (h *Helper) Greet(name string) string {
return fmt.Sprintf("Hello, %s", name)
}
type CustomerService struct {
Greeter
Helper
}
func main() {
c := CustomerService{}
fmt.Println(c.Greet("John")) // ambiguous selector c.Greet
}
Conclusion
While go is not an OOP language, you still can get the benefit of inheritance using the "embedding" technique.
...
🎥 CSS highlight inheritance is changing
📈 17.76 Punkte
🎥 Video | Youtube
🔧 Composition vs Inheritance in React 🔻
📈 17.76 Punkte
🔧 Programmierung
🔧 Composition or Inheritance: What’s better?
📈 17.76 Punkte
🔧 Programmierung
🔧 C# Tip: Records with Inheritance
📈 17.76 Punkte
🔧 Programmierung
🔧 Inheritance and Composition in C#
📈 17.76 Punkte
🔧 Programmierung
🔧 PostgreSQL Role Inheritance at a Glance
📈 17.76 Punkte
🔧 Programmierung
🔧 Day 12: Inheritance
📈 17.76 Punkte
🔧 Programmierung
🔧 Inheritance changes for CSS selection styling
📈 17.76 Punkte
🔧 Programmierung