Ankeet's backend garden

slice

  • concat slices?? just like JavaScript's spread operator but the three dots come after instead of before as shown in example
var x = []int{2, 3, 5}
var y = []int{20, 30, 50}
x = append(x, y...)

how they are stored internally

  • when you use append the slice is not modified but a new slice is created and the older values are copied over to the new slice
  • [go] is pass by value not reference - so any params that are passed to functions are copied inside that's why you need to assign the value of append back to the same variable

capacity

  • slice uses contiguous memory cells and if you increase the size it has to check if the memory locations are available or not
  • so it's not very efficient to increase and allocate on the go - wasted cpu cycles in copying older values to the newer array

make

  • so if you know the size in advance use make to create a slice of the recommended size
x := make([]int, 5, 10)
// type, length, capacity

never specify the capacity lesser than length cuz now you know what's what

Referred in

slice