2019年8月11日日曜日

開発環境

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)
 }
}

func TestLoadCargo(t *testing.T) {
 want := "Loading test cargo"
 wantOk := true
 truckPointer, ok := vehicle.(*Truck)
 if ok != wantOk {
  t.Errorf("got %v, want %v", ok, wantOk)
 }
 got := truckPointer.LoadCargo("test cargo")
 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 {
 return fmt.Sprintf("Loading %s", cargo)
}

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

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

func main() {}

入出力結果(Bash、cmd.exe(コマンドプロンプト)、Terminal)

$ go test
PASS
ok   _/.../go/Head_First_Go/ch11/sample2 0.004s
$ 

0 コメント:

コメントを投稿