Can you pass functions as parameters in Go?
Hi everyone! I just started learning Go, and I have a question. I'm used to languages where functions can be passed as arguments to other functions (for example, in JavaScript or Python). But in Go, I'm not sure if this is possible.
I tried to write a simple calculator that would take an operation (addition, subtraction) as a parameter, but I couldn't get it to work. Here's what I tried:
```go
package main
import "fmt"
func add(a, b int) int {
return a + b
}
func subtract(a, b int) int {
return a - b
}
func calculate(a, b int, op func(int, int) int) int {
return op(a, b)
}
func main() {
result := calculate(10, 5, add)
fmt.Println(result)
}
```
The code compiles and works, but I'm not sure if this is the correct syntax. Why do you need to write `func(int
No answers yet.
Log in to leave an answer