Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a value to the empty slice after the declaration

Tags:

slice

go

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?

like image 835
Venkat Ch Avatar asked Feb 09 '18 07:02

Venkat Ch


People also ask

How do I assign a value to a slice in Golang?

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.

How do you declare an empty slice?

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.

Can you append to a nil slice?

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.

Can a slice be nil?

The zero value of a slice is nil . A nil slice has a length and capacity of 0 and has no underlying array.


1 Answers

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:

  • Append to the slice: s = append(s, 99)
  • or Initialize the slice to be non-empty: s := make([]int, 1)
  • or Initialize your slice with the element you want: s := []int{99}

You can find tutorials on slices in the Go tour, or a lot more details about slice usage and internals.

like image 102
Marc Avatar answered Sep 25 '22 00:09

Marc