Question

Is it possible to use an operator in place of a function in go?

For example, in the following code is it possible to replace add with +?

package main

import "fmt"

var cur, prev int = 1, 1

func fib(f func(int, int) int) int {
    return f(cur, prev)
}

func main() {
    add := func(x int, y int) int { return x + y };
    fmt.Println(fib(add))
}

If it's not possible to use operators as functions, then I would appreciate a link to the documentation clarifying this.

Was it helpful?

Solution

Operators are not first-class values in Go (nor most other languages), so no, you cannot pass them as arguments. Notice that even the Go documentation uses a func(x,y int) int { return x+y } in its examples.

Also note that the grammar for operators does not allow any options for an operator without a corresponding expression to operate on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top