英文:
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 {
range
在 Go 之旅 中有详细介绍。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论