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:
reus:Creating a pointer to a slice is silly. Just create a slice of however you want to naturally store your objects.
zaib0n:If they're read-only, use []Job, otherwise []*Job.
dshills: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
zaib0n: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?
dshills:you are right cause in this case we speak about a slice. But what if it was an array directly ?
djherbis:An interesting question actually. I think as soon as you try to pass it, it becomes a slice automagically.
dshills: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[:]
mihai_stancu:ahhhh that fills a knowledge hole. Thanks for the link.
DavidDavidsonsGhost: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.
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.
