我努力寻找自己的榜样,但是尽管很多问题都非常相似,但我无法理解我在做什么错。
我对golang很陌生,我正在尝试实现生活游戏。
这是我的代码的一部分
// Species struct
type Species struct {
xPos int32
yPos int32
isAlive bool
willChangeState bool
rect sdl.Rect
neighbours []Species
}
type Ecosystem struct {
community []Species
}
func (ecos *Ecosystem) addSpecies(sp Species) {
ecos.community = append(ecos.community, sp)
}
func (s *Species) addNeigbour(neigbour Species) {
s.neighbours = append(s.neighbours, neigbour)
}
我想像此功能那样分配邻居
func (ecos *Ecosystem) distributeNeighbours() {
for _, species := range ecos.community {
for _, potentionalNeighbour := range ecos.community {
if math.Abs(float64(species.xPos-potentionalNeighbour.xPos)) <= speciesSize && math.Abs(float64(species.yPos-potentionalNeighbour.yPos)) <= speciesSize {
if species.xPos == potentionalNeighbour.xPos && species.yPos == potentionalNeighbour.yPos {
continue
}
species.addNeigbour(potentionalNeighbour)
}
}
fmt.Println(len(species.neighbours)) // works here
}
for _, s := range ecos.community {
fmt.Println(len(s.neighbours)) //prints 0
}
}
所以我想我必须使用指针来管理它-一些问题,例如第一个循环中的物种是社区中该物种的副本,因此原始物种不会获得任何邻居。但是我不知道如何解决。
答案 0 :(得分:1)
尝试像这样的指针切片:
// Species struct
type Species struct {
xPos int32
yPos int32
isAlive bool
willChangeState bool
rect sdl.Rect
neighbours []*Species
}
type Ecosystem struct {
community []*Species
}