簡體   English   中英

附加到 golang 中的 struct slice

[英]Append to struct slice in 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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM