tags:

views:

66

answers:

1

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.

+5  A: 

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.

Amber