Created
February 6, 2015 10:04
-
-
Save giwa/9dce3e382b5205ccc0b8 to your computer and use it in GitHub Desktop.
Go by Example: Closures ref: http://qiita.com/giwa@github/items/39ce036a8ae46369e653
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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