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

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

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,但仍然遇到相同的错误。

func roomsInit() ([]*Room, error) {
	r := []*Room{}
	roomdoc, err := readLines("/usr/go/src/gopherit/GopherIT/roomdoc.txt")
	if err != nil {
		return r, err
	}
	i := 0
	index := 1
	for _, str := range roomdoc {
		if i == 0 {
			r[index].roomInitId(str)
			i++
		}
		if i == 1 {
			r[index].roomInitDesc(str)
			i++
		}
		if i == 2 {
			vri := strings.Split(str, ":")
			v, ri := vri[0], vri[1]
			r[index].addLink(v, ri)
			i++
		}
		if i == 3 {
			index++
			i = 0
		}
	}
	return r, err
}
英文:

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.

	r:= []*Room{}
	roomdoc, err := readLines("/usr/go/src/gopherit/GopherIT/roomdoc.txt")
	if err != nil {
		return r, err
	}
	i := 0
	index := 1
	for _, str := range roomdoc {
		if i == 0 {
			r[index].roomInitId(str)
			i++
		}
		if i == 1 {
			r[index].roomInitDesc(str)
			i++
		}
		if i == 2 {
			vri := strings.Split(str, ":")
			v, ri := vri[0], vri[1]
			r[index].addLink(v, ri)
			i++
		}
		if i == 3 {
			index++
			i = 0
		}

	}
	return r, err
}

</details>


# 答案1
**得分**: 0

你正在做的是"嘿,创建一个名为r的变量,它是Room结构体指针的切片",即r:= []*Room{},然后在for循环中使用它,基本上是试图访问在该上下文中不存在的内存位置。

所以你需要将元素追加到该切片中,像这样:```r = append(r, &Room{})```

<details>
<summary>英文:</summary>

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. 

So you need to append into that slice, like ``` r = append(r,&amp;Room{})```  

</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:

确定