Created
January 18, 2018 11:21
-
-
Save MasterBroda/6aa7c31349ba0e3ca7cf0d532d35dedc to your computer and use it in GitHub Desktop.
CoolTautIrishredandwhitesetter created by MasterBroda - https://repl.it/@MasterBroda/CoolTautIrishredandwhitesetter
This file contains hidden or 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
| package main | |
| import "fmt" | |
| type Person struct { | |
| Name string | |
| } | |
| type Saiyan struct { | |
| *Person | |
| Power int | |
| } | |
| // Example of Composition | |
| func main() { | |
| // and to use it: | |
| goku := &Saiyan{ | |
| Person: &Person{"Goku"}, | |
| Power: 9001, | |
| } | |
| goku.Introduce() | |
| } | |
| func (p *Person) Introduce() { | |
| fmt.Printf("Hi, I'm %s\n", p.Name) | |
| } | |
| // because implicit composition is really just a compiler trick, we can “overwrite” the functions of a composed type. For example, our Saiyan structure can have its own Introduce function: | |
| func (s *Saiyan) Introduce() { | |
| fmt.Printf("Hi, I'm %s. Ya!\n", s.Name) | |
| } | |
| // The composed version is always available via s.Person.Introduce() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment