Skip to content

Instantly share code, notes, and snippets.

@blainsmith
Last active December 12, 2016 15:28
Show Gist options
  • Save blainsmith/f93772ac42a7867674012c167cd19483 to your computer and use it in GitHub Desktop.
Save blainsmith/f93772ac42a7867674012c167cd19483 to your computer and use it in GitHub Desktop.
Interface Exmaple
package main
type Dog interface {
Bark() string
Eat(string)
}
type Bulldog struct {
Name string
}
func (b *Bulldog) Bark() string {
return "Woof"
}
func (b *Bulldog) Eat(food string) {
// Do something with food
}
type Lab struct {
FirstName string
LastName string
}
func (l *Lab) Bark() string {
return "Ruff"
}
func (l *Lab) Eat(food string) {
// Do something with food
}
type Lion struct {
Name string
}
func (l *Lion) Meow() string {
return "Roar"
}
package main
func main() {
dogs := make([]Dog)
james := &Bulldog{Name: "James"}
ollie := &Bulldog{Name: "Ollie"}
abbey := &Lab{FirstName: "Abbey", LastName: "Smith"}
stewie := &Lab{FirstName: "Stewie", LastName: "Smith"}
simba := &Lion{Name: "Simba"}
// Can do this since they all "implement" Dog meaning they have function that match Dog function sigs
dogs := append(dogs, james)
dogs := append(dogs, ollie)
dogs := append(dogs, abbey)
dogs := append(dogs, stewie)
// Can't do this!!!
dogs := append(dogs, simba)
// Since they implement Dog you can now call Bark() regardless of their actually struct type
dogs[0].Bark()
dogs[1].Bark()
dogs[2].Bark()
dogs[3].Bark()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment