【问题标题】:panic: runtime error: slice bounds out of range恐慌:运行时错误:切片超出范围
【发布时间】:2014-10-15 14:35:51
【问题描述】:

我正在关注本教程:https://gobyexample.com/slices

我在中间:

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)
}

当我突然遇到这个错误时:

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

这是什么意思?教程有误吗?我能做些什么来解决它?

【问题讨论】:

    标签: go slice


    【解决方案1】:

    您的代码从原始示例中省略了这些行:

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

    没有这些行,len(s) == 3。

    【讨论】:

      【解决方案2】:

      您忘记了 append 增长的部分 s

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

      【讨论】:

        猜你喜欢
        • 2015-11-21
        • 1970-01-01
        • 1970-01-01
        • 2017-05-12
        • 1970-01-01
        • 1970-01-01
        • 2014-11-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多