LoginSignup
3
3

More than 5 years have passed since last update.

Go : defer の実行サンプル

Posted at

Q)defer is 何?
A)returnする直前に特定の処理を実行することができるもの
ちょっと違うけどfinallyに似たものっぽい

hoge.go
package main

import "fmt"

func hoge(i int) string {
    defer fuga()
    if i%2 == 0 {
        return "偶数"
    }
    return "奇数"
}

func fuga() {
    fmt.Println("--- hoge end ---")
    return
}

func main() {
    for i := 1; i <= 5; i++ {
        fmt.Printf("%d is %s\n", i, hoge(i))
    }
}

実行結果

--- hoge end ---
1 is 奇数
--- hoge end ---
2 is 偶数
--- hoge end ---
3 is 奇数
--- hoge end ---
4 is 偶数
--- hoge end ---
5 is 奇数

エラー処理や並列処理、early return関数に有効そう
ただし、finallyとは処理順序が違うので注意

3
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3