索引超出范围 [113],长度为10。

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

index out of range [113] with length 10

问题

我正在尝试编写一个函数来解密从qwerty...到abcdef...的消息。目前我有以下代码:

func Decrypt(strToDecrypt string) string {
    encrStrng := []rune(strings.ToLower(strToDecrypt))
    var decrStrng string = ""

    for _, i := range encrStrng {
        switch encrStrng[i] {
        case 'q':
            decrStrng += "a"
        // 其他的我就不写了,但是是 q>a, w>b, 等等。
        }
    }
}

每当我尝试在主函数中使用fmt.Println(Decrypt("qwerty"))进行测试时,它会返回panic: runtime error: index out of range [113] with length 10。错误出现在switch语句中。我在这个特定问题上找不到任何信息。

英文:

I am trying to make a function to decrypt messages from qwerty... -> abcdef.... Currently I have

func Decrypt(strToDecrypt string) string {
 encrStrng := []rune(strings.ToLower(strToDecrypt))
 var decrStrng string = ""

 for _, i := range encrStrng {
   switch encrStrng[i] {
   case 'q'
    decrStrng += "a"
// not gonna type the rest but its q>a, w>b, etc etc.
 }
}

Whenever i try fmt.Println(Decrypt("qwerty")) (in main function ofc) just as a test, it returns
panic: runtime error: index out of range [113] with length 10. Error is at the switch statement, in particular. I could not find anything on this (specific) issue.

答案1

得分: 2

在对数组进行范围遍历时,第一个值是索引,第二个值是元素值。你正在使用元素值作为索引,以获取元素值。你应该使用索引:

 for i := range encrStrng {
   switch encrStrng[i] {

或者使用值:

 for _, i := range encrStrng {
   switch i {

rangeGo 之旅 中有详细介绍。

英文:

In a range over an array, the first value is the index, the second is the element value. You're using the element value as an index, in order to get the element value. You should either use the index:

 for i := range encrStrng {
   switch encrStrng[i] {

Or use the value:

 for _, i := range encrStrng {
   switch i {

range is covered in the Tour of Go.

huangapple
  • 本文由 发表于 2021年11月25日 03:00:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/70101588.html
匿名

发表评论

匿名网友

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

确定