Go Google 数据存储空值

Go Google Datastore nulls

我的数据存储对象如下所示:

created (timestamp)
guid (string)
details (string)
start (string)
end (string

通常,detailsstartendNULL

在 Go 中,我正在尝试这样做:

    type Edge struct {
        created   time.Time
        details   string `datastore: "details,omitempty"`
        guid      string `datastore: "guid,omitempty"`
        start     string `datastore: "start,omitempty"`
        end       string `datastore: "end,omitempty"`
    }

    for t := client.Run(ctx, q); ; {
        var x Edge
        key, err := t.Next(&x)
        if err == iterator.Done {
            break
        }
        if err != nil {
            fmt.Printf("error caught: %v\n\n", err)
        }
        fmt.Printf("Key=%v\nEdge=%#v\n\n", key, x)
    }

输出错误总是类似于:

error caught: datastore: cannot load field "guid" into a "main.Edge": no such struct field

Key=/edges,4503602429165568
Edge=main.Edge{created:time.Time{wall:0x0, ext:0, loc:(*time.Location)(nil)}, details:"", guid:"", start:"", end:""}

当我在数据存储控制台中搜索该键时,我发现 guid 是一个有效的 string

GetAll 给了我几乎同样的问题。

我的问题是:

谢谢。

立即突出的两个问题:

  1. 必须导出结构字段,因此名称以大写字母开头。
  2. 您的 tag values 是 "invalid"(他们不遵循惯例)。您不能在键 datastore: 和值 "details,omitempty" 之间留下 space。

所以使用下面的结构定义:

type Edge struct {
    Created time.Time `datastore:"created"`
    Details string    `datastore:"details,omitempty"`
    Guid    string    `datastore:"guid,omitempty"`
    Start   string    `datastore:"start,omitempty"`
    End     string    `datastore:"end,omitempty"`
}

以上2个问题见类似问题:

如果数据存储中的 属性 是 null,这对于 Go 结构来说不是问题。在这种情况下,相应的结构字段将是其类型的 zero-value,在 string 类型的情况下是空字符串 ""。如果您希望能够区分 Datastore null、Datastore "missing property" 和实际的空字符串 "",您可以将字段类型更改为指针(如 *string), 在这种情况下,缺失的 属性 和 null 值将对应于一个 nil 指针值,而一个现有但为空的字符串值将是一个非 nil指向空字符串值的指针。