gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:40:50 25 4
gpt4 key购买 nike

结构datastore.Entity看起来非常有用,这就是我想要处理实体的方式,但我没有看到任何使用它的 API。大多数函数(例如 Get)采用一个接口(interface){},它似乎只有在其结构精确与传入数据类似时才有效。 p>

// 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 的实例?)

最佳答案

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

这是你如何使用它:

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

相关文档来自datastore :

Properties

An entity's contents can be represented by a variety of types. These are typically struct pointers, but can also be any type that implements the PropertyLoadSaver interface. If using a struct pointer, you do not have to explicitly implement the PropertyLoadSaver interface; the datastore will automatically convert via reflection. If a struct pointer does implement that interface then those methods will be used in preference to the default behavior for struct pointers. Struct pointers are more strongly typed and are easier to use; PropertyLoadSavers are more flexible.

所以你可以使用任何实现 datastore.PropertyLoadSaver 的类型界面。这个接口(interface)类型是:

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

再次引用 package doc :

The PropertyLoadSaver Interface

An entity's contents can also be represented by any type that implements the PropertyLoadSaver interface. This type may be a struct pointer, but it does not have to be. The datastore package will call Load when getting the entity's contents, and Save when putting the entity's contents. Possible uses include deriving non-stored fields, verifying fields, or indexing a field only if its value is positive.

[...] The *PropertyList type implements PropertyLoadSaver, and can therefore hold an arbitrary entity's contents.

关于go - 有没有办法在不使用自定义结构的情况下检索实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52284710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com