无效操作:(字符串上未定义运算符-)

huangapple go评论82阅读模式
英文:

invalid operation: (operator - not defined on string)

问题

arrayAll := []string{"a", "b", "c", "d", "e"}

x := p[arrayAll[i]-"a"]

Go语言不支持运算符"-"
那么我该如何获取数组arrayAll[i]-"a"的索引呢?

英文:
arrayAll := []string{"a", "b", "c", "d", "e"}

x := p[arrayAll[i]-"a"]

go does not support operators "-",
so how can I get the index of array:arrayAll[i]-"a"

答案1

得分: 2

你想要如何定义字符串的减法运算符-?调用"Hello"-"World"后你期望得到什么结果?

你是想对单个字符进行操作吗?对单个字符进行操作是有明确定义的,你可以预期'c'-'a'的结果确实是2。考虑以下代码:

arrayAll := []byte{'a', 'b', 'c'} // 或者简单地写成 "abc"
x := p[arrayAll[2] - 'a']

无论如何,你很可能不想对字符串进行减法运算,而是想对字符的整数表示进行减法运算。

英文:

How would you define operator - on strings? What result would you expect after calling "Hello"-"World"?

Are you trying to operate on single characters? This is well defined and you can probably expect 'c'-'a' to equal 2 indeed. Consider:

arrayAll := []byte{'a', 'b', 'c'} (or simply "abc")
x := p[arrayAll[2] - 'a']

One way or another you most probably don't want to subtract strings, but integer representations of characters.

huangapple
  • 本文由 发表于 2015年4月27日 18:52:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/29893723.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定