Go language functions as arguments

Go functions

In Go, functions are first-class citizens; they can be assigned, passed, and used just like ordinary variables. Passing a function as an argument to another function is a common programming pattern in Go, often used in scenarios such as callbacks and strategy patterns.


Function assigned to a variable

A function can be assigned to a variable, and the function can be called through that variable:

Example

package main

import (
    "fmt"
    "math"
)

func main() {
    /* Assign the anonymous function to variable getSquareRoot */
    getSquareRoot := func(x float64) float64 {
        return math.Sqrt(x)
    }

    /* Call the function through the variable */
    fmt.Println(getSquareRoot(9))   // Output: 3
    fmt.Println(getSquareRoot(16))  // Output: 4
}

The execution result of the above code is:

3
4

Passing functions as arguments

When passing a function as an argument to another function, the receiver needs to declare a corresponding function type parameter. The following example defines aapplyfunction that takes an operation function and two operands, performing any specified operation on the two numbers:

Example

package main

import (
    "fmt"
    "math"
)

/* Define a function that takes a parameter op of function type */
/* op's type is func(float64, float64) float64, meaning it accepts two float64 parameters and returns a float64 */
func apply(op func(float64, float64) float64, a, b float64) float64 {
    return op(a, b)
}

func main() {
    /* Define the addition function */
    add := func(a, b float64) float64 {
        return a + b
    }

    /* Define the multiplication function */
    multiply := func(a, b float64) float64 {
        return a * b
    }

    /* Pass the add function as an actual argument to apply */
    fmt.Println(apply(add, 3, 4))       // Output: 7

    /* Pass the multiply function as an actual argument to apply */
    fmt.Println(apply(multiply, 3, 4))  // Output: 12

    /* You can also pass an anonymous function directly */
    fmt.Println(apply(func(a, b float64) float64 {
        return math.Pow(a, b) // a raised to the power of b
    }, 2, 10))                          // Output: 1024
}

The execution result of the above code is:

7
12
1024

Practical application: custom sorting rules

One of the most common applications of functions as arguments is custom sorting rules. The Go standard library'ssort.SliceIt takes a comparison function as a parameter:

Example

package main

import (
    "fmt"
    "sort"
)

func main() {
    nums := []int{5, 2, 8, 1, 9, 3}

    /* Pass the comparison function as an actual argument to sort.Slice to sort from smallest to largest */
    sort.Slice(nums, func(i, j int) bool {
        return nums[i] < nums[j]
    })
    fmt.Println("Ascending:", nums)  // Output: Ascending: [1 2 3 5 8 9]

    /* Pass a different comparison function to sort from largest to smallest */
    sort.Slice(nums, func(i, j int) bool {
        return nums[i] > nums[j]
    })
    fmt.Println(Descending:, nums)  // Output: descending: [9 8 5 3 2 1]
}

The execution result of the above code is:

升序:[1 2 3 5 8 9]
降序:[9 8 5 3 2 1]

By passing different functions as arguments, the samesort.Slicecan achieve completely different sorting logic. This is precisely the core value of functions as arguments—parameterizing behavior, making code more flexible and reusable.。

Go functions

other extensions