Functions as values
As with almost everything inGo, functions are also just values. They can be assigned to variables asfollows:
import "fmt"
func main() {
a := func() { 1
fmt.Println("Hello")
} 2
a() 3
}
a
is defined as an anonymous (nameless) function 1.Note the lack of parentheses ()
after a
. If there were, that would be to call_some function with the name a
before we have defined what a
is. Once a
isdefined, then we can _call it, 3.
Functions–as–values may be used in other places, for example maps. Here weconvert from integers to functions:
var xs = map[int]func() int{
1: func() int { return 10 },
2: func() int { return 20 },
3: func() int { return 30 },
}
Note that the final comma on second to last line is mandatory.
Or you can write a function that takes a function as its parameter, for examplea Map
function that works on int
slices. This is left as an exercise for thereader; see the exercise .