Creating a slice from an array
Many functions will accept slices and not arrays. If you have an array of values and need to pass it to a function that wants a slice, you need to create a slice from an array. This is easy and efficient. Creating a slice from an array is a constant-time operation.
How to do it...
Use the [:]
notation to create a slice from the array. The slice will have the array as its underlying storage:
arr := [...]int{0, 1, 2, 3, 4, 5} slice := arr[:] // slice has all elements of arr slice[2]=10 // Here, arr = [...]int{0,1,10,3, 4,5} // len(slice) = 6 // cap(slice) = 6
You can create a slice pointing to a section of the array:
slice2 := arr[1:3] // Here, slice2 = {1,10} // len(slice2) = 2 // cap(slice2) = 5
You can slice an existing slice. The bounds of the slicing operation are determined by the capacity of the original slice:
slice3 := slice2[0:4] // len(slice3)=4 // cap(slice3)=5 // slice3 = {1,10,3,4}
How it works...
A slice is a data...