Closures are also often a good way to nest and defer work. In the following example, we can see a function closure that allows us to nest work:
package main
import (
"fmt"
"sort"
)
func main() {
input := []string{"foo", "bar", "baz"}
var result []string
// closure callback
func() {
result = append(input, "abc") // Append to the array
result = append(result, "def") // Append to the array again
sort.Sort(sort.StringSlice(result)) // Sort the larger array
}()
fmt.Print(result)
}
In this example, we can see that we append to the string slice twice and sort the result. We will later see how we can nest an anonymous function in a goroutine to help improve performance.