背景
goのtutorialをやっていて、closureの箇所をやっていたのだけれど、定義がわかんなくなったので、調べていた。
定義
英語版のwikipediaに書いてある定義が一番しっくりきた。
In computer science, a closure is a function that has an environment of its own. In this environment, there is at least one bound variable (a name that has a value, such as a number). The closure's environment keeps the bound variables in memory between uses of the closure.
ざっくり和訳するとこんな感じ。
コンピュータサイエンスにおいて、closureとはそれ自身の環境を持つ関数である。その環境では少なくとも一つの変数がある。そのclosureの環境はそのclosureを使用する限りにおいて、その変数を保持する。
勘違いしやすいやつ
よく出される例だと勘違いしやすいので、定義に則って考えると、こうなる
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
// このfibonacciは関数を返す関数なので、closureではない。言わばclosureを返す関数。
func fibonacci() func() int {
before_two := make([]int, 2)
before_two[0] = 0
before_two[1] = 1
return func() int{
this_fibo_num := before_two[0] + before_two[1]
before_two[0] = before_two[1]
before_two[1] = this_fibo_num
return this_fibo_num
}
}
func main() {
f := fibonacci() // このfはclosure
b := fibonacci() // このbもclosure
for i := 0; i < 10; i++ {
fmt.Println(f())
}
for i := 0; i < 10; i++ {
fmt.Println(b())
}
}
雑感
今までの、イメージ的では関数を返す関数みたいなのが、closureって思っていたけど、違うってことが分かってよかった。