英文:
panic: runtime error: index out of range [5] with length 5
问题
我写了这个程序,
package main
import "fmt"
func main() {
x := "Hello"
for i := 0; i <= 10; i++ {
fmt.Printf("%#U\n", x[i])
}
}
链接:https://go.dev/play/p/yrMu2hlAvkZ
恐慌:运行时错误:索引超出范围 [5],长度为 5
我知道为什么会出现错误,这是由于循环条件中的 i<=10
,如果我移除 =
,就不会出现错误。
但是假设我想以这样的方式编写代码,即使我仍然使用 i<=10
,也不会出现错误。该怎么做?
英文:
I wrote this program,
package main
import "fmt"
func main() {
x := "Hello"
for i := 0; i <= 10; i++ {
fmt.Printf("%#U\n", x[i])
}
}
https://go.dev/play/p/yrMu2hlAvkZ
panic: runtime error: index out of range [5] with length 5
I know the reason why it's giving the error, it's due to the condition in for loop i<=10
and if I remove the =
it will not give me the error.
But let's say I want to code it in such a way that I won't get errors if I still use i<=10
. How can it be done?
答案1
得分: 1
你可以这样安全地循环:
package main
import "fmt"
func main() {
x := "Hello"
for i := 0; i <= 10 && i < len(x); i++ {
fmt.Printf("%#U\n", x[i])
}
}
或者这样:
package main
import "fmt"
func main() {
x := "Hello"
for i := 0; i <= 10; i++ {
fmt.Printf("%#U\n", x[i%len(x)])
}
}
链接:
英文:
> I want to code it in such a way that I won't get error if i still use
> "i<=10". How can it be done?
You can safely loop like this,
package main
import "fmt"
func main() {
x := "Hello"
for i := 0; i <= 10 && i < len(x); i++ {
fmt.Printf("%#U\n", x[i])
}
}
https://go.dev/play/p/2NknjS3Ql6k
Or this,
package main
import "fmt"
func main() {
x := "Hello"
for i := 0; i <= 10; i++ {
fmt.Printf("%#U\n", x[i%len(x)])
}
}
答案2
得分: 0
你可以选择更改条件,将 i <= 10
改为
i <= 4 // 4 是你的字符串的最后一个索引
或者你可以增加字符串的长度,将 x := "Hello"
改为
x := "Hello World"
英文:
You can either change your condition, from i <= 10
to
i <= 4 // 4 is the last index of your string
or you can increase your string length, from x := "Hello"
to
x := "Hello World"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论