Skip to content

Instantly share code, notes, and snippets.

@giwa
Created February 6, 2015 10:04
Show Gist options
  • Save giwa/9dce3e382b5205ccc0b8 to your computer and use it in GitHub Desktop.
Save giwa/9dce3e382b5205ccc0b8 to your computer and use it in GitHub Desktop.
package main
import "fmt"
// このintSeqの関数はintSeqのbodyで定義されたanonymous functionを返します。帰ってくる関数はclosureを作るために変数iを含んでいます。
func intSeq() func() int {
i := 0
return func() int {
i += 1
return i
}
}
func main() {
// intSeqを呼んで、結果(関数)をnextIntを代入します。この関数はnextIntを呼ぶたびに更新される変数iを含んでいます。
nextInt := intSeq()
// nextIntを何回か呼ぶことでclosureの影響を見てみましょう。
fmt.Println(nextInt())
fmt.Println(nextInt())
fmt.Println(nextInt())
// その状態は特定の関数で一意であることを確認するために新しい物を作ってテストしてみましょう。
newInts := intSeq()
fmt.Println(newInts())
}
$ go run closures.go
1
2
3
1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment