Not sure if I understand Slices/Strings

polaris · · 507 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>In the process of learning Go</p> <p>I managed to fix all but 3 errors and I&#39;m not sure how to fix these last few. I feel like they&#39;re pretty simple to fix, though.</p> <p>I feel like it&#39;s a problem with using slices.</p> <p><a href="http://pastebin.com/gm8YDMzc" rel="nofollow">http://pastebin.com/gm8YDMzc</a></p> <hr/>**评论:**<br/><br/>sauerbraten_: <pre><p>Is this what you are trying to do?</p> <p><a href="http://play.golang.org/p/UksdO9ThQQ" rel="nofollow">http://play.golang.org/p/UksdO9ThQQ</a></p> <p>Slices are a little bit like &#34;flexible&#34; arrays. In you code, you gave a string to a function that wants a slice of strings, i.e. multiple strings. I assumed you wanted to print the first character (rune in Go) that the predicate applies to.</p> <p>When ranging over a slice, you get two values: the first is the index in the slice and the second is the element at that index. When ranging over a string, you get the position of the character in the string as first value and the character (rune) as the second. When ranging over a map, the first value is the key, and the second is the value associated to the key in the map.</p> <p>Let me know if you have any more questions, or if what I wrote is not what you were trying to do.</p> <p>By the way, a more idiomatic way to implement your program in Go would be to pass a function to the findFirst[Rune] function which it would use to check the predicate, like here: <a href="http://play.golang.org/p/R3gEEd4AV_" rel="nofollow">http://play.golang.org/p/R3gEEd4AV_</a></p></pre>aylobng: <pre><p>Oops, I didn&#39;t mean to find if the index was even. I want to print the first element in the array/slice that fulfills the conditions from the user (either &#34;even&#34; or &#34;odd&#34;).</p> <p>So if the users says &#34;odd&#34; and &#34;1 2 3 4&#34;, then it would show 1. If it was &#34;even&#34; &#34;1 2 3 4&#34; it would be 2.</p> <p>Would that just be saying list[index]?</p></pre>barsonme: <pre><p>How does this look?</p> <p><a href="https://play.golang.org/p/aUdCKy25L5" rel="nofollow">https://play.golang.org/p/aUdCKy25L5</a></p></pre>aylobng: <pre><p>That was a very different method. It was interesting to see it being done like that. That was great, thanks!</p></pre>horsebees: <pre><p>Maybe?<a href="http://play.golang.org/p/pEArDVhgAu" rel="nofollow">http://play.golang.org/p/pEArDVhgAu</a></p></pre>

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

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