0
0

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.

クロージャ

Posted at

クロージャが分からなかったのでメモ

package main

import "fmt"

func adder() func(int) int {
	sum := 0
	fmt.Println("sum: ", sum) // 最初に表示される
	return func(x int) int {
		fmt.Println("sumを加算します:", sum) // 3番目に呼び出される
		sum += x
		fmt.Println("sumが加算されました:", sum) // 4番目に呼び出される
		return sum
	}
}

func main() {
	pos := adder()
	fmt.Println("posが設定されました。") // 2番目に表示される
	for i := 0; i < 3; i++ {
		fmt.Println(
			"posを呼び出します", // 5番目に呼び出される
			pos(i),
		)
	}
}
実行結果
sum:  0
posが設定されました。
sumを加算します: 0
sumが加算されました: 0
posを呼び出します 0
sumを加算します: 0
sumが加算されました: 1
posを呼び出します 1
sumを加算します: 1
sumが加算されました: 3
posを呼び出します 3

以下、実行順序(予想)
1.関数を変数にセットする
2.adder()のreturn文以外が実行される?
3.main()に戻る
4.関数がセットされた変数を実行すると、return文が実行される?

実務で利用する場面が想像できない。

クロージャのサンプルにあるフィボナッチ関数

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
	num1 := 0
	num2 := 1
	return func() int{
		answer := num1
		num1, num2 = num2, num1+num2
		return answer
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?