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
}
What are you doing is "Hey go make a variable r that is a slice of pointers from the Room Struct" r:= []*Room{}" and then using on the For, so is basic trying to access a position in memory that doesn't exist in that context.
So you need to append into that slice, like r = append(r,&Room{})