Skip to content

Instantly share code, notes, and snippets.

@loghound
Last active December 19, 2015 14:39
Show Gist options
  • Save loghound/5970802 to your computer and use it in GitHub Desktop.
Save loghound/5970802 to your computer and use it in GitHub Desktop.
Showing an alternate way to support OO in go (original reference http://www.goinggo.net/2013/07/object-oriented-programming-in-go.html)
package main
import (
"fmt"
)
type Animal struct {
Name string
mean bool
}
type AnimalSound interface {
MakeNoise()
}
type Dog struct {
Animal
BarkStrength int
}
type Cat struct {
Basics Animal
MeowStrength int
}
func main() {
myDog := &Dog{Animal{"rover", false}, 2}
// you can now reference myDog.Name and myDog.mean alongside myDog.BarkStrength
myCat := &Cat{
Basics: Animal{
Name: "Julius",
mean: true,
},
MeowStrength: 3,
}
MakeSomeNoise(myDog)
MakeSomeNoise(myCat)
}
func (animal *Animal) MakeNoise(strength int, sound string) {
if animal.mean == true {
strength = strength * 5
}
for voice := 0; voice < strength; voice++ {
fmt.Printf("%s ", sound)
}
fmt.Printf("\n")
}
func (dog *Dog) MakeNoise() {
dog.Animal.MakeNoise(dog.BarkStrength, "BARK")
}
func (cat *Cat) MakeNoise() {
cat.Basics.MakeNoise(cat.MeowStrength, "MEOW")
}
func MakeSomeNoise(animal AnimalSound) {
animal.MakeNoise()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment