Sobes.tech
Junior

What is the standard behavior in Go when passing functions?

sobes.tech AI

Answer from AI

In Go, functions are first-class objects. When passing a function to another function or assigning it to a variable, a pointer to that function is passed.

This means that:

  • A reference to the existing function is passed, not a copy.
  • Changes inside the passed function (for example, modifying closure values) will be reflected in the original function if it captures variables from the outer scope.
  • When comparing two variables of function type, their addresses are compared.

Example of passing a function:

// Function that takes another function as an argument
func executeOperation(operation func(int, int) int, a, b int) int {
	return operation(a, b)
}

// Simple addition function
func add(x, y int) int {
	return x + y
}

// Using executeOperation with add function
// result := executeOperation(add, 5, 3) // result will be 8

Example of using a closure:

// Function that returns another function (closure)
func counter() func() int {
	count := 0
	return func() int {
		count++
		return count // closure captures the count variable
	}
}

// Getting the closure
// nextCount := counter()

// Calls to the closure modify the same count variable
// fmt.Println(nextCount()) // outputs 1
// fmt.Println(nextCount()) // outputs 2