恐慌:运行时错误:索引超出范围 [5],长度为 5

我写了这个程序,

package mainimport "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

我知道它给出错误的原因,这是由于 for 循环中的条件,i<=10如果我删除=它不会给我错误。

但是,假设我想以这样一种方式对其进行编码,即如果我仍然使用i<=10. 怎么做到呢?


长风秋雁
浏览 260回答 2
2回答

qq_花开花谢_0

我想以这样的方式编码它,如果我仍然使用“i <= 10”,我不会出错。怎么做到呢?你可以像这样安全地循环,package mainimport "fmt"func main() {&nbsp; &nbsp; x := "Hello"&nbsp; &nbsp; for i := 0; i <= 10 && i < len(x); i++ {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%#U\n", x[i])&nbsp; &nbsp; }}https://go.dev/play/p/2NknjS3Ql6k或这个,package mainimport "fmt"func main() {&nbsp; &nbsp; x := "Hello"&nbsp; &nbsp; for i := 0; i <= 10; i++ {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%#U\n", x[i%len(x)])&nbsp; &nbsp; }}https://go.dev/play/p/0eKTcxXipwB

互换的青春

你可以改变你的条件,i <= 10从i&nbsp;<=&nbsp;4&nbsp;//&nbsp;4&nbsp;is&nbsp;the&nbsp;last&nbsp;index&nbsp;of&nbsp;your&nbsp;string或者你可以增加你的字符串长度,从x := "Hello"到x&nbsp;:=&nbsp;"Hello&nbsp;World"
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go