恐慌:运行时错误:切片边界超出范围

huangapple go评论91阅读模式
英文:

panic: runtime error: slice bounds out of range

问题

这个错误是由于切片的索引超出范围导致的。在你的代码中,你尝试访问 s 的索引为 2 到 5 的元素,但是 s 的长度只有 3。所以当你尝试访问 s[2:5] 时,就会出现索引超出范围的错误。

要修复这个问题,你可以先检查切片的长度,确保你的索引在有效范围内。在这个例子中,你可以将 l := s[2:5] 改为 l := s[2:3],这样就不会超出索引范围了。

修复后的代码如下:

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:3] // 修改这里的索引范围
	fmt.Println("sl1:", l)
}

这样修改后,你应该不会再遇到索引超出范围的错误了。

英文:

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?

答案1

得分: 8

你的代码省略了原始示例中的以下几行:

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

没有这些行,len(s)的值为3。

英文:

Your code omits these lines from the original example:

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

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

答案2

得分: 4

你忘记了增加 append 部分来扩展 s

s = append(s, "d")
s = append(s, "e", "f")
fmt.Println("apd:", s)
英文:

You forgot the append part that grows s.

s = append(s, "d")
s = append(s, "e", "f")
fmt.Println("apd:", s)

huangapple
  • 本文由 发表于 2014年10月15日 22:35:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/26385228.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定