Go:如何将struct转换为[] byte?

时间:2013-04-20 22:36:02

标签: google-app-engine go

我正在尝试使用“appengine / memcache”将数据存储在缓存中, memcache.Item的Value字段是[] byte

如何将结构转换为[]字节以进行存储?

例如:

type Link struct {
    Files []string
}

3 个答案:

答案 0 :(得分:9)

请参阅memcache.Codec类型,这可用于转换memcache项。 appengine / memcache包有两个已编写的编解码器,memcache.Gob和memcache.JSON。您可以使用这些编解码器代替直接调用来存储和检索缓存中的项目,例如像gob编码的项目一样:

    item := &memcache.Item{
        Key:    myCacheKey,
        Object: &myLinkVar,
    }
    err := memcache.Gob.Set(context, item)

答案 1 :(得分:2)

encoding/gob包可能是您的最佳选择。

您也可以使用encoding/json包。

如果您使用encoding/json,您将获得能够从Go以外的语言中读取值的好处。

如果您使用encoding/gob,您可以获得更快的速度。

答案 2 :(得分:0)

您可以使用gob#Encoder.Encode

package main

import (
   "bytes"
   "encoding/gob"
   "fmt"
)

type link struct {
   Files []string
}

func main() {
   s := link{
      []string{"south", "north"},
   }
   b := new(bytes.Buffer)
   gob.NewEncoder(b).Encode(s)
   // "\x1d\xff\x81\x03\x01\x01\x04link\x01\xff\x82\x00\x01\x01\x01\x05Files\x01\xff\x84\x00\x00\x00\x16\xff\x83\x02\x01\x01\b[]string\x01\xff\x84\x00\x01\f\x00\x00\x11\xff\x82\x01\x02\x05south\x05north\x00"
   fmt.Printf("%q\n", b)
}

https://golang.org/pkg/encoding/gob#Encoder.Encode