在Go中修改结构中的结构切片

时间:2017-03-07 03:42:00

标签: pointers go struct slice

在以下示例中,personfriendship个片段,我尝试初始化friendship作为指向另一个person对象的指针,但是某种原因它失败了,结果就是没有人有friendship个。我不是在我应该去的地方使用指针吗?

package main

import (
    "fmt"
    "math/rand"
)

type friendship struct {
    friend *person
}

type person struct {
    name       int
    friendship []friendship
}

func createPerson(id int) person {
    return person{id, make([]friendship, 0)}
}

func (p *person) addFriends(possibleFriends []*person, numFriends int) {
    var friend *person
    for i := 0; i < numFriends; i++ {
        friend = possibleFriends[rand.Intn(len(possibleFriends))]
        p.friendship = append(p.friendship, friendship{friend})
    }
}

func main() {
    numPeople := 20
    people := make([]person, numPeople)
    possibleFriends := make([]*person, numPeople)
    for i := 0; i < numPeople; i++ {
        people[i] = createPerson(i)
        possibleFriends[i] = &(people[i])
    }
    for _, p := range people {
        p.addFriends(possibleFriends, 2)
    }
    fmt.Println(people)
}

1 个答案:

答案 0 :(得分:2)

使用

for i := 0; i < numPeople; i++ {
        people[i].addFriends(possibleFriends, 2)
}

 for i, _ := range people {
        people[i].addFriends(possibleFriends, 2)
 }

而不是

 for _, p := range people {
        p.addFriends(possibleFriends, 2)
 }

这是因为ppeople[i]的副本,addFriends对切片people没有影响