如何通过引用传递结构体数组作为接口

我正在尝试读取给定Firestore集合下的所有文档,并将这些文档作为struct数组返回。函数内的日志将数据作为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接口绝对是一个包含元素的数组,结果仍然是一个空数组。

beixiaonuan 回答:如何通过引用传递结构体数组作为接口

感谢@mkopriva,以下代码有效:

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
    }
本文链接:https://www.f2er.com/3153591.html

大家都在问