首页 > 解决方案 > 如何在 Go 中使用中缀(比较)运算符作为参数

问题描述

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

标签: goparametersparameter-passinginfix-operator

解决方案


不,根据Go 语言规范,这不是一个正确的程序。


函数类型定义为包含一个参数列表,每个参数都包含一个参数声明:[ IdentifierList ] [ "..." ] Type.

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

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

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

此外,函数调用规范要求调用中的参数是单值表达式。二元运算符本身不是表达式

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


推荐阅读