【问题标题】:How to Use Infix (Comparison) operators as parameters in Go如何在 Go 中使用中缀(比较)运算符作为参数
【发布时间】:2018-08-31 19:20:56
【问题描述】:

在 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 parameters parameter-passing infix-operator


【解决方案1】:

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


函数类型defined,其中包含一个参数列表,每个参数都包含一个参数声明:[ IdentifierList ] [ "..." ] Type

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 2018-03-19
    • 1970-01-01
    • 2021-06-18
    • 2017-05-12
    • 1970-01-01
    相关资源
    最近更新 更多