2
2

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 by Example: Closures

2
Posted at

(この記事は Go by Example: Closure を翻訳したものです。)

Goはclosureの形にできるanonymous functions anonymous functionは名前を与えず関数を定義するときに便利です。

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

今回見る最後の関数の特徴は再帰です。

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?