Efficient Go serialization of struct to disk

后端 未结 3 554
情书的邮戳
情书的邮戳 2020-12-01 15:06

I\'ve been tasked to replace C++ code to Go and I\'m quite new to the Go APIs. I am using gob for encoding hundreds of key/value entries to disk pages but the gob encoding h

3条回答
  •  醉酒成梦
    2020-12-01 15:47

    Use protobuf to efficiently encode your data.

    https://github.com/golang/protobuf

    Your main would look like this:

    package main
    
    import (
        "fmt"
        "log"
    
        "github.com/golang/protobuf/proto"
    )
    
    func main() {
        e := &Entry{
            Key: proto.String("k1"),
            Val: proto.String("v1"),
        }
        data, err := proto.Marshal(e)
        if err != nil {
            log.Fatal("marshaling error: ", err)
        }
        fmt.Println(data)
    }
    

    You create a file, example.proto like this:

    package main;
    
    message Entry {
        required string Key = 1;
        required string Val = 2;
    }
    

    You generate the go code from the proto file by running:

    $ protoc --go_out=. *.proto
    

    You can examine the generated file, if you wish.

    You can run and see the results output:

    $ go run *.go
    [10 2 107 49 18 2 118 49]
    

提交回复
热议问题