2019年6月21日金曜日

開発環境

Head First Go (Jay McGavren(著)、O'Reilly Media)のChapter 12(back on your feet - Recovering from Failure)、Code Magnets(356)の解答を求めてみる。

コード

package main

import (
 "fmt"
 "log"
)

func find(item string, slice []string) bool {
 for _, sliceItem := range slice {
  if item == sliceItem {
   return true
  }
 }
 return false
}

type Refrigerator []string

func (r Refrigerator) Open() {
 fmt.Println("Opening refrigerator")
}
func (r Refrigerator) Close() {
 fmt.Println("Closing refrigerator")
}
func (r Refrigerator) FindFood(food string) error {
 r.Open()
 defer r.Close()
 if find(food, r) {
  fmt.Println("Found", food)
 } else {
  return fmt.Errorf("%s not found", food)
 }
 return nil
}

func main() {
 fridge := Refrigerator{"Milk", "Pizza", "Salsa"}
 for _, food := range []string{"Milk", "Bananas"} {
  err := fridge.FindFood(food)
  if err != nil {
   log.Fatal(err)
  }
 }
}

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

$ go run sample1.go
Opening refrigerator
Found Milk
Closing refrigerator
Opening refrigerator
Closing refrigerator
2019/06/21 14:43:15 Bananas not found
exit status 1
$ 

0 コメント:

コメントを投稿