golang gencode 序列化/反序列化数据

栏目: Go · 发布时间: 9年前

内容简介: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


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

Numerical Methods and Methods of Approximation in Science and En

Numerical Methods and Methods of Approximation in Science and En

Karan Surana / CRC Press / 2018-10-31

ABOUT THIS BOOK Numerical Methods and Methods of Approximation in Science and Engineering prepares students and other readers for advanced studies involving applied numerical and computational anal......一起来看看 《Numerical Methods and Methods of Approximation in Science and En》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具