LoginSignup
9
8

More than 5 years have passed since last update.

encoding/gob のメモ

Last updated at Posted at 2013-11-26

メモ

  • 主にRPC用のシリアライザ
  • 型情報をデータに含む。ただし型情報を出力するのはその型を最初にEncodeしたときのみ。なので、たとえシリアライズ後のデータサイズがわかっていたとしても途中から読み初めることはできない
  • 再帰型(treeのような型)もサポートしているが将来のバージョンで変更される可能性がある
  • 内部的にはリフレクションをつかっている

サンプルコード

package main

import (
        "encoding/gob"
        "fmt"
)

type Buf struct {
        buf []byte
        pos int
}

func NewBuf() *Buf {
        return &Buf{make([]byte, 0), 0}
}

func (b *Buf) Write(p []byte) (n int, err error) {
        b.buf = append(b.buf, p...)
        n = len(p)
        return
}

func (b *Buf) Read(p []byte) (n int, err error) {
        for n = 0; n < len(p) && b.pos < len(b.buf); {
                p[n] = b.buf[b.pos]
                n++
                b.pos++
        }
        return
}

func main() {
        buf := NewBuf()
        e := gob.NewEncoder(buf)
        e.Encode("asdf")
        e.Encode(1)
        e.Encode(2)

        var s string
        var i int
        var err error
        d := gob.NewDecoder(buf)
        err = d.Decode(&s)
        fmt.Println(s, err)
        err = d.Decode(&i)
        fmt.Println(i, err)
        err = d.Decode(i)
        fmt.Println(i, err)
        err = d.Decode(&i)
        fmt.Println(i, err)
}

所感

  • Goだけで完結することがわかってるなら簡単につかえて便利だが、 型情報がデータ中のどこに現れるかわからないので、途中からデコードしたりはできない。
  • 独自ファイルフォーマットのためのシリアライザとしては使いにくい
9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8