1

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.

Tim
  • 1
  • 141
  • 372
  • 590
  • 2
    https://gobyexample.com/slices – abhink Jul 27 '16 at 18:39
  • 1
    Also in [Effective Go](https://golang.org/doc/effective_go.html#append), the [Go Language Specification](https://golang.org/ref/spec#Appending_and_copying_slices) and in the [Tour of Go](https://tour.golang.org/moretypes/7) – JimB Jul 27 '16 at 18:45
  • See also: http://stackoverflow.com/questions/20195296/golang-append-an-item-to-a-slice/20197469#20197469 – gavv Jul 27 '16 at 18:54
  • Go slices are somewhat similar to python lists, but making assumptions based on that similarity is only going to cause confusion. Slices are very simple data structures, and it's better to just understand how they work to begin with. – JimB Jul 27 '16 at 19:01

1 Answers1

3

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
Sam Whited
  • 6,880
  • 2
  • 31
  • 37