2019年8月10日土曜日

開発環境

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

コード

sample1_test.go

package main

import "testing"

func TestVehicle(t *testing.T) {
 wants := []string{
  "Speeding up",
  "Turning left",
  "Stopping",
  "Turning right",
 }
 car := Car("Toyda Yarvic")
 var vehicle Vehicle = &car
 gots := []string{
  vehicle.Accelerate(),
  vehicle.Steer("left"),
 }
 truck := Truck("Fnord F180")
 vehicle = &truck
 gots = append(gots, vehicle.Brake(), vehicle.Steer("right"))

 for i, want := range wants {
  got := gots[i]
  if got != want {
   t.Errorf("got %v, want %v", got, want)
  }
 }
}

sample1.go

package main

import "fmt"

type Car string

func (c *Car) Accelerate() string {
 return "Speeding up"
}
func (c *Car) Brake() string {
 return "Stopping"
}
func (c *Car) Steer(direction string) string {
 return fmt.Sprintf("Turning %s", direction)
}

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
}

func main() {}

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

$ go test
# _/.../go/Head_First_Go/ch11/sample1 [_/.../go/Head_First_Go/ch11/sample1.test]
./sample1_test.go:12:9: undefined: Car
./sample1_test.go:13:14: undefined: Vehicle
./sample1_test.go:18:11: undefined: Truck
FAIL _/.../go/Head_First_Go/ch11/sample1 [build failed]
$ go test
PASS
ok   _/.../go/Head_First_Go/ch11/sample1 0.004s
$ 

0 コメント:

コメントを投稿