亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

golang在for循環中追加問題

golang在for循環中追加問題

Go
皈依舞 2022-06-01 16:41:22
問題: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: [email protected], password: 12345678userID: 53f21c4f-2cd8-4e67-b3e9-5ef344806230, username: sunnysan2, email: [email protected], password: 12345678userID: 0a47d3af-03dc-4050-a028-7a41599af497, username: sunnysan3, email: [email protected], password: 12345678 在 for 循環之后,log.Printf("%v", userRxs)打印這個[  User {     userID: 0a47d3af-03dc-4050-a028-7a41599af497,     username: sunnysan3,     email: [email protected],     password: 12345678   }  User {     userID: 0a47d3af-03dc-4050-a028-7a41599af497,     username: sunnysan3,     email: [email protected],     password: 12345678   }  User {     userID: 0a47d3af-03dc-4050-a028-7a41599af497,     username: sunnysan3,     email: [email protected],     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})

    }


查看完整回答
反對 回復 2022-06-01
  • 1 回答
  • 0 關注
  • 100 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號