Returning a reference to a slice or retrning a slice of references

blov · 2015-04-13 14:12:07 · 985 次点击    
这是一个分享于 2015-04-13 14:12:07 的资源,其中的信息可能已经有所发展或是发生改变。

Hey,

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 ?


评论:

binaryblade:

Creating a pointer to a slice is silly. Just create a slice of however you want to naturally store your objects.

reus:

If they're read-only, use []Job, otherwise []*Job.

zaib0n:

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

dshills:

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?

zaib0n:

you are right cause in this case we speak about a slice. But what if it was an array directly ?

dshills:

An interesting question actually. I think as soon as you try to pass it, it becomes a slice automagically.

djherbis:

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:

mySlice := myArray[:]

http://blog.golang.org/go-slices-usage-and-internals

dshills:

ahhhh that fills a knowledge hole. Thanks for the link.

mihai_stancu:

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.

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.

DavidDavidsonsGhost:

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.


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

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