gob编码解码

gob可以正确编码解码slice和指针。 

package main

import (
    "bytes"
    "encoding/gob"
    "fmt"
    "log"
)

type Fobj struct {
    Path string
    Stamp int
}

type P struct {
    Fobjs []*Fobj
}


// This example shows the basic usage of the package: Create an encoder,
// transmit some values, receive them with a decoder.
func test() {
    // Initialize the encoder and decoder. Normally enc and dec would be
    // bound to network connections and the encoder and decoder would
    // run in different processes.
    var network bytes.Buffer        // Stand-in for a network connection
    enc := gob.NewEncoder(&network) // Will write to network.
    dec := gob.NewDecoder(&network) // Will read from network.

    p := new(P)
    p.Fobjs = append(p.Fobjs, &Fobj{Path:"aaa", Stamp:111})
    p.Fobjs = append(p.Fobjs, &Fobj{Path:"aaabbb", Stamp:111222})


    // Encode (send) some values.
    err := enc.Encode(p)
    if err != nil {
        log.Fatal("encode error:", err)
    }

    // Decode (receive) and print the values.
    var q P
    err = dec.Decode(&q)
    if err != nil {
        log.Fatal("decode error 1:", err)
    }

    for _, x := range q.Fobjs {
        fmt.Println(x.Path, x.Stamp)
    }
}

func main() {
    test()
}

 

 

 

输出:

aaa 111
aaabbb 111222

 

转载于:https://my.oschina.net/u/3665115/blog/1528066

你可能感兴趣的:(gob编码解码)