Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
package main
import (
"fmt"
)
type Vehicle struct {
speed int
}
func(v *Vehicle) Speed() int {
return v.speed
}
type Drivable interface {
Accelerate(delta uint)
Brake(delta uint)
Speed() int
}
type Car struct {
Vehicle
}
func(c *Car) Accelerate(delta uint) {
c.Vehicle.speed += int(delta)
}
func(c *Car) Brake(delta uint) {
c.Vehicle.speed -= int(delta)
}
func NewCar() Drivable {
c := new(Car)
c.Vehicle.speed = 0
return c
}
type Boat struct {
Vehicle
}
func(b *Boat) Accelerate(delta uint) {
b.Vehicle.speed += int(delta)
}
func(b *Boat) Brake(delta uint) {
b.Vehicle.speed -= int(delta)
}
func NewBoat() Drivable {
b := new(Boat)
b.Vehicle.speed = 0
return b
}
type Amphibian struct {
Car
Boat
swimming bool
}
func NewAmphibian() *Amphibian {
a := new(Amphibian)
a.swimming = false
return a
}
func(a *Amphibian) Swimming() bool {
return a.swimming
}
func(a *Amphibian) Swim(swim bool) {
a.swimming = swim
}
func(a *Amphibian) Accelerate(delta uint) {
if (a.swimming) {
a.Boat.Accelerate(delta)
} else {
a.Car.Accelerate(delta)
}
}
func(a *Amphibian) Brake(delta uint) {
if (a.swimming) {
a.Boat.Brake(delta)
} else {
a.Car.Brake(delta)
}
}
func(a *Amphibian) Speed() int {
if (a.swimming) {
return a.Boat.Speed()
}
return a.Car.Speed()
}
func main() {
c := NewCar()
fmt.Printf("car speed: %d kph\n", c.Speed())
c.Accelerate(20)
fmt.Printf("car speed: %d kph\n", c.Speed())
c.Brake(10)
fmt.Printf("car speed: %d kph\n", c.Speed())
b := NewBoat()
fmt.Printf("boat speed: %d kph\n", b.Speed())
a := NewAmphibian()
a.Accelerate(10)
a.Swim(true)
a.Accelerate(20)
fmt.Printf("amphibian speed swimming: %d kph\n", a.Speed())
a.Swim(false)
fmt.Printf("amphibian speed on land: %d kph\n", a.Speed())
var d Drivable
d = a
fmt.Printf("amphibian speed on land (as drivable): %d kph\n", d.Speed())
a.Swim(true)
fmt.Printf("amphibian speed swimming (as drivable): %d kph\n", d.Speed())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.