Last active
August 29, 2015 14:05
-
-
Save localhots/cb7f9b4379765a68ac12 to your computer and use it in GitHub Desktop.
Examples of inheritance (embedded types) and interfaces in Go language
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 | |
| age int | |
| } | |
| employee struct { | |
| person | |
| position string | |
| } | |
| ) | |
| func main() { | |
| // Alternative initialization techniques | |
| // | |
| // b := employee{ | |
| // person: person{ | |
| // name: "John", | |
| // age: 25, | |
| // }, | |
| // pos: "Manager", | |
| // } | |
| // | |
| // b := employee{person{"John", 25}, "Manager"} | |
| b := employee{} | |
| b.name = "John" | |
| b.age = 25 | |
| b.position = "Manager" | |
| fmt.Println(b) | |
| // Outputs: {{John 25} Manager} | |
| } |
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 ( | |
| greeter interface { | |
| hello() string | |
| } | |
| cat struct{} | |
| dog struct{} | |
| cow struct{} | |
| ) | |
| func (c cat) hello() string { | |
| return "meow!" | |
| } | |
| func (d dog) hello() string { | |
| return "bark!" | |
| } | |
| func (c cow) hello() string { | |
| return "mooo!" | |
| } | |
| func greet(g greeter) { | |
| hi := g.hello() | |
| fmt.Println(hi) | |
| } | |
| func main() { | |
| greet(cat{}) | |
| // Outputs: meow! | |
| greet(dog{}) | |
| // Outputs: bark! | |
| greet(cow{}) | |
| // Outputs: mooo! | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment