Junior — Middle
How can a function be passed as an argument to be called inside another function?
sobes.tech AI
Answer from AI
In Go, functions are first-class citizens, so they can be passed as arguments to other functions.
Example of passing a function to another function:
package main
import "fmt"
// Function that takes another function as an argument
func applyOperation(a, b int, op func(int, int) int) int {
return op(a, b)
}
func main() {
sum := func(x, y int) int {
return x + y
}
result := applyOperation(3, 4, sum)
fmt.Println(result) // Outputs 7
}
Here, applyOperation takes two numbers and a function op that defines the operation on these numbers. In main, we pass an anonymous addition function.
Thus, to pass a function in Go, it is enough to specify the argument type as func(...) ... and pass the desired function when calling.