简体   繁体   中英

Modifying a struct slice within a struct in Go

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)
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM