Functions as values

As with almost everything inGo, functions are also just values. They can be assigned to variables asfollows:

  1. import "fmt"
  2. func main() {
  3. a := func() { 1
  4. fmt.Println("Hello")
  5. } 2
  6. a() 3
  7. }

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:

  1. var xs = map[int]func() int{
  2. 1: func() int { return 10 },
  3. 2: func() int { return 20 },
  4. 3: func() int { return 30 },
  5. }

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 .