2
2

More than 1 year has passed since last update.

Goの「クロージャ」とは

Posted at

はじめに

Goを触り始めてクロージャというものに遭遇しました。

どういう機能なのか、理解した内容を書きます。

結論

関数内で状態を保持する機能

詳細

docsでは

Closure occurs when an anonymous function in Go has access to its surroundings. Then it can hold a unique state of its own. The state then becomes isolated as we create new instances of the function.
クロージャは、Goの無名関数がその周囲にアクセスできるようになったときに発生します。そうすると、それ自身のユニークな状態を保持できるようになります。そして、その状態は、関数の新しいインスタンスを作成するときに分離されます。
Closures in GoLang - GoLang Docsより

イメージとしては「クラスのインスタンスを作って、フィールドの値を保持する」に近そうです。

具体例

サンプルコード)

package main

import (
	"fmt"
)

func intSeq() func() int {
	i := 0
	return func() int {
		i++
		return i
	}
}

func main() {
	nextInt := intSeq()
	fmt.Println(nextInt())
	fmt.Println(nextInt())
	fmt.Println(nextInt())

	newInts := intSeq()
	fmt.Println(newInts())
}

Go Playground - The Go Programming Languageより
※コメントアウトは消しています

上記を実行すると、以下が出力されます

1
2
3
1

この場合状態が保持されるのはintSeq()内のiですね

nextInt内ではi++する無名関数が実行されて、intSeq()のiが1ずつ足されていきます。

intSeq()を別の変数(newInts)に代入すると、
そちらは別の状態が保持されるので、最後は1が出力されています。

終わりに

JSにもあるらしいですが、使ったこともみたこともないなあ。。
JSはクラスが導入されたからかな。

参考文献

Closures in GoLang - GoLang Docs

Go Playground - The Go Programming Language

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