声明后如何为空切片分配值

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?

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.

// slice declaration; no memory allocation
var slice []int 

//slice initialization with length (0) and capacity (10);
//memory allocated for 10 ints
slice = make([]int, 0, 10)

 // push to the slice value - than increase length
slice = append(slice, 1)

//change the value. Index has to be lower then length of slice
slice[0] = 2

Take a loot at this output - https://play.golang.com/p/U426b1I5zRq

Of course, you can skip initialization with make, append will do it for you with default value of capacity (2). But for performance it is better to allocate memory only once (if you know how many elements are going to be added to the slice)

You can do that by using append function.

func main() {
    var s []int
    s = append(s,99)
    fmt.Println(s)  // [99]
}

https://play.golang.org/p/XATvSo2OB6f

var s []int{99}

The above works but if you want to assign after declaration, then you would need to create a slice using make function with enough length

s := make([]int, 10)
s[0] = 10
fmt.Println(s)

This will initialize slice and set the length to 10 and its elements to zero values

Note: doing s[10] or any greater index will panic since the slice is initialised with length 10. If you want to dynamically increase the slice size, then use append