encoding/gob decode []byte to multi struct types

134 views
Skip to first unread message

casp...@gmail.com

unread,
Jan 17, 2017, 4:16:37 PM1/17/17
to golang-nuts
I got two struct types encoded into bytes by gob, I want to decode the bytes into a specific struct, is it possible without try all struct types(maybe 3 or more struct types)?

 I want to decode bytes without specify which elem in mixedBytes is struct A, and which is struct B.
This is the playground url:  https://play.golang.org/p/F0Wp5eWdGu

Is is possible to implement it by a map or something like this?

var typesMap = map[string]reflect.Value{
    "A": reflect.ValueOf(A{}),
    "B": reflect.ValueOf(B{}),
}



Felipe Spinolo

unread,
Jan 17, 2017, 10:12:05 PM1/17/17
to golang-nuts
Why not just create a wrapper struct? Something like:

type Mixed struct{
    A
*A
    B
*B
}

And then just encode/decode that?

casp...@gmail.com

unread,
Jan 18, 2017, 1:07:49 AM1/18/17
to golang-nuts
First thanks for you reply. 
Because in fact, I have about more than 10 different struct types (maybe more and more), your suggest is good, this is better
type Info struct{
    typeStr
string // store the type info to decode IData
   
IData interface{}
}

But I don't like to send the typeInfo through rpc call(I'm using gob to do rpc call),maybe there's a better way to do it, just I haven't found it。

在 2017年1月18日星期三 UTC+8上午11:12:05,Felipe Spinolo写道:

Jordan Krage

unread,
Jan 18, 2017, 9:43:27 AM1/18/17
to golang-nuts
How about a compromise with denser type info? (could consider an int8 as well) 
 
type infoType int

const (
    firstType infoType = iota
    secondType
    ...
)

type 
Info struct{
    infoType

    
IData interface{}
}

Jordan Krage

unread,
Jan 18, 2017, 9:51:51 AM1/18/17
to golang-nuts
Actually, it looks like the int/int8 distinction doesn't matter for gob.
There is no int8, int16 etc. discrimination in the gob format; there are only signed and unsigned integers.

casp...@gmail.com

unread,
Jan 18, 2017, 9:27:42 PM1/18/17
to golang-nuts
Thanks for you reply, I got it done: https://play.golang.org/p/oOEELLyaVv
This is how I did it, pass *interface{} to gob.Encode, not interface{}  
  the same with gob.Decode, then get the type info from the decoded value interface{}

在 2017年1月18日星期三 UTC+8下午10:51:51,Jordan Krage写道:
Reply all
Reply to author
Forward
0 new messages