Skip to content

Instantly share code, notes, and snippets.

@localhots
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save localhots/cb7f9b4379765a68ac12 to your computer and use it in GitHub Desktop.

Select an option

Save localhots/cb7f9b4379765a68ac12 to your computer and use it in GitHub Desktop.
Examples of inheritance (embedded types) and interfaces in Go language
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}
}
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