48
43

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Go言語] deferに関する実験

Last updated at Posted at 2013-09-29

実験1:最後に書いたものが

最後に書いたものが最初に呼ばれるよ。

package main

import "fmt"

func f() {
	defer fmt.Println("1")
	defer fmt.Println("2")
	defer fmt.Println("3")
}

func main() {
	f()
}

実験2:引数の評価は

引数の評価は、deferで関数の呼び出しが予約される時に行なわれるよ。

package main

import "fmt"

func f() {
	i := 0
	defer fmt.Printf("i is %d", i)
	i = 100
}

func main() {
	f()
}

package main

import "fmt"

func f() (ret int) {
	defer func(n int) {
		fmt.Println(n)
		fmt.Println(ret)
	}(ret) // retはゼロ値で初期化されている

	return 100
}

func main() {
	fmt.Println(f())
}

実験3:メソッドオブジェクトでも

メソッドオブジェクトでもdefer呼び出しはいける

package main

import "fmt"

type Hoge struct {
	N int
}

func (h *Hoge) PrintN() {
	fmt.Println(h.N)
}

func f() {
	h := &Hoge{100}
	m := h.PrintN
	defer m()
	h.N = 200
}

func main() {
	f()
}
48
43
0

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
48
43

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?