I'm trying to learn Golang so I'm writing a "game".
The rooms in the game need to access each other for purposes of sending players to / from rooms. However, I am getting a stack overflow error.
I think I understand why it's happening, but I'm not sure how to resolve it.
I believe it's happening because when I access room1, it tries to initialize room2 which then tries to initilize another room1 which then tries to initilize another room2 forever.
I thought my GetRoom method would save the room's address in memory to an object after it's initialized but it doesn't appear to do what I thought it would.
Any advice would be appreciated.
package main
import "fmt"
type Room struct {
accesses []*Room
}
type World struct {
rooms map[string]*Room
}
func (w *World) GetRoom(name string) *Room {
if room, ok := w.rooms[name]; ok {
return room
} else {
switch name {
case "room1":
w.rooms[name] = NewRoom1(w)
case "room2":
w.rooms[name] = NewRoom2(w)
default:
panic("Room not found")
}
return w.rooms[name]
}
}
func NewRoom1(w *World) *Room {
return &Room{
accesses: []*Room{
w.GetRoom("room2"),
},
}
}
func NewRoom2(w *World) *Room {
return &Room{
accesses: []*Room{
w.GetRoom("room1"),
},
}
}
func main() {
world := World{
rooms: make(map[string]*Room),
}
room := world.GetRoom("room1")
fmt.Println(room)
}
GetRoommethod would save the rooms address in memory to an object after its initialized" it would ifGetRoomever returned, but it never gets past the call toNewRoom*which is before theroomsentry gets defined. I'd makeaccessesa slice of strings and just access the room by name, or initialize an emptyRoomand populateaccesseslater.