Google app engine 在Google App Engine for Go中,一个属性如何具有多种类型的值?

Google app engine 在Google App Engine for Go中,一个属性如何具有多种类型的值?,google-app-engine,go,google-cloud-datastore,Google App Engine,Go,Google Cloud Datastore,Go的谷歌应用引擎说,“ 属性可以有多种类型的值“。没有例子或进一步的解释。(版本:appengine 1.9.19) 如果必须在支持结构中声明具有特定类型的属性,那么属性如何具有多个类型?您不必为支持结构中的属性声明特定类型 通过实现该接口,您可以在加载期间或保存之前动态地处理实体的属性。请参阅其中显示如何将实体表示为Go中的常规map[string]接口{}类型,以便它可以具有动态属性 回到你的问题: 属性可以具有多种类型的值 这是真的。但是,如果您想实现这一点,还必须通过PropertyL

Go的谷歌应用引擎说,“ 属性可以有多种类型的值“。没有例子或进一步的解释。(版本:appengine 1.9.19)


如果必须在支持结构中声明具有特定类型的属性,那么属性如何具有多个类型?

您不必为支持结构中的属性声明特定类型

通过实现该接口,您可以在加载期间或保存之前动态地处理实体的属性。请参阅其中显示如何将实体表示为Go中的常规
map[string]接口{}
类型,以便它可以具有动态属性

回到你的问题: 属性可以具有多种类型的值

这是真的。但是,如果您想实现这一点,还必须通过
PropertyLoadSaver
接口使用自定义加载/保存机制

首先定义一个backing
struct
,其中具有多个不同类型值的属性可以是一个
[]接口{}

type MyMy struct {
    Objects []interface{}
}
接下来,我们必须实现
PropertyLoadSaver
。加载时,我们只需将所有值附加到名为
“Objects”
对象
切片

保存时,我们将在
对象
切片的元素上循环,并发送具有相同属性名的所有值。这将确保它们保存在同一属性下,我们还必须将
多个
字段指定为
(多值属性):

func (m *MyMy) Load(ch <-chan datastore.Property) error {
    for p := range ch { // Read until channel is closed
        if p.Name == "Objects" {
            m.Objects = append(m.Objects, p.Value)
        }
    }
    return nil
}

func (m *MyMy) Save(ch chan<- datastore.Property) error {
    defer close(ch)
    for _, v := range m.Objects {
        switch v2 := v.(type) {
        case int64: // Here v2 is of type int64
            ch <- datastore.Property{Name: "Objects", Value: v2, Multiple: true}
        case string:  // Here v2 is of type string
            ch <- datastore.Property{Name: "Objects", Value: v2, Multiple: true}
        case float64: // Here v2 is of type float64
            ch <- datastore.Property{Name: "Objects", Value: v2, Multiple: true}
        }
    }
    return nil
}
m := MyMy{[]interface{}{int64(1234), "strval", 32.2}}
key, err := datastore.Put(c, datastore.NewIncompleteKey(c, "MyMy", nil), &m)