How to Use Functions as First-Class Values in Go

Go treats functions as first-class values, allowing them to be assigned to variables, passed as arguments, and returned from other functions.

In Go, functions are first-class values, meaning you can assign them to variables, pass them as arguments, and return them from other functions. Define a function type or use a function literal to treat functions as data.

package main

import "fmt"

func add(a, b int) int {
	return a + b
}

func main() {
	// Assign function to variable
	var op func(int, int) int = add
	fmt.Println(op(2, 3)) // Output: 5

	// Pass function as argument
	calculate(5, 6, add)

	// Return function from function
	multiplier := makeMultiplier(3)
	fmt.Println(multiplier(10)) // Output: 30
}

func calculate(x, y int, fn func(int, int) int) {
	fmt.Println(fn(x, y))
}

func makeMultiplier(factor int) func(int) int {
	return func(n int) int {
		return n * factor
	}
}