drl47263 2017-04-21 18:44
浏览 36
已采纳

无法将字节数组存储在Google的数据存储区中

I'm using Google's datastore in my Go app. I have a Song struct, which has a uuid.UUID field.

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

This UUID is taken from github.com/satori/go.uuid and is defined as

type UUID [16]byte

It seems that datastore can't handle byte arrays but in this use case only byte slices or strings. In the json package I can use a tag to interpret it as a string

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

Is there a way of telling datastore to interpret the UUID as a slice/string or do I either have to give up "type"-safety and just store a string or use a custom PropertyLoadSaver?

  • 写回答

1条回答 默认 最新

  • dongtang2376 2017-04-21 19:50
    关注

    Per 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.

    So, you will have to use a byte slice or string. You could do some behind the scenes manipulation when you need to do your setting or getting like (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)
    }
    

    This could also be done through methods. (Playground example)

    Alternatively, you could have an entity specific to the datastore that carries the byte slice, and the transformers that go to and from that entity know how to do the conversion.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用