Skip to content

Instantly share code, notes, and snippets.

@emmaly
Created September 26, 2016 05:58
Show Gist options
  • Save emmaly/88c56eca33f102b71b562b1b372f6e34 to your computer and use it in GitHub Desktop.
Save emmaly/88c56eca33f102b71b562b1b372f6e34 to your computer and use it in GitHub Desktop.
golang: Interfaces, type casting
package main
import "fmt"
func main() {
bob := NewHuman("Bob")
jim := NewHuman("Jim")
joe := NewHuman("Joe")
bob.Greet(jim)
jim.Greet(bob)
bob.Greet(joe)
joe.Greet(bob)
bingo := NewDog("Bingo")
frank := NewDog("Frank")
rover := NewDog("Rover")
bingo.Greet(frank)
frank.Greet(bingo)
bingo.Greet(rover)
rover.Greet(bingo)
bob.Greet(bingo)
bingo.Greet(bob)
jim.Greet(frank)
frank.Greet(jim)
joe.Greet(rover)
rover.Greet(joe)
}
// Being is a being
type Being interface {
Name() string
Greet(Being)
}
// HUMAN
// Human is a human being
type Human struct {
name string
}
// NewHuman returns a new Human
func NewHuman(name string) *Human {
return &Human{name: name}
}
// SetName sets the Human's name
func (h *Human) SetName(name string) {
h.name = name
}
// Name is the Human's name
func (h *Human) Name() string {
return h.name
}
// Greet is the greeting from Human to Being
func (h *Human) Greet(b Being) {
special := ""
switch b.(type) {
case *Human:
special = " (dude!)"
case *Dog:
special = " (arf, arf?)"
}
fmt.Printf("Hello %s, I am %s.%s\n", b.Name(), h.Name(), special)
}
// DOG
// Dog is a dog being
type Dog struct {
name string
}
// NewDog returns a new Dog
func NewDog(name string) *Dog {
return &Dog{name: name}
}
// SetName sets the Human's name
func (d *Dog) SetName(name string) {
d.name = name
}
// Name is the Dog's name
func (d *Dog) Name() string {
return d.name
}
// Greet is the greeting from Dog to Being
func (d *Dog) Greet(b Being) {
special := ""
switch b.(type) {
case *Human:
special = " (give me a treat)"
case *Dog:
special = " (greetings, fellow Dog)"
}
fmt.Printf("Woof %s, woof woof %s.%s\n", b.Name(), d.Name(), special)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment