dsolwotv00116 2016-08-02 19:30
浏览 69
已采纳

转到-在结构上追加到切片不会持久

I have a hard time understanding what seems to be a pretty basic operation. I want to create two structs, where one of the structs will hold a slice of another struct. Here' a simple example to illustration the problem:

// Post structure
type Post struct {
    User string `bson:"user"`
    Body string `bson:"body"`
}

// User structure
type User struct {
    Name  string `bson:"name"`
    Posts []Post `bson:"posts"`
}

func (u *User) appendPost(post Post) []Post {
    u.Posts = append(u.Posts, post)
    return u.Posts
}

func main() {
    p1 := Post{User: "Jane", Body: "First Jane's post"}
    u := User{Name: "Jane"}

    users := []User{}
    users = append(users, u)

    for _, user := range users {
        user.appendPost(p1)
    }

    // [{Jane []}]
    fmt.Println(users)
}

This code produces no errors and also no effect. If I initialize and append a user with the predefined post like this: u := User{Name: "Jane", Posts: []Post{p1}} - everything works as expected. But I can't figure out why the same operation doesn't work in a two steps: 1. Create user with only Name and later append posts in a for loop. Thanks in advance.

This code on the playground

  • 写回答

1条回答 默认 最新

  • dongmeiran609914 2016-08-02 19:33
    关注

    for loop used with range creates a copy of the slice variable. So user above in your for loop is a copy of the User object in your users slice. It's this copy that's getting updated and the reason why you don't see any effect on the desired value. Try rhis:

    for i, _ := range users {
        // users[i] now refers to the actual User object in the slice
        users[i].appendPost(p1)
    }
    

    Demo: https://play.golang.org/p/CLkNQ2oh0O

    Check out For Statement in the language specs here.

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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化