Created
January 5, 2023 20:27
-
-
Save Elshaman/7b4057dfbe1822b24c958f23efdb31cc to your computer and use it in GitHub Desktop.
Object composition over inheritance in Golang: example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
go build -o structura_inherit main. Go | |
./structura_inherit |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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