0

In the following example, a person has a slice of friendships, 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 friendships. 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)
}
mgoldwasser
  • 14,558
  • 15
  • 79
  • 103

1 Answers1

2

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

simon_xia
  • 2,394
  • 1
  • 20
  • 32