Go の重要トピック
Go Closures and Function Values
Functions are values in Go: store them, pass them, return them, and let them remember variables.
学べること
- Functions as values
- Closures keep state
- Passing a function
next := counter()
1next()
2next()
3next()
A function that remembers
In Go a function is a value: you can store it in a variable, pass it to another function or return it. A closure is a function that keeps using variables from the place where it was created.
counter returns a function that remembers its own count between calls, and each call to counter creates a separate count. apply takes a function as a parameter. The function literal passed to apply reads bonus from main.
重要なポイント
- counter returns a function with its own count.
- Each call to counter starts a new count.
- A function literal can use variables around it.
実行できる Go のサンプル
Go
main.go
package main
import "fmt"
func counter() func() int {
count := 0
return func() int {
count++
return count
}
}
func apply(values []int, transform func(int) int) []int {
result := make([]int, len(values))
for i, value := range values {
result[i] = transform(value)
}
return result
}
func main() {
next := counter()
fmt.Println(next(), next(), next())
other := counter() // a separate count
fmt.Println(other())
bonus := 10
fmt.Println(apply([]int{1, 2, 3}, func(n int) int { return n*2 + bonus }))
}
1 2 3
1
[12 14 16]練習
サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。
このレッスンを終えましたか?
学習済みにすると進み具合を記録できます。
進み具合はこのブラウザーに保存されています ログインすると、どのデバイスでも引き継げます。
チャレンジで練習する
このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。
- 選んだキーで並べ替え 実行時に選んだ比較器で、名前または年齢順に人を並べ替え、同順位は一貫した方法で解消します。 簡単
- イベントの購読者 observer パターンのように各トピックの購読者へイベントを届け、各人が受け取った通知を数えます。 簡単