问题:append下面的内部Users()for 循环将users3x 中的最后一项添加到userRxs []*UserResolver期待:append应该将里面的每个项目添加users到userRxs []*UserResolver// Users return all users from Dbfunc (r *RootResolver) Users() ([]*UserResolver, error) { var userRxs []*UserResolver users := r.Db.Users() for _, u := range users { log.Printf("userID: %s, username: %s, email: %s, password: %s", u.UserID, u.Username, u.Email, u.Password) userRxs = append(userRxs, &UserResolver{&u}) } log.Printf("%v", userRxs) return userRxs, nil}在 for 循环内,log.Printf打印这个userID: 0374402a-3dc4-48da-86c4-949905ccc26c, username: sunnysan, email: sunnysan@gmail.com, password: 12345678userID: 53f21c4f-2cd8-4e67-b3e9-5ef344806230, username: sunnysan2, email: sunnysan2@gmail.com, password: 12345678userID: 0a47d3af-03dc-4050-a028-7a41599af497, username: sunnysan3, email: sunnysan3@gmail.com, password: 12345678 在 for 循环之后,log.Printf("%v", userRxs)打印这个[ User { userID: 0a47d3af-03dc-4050-a028-7a41599af497, username: sunnysan3, email: sunnysan3@gmail.com, password: 12345678 } User { userID: 0a47d3af-03dc-4050-a028-7a41599af497, username: sunnysan3, email: sunnysan3@gmail.com, password: 12345678 } User { userID: 0a47d3af-03dc-4050-a028-7a41599af497, username: sunnysan3, email: sunnysan3@gmail.com, password: 12345678 }]这是整个文件以获取更多上下文package mainimport ( "fmt" "log" graphql "github.com/graph-gophers/graphql-go")/* * User GQL type type User { userID: ID! username: String! email: String! password: String! }*/// User type should match the exact shape of the schema commented abovetype User struct { UserID graphql.ID Username string Email string Password string}// RootResolver ingests Db to run queries (getters) against ittype RootResolver struct { *Db}
1 回答
汪汪一只猫
TA贡献1898条经验 获得超8个赞
范围变量在每次迭代时都会被覆盖,并且&u是相同的。所以你最终UserResolver会多次附加一个包含相同地址的地址。您需要使用该变量的本地副本。尝试这个:
for _, u := range users {
u:=u // Make a copy of the variable and redeclare it
userRxs = append(userRxs, &UserResolver{&u})
}
- 1 回答
- 0 关注
- 118 浏览
添加回答
举报
0/150
提交
取消
