Three-variable range over strings

agolangf · · 357 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>What would you say if you could use three variables in a for loop when iterating over strings? That is, if you could write</p> <pre><code>for runeIndex, byteIndex, r := range s { // code } </code></pre> <p>instead of</p> <pre><code>runeIndex := 0 for byteIndex, r := range s { // code runeIndex++ } </code></pre> <p>?</p> <p>As far as I can see, the proposed syntax wouldn&#39;t violate the Go1 compatibility promise, would it?</p> <hr/>**评论:**<br/><br/>TheMerovius: <pre><p>Honestly: It was a mistake to make range over <code>string</code>s behave differently from <code>[]byte</code>s. It would&#39;ve been better addressed by building a rune-iterator into unicode/utf8. This way</p> <ul> <li>People assume strings will always contain valid utf8, which is false.</li> <li>People assume iterating over runes is the best thing to do, which is <em>especially</em> false with the last point.</li> <li>People get confused by the fact, that those two very similar types create such different behavior.</li> </ul></pre>HectorJ: <pre><p>This would add complexity to the language, just for some minor syntactic sugar.</p></pre>robertmeta: <pre><p>At first blush to me, feels a bit confusing, because the range keyword always returns index, value elsewhere: arrays, slices, maps, strings. The 3 value syntax would <strong>only</strong> be useful with strings seems like. </p></pre>gohacker: <pre><p>Yes, you couldn&#39;t use it with arrays, slices and maps, like 2-value syntax cannot be used with channels.</p></pre>robertmeta: <pre><p>Fair point -- actually that makes me withdraw my complaints about it. </p></pre>YEPHENAS: <pre><p>The reason of existence for the index variable in for-range loops is to make it possible to access the current element via the [] operator, but you can&#39;t access a position in a string with s[runeIndex].</p></pre>xiegeo: <pre><p>I want range to take an interable interface. Sorry for going of in a tangent.</p></pre>ultra_brite: <pre><p>Don&#39;t bother, nobody maintaining Go is interested in community input when it comes to changing the syntax of the language.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

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