for range function expected behavior or bug?

xuanbao · · 413 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I was trying to iterate through an array using a for range loop and found an odd behavior. </p> <pre><code>list := []string{&#34;a&#34;,&#34;b&#34;,&#34;c&#34;,&#34;d&#34;} // 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 &#39;bcd&#39; for list[i:] instead of &#39;abc&#39;. 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&#39;re getting i values of 0,1,2 that correspond to that range [&#34;b&#34;,&#34;c&#34;,&#34;d&#34;], but what you&#39;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&#39;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 &#39;list&#39; variable was the new array, list[1:]. xD</p> <p>Since the list size doesn&#39;t change, I&#39;ll just use the following code: </p> <pre><code>for i := range list[1:] { fmt.Print(list[i+1]) // i+1 can&#39;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

413 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传