go - 在golang中附加到结构切片
问题描述
我努力寻找我的例子,但尽管一堆问题非常相似,但我无法理解我做错了什么。
我对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
}
}
所以我想我必须用指针来管理它 - 像第一个循环中的物种这样的问题是社区中那个物种的副本,所以原始物种不会获得任何邻居。但我不知道如何解决它。
解决方案
尝试指针切片,如下所示:
// Species struct
type Species struct {
xPos int32
yPos int32
isAlive bool
willChangeState bool
rect sdl.Rect
neighbours []*Species
}
type Ecosystem struct {
community []*Species
}
推荐阅读
- swift - collectionView iOS 13.2 中的 UILongPressGestureRecognizer 位置功能问题
- plsql - 检查 Oracle Apex PL/SQL 中的变量集是否包含 NULL
- css - 有什么方法可以使对话框的页眉和页脚在角材料中具有粘性
- python - 如何在python中使用嵌套的for循环?
- c++ - 使用 __block 时,clang BlocksRuntime 在可执行文件中嵌入“过时编译器”警告
- python - 第一次使用 XGBoost 回归器
- java - 有没有办法使用 Maven 来引用依赖项或 artifactItem 中的特定元素?
- node.js - 实施服务帐户密钥轮换的挑战
- snakemake - Snakemake:我可以在规则之外访问通配符吗?
- android - CardStackView 不能与 Scrollview 一起使用?