How can I turn a string into a statement?

Is there a way to convert a string (like "+", "-", "/", "*") to the corresponding math operators (+, -, /, *)?

In Python, you can:

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

      

Is there a similar library or method for Go?

+3


source to share


3 answers


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

      

Exit: Go to the playground

6
2
8
2

      



For a good print:

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

      

Output:

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

      

+7


source


There are several options, but I would recommend simply creating a problem in the switch, or using it map[string]func

to provide a function that 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 that;



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

      

What I use will probably depend on the volume. Imo is more portable. The card is not readable, so, for example, someone else can simply put it on completely by assigning a different method "+"

.

EDIT: After thinking about it, the card sucks and I would recommend against it. The function is more understandable, stable, consistent, predictable, encapsulated ect.

+4


source


Here's a different implementation. This gives or takes 3x faster than the string switch implementation, but slightly less readable.

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

      

-1


source







All Articles