<p>I was trying to iterate through an array using a for range loop and found an odd behavior. </p>
<pre><code>list := []string{"a","b","c","d"}
// expect: abcd
for i := range list {
fmt.Print(list[i])
}
// output: abcd
// expect: bcd
for i := range list[1:] {
fmt.Print(list[i])
}
// output: abc
</code></pre>
<p>I would expect to get 'bcd' for list[i:] instead of 'abc'. Is this a bug or is this expected behavior? If so, why?</p>
<p><a href="https://play.golang.org/p/dmLjXpQsh8" rel="nofollow">https://play.golang.org/p/dmLjXpQsh8</a></p>
<hr/>**评论:**<br/><br/>JHunz: <pre><p>The first return value from a range is the index of each item into the range specified. The range you specified is list[1:], so you're getting i values of 0,1,2 that correspond to that range ["b","c","d"], but what you're printing are items indexed into the original list instead. </p>
<p>The simplest way to fix this is just to use the version of the range operator which returns the actual item as well as the index, since that's what you seem to care about: </p>
<p>for _, v := range list[1:] {
fmt.Print(v)
}</p></pre>atishpatel2012: <pre><p>Ohhh, that makes sense. In my head, I thought the 'list' variable was the new array, list[1:]. xD</p>
<p>Since the list size doesn't change, I'll just use the following code: </p>
<pre><code>for i := range list[1:] {
fmt.Print(list[i+1]) // i+1 can't be out of bound
}
</code></pre>
<p>Thank you for the help!</p>
<p>*edit: note that list[1:] creates panic on a slice of length 0. </p></pre>UniverseCity: <pre><p>This is a better way to do the same thing:</p>
<pre><code>for _, item := range list[1:] {
fmt.Print(item)
}
</code></pre></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传