dongqi8863 2017-03-07 03:42
浏览 39
已采纳

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

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)
}
  • 写回答

1条回答 默认 最新

  • douhei8633 2017-03-07 03:58
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大