Go - back on your feet - Recovering from Failure - deffered function calls
Head First Go、 Jay McGavren(著)、O’Reilly Media)の Chapter 12(back on your feet - Recovering from Failure)、p.356(Code Magnets)の解答を求めてみる。
コード
main.go
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", "Salasa"}
for _, food := range []string{"Milk", "Bananas"} {
err := fridge.FindFood(food)
if err != nil {
log.Fatal(err)
}
}
}
入出力結果(Terminal, Zsh)
% go run main.go
Opening refrigerator
Found Milk
Closing refrigerator
Opening refrigerator
Closing refrigerator
2025/01/18 16:45:22 Bananas not found
exit status 1
%