golang gob将指针转换为0转换为nil指针

时间:2017-03-08 15:14:58

标签: go encoding gob

我正在尝试使用go的net / rpc包来发送数据结构。数据结构包括指向uint64的指针。指针永远不会为零,但值可能为0.我发现当值为0时,接收器会看到一个nil指针。当值为非0时,接收器会看到指向正确值的非零指针。这是有问题的,因为这意味着RPC打破了我的数据结构的不变量:指针永远不会是零。

我有一个去游乐场,在这里演示了这种行为: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)
}

此代码的输出为:

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)}

因此当Ptr指向0时,它在接收器端变为零。当Ptr指向1时,它会正常通过。

这是一个错误吗?有没有解决这个问题的方法?我想避免在接收器端解组我的detastructure来修复所有意外的无指针......

1 个答案:

答案 0 :(得分:1)

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

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

相关问题