Sum slice using range in golang

polaris · · 1150 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hi i am currently learning go and tried to write a function which takes a slice of integers and sums them up.</p> <p>My function looks like this:</p> <p><a href="https://gist.github.com/Rapdrei/112b713e7f3b1dd583143db0280744a5" rel="nofollow">https://gist.github.com/Rapdrei/112b713e7f3b1dd583143db0280744a5</a></p> <p>Surprisingly it sums just the first n-1 elements of the slice and leaves the last one. Any idea what i am missing here?</p> <p>best</p> <hr/>**评论:**<br/><br/>dgryski: <pre><p>You&#39;re ranging over the indices not the values. Use the two-valued form of the range.</p></pre>rap3: <pre><p>Thank you! :)</p></pre>mywillislaw: <pre><p>Two ways to approach the issue. I&#39;d like to point out that the way dgryski suggests( the later is the examples below) incurs overhead through copying while the former uses the value directly. I will probably get banned for constructive criticism of such a naive comment by dgryski, just like I have in the past....</p> <pre><code>package main import &#34;fmt&#34; func main() { sum(1, 2, 3, 4, 6) } func sum(input ...int) int { sum := 0 for i := range input { sum += input[i] } fmt.Println(&#34;sum was &#34;, sum) return sum } package main import &#34;fmt&#34; func main() { sum(1, 2, 3, 4, 6) } func sum(input ...int) int { sum := 0 for _, i := range input { sum += i } fmt.Println(&#34;sum was &#34;, sum) return sum } </code></pre></pre>

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

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