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

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

Go 和 MongoDb 錯誤:沒有字段或方法

Go 和 MongoDb 錯誤:沒有字段或方法

Go
夢里花落0921 2021-12-07 16:18:22
我是 Golang 的新手。在嘗試password從 MongoDb 查詢結果中提取時,出現以下錯誤:“./1.go:73: results.password 未定義(類型 []Person 沒有字段或方法密碼)”該錯誤是由代碼中的倒數第二行引起的。我們如何分離查詢結果?代碼:package mainimport ("fmt""html/template""log""net/http""reflect""gopkg.in/mgo.v2/bson""gopkg.in/mgo.v2")type login struct {UserName stringPassword  string}type Person struct {ID        bson.ObjectId `bson:"_id,omitempty"`FirstName      string   LastName     string Email       stringPassword    string}func main() {// DB Connectionsession, err := mgo.Dial(":27017")if err != nil {    panic(err)}defer session.Close()c := session.DB("reg").C("people")session.SetMode(mgo.Monotonic, true)// parse templatetpl, err := template.ParseFiles("Login.html")if err != nil {    log.Fatalln(err)}http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request)    {    // receive form submission    uname := req.FormValue("username")    pwd := req.FormValue("password")    fmt.Println("fName: ", uname)    fmt.Println("[]byte(uname): ", []byte(uname))    fmt.Println("typeOf: ", reflect.TypeOf(uname))            fmt.Println("pwd : ", pwd)    fmt.Println("[]byte(pwd ): ", []byte(pwd))    fmt.Println("typeOf: ", reflect.TypeOf(pwd))    // execute template    err = tpl.Execute(res, login{uname,pwd})    if err != nil {        http.Error(res, err.Error(), 500)        log.Fatalln(err)    }    //DB access    var results []Person    err = c.Find(bson.M{"firstname": uname}).Sort("-id").All(&results)    if err != nil {        panic(err)    }    fmt.Println("Results All: ", results)    //Next Line Causes Error....    fmt.Println("New Password ", results.password)})http.ListenAndServe(":9000", nil)}
查看完整描述

1 回答

?
Qyouu

TA貢獻1786條經驗 獲得超11個贊

您的results變量是Persons 的一部分:


var results []Person

Password是 的一個字段Person。所以這一行:


fmt.Println("New Password ", results.password)

是編譯時錯誤,因為password它不是類型的字段(或方法)[]Person(還要注意與password不同Password)。


您可以像這樣引用切片的第一個元素:


if len(results) > 0 {

    fmt.Println("New Password:", results[0].Password)

} else {

    fmt.Println("No peope")

}


查看完整回答
反對 回復 2021-12-07
  • 1 回答
  • 0 關注
  • 202 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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