Tim
Tim

Reputation: 99616

How to append a new element to a slice?

I tried to append a new element to a slice, just like appending a new element to a list in Python, but there is an error

package main

import "fmt"

func main() {
    s := []int{2, 3, 5, 7, 11, 13}
    printSlice(s)

    s[len(s)] = 100
    printSlice(s)
}

func printSlice(s []int) {
    fmt.Printf("%v\n", s)
}

and the output is

[2 3 5 7 11 13]

panic: runtime error: index out of range

How can I append a new element to a slice then?

Is it correct that slice in Go is the closet data type to list in Python?

Thanks.

Upvotes: 1

Views: 536

Answers (1)

user1087001
user1087001

Reputation:

Appending in Go uses the builtin method append. For example:

s := []byte{1, 2, 3}
s = append(s, 4, 5, 6)
fmt.Println(s)
// Output: [1 2 3 4 5 6]

You are correct, slices in Go are close to Python's list, and, in fact, many of the same indexing and slicing operations work on them.

When you do:

s[len(s)] = 100

it panics because you cannot access a value beyond the length of the slice. There appears to be some confusion here, because in Python this works the exact same way. Attempting the above in Python (unless you've already expanded the list) will give:

IndexError: list assignment index out of range

Upvotes: 3

Related Questions