関数による状態の捕捉
Coddyの「C++開発者のためのGo」コースのレッスン 22/48。
C++のラムダキャプチャリストでは、値キャプチャと参照キャプチャを選択できます。Goのクロージャは、キャプチャリストの構文を使わずに字句的な変数をキャプチャします。Goのコールバックを作成しても、変化する外側の変数が自動的にスナップショットされるわけではありません。スナップショットが必要な場合は、適切なスコープで別の値を作成します。
関数は値であり、周囲の変数を閉じ込めることができます。クロージャは、それを囲む関数が戻った後も変更可能な状態を保持できます。ファクトリー関数を個別に呼び出すと、それぞれに別個のローカル変数が作られます。関数を返しても、その関数が参照するすべてのものが自動的に複製されるわけではありません。
C++の例
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
int main() {
int factor = 2;
auto captured = [factor](int x) { return x * factor; };
auto referenced = [&factor](int x) { return x * factor; };
factor = 3;
std::cout << captured(4) << ' ' << referenced(4) << '\n';
}ソースの出力:
8 12Goの例
package main
import ("fmt")
func Sequence() func() int { n:=0; return func() int { n++; return n } }
func main(){next:=Sequence()
fmt.Println(next(),next())}Goの出力:
1 2チャレンジ
簡単MakeAdder(base int) func(int) intを実装してください。返された関数は、baseを変更せずに、引数にbaseを加算します。Solveはこれを3に適用します。
宣言されたAPIを実装し、結果を返してください。出力はしないでください。ドライバーは必要なAPIを確認し、呼び出し元の入力を保持します。コレクションの標準出力には、JSONではなくGoの角括弧形式が使われます。
コードはadder.goとexercise.goに記述してください。main.goには提供された入出力コードが含まれており、編集できません。フラットなpackage mainを1つだけ使い、2つ目のmainを追加しないでください。
自分で試してみよう
package main
import ("fmt";"strings";"strconv";"bufio";"os")
var input []string
func L(i int)string{if i<len(input){return input[i]};return ""}
func I(i int)int{n,e:=strconv.Atoi(L(i));if e!=nil{panic(e)};return n}
func Ints(i int)[]int{out:=[]int{};if L(i)==""{return out};for _,s:=range strings.Split(L(i),","){n,e:=strconv.Atoi(s);if e!=nil{panic(e)};out=append(out,n)};return out}
func Words(i int)[]string{if L(i)==""{return []string{}};return strings.Split(L(i),",")}
func must(ok bool,message string){if !ok{panic("API: "+message)}}
func main(){
scanner:=bufio.NewScanner(os.Stdin);for scanner.Scan(){input=append(input,scanner.Text())};if scanner.Err()!=nil{panic(scanner.Err())}
a0:=I(0); before0:=fmt.Sprint(a0)
f:=MakeAdder(5); g:=MakeAdder(-2); must(f(1)==6 && f(2)==7 && g(1)==-1,"closure API");
result:=Solve(a0)
must(fmt.Sprint(a0)==before0,"input mutation")
fmt.Println(result)
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
C++開発者のためのGoのすべてのレッスン
自分で練習してみよう: Goオンラインコンパイラ