gob and embedded struct with no exported fields

2,472 views
Skip to first unread message

Albert Strasheim

unread,
Mar 18, 2012, 3:15:40 AM3/18/12
to golan...@googlegroups.com
Hello all

gob question. I have the follow structs:

type Internal struct {
    i, j, k int
}

func (i *Internal) SomeUsefulFunction() int { return i+j+k }

type SomeMessage struct {
    Internal
    J int
}

Now SomeMessage has SomeUsefulFunction, which I use in other places. I don't want to send the internals over the wire, as they are only applicable inside the process where the message lives. The receiving end will fill in its own values for the internal stuff while processing the message.

However, gob can't encode SomeMessage, saying that Internal has no exported fields. I also can't write a GobEncode/GobDecode on Internal to just do nothing, because then SomeMessage also gets these functions.

I've resorted to

type Internal struct {
    i, j, k int
    XXX struct{}
}

but that seems quite unfortunate.

Any ideas?

Regards

Albert

Albert Strasheim

unread,
Mar 18, 2012, 5:27:08 AM3/18/12
to golan...@googlegroups.com
Hello

On Sunday, March 18, 2012 9:15:40 AM UTC+2, Albert Strasheim wrote:
gob question. I have the follow structs:

Just ran into another issue trying to send the result of errors.New as a field in a message:

gob: type not registered for interface: errors.errorString

Let's try to register it. gob.Register(errors.New("")). Now:

gob: type errors.errorString has no exported fields

Mmm... 

Regards

Albert

Peter Bourgon

unread,
Mar 18, 2012, 5:58:45 AM3/18/12
to Albert Strasheim, golan...@googlegroups.com
Invert your structure. Your Internal may embed a SomeMessage.

Albert Strasheim

unread,
Mar 18, 2012, 6:02:38 AM3/18/12
to Peter Bourgon, golan...@googlegroups.com
Hello

On Sun, Mar 18, 2012 at 11:58 AM, Peter Bourgon <pe...@bourgon.org> wrote:
> Invert your structure. Your Internal may embed a SomeMessage.

The problem is that I want access to the fields of SomeMessage so I
can easily fill them in.

And there is in actually SomeMessage1, SomeMessage2, etc.

I guess I could add a function on Internal like

External() interface{}

and then

msg.External().(*SomeMessage2).Foo = "whatever"

but that seems a bit messy.

Thanks for the idea though. Maybe there's still something I can do with it.

Regards

Albert

Reply all
Reply to author
Forward
0 new messages