Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

panic: runtime error: slice bounds out of range

Tags:

slice

go

I'm following this tutorial: https://gobyexample.com/slices

I was in the middle:

package main

import "fmt"

func main() {

    s := make([]string, 3)
    fmt.Println("emp:", s)

    s[0] = "a"
    s[1] = "b"
    s[2] = "c"
    fmt.Println("set:", s)

    c := make([]string, len(s))
    copy(c, s)
    fmt.Println("copy:", c)

    l := s[2:5]
    fmt.Println("sl1:", l)
}

when I suddenly encountered this error:

alex@alex-K43U:~/golang$ go run hello.go
emp: [  ]
set: [a b c]
copy: [a b c]
panic: runtime error: slice bounds out of range

goroutine 1 [running]:
main.main()
    /home/alex/golang/hello.go:19 +0x2ba

goroutine 2 [syscall]:
created by runtime.main
    /usr/lib/go/src/pkg/runtime/proc.c:221
exit status 2

What does it mean? Is the tutorial mistaken? What can I do to fix it?

like image 212
alexchenco Avatar asked Oct 15 '14 14:10

alexchenco


2 Answers

Your code omits these lines from the original example:

s = append(s, "d")
s = append(s, "e", "f")

Without these lines, len(s) == 3.

like image 101
Bayta Darell Avatar answered Oct 22 '22 11:10

Bayta Darell


You forgot the append part that grows s.

s = append(s, "d")
s = append(s, "e", "f")
fmt.Println("apd:", s)
like image 4
Ainar-G Avatar answered Oct 22 '22 11:10

Ainar-G