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

时间:2015-06-10 19:10:57

标签: go

有没有办法将字符串(例如“+”,“ - ”,“/”,“*”)转换为各自的数学运算符(+, - ,/,*)?

在Python中你可以这样做:

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

Go是否有类似的库或方法?

3 个答案:

答案 0 :(得分:6)

您可以使用函数值执行此操作:

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))

输出:Go Playground

6
2
8
2

打印出色:

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

输出:

4 / 2 = 2
4 + 2 = 6
4 - 2 = 2
4 * 2 = 8

答案 1 :(得分:4)

选项很少,但我建议只在交换机中构建问题或使用map[string]func提供相同的功能。所以...要么这个;

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

或者这个;

func doOp(string op, lhs, rhs int) int {
     switch (op) {
          case "+":
             return lhs + rhs
           // ect
           default:
              // error cause they gave an unknown op string
     }
}

我使用的可能取决于范围。函数imo更便携。地图不是只读的,例如其他人可以通过为"+"分配不同的方法来完全填充它。

编辑:在考虑之后,地图很糟糕,我建议不要这样做。该功能更清晰,稳定,一致,可预测,封装等。

答案 2 :(得分:-1)

这是另一种实施方式。这比基于字符串的交换机实现快3倍,但可读性稍差。

func RunOp(sign string, a, b int) int {
    s := byte(sign[0])
    switch s {
    case byte(43):
            return a+b
    case byte(45):
            return a-b
    case byte(47):
            return a/b
    case byte(42):
            return a*b
    default:
            return 0
    }
}