In Google App Engine for Go, how can a property have values of more than one type? -
the google app engine go datastore docs say, " property can have values of more 1 type". there no example or further explanation. (version: appengine 1.9.19.)
how can property have more 1 type if must declare property specific type in backing struct?
you not have declare specific type property in backing struct.
by implementing propertyloadsaver interface, can dynamically whatever want properties of entity during loading or before saving. see this answer shows how represent entity general map[string]interface{} type in go, can have dynamic properties.
back question:
a property can have values of more 1 type.
this true. if want make work, have utilize custom loading/saving mechanism through propertyloadsaver interface.
first define backing struct property have multiple values of different types may []interface{}:
type mymy struct { objects []interface{} } next have implement propertyloadsaver. when loading, append values objects slice come name "objects".
when saving, loop on elements of objects slice , send values same property name. ensure saved under same property, , have specify multiple field true (multi-value property):
func (m *mymy) load(ch <-chan datastore.property) error { p := range ch { // read until channel 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) _, v := range m.objects { switch v2 := v.(type) { case int64: // here v2 of type int64 ch <- datastore.property{name: "objects", value: v2, multiple: true} case string: // here v2 of type string ch <- datastore.property{name: "objects", value: v2, multiple: true} case float64: // here v2 of type float64 ch <- datastore.property{name: "objects", value: v2, multiple: true} } } return nil } note setting value of type interface{} property.value result in error, why used type switch set concrete types. in example supported 3 types (int64, string , float64) can add more types adding new case branches.
and using it:
and using our custom mymy type save new entity property "objects" have multiple values , of different types:
m := mymy{[]interface{}{int64(1234), "strval", 32.2}} key, err := datastore.put(c, datastore.newincompletekey(c, "mymy", nil), &m)
Comments
Post a Comment