Slices
A Slice is like a dynamically-sized array. A slice type is written []T
,where elements has type T
. So it’s like an array without size defined.
A Slice is a light weight data structure that gives access to sequence of elements of an array, also known as slice’s underlying array.
Syntax
a[i:j]
– Slice with range from i to ja[i:]
– Slice with range from i to end of the underlying arraya[:j]
– Slice with range from start of the underlying array to ja[:]
– Slice, whose range is the whole array
Example
Consider the example below, arr
is an array of size 5 and arr[1:4]
slices it from index 1 to 3
So it excludes the last one.
package main import "fmt" func main() { arr := [4]int{1, 2, 3, 4} var s1 []int = arr[0:2] var s2 []int = arr[1:3] fmt.Println(s1) fmt.Println(s2) }
Result
[1 2] [2 3]
If we represent this in a mathematical fashion, slice operator is s[i:j]
where 0<=i<=j<=cap(s)
Length and Capacity
Length: Length is the number of slice elements
Capacity: Capacity is the number of elements between start of slice and the end of underlying array.
The Length and capacity of a slice is defined by the function len()
and cap()
For the Same example above, let’s execute below,
package main import "fmt" func main(){ arr := [6]int {1,2,3,4,5,6} var s1 []int = arr[3:4] fmt.Println(s1) fmt.Println(len(s1),cap(s1)) }
Result
[4] 1 3
Note: A slice does not store any data, it only describes a section of an underlying array. Changing the elements of a slice will modify the corresponding elements of its underlying array
Consider the below declaration, by no defining the size of the array, the compiler will recognize this as a slice and will create the underlying array first and then creates slice pointing it
sli := []int{1,2,3}