In Python's App Engine, the Expando Model enables the dynamic assignment of attributes to entities without prior declaration. This article explores how to achieve similar functionality in Go using the Google App Engine Datastore.
The key to defining dynamic entities in Go is the PropertyLoadSaver interface. By implementing this interface, you gain the ability to dynamically construct an entity's properties at save time.
The Go App Engine platform offers the PropertyList type, which is a list of Property instances and implements the PropertyLoadSaver interface. By leveraging PropertyList, you can create dynamic entities without implementing the interface yourself.
props := datastore.PropertyList{ {Name: "time", Value: time.Now()}, {Name: "email", Value: "johndoe@example.com"}, }
To save this list as an entity, you can use:
key, err := datastore.Put(c, k, &props)
For further flexibility, you can implement the PropertyLoadSaver interface on your own custom types, such as maps.
type DynEnt map[string]interface{} func (d *DynEnt) Load(props []datastore.Property) error { for _, p := range props { (*d)[p.Name] = p.Value } return nil } func (d *DynEnt) Save() (props []datastore.Property, err error) { for k, v := range *d { props = append(props, datastore.Property{Name: k, Value: v}) } return }
With this custom implementation, you can now load and save dynamic entities with ease:
d := DynEnt{"email": "johndoe@example.com", "time": time.Now()} key, err := datastore.Put(c, k, &d)
This approach grants you full control over the property definitions of your dynamic entities.
The above is the detailed content of How Can I Create Dynamic Entities in Go\'s Google App Engine Datastore?. For more information, please follow other related articles on the PHP Chinese website!