Gob 解码给出 "DecodeValue of unassignable value" 错误

Gob Decode Giving "DecodeValue of unassignable value" Error

我是 Go 的新手,在将 gob 连接到网络时遇到了一些问题。我写了一个我认为会通过的快速测试,但解码调用返回 "DecodeValue of unassignable value" 错误。这是代码:

type tester struct {
    Payload string
}

func newTester(payload string) *tester {
    return &tester {
        Payload: payload,
    }
}

func TestEncodeDecodeMessage(t *testing.T) {
    uri := "localhost:9090"
    s := "the lunatics are in my head"
    t1 := newTester(s)
    go func(){
        ln, err := net.Listen("tcp", uri)
        assert.NoError(t, err)
        conn, err := ln.Accept()
        assert.NoError(t, err)

        var t2 *tester
        decoder := gob.NewDecoder(conn)
        err = decoder.Decode(t2)
        assert.NoError(t, err)
        conn.Close()
        assert.NotNil(t, t2)
    }()

    time.Sleep(time.Millisecond * 100)
    conn, err := net.Dial("tcp", uri)
    assert.NoError(t, err)

    gob.Register(t1)
    encoder := gob.NewEncoder(conn)
    err = encoder.Encode(t1)
    assert.NoError(t, err)
    conn.Close()
    time.Sleep(time.Millisecond * 100)
}

我想我在这里遗漏了一些愚蠢的东西,感谢您提供的任何帮助。

有朋友看过这个,他指出 gob 不允许你分配给 nil 指针。来自 gob 包 docs:"Nil pointers are not permitted, as they have no value." 看起来 gob 反映了传入的结构的字段,并尝试从编码流中分配值。改变这个:

var t2 *tester

为此:

t2 := &tester{}

使测试通过。