簡體   English   中英

panic:運行時錯誤:切片范圍超出范圍

[英]panic: runtime error: slice bounds out of range

我正在關注本教程: 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

這是什么意思? 教程錯了嗎? 我該怎么辦才能修復它?

你忘了了增長s append部分。

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

您的代碼省略了原始示例中的這些行:

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

沒有這些行,len(s)== 3。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM