## 2019年8月11日日曜日

### Go - what can you do? - Interfaces - Type Assertions

Head First Go (Jay McGavren(著)、O'Reilly Media)のChapter 11(what can you do? - Interfaces)、Pool Puzzle(339)の解答を求めてみる。

コード

sample2_test.go

```package main

import "testing"

func TestAccelerate(t *testing.T) {
want := "Speeding up"
got := vehicle.Accelerate()
if got != want {
t.Errorf("got %v, want %v", got, want)
}
}

func TestSteerLeft(t *testing.T) {
want := "Turning left"
got := vehicle.Steer("left")
if got != want {
t.Errorf("got %v, want %v", got, want)
}
}

func TestSteerRight(t *testing.T) {
want := "Turning right"
got := vehicle.Steer("right")
if got != want {
t.Errorf("got %v, want %v", got, want)
}
}

func TestBrake(t *testing.T) {
want := "Stopping"
got := vehicle.Brake()
if got != want {
t.Errorf("got %v, want %v", got, want)
}
}

wantOk := true
truckPointer, ok := vehicle.(*Truck)
if ok != wantOk {
t.Errorf("got %v, want %v", ok, wantOk)
}
if got != want {
t.Errorf("got %v, want %v", got, want)
}
}
```

sample2.go

```package main

import "fmt"

type Truck string

func (t *Truck) Accelerate() string {
return "Speeding up"
}
func (t *Truck) Brake() string {
return "Stopping"
}
func (t *Truck) Steer(direction string) string {
return fmt.Sprintf("Turning %s", direction)
}
func (t *Truck) LoadCargo(cargo string) string {
}

type Vehicle interface {
Accelerate() string
Steer(string) string
Brake() string
}

var truck Truck = Truck("Fnord F180")
var vehicle Vehicle = &truck

func main() {}
```

```\$ go test
PASS