无法在 google 的数据存储中存储字节数组

Can't store byte array in google's datastore

我在我的 Go 应用程序中使用 Google 的数据存储。我有一个 Song 结构,它有一个 uuid.UUID 字段。

type Song struct {
    ID: uuid.UUID
    Title: string
    ...
}

这个UUID取自github.com/satori/go.uuid,定义为

type UUID [16]byte

数据存储区似乎无法处理字节数组,但在此用例中只能处理字节切片或字符串。在 json 包中,我可以使用标签将其解释为字符串

type Song struct {
    ID: uuid.UUID `json:"id,string"`
    ....
}

有没有办法告诉数据存储将 UUID 解释为 slice/string,或者我是否必须放弃 "type"-safety 而只存储字符串或使用自定义 PropertyLoadSaver?

根据 Google's Documentation:

Valid value types are:

  • signed integers (int, int8, int16, int32 and int64),
  • bool,
  • string,
  • float32 and float64,
  • []byte (up to 1 megabyte in length),
  • any type whose underlying type is one of the above predeclared types,
  • ByteString,
  • *Key,
  • time.Time (stored with microsecond precision),
  • appengine.BlobKey,
  • appengine.GeoPoint,
  • structs whose fields are all valid value types,
  • slices of any of the above.

因此,您将不得不使用字节切片或字符串。当您需要进行设置或获得类似 (Playground Example):

时,您可以在幕后进行一些操作
type uuid [16]byte

type song struct {
    u []byte
}

func main() {
    var b [16]byte
    copy(b[:], "0123456789012345")

    var u uuid = uuid(b) //this would represent when you get the uuid

    s := song{u: []byte(u[:])}

    copy(b[:], s.u)
    u = uuid(b)
    fmt.Println(u)
}

这也可以通过方法来完成。 (Playground example)

或者,您可以拥有一个特定于携带字节切片的数据存储的实体,并且进出该实体的转换器知道如何进行转换。