gpt4 book ai didi

go - 无法将字节数组存储在谷歌的数据存储中

转载 作者:IT王子 更新时间:2023-10-29 01:58:06 24 4
gpt4 key购买 nike

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

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

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

type UUID [16]byte

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

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

有没有办法告诉数据存储将 UUID 解释为 slice/字符串,或者我是否必须放弃“类型”-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.

因此,您将不得不使用字节 slice 或字符串。当您需要进行设置或获得类似 (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 )

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

关于go - 无法将字节数组存储在谷歌的数据存储中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43549905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com