計算機科学のブログ

Go - back on your feet - Recovering from Failure - panic, defer

Head First GoJay McGavren(著)、O’Reilly Media)の Chapter 12(back on your feet - Recovering from Failure)、p.369(Exercise)の解答を求めてみる。

コード

main.go

package main

import "fmt"

func snack() {
	defer fmt.Println("Closing refrigerator")
	fmt.Println("Opening refrigerator")
	panic("refrigerator is empty")
}

// Opening refrigerator
// Closing refrigerator
// panic: refrigerator is empty

// main.snack()
func main() {
	snack()
}

入出力結果(Terminal, Zsh)

% go run ./main.go
Opening refrigerator
Closing refrigerator
panic: refrigerator is empty

goroutine 1 [running]:
main.snack()
...
%