Gaaker Go

Golang Anonymous functions

A function is a first-class value, it can be assigned to a variable, just like v := func1.

Functions that do not need to be named are called anonymous functions.

When we don’t want to name the function, we can use anonymous functions.

An anonymous function can be assigned to a variable or called directly.

As the example shows:

Declare an anonymous function to calculate the sum of integers from 1 to max.

The last () represents the call to the anonymous function, and 100 is the actual parameter of the anonymous function.

The following is a complete code example.

package main

import "fmt"

func main() {
    var max = func(a, b int) int {
        if a >= b {
            return a
        }
        return b
    }
    x := max(7, 15)
    fmt.Printf("The maximum is: %d", x)

    func(max int) {
        sum := 0
        for i := 1; i <= max; i++ {
            sum += i + add
        }
		fmt.Printf("The sum is: %d", sum)
	}(100)
}

Below is the program output:

The maximum is: 15
The sum is: 5050
< Anonymous functions Anonymous functions >