1

I'm trying to use go's net/rpc package to send data structures. The data structure includes a pointer to uint64. The pointer is never nil, but the value may be 0. I'm finding that when the value is 0, the receiver sees a nil pointer. When the value is non-0, the receives sees a non-nil pointer that points to a proper value. This is problematic, because it means that the RPC is breaking an invariant of my data structure: the pointer will never be nil.

I have a go playground that demonstrates this behavior here: https://play.golang.org/p/Un3bTe5F-P

package main

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

type P struct {
    Zero, One int
    Ptr    *int
}

func main() {
    // 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.
    // Encode (send) the value.
    var p P
    p.Zero = 0
    p.One = 1
    p.Ptr = &p.Zero
    fmt.Printf("p0: %s\n", p)
    err := enc.Encode(p)
    if err != nil {
        log.Fatal("encode error:", err)
    }
    // Decode (receive) the value.
    var q P
    err = dec.Decode(&q)
    if err != nil {
        log.Fatal("decode error:", err)
    }
    fmt.Printf("q0: %s\n", q)

    p.Ptr = &p.One
    fmt.Printf("p1: %s\n", p)
    err = enc.Encode(p)
    if err != nil {
        log.Fatal("encode error:", err)
    }

    err = dec.Decode(&q)
    if err != nil {
        log.Fatal("decode error:", err)
    }
    fmt.Printf("q1: %s\n", q)
}

The output from this code is:

p0: {%!s(int=0) %!s(int=1) %!s(*int=0x1050a780)}
q0: {%!s(int=0) %!s(int=1) %!s(*int=<nil>)}
p1: {%!s(int=0) %!s(int=1) %!s(*int=0x1050a784)}
q1: {%!s(int=0) %!s(int=1) %!s(*int=0x1050aba8)}

So when Ptr points to a 0, it becomes nil on the receiver side. When Ptr points to 1, it is passed through normally.

Is this a bug? Is there a way around this problem? I want to avoid having to unmarshall my detastructure on the receiver side to fix all the unexpected nil pointers...

4

1 回答 1

1

根据 2013 年提出的缺陷,此行为是 gob 协议的限制 - 请参阅https://github.com/golang/go/issues/4609

请记住,gob 不发送指针,指针被取消引用并且值被传递。因此,当 p.Ptr 设置为 &p.One 时,您会发现 q.Ptr != &q.One

于 2017-03-08T23:54:41.187 回答