开发者

Using an operator in place of a function

Is it possible to us开发者_C百科e 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜