使用运算符代替函数

huangapple go评论80阅读模式
英文:

Using an operator in place of a function

问题

在Go语言中,不可以直接使用运算符来替代函数。

例如,在下面的代码中,不可以用+来替代add

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))
}

如果无法使用运算符作为函数,我可以提供一份相关文档的链接以供参考。

英文:

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.

答案1

得分: 6

在Go语言(以及大多数其他语言)中,运算符不是一等值,因此不能将它们作为参数传递。请注意,即使是Go文档在其示例中也使用了func(x,y int) int { return x+y }

还要注意,运算符的语法不允许没有相应表达式的运算符选项。

英文:

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.

huangapple
  • 本文由 发表于 2009年12月5日 17:17:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/1851677.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定