Go Slice
Go Language - Slice
Go slices are very similar to arrays. But slices overcome the limitations of array. Arrays are not allowed to dynamically change their size or return a sub-array of themselves. Thus slices provide functions to solve those issues.
To define a slice, we have some options. Example : var numbers []int or numbers = make([]int,5,5)where length and slice are set to 5.
Functions provided by slices are len() and cap(). Len() function returns the number of element present in the slice and cap() function returns the maximum number of elements that the slice can accommodate.
Example :
CODE/PROGRAM/EXAMPLE
var numbers = make([]int,3,5)
fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x)
This will return ‘len = 3 cap = 5 slice = [0 0 0]’
If a slice is declared with no inputs, it’s called a null slice. It’s length and capacity are zero. Example: var numbers []int
Subslicing :
Specifying the lower-bound and the upper-bound of the slice will return the subslice of itself.
It is to be noted that the lower-bound is included and the upper-bound is excluded. Example: numbers := []int{0,1,2,3,4,5,6,7,8}; numbers[1:4] will return [1 2 3].
Also, not specifying the lower-bound means it starts from 0th index and not specifying the upper-bound means it takes the number of element present in that slice.
Example : numbers := []int{0,1,2,3,4,5,6,7,8}; numbers[:3] will return [0 1 2] and number[4:] will return [4 5 6 7 8].
Functions available under slice :
append() function can increase the capacity of the slice.
Example :
CODE/PROGRAM/EXAMPLE
var numbers1 []int{1,2,3,4,5};
var numbers2 []int;
numbers = append(numbers, 6)
it will make numbers1 as {1,2,3,4,5,6} copy (numbers2,numbers1) will make numbers2 as {1,2,3,4,5,6}.