go - 如何在 Go 中使用中缀(比较)运算符作为参数

标签 go parameters parameter-passing infix-operator

在 GoLang 中,可以使用函数作为参数,例如在这个简单的例子中,根据小于等于 (<=) 或大于等于运算符 (>=) 比较两个数字。 )

package main

func leq(x, y int) bool {
    return x <= y
}

func geq(x, y int) bool {
    return x >= y
}

func compare(x, y int, comparator func(int, int) bool) bool {
    return comparator(x, y)
}

func main() {
    println(compare(3, 5, leq)) //true
    println(compare(5, 3, leq)) //false
    println(compare(3, 5, geq)) //false
    println(compare(5, 3, geq)) //true
}

有没有办法将中缀运算符而不是函数作为函数参数?

如:

func compare(x, y int, comparator <something here>) bool {
    return comparator(x, y)
}

func main() {
    println(compare(3, 5, <=)) //true
    println(compare(5, 3, <=)) //false
    println(compare(3, 5, >=)) //false
    println(compare(5, 3, >=)) //true
}

或者我最好的选择是像第一个示例那样为运算符编写包装器吗?

此外,如果上述情况可行,是否可以使用带有中缀语法的中缀运算符参数?比如

func compare(x, y int, c <something here>) bool {
    return x c y
}

最佳答案

不,根据 Go language specification 这不是一个正确的程序.


函数类型defined除了其他术语外,还包含一个参数列表,每个参数都包含一个参数声明:[ IdentifierList ] [ "..."] Type

这要求函数的所有参数都具有类型,指定为生产 Type,因此:

TypeLit = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
          SliceType | MapType | ChannelType

内置操作数(例如相等和比较运算符)是语言内部的,不会在此处公开为可能的类型文字。

此外,specification for function calls要求调用中的参数是单值表达式。二元运算符是 not themselves expressions .

因此,您不能将“中缀”运算符作为参数传递给函数调用。您应该定义自己的接口(interface)或函数类型来包装运算符,并将其传递给您的比较函数。

关于go - 如何在 Go 中使用中缀(比较)运算符作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52121569/

相关文章:

java - 使用参数调用 RESTful webservice

go - 为什么超时直接关闭连接而不调用closeHandler方法?

java - 使用 Java 从网页中抓取信息?

utf-8 - 如何解压缩 gzip 格式的 []byte 内容,解码时出错

java - 防止 JSF 中的 XSS 反射 <f :param>

function - scala - 传递一个以另一个函数作为参数的函数

python - 关键字参数中的引用参数

sql - 在单个参数中传递多个值

go - 如何将带参数的函数句柄传递给 Go 中的另一个函数?

go - runtime.LockOSThread 是否允许子 goroutine 在同一个操作系统线程中运行?