在以下示例中,person
有friendship
个片段,我尝试初始化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)
}
答案 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)
}
这是因为p
是people[i]
的副本,addFriends
对切片people
没有影响