-3

I'm trying to make my code more performative saving memory if possible

I did some research but couldn't find anything about this specific case.

func createSlice() []int {
    return s[]int{1,2,3}
}

func main() {
    s2 := createSlice()
}

Would s2 be a completely new slice with its own underlying arrays or it would be a slice pointing to the underlying arrays of s?

nicolasassi
  • 490
  • 4
  • 14
  • 4
    You haven't found anything on how slices work? https://blog.golang.org/go-slices-usage-and-internals, https://tour.golang.org/moretypes/7, https://golang.org/doc/effective_go.html#slices, https://gobyexample.com/slices. `s2` is a copy of the slice header, referring to the same underlying array. – JimB Aug 08 '19 at 19:00
  • Hey JimB, thanks for the sources! I read some of them, but I could not understand how it would apply for the case I mentioned. – nicolasassi Aug 08 '19 at 19:09
  • 4
    It applies the same in all cases. A slice value is a header containing length, capacity, and a pointer to an underlying array. Assignment copies values, so you get a copy of the slice header containing a pointer to the same underlying array. It doesn't matter if that assignment is a function argument or function return value or anything else. – Adrian Aug 08 '19 at 19:12

1 Answers1

2

You must know about the header of Go Slices. Then, you can have your answer yourself.

See what's in a slice header by checking out the reflect.SliceHeader type:

type SliceHeader struct {
    Data uintptr
    Len  int
    Cap  int
}

Actually, Slice value is a header, containing the backing array along with the length and the capacity. It contains a pointer to the array of the elements are actually stored. The slice value does not contain the elements (unlike arrays).

So, when a slice is passed or returned, a copy will be passed or returned from this header along with the pointer. This pointer points to the same backed array. So, if you modify the elements of the slice, it modifies the backed array too and so all slices (those share the same backed array) also get the change.

So when you pass a slice to a function, a copy will be made from this header, including the pointer, which will point to the same backing array. Modifying the elements of the slice implies modifying the elements of the backing array, and so all slices which share the same backing array will "observe" the change.

See the blog https://blog.golang.org/go-slices-usage-and-internals.

Ref: Are golang slices passed by value?

Shudipta Sharma
  • 5,178
  • 3
  • 19
  • 33