net/rpc handling of maps

498 views
Skip to first unread message

Jeremy Thorpe

unread,
Mar 18, 2012, 6:01:48 PM3/18/12
to golan...@googlegroups.com
Hi golang,

I have a question about how net/rpc (and perhaps encoding/gob) handles maps.

I have an RPC server with code like this:

func (r *Receiver) Foo(_ struct{}, m *map[int] int) error {
*m = make(map[int] int)
(*m)[1] = 1
return nil
}

and I call it like this:

m := make(map[int] int)
m[0] = 0
err = h.Call("Receiver.Foo", struct{}{}, &m)
fmt.Println(m)

Should I expect to see 0:0 in my map after the call, or is the "Call"
supposed to create a new map? The documentation of encoder/gob seems
to support, if anything, the second theory: "...if the sender has
allocated a map, the receiver will allocate a map even no elements are
transmitted." However, what's actually printed is [0:0, 1:1], which
implies that the map is being reused (and not cleared).

Is this expected?

Thanks,
-Jeremy

Kyle Lemons

unread,
Mar 19, 2012, 4:01:53 PM3/19/12
to Jeremy Thorpe, golan...@googlegroups.com
Looks correct.  If you have a map field in a struct or pass a reference to a nil map, I think it's implying that the map may be allocated and have zero entries (so don't compare to nil, check its length to see if its empty).
Reply all
Reply to author
Forward
0 new messages