douzao2590 2015-06-10 19:10
浏览 348
已采纳

如何将字符串转换为运算符?

Is there a way to convert a string (e.g. "+", "-", "/", "*") into their respective math operators (+, -, /, *)?

In Python you can do:

import operator
ops = {"+": operator.add, "-": operator.sub} # etc.
print ops["+"](1,1) # prints 2

Is there a similar library or method for Go?

  • 写回答

3条回答 默认 最新

  • dongmaxi6763 2015-06-10 19:16
    关注

    You can do this with function values:

    ops := map[string]func(int, int) int{
        "+": func(a, b int) int { return a + b },
        "-": func(a, b int) int { return a - b },
        "*": func(a, b int) int { return a * b },
        "/": func(a, b int) int { return a / b },
    }
    
    fmt.Println(ops["+"](4, 2))
    fmt.Println(ops["-"](4, 2))
    fmt.Println(ops["*"](4, 2))
    fmt.Println(ops["/"](4, 2))
    

    Output: Go Playground

    6
    2
    8
    2
    

    For a nice print:

    a, b := 4, 2
    for op, fv := range ops {
        fmt.Printf("%d %s %d = %d
    ", a, op, b, fv(a, b))
    }
    

    Output:

    4 / 2 = 2
    4 + 2 = 6
    4 - 2 = 2
    4 * 2 = 8
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度