Go 如何将字符串转换为运算符?
是否有方法将字符串(例如“+”、“-”、“/”、“*”)转换为各自的数学运算符(+、-、/、*) 在Python中,您可以执行以下操作:Go 如何将字符串转换为运算符?,go,Go,是否有方法将字符串(例如“+”、“-”、“/”、“*”)转换为各自的数学运算符(+、-、/、*) 在Python中,您可以执行以下操作: import operator ops = {"+": operator.add, "-": operator.sub} # etc. print ops["+"](1,1) # prints 2 Go是否有类似的库或方法?您可以使用函数值执行此操作: ops := map[string]func(int, int) int{ "+": func(a
import operator
ops = {"+": operator.add, "-": operator.sub} # etc.
print ops["+"](1,1) # prints 2
Go是否有类似的库或方法?您可以使用函数值执行此操作:
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))
输出:
要获得漂亮的打印:
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
有几个选项,但我建议只在开关中构造问题,或者使用
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的功能更具可移植性。地图不是只读的,因此,例如,其他人可以通过为“+”
指定不同的方法来完全读取地图
编辑:想了想,这张地图糟透了,我建议不要。功能更加清晰、稳定、一致、可预测、封装等。这里是另一个实现。这比基于字符串的开关实现快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
}
}
与Python版本的不同之处在于,在Python中,操作数的类型和结果没有预先指定(即,
ops[“+”](4.5,2)
给出6.5
)。不要使用大小写字节(43):
作为一个非常难读的case`+`:
版本。同时做符号字符串
有点傻。没有理由不只是执行op byte
然后执行RunOp(`+`,1,2)
。简单地将字节文本放入常量可以提高可读性,我提到我的方法可读性稍差。另外,您如何调用以“op byte”作为参数的方法,而不强制用户执行byte(符号[0])?(哦,在上面的例子中,我的意思当然是case'+':
;单引号与反勾号),您的观点是什么?基于字符串的实现更具可读性?如果您需要对运算符进行运行时注册,则映射是有意义的,但可能仍应封装在函数调用中。
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
}
}