Working with slices
A slice is a view over an array. You may be dealing with multiple slices that work with the same underlying data.
The zero-value for a slice is nil. Reading or writing a nil slice will panic
; however, you can append to a nil slice, which will create a new slice.
Creating slices
There are several ways a slice can be created.
How to do it...
Use make(sliceType,length[,capacity])
:
slice1 := make([]int,0) // len(slice1)=0, cap(slice1)=0 slice2 := make([]int,0,10) // len(slice2)=0, cap(slice2)=10 slice3 := make([]int,10) // len(slice3)=10, cap(slice3)=10
In the previous code snippet, you see three different uses of make
to create a slice:
slice1:=make([]int,0)
creates an empty slice,0
being the length of the slice. Theslice1
variable is initialized as a non-nil, 0-length slice.slice2 := make([]int,0,10)
creates an empty slice with capacity10
. This is what you should prefer if you know the likely maximum size for this slice. This slice...