<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'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'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 "fmt"
func main() {
sum(1, 2, 3, 4, 6)
}
func sum(input ...int) int {
sum := 0
for i := range input {
sum += input[i]
}
fmt.Println("sum was ", sum)
return sum
}
package main
import "fmt"
func main() {
sum(1, 2, 3, 4, 6)
}
func sum(input ...int) int {
sum := 0
for _, i := range input {
sum += i
}
fmt.Println("sum was ", sum)
return sum
}
</code></pre></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传