Last active
December 19, 2015 21:58
-
-
Save edmore/6023495 to your computer and use it in GitHub Desktop.
Using Go interfaces for Duck typing like features
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
// Simple Duck Typing in Go | |
package main | |
import "fmt" | |
type Animal interface { | |
sound() string | |
getName() string | |
} | |
type Dog struct { | |
name string | |
} | |
func (d *Dog) sound() string { | |
return "Woof!" | |
} | |
func (d *Dog) getName() string { | |
return d.name | |
} | |
type Duck struct { | |
name string | |
} | |
func (d *Duck) sound() string { | |
return "Quack!" | |
} | |
func (d *Duck) getName() string { | |
return d.name | |
} | |
func makeSound(a Animal) string { | |
return a.getName() + " makes this sound : " + a.sound() | |
} | |
func main() { | |
var dog *Dog = new(Dog) | |
var duck *Duck = new(Duck) | |
dog.name = "Brewster" | |
duck.name = "Donald" | |
fmt.Println(makeSound(dog)) // Dog implements Animal interface | |
fmt.Println(makeSound(duck)) // Duck implements Animal interface | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment