YouTip LogoYouTip

Go Slice

# Go Slices A Go slice is an abstraction over an array. Go arrays have a fixed length, which makes them less suitable for certain scenarios. Go provides a flexible, powerful built-in type called a slice ("dynamic array"). Unlike arrays, slices have a variable length and can have elements appended to them, which may increase the slice's capacity. * * * ## Defining a Slice You can declare a slice by declaring an array without specifying its size: var identifier []type A slice does not require specifying its length. Or use the **make()** function to create a slice: var slice1 []type = make([]type, len) This can also be written as slice1 := make([]type, len) You can also specify the capacity, where **capacity** is an optional parameter. make([]T, length, capacity) Here, `len` is the length of the array and also the initial length of the slice. ### Slice Initialization s :=[] int {1,2,3 } Directly initialize a slice. `[]` indicates it's a slice type, **{1,2,3}** are the initial values 1, 2, 3, and its **cap=len=3**. s := arr[:] Initialize slice **s** as a reference to array `arr`. s := arr[startIndex:endIndex] Create a new slice from elements in `arr` from index `startIndex` to `endIndex-1`. s := arr[startIndex:] When `endIndex` is omitted, it defaults to the last element of `arr`. s := arr[:endIndex] When `startIndex` is omitted, it defaults to the first element of `arr`. s1 := s[startIndex:endIndex] Initialize slice `s1` from slice `s`. s :=make([]int,len,cap) Initialize slice **s** using the built-in function **make()**. **[]int** indicates it's a slice with elements of type int. * * * ## len() and cap() Functions Slices are indexable, and their length can be obtained using the `len()` method. Slices provide a method to calculate capacity using `cap()`, which measures the maximum length the slice can reach. Here is a concrete example: ## Example package main import"fmt" func main(){ var numbers =make([]int,3,5) printSlice(numbers) } func printSlice(x []int){ fmt.Printf("len=%d cap=%d slice=%vn",len(x),cap(x),x) } The output of the above example is: len=3 cap=5 slice= * * * ## Empty (nil) Slice A slice is `nil` by default before initialization, with a length of 0. Example: ## Example package main import"fmt" func main(){ var numbers []int printSlice(numbers) if(numbers ==nil){ fmt.Printf("Slice is empty") } } func printSlice(x []int){ fmt.Printf("len=%d cap=%d slice=%vn",len(x),cap(x),x) } The output of the above example is: len=0 cap=0 slice=[]Slice is empty * * * ## Slicing a Slice You can slice a slice by setting a lower and upper bound _[lower-bound:upper-bound]_. Example: ## Example package main import"fmt" func main(){ /* Create a slice */ numbers :=[]int{0,1,2,3,4,5,6,7,8} printSlice(numbers) /* Print original slice */ fmt.Println("numbers ==", numbers) /* Print sub-slice from index 1 (inclusive) to index 4 (exclusive) */ fmt.Println("numbers[1:4] ==", numbers[1:4]) /* Default lower bound is 0 */ fmt.Println("numbers[:3] ==", numbers[:3]) /* Default upper bound is len(s) */ fmt.Println("numbers[4:] ==", numbers[4:]) numbers1 :=make([]int,0,5) printSlice(numbers1) /* Print sub-slice from index 0 (inclusive) to index 2 (exclusive) */ number2 := numbers[:2] printSlice(number2) /* Print sub-slice from index 2 (inclusive) to index 5 (exclusive) */ number3 := numbers[2:5] printSlice(number3) } func printSlice(x []int){ fmt.Printf("len=%d cap=%d slice=%vn",len(x),cap(x),x) } The output of the above code is: len=9 cap=9 slice= numbers == numbers[1:4] == numbers[:3] == numbers[4:] == len=0 cap=5 slice=[] len=2 cap=9 slice= len=3 cap=7 slice= * * * ## append() and copy() Functions To increase the capacity of a slice, we must create a new, larger slice and copy the contents of the original slice over. The following code demonstrates the `copy` method for copying slices and the `append` method for adding new elements to a slice. ## Example package main import"fmt" func main(){ var numbers []int printSlice(numbers) /* Allow appending to an empty slice */ numbers = append(numbers,0) printSlice(numbers) /* Add one element to the slice */ numbers = append(numbers,1) printSlice(numbers) /* Add multiple elements at once */ numbers = append(numbers,2,3,4) printSlice(numbers) /* Create slice numbers1 with twice the capacity of the previous slice */ numbers1 :=make([]int,len(numbers),(cap(numbers))*2) /* Copy contents of numbers to numbers1 */ copy(numbers1,numbers) printSlice(numbers1) } func printSlice(x []int){ fmt.Printf("len=%d cap=%d slice=%vn",len(x),cap(x),x) } The output of the above code is: len=0 cap=0 slice=[] len=1 cap=1 slice= len=2 cap=2 slice= len=5 cap=6 slice= len=5 cap=12 slice=
← Go RecursionGo Range β†’