将ID添加到数据存储实体的最佳实践?

When creating an entity using an IncompleteKey so that each record is inherently unique, what is the best way to add the key back into the record so it can be passed around in the structure- at the time of creation?

For example, is something like this (untested code) a good idea, using Transactions?

 err = datastore.RunInTransaction(c, func(c appengine.Context) error {
        incompleteKey := datastore.NewIncompleteKey(c, ENTITY_TYPE, nil)
        entityKey, err := datastore.Put(c, incompleteKey, &MyStruct)
        if(err != nil) {
            return err
        }

        MyStruct.SelfID = entityKey.IntID()
        _, err = datastore.Put(c, entityKey, &MyStruct)

        return err
    }, nil)

As a followup- I'm guessing this should almost never fail since it will almost never operate over the same incompleteKey?

You don't need to put the MyStruct into DB twice - it's unnecessary overhead. The key stored as a part of the entity and can be retrieved when needed.

There is a good example in docs on how to store an entity and used it ID as a reference: https://cloud.google.com/appengine/docs/go/datastore/entities#Go_Ancestor_paths

When you want to get keys for entities you can do this using this approach: https://cloud.google.com/appengine/docs/go/datastore/queries#Go_Retrieving_results - (edited) notice in the example that keys and structs are populated in 1 operation.

If you query the an entity by key you already know it ID.

So there is no need to have an ID as a separate property. If you want to pass it around with the entity for your business logic you can create a wrapper - either generalized using interface() for the entity struct or a strongly typed (1 per each entity struct).