Intern
How to declare a slice in Go?
sobes.tech AI
Answer from AI
In Go, slices can be declared in several ways:
-
Using a slice literal:
// Declare and initialize a slice of integers s := []int{1, 2, 3} -
Using
make:// Declare a slice of integers with length 5 and capacity 5 s1 := make([]int, 5) // Declare a slice of integers with length 0 and capacity 10 s2 := make([]int, 0, 10)Syntax
make([]Type, length, capacity):Type: The element type of the slice.length: The initial length of the slice (number of accessible elements).capacity(optional): The capacity of the slice (maximum number of elements that can be added before reallocating the underlying array). If not specified, it defaults tolength.
-
Declaring a slice without initialization (default value
nil):// Declare a slice of integers with default value nil var s []intA
nilslice has length 0, capacity 0, and no underlying array. -
Creating a slice from an existing array or another slice:
arr := [5]int{10, 20, 30, 40, 50} // Create a slice from the first three elements of the array s := arr[0:3] // [10, 20, 30] otherSlice := []string{"a", "b", "c", "d", "e"} // Create a new slice from a subset of another slice subSlice := otherSlice[1:4] // ["b", "c", "d"]Syntax
arrayOrSlice[low:high]orarrayOrSlice[low:high:max]:low: Starting index (inclusive).high: Ending index (exclusive).max(optional): Index that determines the capacity of the new slice.
Each of these methods has its own features and is used depending on the use case.