索引超出范围 [1],长度为0。

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

Index out of range [1] with length 0

问题

我正在使用Go语言编写一个小型MUD游戏,并尝试从文件中读取一系列带有出口的房间。

我期望代码能够遍历文件的每一行,将索引为1的行填充到房间ID中,将索引为2的行填充到房间描述中,将索引为3的行填充到房间的链接中。然而,当我运行代码时,出现了一个错误:panic: runtime error: index out of range [1] with length 0。我已经思考了两天,但没有找到解决办法,希望能得到帮助。

编辑:我尝试使用r:= []*Room{}来初始化r,但仍然遇到相同的错误。

  1. func roomsInit() ([]*Room, error) {
  2. r := []*Room{}
  3. roomdoc, err := readLines("/usr/go/src/gopherit/GopherIT/roomdoc.txt")
  4. if err != nil {
  5. return r, err
  6. }
  7. i := 0
  8. index := 1
  9. for _, str := range roomdoc {
  10. if i == 0 {
  11. r[index].roomInitId(str)
  12. i++
  13. }
  14. if i == 1 {
  15. r[index].roomInitDesc(str)
  16. i++
  17. }
  18. if i == 2 {
  19. vri := strings.Split(str, ":")
  20. v, ri := vri[0], vri[1]
  21. r[index].addLink(v, ri)
  22. i++
  23. }
  24. if i == 3 {
  25. index++
  26. i = 0
  27. }
  28. }
  29. return r, err
  30. }
英文:

I'm working ona little MUD in Go, and I'm trying to read a list of rooms with exits from a file.
I expect the code to iterate through the lines of the file, filing every line with the index 1 to the room ID, every line with the index 2 to the room Description and every line wit the index 3 to be used to fill in the room's links. However when I run the code, i get a panic: runtime error: indext out of range[1] with length 0. I've been mulling over this for two days with no luck, any help would be mucho appreciado.

Edit: tried initializing r with r:= []*Room{} but am still getting the same error.

  1. r:= []*Room{}
  2. roomdoc, err := readLines("/usr/go/src/gopherit/GopherIT/roomdoc.txt")
  3. if err != nil {
  4. return r, err
  5. }
  6. i := 0
  7. index := 1
  8. for _, str := range roomdoc {
  9. if i == 0 {
  10. r[index].roomInitId(str)
  11. i++
  12. }
  13. if i == 1 {
  14. r[index].roomInitDesc(str)
  15. i++
  16. }
  17. if i == 2 {
  18. vri := strings.Split(str, ":")
  19. v, ri := vri[0], vri[1]
  20. r[index].addLink(v, ri)
  21. i++
  22. }
  23. if i == 3 {
  24. index++
  25. i = 0
  26. }
  27. }
  28. return r, err
  29. }
  30. </details>
  31. # 答案1
  32. **得分**: 0
  33. 你正在做的是"嘿,创建一个名为r的变量,它是Room结构体指针的切片",即r:= []*Room{},然后在for循环中使用它,基本上是试图访问在该上下文中不存在的内存位置。
  34. 所以你需要将元素追加到该切片中,像这样:```r = append(r, &Room{})```
  35. <details>
  36. <summary>英文:</summary>
  37. What are you doing is &quot;Hey go make a variable r that is a slice of pointers from the Room Struct&quot; r:= []*Room{}&quot; and then using on the For, so is basic trying to access a position in memory that doesn&#39;t exist in that context.
  38. So you need to append into that slice, like ``` r = append(r,&amp;Room{})```
  39. </details>

huangapple
  • 本文由 发表于 2021年8月2日 01:52:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/68613015.html
匿名

发表评论

匿名网友

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

确定