卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64334本站已运行4115

将 firestore“integer_value”转换为整数

将 firestore“integer_value”转换为整数

问题内容

使用 golang firestore 1.8 库,我尝试使用 google 去年秋天推出的 firestore 的新 count() 函数。这些文档似乎还没有示例,不是我发现的,但我拼凑了一些有点可行的代码,这些代码几乎让我完成了所有工作,只是没有实际生成一个整数。该片段底部的“result[usercountalias]”值是我感兴趣的转换为整数的值,但我不太确定如何转换。当然,我可以将它作为一个字符串,在冒号上拆分,然后解析它,但这看起来很难看。

任何提示将不胜感激!

非常感谢。

func (s UserService) Count(labID string) (int64, error) {

    if s.DB == nil {
        return -1, customerrors.ErrDatabaseMissing
    }

    query := s.DB.
        Collection(CollectionUsers).
        Where("lab_id", "==", labID)


    userCountAlias := "userCount"

    ag := query.NewAggregationQuery()

    //result is a firestore.AggregationResult, which seems to consist of just a 
    //map[string]interface{}
    result, err := ag.WithCount(userCountAlias).Get(s.Ctx)

    if err != nil {
        return -1, err
    }

    v := result[userCountAlias]//How do I cast this to an integer?
    fmt.Printf("Type = %v", v) //Prints "Type = integer_value:379"

    return -1, nil
}


正确答案


尝试 fmt.printf("type = %t", v) 找出 v 的类型。

v 最有可能是 firestorepb.value。请注意,这在 1.8 中尚不可用。尝试将 cloud.google.com/go/firestore 升级到最新版本(目前为 1.9)。

package main

import (
    "fmt"

    "cloud.google.com/go/firestore/apiv1/firestorepb"
)

func main() {
    var v interface{} = &firestorepb.Value{
        ValueType: &firestorepb.Value_IntegerValue{
            IntegerValue: 379,
        },
    }

    fmt.Printf("%Tn", v) // *firestorepb.Value
    fmt.Printf("%vn", v) // integer_value:379

    if v, ok := v.(*firestorepb.Value); ok {
        fmt.Printf("%vn", v.GetIntegerValue()) // 379
    }
}

官方存储库中的测试以相同的方式检索值。请参阅 testintegration_countaggregationquery。

卓越飞翔博客
上一篇: 使用通道更快地关闭 goroutine
下一篇: Golang 上下文切换
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏