<p>Hey, </p>
<p>So I have a function which should return a list of "Job" structs. What would be the prefered way to return it? Should it be a []*Job or *[]Job ?</p>
<hr/>**评论:**<br/><br/>binaryblade: <pre><p>Creating a pointer to a slice is silly. Just create a slice of however you want to naturally store your objects.</p></pre>reus: <pre><p>If they're read-only, use []Job, otherwise []*Job. </p></pre>zaib0n: <pre><p>is the type of access should be the only concern ?
passing the jobs by value means make a copy of each job, right ?
So wouldn't it be more efficient to pass jobs by reference, so the copy is not needed ?
I'm never sure what's the correct way to choose between the two</p></pre>dshills: <pre><p>That doesn't sound right. The slice will be copied but it carries a reference to the backing array. The reference will be copied but not the backing array. The jobs in the backing array would not get copied. The receiver would have a copied slice but full access to the original job backing array. Or am I missing something?</p></pre>zaib0n: <pre><p>you are right cause in this case we speak about a slice. But what if it was an array directly ?</p></pre>dshills: <pre><p>An interesting question actually. I think as soon as you try to pass it, it becomes a slice automagically. </p></pre>djherbis: <pre><p>Arrays are copied when they are passed, they don't get converted to slices. If you want to convert an array to a slice just do: </p>
<pre><code>mySlice := myArray[:]
</code></pre>
<p><a href="http://blog.golang.org/go-slices-usage-and-internals" rel="nofollow">http://blog.golang.org/go-slices-usage-and-internals</a></p></pre>dshills: <pre><p>ahhhh that fills a knowledge hole. Thanks for the link.</p></pre>mihai_stancu: <pre><p>Slices themselves ar small enough to pass around by value and they were designed to be passed around by value. So a pointer to a slice wouldn't make that much sense.</p>
<p>If your Job objects are already in a slice by value ([]Job) then creating and passing a []Job slice would be trivial. While creating and passing a []*Job slice would require a few more lines of code.</p></pre>DavidDavidsonsGhost: <pre><p>Slices are references to arrays. They consist of a pointer to the backing array a capacity and a length. Just pass the slice around by value, unless you want to be able to modify the original slice.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传