Question:
How can I use nested structs with the Google App Engine (GAE) datastore when working with Go?
Answer:
The Datastore API in Go does not directly support nested structs. However, a solution is to utilize the PropertyLoadSaver interface provided by the API.
Implementation:
Example:
<code class="go">type Post struct { Field1 string Field2 string User User } type User struct { UserField1 string UserField2 string } func (p Post) Load(ps []Property) error { for _, prop := range ps { switch prop.Name { case "Field1": p.Field1 = prop.Value.(string) case "Field2": p.Field2 = prop.Value.(string) case "User": if err := prop.Load(&p.User); err != nil { return err } } } return nil } func (p Post) Save() ([]Property, error) { props := []Property{ {Name: "Field1", Value: p.Field1}, {Name: "Field2", Value: p.Field2}, } pLoad, err := appengine.Datastore().SaveStruct(p.User) if err != nil { return nil, err } props = append(props, pLoad...) return props, nil } // Usage key := datastore.NewKey("Post", "someID", nil) _, err := datastore.Put(ctx, key, &post)</code>
This implementation allows you to store and retrieve nested structs in a structured way, while still benefiting from Datastore's filtering and query capabilities.
The above is the detailed content of How do I work with nested structs in the Google App Engine (GAE) Datastore using Go?. For more information, please follow other related articles on the PHP Chinese website!