英文:
Modifying a struct slice within a struct in Go
问题
在下面的示例中,一个 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)
}
以下是翻译好的代码部分,不包括问题部分。
英文:
In the following example, a person
has a slice of friendship
s, and I try to initialize a friendship
as a pointer to another person
object, but for some reason it fails, and the result is that nobody has any friendship
s. Am I not using a pointer somewhere where I should be?
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
得分: 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]
的副本,对切片people
的addFriends
操作没有影响。
英文:
use
for i := 0; i < numPeople; i++ {
people[i].addFriends(possibleFriends, 2)
}
or
for i, _ := range people {
people[i].addFriends(possibleFriends, 2)
}
instead of
for _, p := range people {
p.addFriends(possibleFriends, 2)
}
this is because p
is a copy of people[i]
, addFriends
has no effect on slice people
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论