我正在嘗試創(chuàng)建一個采用接口而不是特定類型并調(diào)用 FindOne 函數(shù)的函數(shù)。有誰知道為什么 printFirstTrainerByInterface 函數(shù)不能正常工作?我正在使用官方的 Go Mongo-Driver 和來自mongodb-go-driver-tutorial 的示例片段。package mainimport ( "context" "fmt" "log" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options")type Trainer struct { Name string Age int City string}var db *mongo.Databasefunc main() { opts := options.Client().ApplyURI("mongodb://localhost:27017") client, err := mongo.Connect(context.TODO(), opts) if err != nil { log.Fatal(err) } err = client.Ping(context.TODO(), nil) if err != nil { log.Fatal(err) } db = client.Database("test") insertTestDocument() var result Trainer printFirstTrainer(result) var result2 Trainer printFirstTrainerByInterface(&result2)}func insertTestDocument() { ash := Trainer{"Ash", 10, "Pallet Town"} res, err := db.Collection("trainers").InsertOne(context.TODO(), ash) if err != nil { log.Fatal(err) } fmt.Println("Inserted a test document: ", res.InsertedID)}func printFirstTrainer(result Trainer) { collection := db.Collection("trainers") err := collection.FindOne(context.TODO(), bson.M{}).Decode(&result) if err != nil { log.Fatal(err) } fmt.Printf("Found a single document: %+v\n", result)}func printFirstTrainerByInterface(result interface{}) { collection := db.Collection("trainers") err := collection.FindOne(context.TODO(), bson.M{}).Decode(&result) if err != nil { log.Fatal(err) } fmt.Printf("Found a single document: %+v\n", result)}輸出:Inserted a test document: ObjectID("5e8216f74f41a13f01061d61")Found a single document: {Name:Ash Age:10 City:Pallet Town}Found a single document: [{Key:_id Value:ObjectID("5e8216f74f41a13f01061d61")} {Key:name Value:Ash} {Key:age Value:10} {Key:city Value:Pallet Town}]
1 回答

GCT1015
TA貢獻(xiàn)1827條經(jīng)驗 獲得超4個贊
您將要解碼的結(jié)構(gòu)的地址作為接口傳遞。您必須將其作為參數(shù)傳遞給解碼,而不是接口的地址。嘗試:
err := collection.FindOne(context.TODO(), bson.M{}).Decode(result)
- 1 回答
- 0 關(guān)注
- 212 瀏覽
添加回答
舉報
0/150
提交
取消