Skip to content

Instantly share code, notes, and snippets.

@edmore
Last active December 19, 2015 21:58
Show Gist options
  • Save edmore/6023495 to your computer and use it in GitHub Desktop.
Save edmore/6023495 to your computer and use it in GitHub Desktop.
Using Go interfaces for Duck typing like features
// 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