Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: how to convert struct to []byte?

I'm trying to use "appengine/memcache" to store data in the cache, memcache.Item's Value field is []byte

how do I convert a struct to []byte for storing it ?

for example:

type Link struct {
    Files []string
}
like image 952
Gal Ben-Haim Avatar asked Apr 20 '13 22:04

Gal Ben-Haim


People also ask

How do you convert structs to bytes?

The most straightforward but pretty inefficient method to convert a struct into a byte slice is to marshal it to JSON/YAML or any other markup language format.

What does [] byte mean in go?

A byte in Go is an unsigned 8-bit integer. It has type uint8 . A byte has a limit of 0 – 255 in numerical range. It can represent an ASCII character.

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.


1 Answers

See the memcache.Codec type, this can be used to convert memcache items. The appengine/memcache package has two codecs already prepared, memcache.Gob and memcache.JSON. You use these codecs instead of the direct call to store and retrieve items from the cache, for example like this for a gob encoded item:

    item := &memcache.Item{
        Key:    myCacheKey,
        Object: &myLinkVar,
    }
    err := memcache.Gob.Set(context, item)
like image 165
jum Avatar answered Sep 29 '22 02:09

jum