有没有办法在不使用自定义结构的情况下检索实体?

问题描述 投票:2回答:1

struct datastore.Entity看起来非常有用,它是我想要处理实体的方式,但我没有看到任何API使用它。大多数函数(例如Get)都使用interface{},如果它的结构与输入数据一样精确,那么它似乎才有效。

// https://godoc.org/cloud.google.com/go/datastore#Client.Get

ctx := context.Background()
client, err := datastore.NewClient(ctx, "project-id")
if err != nil {
    // TODO: Handle error.
}

type Article struct {
    Title       string
    Description string
    Body        string `datastore:",noindex"`
    Author      *datastore.Key
    PublishedAt time.Time
}
key := datastore.NameKey("Article", "articled1", nil)
article := &Article{}
if err := client.Get(ctx, key, article); err != nil {
    // TODO: Handle error.
}

我如何以一般化的方式获得这个实体?如果我不完全了解结构怎么办? (更具体地说,我如何获得datastore.Entity的实例呢?)

go google-cloud-datastore
1个回答
2
投票

所以你想要一个可以容纳任何类型实体的“通用”类型? datastore包已经为您提供了这样一种类型:datastore.PropertyList

这是你如何使用它:

var entity datastore.PropertyList
if err := client.Get(ctx, key, &entity); err != nil {
    // TODO: Handle error.
}

来自datastore的相关文档:

Properties

实体的内容可以用各种类型表示。这些通常是结构指针,但也可以是实现PropertyLoadSaver接口的任何类型。如果使用结构指针,则不必显式实现PropertyLoadSaver接口;数据存储区将通过反射自动转换。如果结构指针确实实现了该接口,那么这些方法将优先于struct指针的默认行为。结构指针的类型更强,更易于使用; PropertyLoadSavers更灵活。

所以你可以使用任何实现datastore.PropertyLoadSaver接口的类型。此接口类型是:

type PropertyLoadSaver interface {
    Load([]Property) error
    Save() ([]Property, error)
}

再次引用package doc

The PropertyLoadSaver Interface

实体的内容也可以由实现PropertyLoadSaver接口的任何类型表示。此类型可能是结构指针,但不一定是。获取实体内容时,数据存储区将调用Load,放置实体内容时将调用Save。可能的用途包括导出非存储字段,验证字段或仅在字段值为正时索引字段。

[...] * PropertyList类型实现了PropertyLoadSaver,因此可以保存任意实体的内容。

© www.soinside.com 2019 - 2024. All rights reserved.