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

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

如何通過引用將結構數組作為接口傳遞

如何通過引用將結構數組作為接口傳遞

Go
ABOUTYOU 2023-07-31 17:15:27
我正在嘗試讀取給定 Firestore 集合下的所有文檔并將文檔作為結構數組返回。函數內的日志將數據輸出為Firestore文檔,但函數外的struct數組始終是空數組。讀取集合下所有文檔的功能。func (fc *FirebaseClient) ReadCollection(collectionPath string, objects interface{}) error {    ctx := context.Background()    opt := option.WithCredentialsJSON([]byte(os.Getenv("FIREBASE_CREDENTIALS")))    client, err := firestore.NewClient(ctx, os.Getenv("FIREBASE_PROJECT_ID"), opt)    if err != nil {        return err    }    defer client.Close()    collectionRef := client.Collection(collectionPath)    docs, err := collectionRef.DocumentRefs(ctx).GetAll()    if err != nil {        return err    }    log.Printf("Total documents: %i", len(docs))    objs := make([]interface{}, len(docs))    for i, doc := range docs {        docsnap, err := doc.Get(ctx)        if err != nil {            return err        }        if err := docsnap.DataTo(&objs[i]); err != nil {            return err        }        log.Printf("obj: %v", objs[i])    }    objects = objs    log.Printf("objects: %v", objects)    return nil}調用函數的代碼    var ss []SomeStruct    fc := new(insightech.FirebaseClient)    if err := fc.ReadCollection("mycollection", ss); err != nil {        return    }ss始終是一個空數組。我不想指定結構類型的原因是使 ReadCollection 函數通用,這樣我就可以調用它來讀取不同的集合。該代碼不會觸發任何錯誤,但結果是一個空數組,即使接口objects肯定是一個包含元素的數組。
查看完整描述

1 回答

?
長風秋雁

TA貢獻1757條經驗 獲得超7個贊

以下代碼可以運行:


func (fc *FirebaseClient) ReadCollection(collectionPath string, objects interface{}) error {

    ctx := context.Background()

    opt := option.WithCredentialsJSON([]byte(os.Getenv("FIREBASE_CREDENTIALS")))

    client, err := firestore.NewClient(ctx, os.Getenv("FIREBASE_PROJECT_ID"), opt)

    if err != nil {

        return err

    }

    defer client.Close()


    collectionRef := client.Collection(collectionPath)

    docs, err := collectionRef.DocumentRefs(ctx).GetAll()

    if err != nil {

        return err

    }

    log.Printf("Total documents: %i", len(docs))


    dest := reflect.ValueOf(objects).Elem()



    log.Printf("dest: %v", dest)

    for _, doc := range docs {

        docsnap, err := doc.Get(ctx)

        if err != nil {

            return err

        }


        obj := reflect.New(dest.Type().Elem())


        if err := docsnap.DataTo(obj.Interface()); err != nil {

            return err

        }

        log.Printf("obj: %v", obj)

        dest = reflect.Append(dest, obj.Elem())



    }


    reflect.ValueOf(objects).Elem().Set(dest)

    log.Printf("objects: %v", dest)

    return nil

}

    var ss []SomeStruct


    fc := new(insightech.FirebaseClient)

    if err := fc.ReadCollection("mycollection", &ss); err != nil {

        return

    }


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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