Go allows creation of anonymous functions which may be
assigned to variables or passed as parameters.
package main
import "fmt"
/*
* Making anonymous functions.
*/
/*
* Boring slice print function
*/
func pr(data [] int) {
for _,v := range(data) {
fmt.Print(v," ")
}
fmt.Println()
}
/*
* Operate on each member of the slice.
*/
func applyto(data []int, f func(v int) int) {
for i,_ := range(data) {
data[i] = f(data[i])
}
}
/*
* Use the function which applies another function.
*/
func main() {
// Create an array and let's see it.
data := []int { 4, 9, 18, 7, -3, 22 }
pr(data)
// Add three to all items.
applyto(data, func(v int) int { return v + 3 })
pr(data)
// Square them all.
applyto(data, func(v int) int { return v*v })
pr(data)
// Functions are closures.
sum := 0
summer := func(v int) int { sum += v; return v; }
applyto(data, summer)
fmt.Println(sum)
}