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.
Top comments (0)