Go必须采用什么方法轻松地将数据转换为字节或字符串

I've been developing a couple apps using Google App Engine Go SDK that use Memcache as a buffer for loading data from the Datastore. As the Memcache is only able to store data as []byte, I often find myself creating functions to encode the various structures as strings, and also functions to reverse the process. Needless to say, it is quite tedious when I need to do this sort of thing 5 times over.

Is there an easy way to convert any arbitrary structure that can be stored in Datastore into []byte in order to store it in Memcache and then load it back without having to create custom code for various structures in GAE Golang?

http://golang.org/pkg/encoding/gob or http://golang.org/pkg/encoding/json can turn arbitrary datatypes into []byte slices given certain rules apply to the datastructures being encoded. You probably want one of them gob will encode to smaller sizes but json is more easily shareable with other languages if that is a requirement.

I found myself needing the same thing. So I created a package called:

AEGo/ds

Documentation | Source

go get github.com/scotch/aego/ds

It uses the same API as the "appengine/datastore" so It will work as a drop in replacement.

import "github.com/scotch/aego/v1/ds"

u = &User{Name: "Bob"}
key := datastore.NewKey(c, "User", "bob", 0, nil)
key, err := ds.Put(c, key, u)

u = new(User)
err = ds.Get(c, key, u)

By default it will cache all Puts and Gets to memcache, but you can modify this behavior by calling the ds.Register method:

ds.Register("User", true, false, false)

The Register method takes a string representing the Kind and 3 bool - userDatastore, useMemcache, useMemory. Passing a true value will cause AEgo/ds to persist the record to that store. The Memory store is useful for records that you do not expect to change, but could contain stale data if you have more then one instance running.

Supported methods are:

Put
PutMulti
Get
GetMulti
Delete
DeleteMulti
AllocateIDs

Note: Currently cashing only occures with Get. GetMulti pulls from the datastore.

AEGo/ds is a work in progress, but the code is well tested. Any feedback would be appreciated.

And to answer you question here's how I serialized the entities to gob for the memcache persistence.