英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论