Skip to content

Instantly share code, notes, and snippets.

@Elshaman
Created January 5, 2023 20:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Elshaman/7b4057dfbe1822b24c958f23efdb31cc to your computer and use it in GitHub Desktop.
Save Elshaman/7b4057dfbe1822b24c958f23efdb31cc to your computer and use it in GitHub Desktop.
Object composition over inheritance in Golang: example
go build -o structura_inherit main. Go
./structura_inherit
// types/structs/embed/begin/main.go
package main
import "fmt"
type person struct {
first string
last string
}
// fullName returns the full name of a person
func (p person) fullName() string {
return p.first + " " + p.last
}
func(p *person) changeName(first, last string){
p.first = first
p.last = last
}
// define author and embed person
//
type author struct{
person
penName string
}
// override fullName method for author
//
func(a author) fullname() string{
return fmt.Sprintf("%s (%s)" , a.person.fullName(), a.penName)
}
func main() {
// initialize and print a person's full name
p := person{
first: "Toni",
last: "Morrison",
}
fmt.Println(p.fullName())
p.changeName("Tamara" , "Chaverra")
// initialize and print an author's full name
fmt.Println(p.fullName())
fmt.Println("----------------------------")
//initialize author
a:=author{
person:person{
first:"James",
last: "Bond",
},
penName:"MoneyPenny",
}
fmt.Println(a.fullName())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment