I am trying to assign a value to the empty slice as follows.
func main() {
var s []int
fmt.Println(s, len(s), cap(s))
s[0] = 99
}
And it throws an exception,
panic: runtime error: index out of range
Note: I know one way of doing this by initializing the value at declaration part as follows. But in the above example I am trying to assign a value after the declaration.
var s []int{99}
Is there a way to achieve this?
Go slice make function It allocates an underlying array with size equal to the given capacity, and returns a slice that refers to that array. We create a slice of integer having size 5 with the make function. Initially, the elements of the slice are all zeros. We then assign new values to the slice elements.
To declare the type for a variable that holds a slice, use an empty pair of square brackets, followed by the type of elements the slice will hold.
Appending to nil slice: As we know that zero value slice type is nil and the capacity and the length of such type of slice is 0. But with the help of append function, it is possible to append values to nil slice.
The zero value of a slice is nil . A nil slice has a length and capacity of 0 and has no underlying array.
Empty slices cannot just be assigned to. Your print statement shows that the slice has length and capacity of 0. Indexing at [0]
is definitely out of bounds.
You have (at least) three choices:
s = append(s, 99)
s := make([]int, 1)
s := []int{99}
You can find tutorials on slices in the Go tour, or a lot more details about slice usage and internals.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With