box-o-sand/c&s20150725/inheritance.go

56 lines
775 B
Go
Raw Normal View History

2015-07-25 18:11:53 +00:00
package main
import "fmt"
type Pet struct {
Name string
IsRunning bool
}
func NewPet(name string) *Pet {
return &Pet{Name: name}
}
func (p *Pet) Run() string {
p.IsRunning = true
return p.Name + " is running"
}
type Dog struct {
Pet
currentChaseTarget *Pet
}
func NewDog(name string) *Dog {
dog := &Dog{}
dog.Name = name
return dog
}
func (d *Dog) Chase(target *Pet) string {
d.IsRunning = true
d.currentChaseTarget = target
d.currentChaseTarget.Run()
return d.Name + " is chasing " + target.Name
}
func main() {
cat := NewPet("Felix")
fmt.Printf("%#v\n", cat)
cat.Run()
fmt.Printf("%#v\n", cat)
dog := NewDog("Fido")
fmt.Printf("%#v\n", dog)
fmt.Printf("%#v\n", dog.Chase(cat))
fmt.Printf("%#v\n", dog)
fmt.Printf("%#v\n", cat)
}