gpt4 book ai didi

Go - append 到结构上的 slice 不会持续存在

转载 作者:IT王子 更新时间:2023-10-29 01:09:46 25 4
gpt4 key购买 nike

我很难理解看似非常基本的操作。我想创建两个结构,其中一个结构将保存另一个结构的一部分。这是一个简单的例子来说明问题:

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

这段代码没有产生任何错误,也没有任何效果。如果我用这样的预定义帖子初始化并 append 用户:u := User{Name: "Jane", Posts: []Post{p1}} - 一切都按预期进行。但我无法弄清楚为什么相同的操作不能分两步进行:1. 创建只有 Name 的用户,然后在 for 循环中 append 帖子。提前致谢。

This code on the playground

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com