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

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?

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

There are few options but I would recommend just constructing the problem in a switch or using a map[string]func to provide a function which does the same. So... Either this;

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

or this;

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

Which I use would probably depend on scope. The function imo is more portable. The map isn't read only so for example someone else could just hose it entirely by assigning a different method to "+".

EDIT: After thinking about it the map sucks and I'd recommend against it. The function is more clear, stable, consistent, predictable, encapsulated ect.

Here's another implementation. This is give or take 3x faster than the string-based switch implementation but readability is a little less.

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