内容简介:golang gencode 序列化/反序列化数据
andyleap/gencode 是一个快速的且体积很小的序列化库,速度是标准库10x倍。
首先定义数据结构:test.schema
struct Person {
Name string
Age uint8
}
然后通过gencode 命令行生成test.schema.gen.go:
$ gencode go -schema test.schema -package main
下面是结合bolt 来存储数据:
package main
import (
"fmt"
"log"
"time"
"github.com/boltdb/bolt"
)
func main() {
db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 1 * time.Second})
if err != nil {
log.Fatal(err)
}
defer db.Close()
db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte("person"))
if err != nil {
return err
}
return nil
})
person := Person{
Name: "testname",
Age: 20,
}
db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("person"))
buf, _ := person.Marshal(nil)
fmt.Println(buf, string(buf))
b.Put([]byte(person.Name), buf)
fmt.Printf("Gencode encoded size: %v\n", len(buf))
return nil
})
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("person"))
if err := b.ForEach(func(k, v []byte) error {
fmt.Printf("%s is %s.\n", k, v)
p := Person{}
p.Unmarshal(v)
fmt.Println(p)
return nil
}); err != nil {
return err
}
return nil
})
}
输出:
[8 116 101 115 116 110 97 109 101 20]testname
Gencode encoded size: 10
testname istestname.
{testname 20}
因为 gencode 不会写入字段的名字,所以体积很小,正因为如此,用gencode 序列化和反序列化数据时应该注意,数据结构不能动态改变。
项目地址 andyleap/gencode 1
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Web Designer's Idea Book, Vol. 2
Patrick McNeil / How / 2010-9-19 / USD 30.00
Web Design Inspiration at a Glance Volume 2 of The Web Designer's Idea Book includes more than 650 new websites arranged thematically, so you can easily find inspiration for your work. Auth......一起来看看 《The Web Designer's Idea Book, Vol. 2》 这本书的介绍吧!
Base64 编码/解码
Base64 编码/解码
RGB CMYK 转换工具
RGB CMYK 互转工具