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

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

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 &quot;fmt&quot;

func main() {
    x := &quot;Hello&quot;

    for i := 0; i &lt;= 10; i++ {
	    fmt.Printf(&quot;%#U\n&quot;, 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&lt;=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&lt;=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 &quot;fmt&quot;

func main() {
	x := &quot;Hello&quot;
	for i := 0; i &lt;= 10 &amp;&amp; i &lt; len(x); i++ {
		fmt.Printf(&quot;%#U\n&quot;, x[i])
	}
}

https://go.dev/play/p/2NknjS3Ql6k

Or this,

package main

import &quot;fmt&quot;

func main() {
	x := &quot;Hello&quot;
	for i := 0; i &lt;= 10; i++ {
		fmt.Printf(&quot;%#U\n&quot;, x[i%len(x)])
	}
}

https://go.dev/play/p/0eKTcxXipwB

答案2

得分: 0

你可以选择更改条件,将 i <= 10 改为

i <= 4 // 4 是你的字符串的最后一个索引

或者你可以增加字符串的长度,将 x := "Hello" 改为

x := "Hello World"
英文:

You can either change your condition, from i &lt;= 10 to

i &lt;= 4 // 4 is the last index of your string

or you can increase your string length, from x := &quot;Hello&quot; to

x := &quot;Hello World&quot;

huangapple
  • 本文由 发表于 2021年11月24日 12:33:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/70090776.html
匿名

发表评论

匿名网友

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

确定