Reputation: 55323
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?
Upvotes: 13
Views: 80227
Reputation: 121139
Your code omits these lines from the original example:
s = append(s, "d")
s = append(s, "e", "f")
Without these lines, len(s) == 3.
Upvotes: 8
Reputation: 36259
You forgot the append
part that grows s
.
s = append(s, "d")
s = append(s, "e", "f")
fmt.Println("apd:", s)
Upvotes: 4