dqzuo0327 2019-08-12 17:55
浏览 24

按名称致电接线员

What is the Go equivalent of, for example, Python's operator package for calling builtin operators by name?

Meaning, how can I do something like:

func f(op func(int, int)bool, a int, b int)
    ...
    if op(a, b) {
        ...

f(operators.LessThan, 1, 2) // true

Stated otherwise, how to write a function that takes in what basic operator to apply as a function argument?

  • 写回答

1条回答 默认 最新

  • dqysi86208 2019-08-13 12:25
    关注

    First, you shouldn't assume language X has any equivalent for feature Y in language Z. Also you should write/design code for the language you're using rather than designing as if it was another language and then translating line-by-line or function-by-function.

    As comments mentioned, operators are builtin in Go with no operator overloading or functional equivalents. If you haven't already you should take the Go Tour and read the Language Specification to see what Go does have.

    If you really want/need to do something like you ask this is one way:

    package main
    
    import "fmt"
    
    type Compare func(int, int) bool
    
    func DoCompare(cmp Compare, a, b int) bool {
        return cmp(a, b)
    }
    
    var (
        CmpLessThan           = func(a, b int) bool { return a < b }
        CmpLessThanOrEqual    = func(a, b int) bool { return a <= b }
        CmpGreaterThan        = func(a, b int) bool { return a > b }
        CmpGreaterThanOrEqual = func(a, b int) bool { return a >= b }
    )
    
    func main() {
        fmt.Println(DoCompare(CmpLessThan, 1, 2))
    }
    

    Go Playground.

    Normally if something like this is needed, instead of multiple comparison functions, a single compare function is used that returns <0, 0, or, >0 (e.g. -1, 0, +1) for less-than, equal, greater-than. For example, big.Int.Cmp.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起