SJC
SJC

Reputation: 652

Casting Interface{} to specific Type

I'm trying to make a generic function for saving to the datastore. The second of the following two examples works, but the first gives me a "datastore: invalid entity type" error.

I'm vastly ignorant about Go at the moment, but attempting to decrease my ignorance. Is there some way to cast object in the first example into a type the name of which is held in a string. Eg some kind of reflection. I tried reflect.ValueOf, but failed with it.

Thanks in advance

Example 1:

func save(kind string, c.appengine.Context, object interface{}) {
    k := datastore.NewKey(c, kind, "some_key", 0, nil)
    _, err := datastore.Put(c, k, &object)
}
save("MyType", c, someMyTypeObject)

Example2:

func save(kind string, c.appengine.Context, object MyType) {
    k := datastore.NewKey(c, kind, "some_key", 0, nil)
    _, err := datastore.Put(c, k, &object)
}
save("MyType", c, someMyTypeObject)

Upvotes: 0

Views: 128

Answers (1)

user2172816
user2172816

Reputation: 1200

datastore.Put takes a struct pointer as its 3rd parameter, but you are passing a pointer to an interface which is invalid in this case.

To get around this, you need to pass a pointer when calling save and pass that as is to datastore.Put.

func save(kind string, c appengine.Context, object interface{}) {
    k := datastore.NewKey(c, kind, "some_key", 0, nil)
    _, err := datastore.Put(c, k, object)
}
save("MyType", c, &someMyTypeObject)

You can think of this as passing someMyTypeObject to datastore.Put via save without save knowing what it is.

Upvotes: 1

Related Questions