Closures and Function Values
Functions are values. A closure captures variables from its surroundings and keeps them alive between calls.
Example
package main
import "fmt"
func counter() func() int {
c := 0
return func() int {
c++
return c
}
}
func apply(xs []int, f func(int) int) []int {
out := make([]int, len(xs))
for i, x := range xs {
out[i] = f(x)
}
return out
}
func main() {
next := counter()
next()
fmt.Println(next())
fmt.Println(apply([]int{1, 2, 3}, func(x int) int { return x * x }))
}Result
2 [1 4 9]
Exercise
Declare a function literal.
f := (x int) int { return x }
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.