The encoding/decoding protocol is not stateless: the first time a new type 
is seen, some type information is transmitted and the Encoder/Decoder 
objects keep track of that. My guess is that the thing gets messed up by 
the fact that you are encoding once and decoding twice.

I would rewrite your program like this:
https://play.golang.org/p/bMFSoaBDAyX

You can see that everything goes smoothly and the first encode/decode uses 
more bytes than the second, which is for the transmission of type 
information.

On Tuesday, November 20, 2018 at 6:02:34 AM UTC+1, Lazytiger wrote:
>
>
> package main
>
> import (
>    "bytes"
>    "encoding/gob"
>    "fmt"
> )
>
> var data = bytes.NewBuffer(nil)
> var buff = bytes.NewBuffer(nil)
> var encoder = gob.NewEncoder(data)
> var decoder = gob.NewDecoder(buff)
>
> func main() {
>    encode()
>    decode()
>    decode()
> }
>
> func encode() {
>    n := [][]int32{[]int32{1}, []int32{2, 3}, []int32{4, 5, 6}}
>    encoder.Encode(&n)
>    fmt.Printf("encode bytes:%v len:%d\n", data.Bytes(), data.Len())
> }
>
> func decode() {
>    buff.Write(data.Bytes())
>    println("data size", buff.Len(), data.Len())
>    var n [][]int32
>    err := decoder.Decode(&n)
>    if err != nil {
>       println("decode err:", err.Error())
>    }
>    println("data left:", buff.Len())
>    fmt.Printf("%v\n", n)
> }
>
> Run output:
>
> encode bytes:[13 255 131 2 1 2 255 132 0 1 255 130 0 0 12 255 129 2 1 2 255 
> 130 0 1 4 0 0 13 255 132 0 3 1 2 2 4 6 3 8 10 12] len:41data size 41 41
> data left: 0[[1] [2 3] [4 5 6]]data size 41 41
> decode err: extra data in buffer
> data left: 27[]
>
>
> I found that, encode a slice would failed, but a struct ok. Is this a bug 
> or limitation of gob?
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to