dongtanzhu5417 2017-10-10 16:32 采纳率: 100%
浏览 172
已采纳

Gob解码给出“无法分配的值的DecodeValue”错误

I'm new-ish to Go and I'm having some trouble putting a gob on the wire. I wrote a quick test that I thought would pass, but the decode call is returning a "DecodeValue of unassignable value" error. Here's the code:

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

I suspect I'm missing something stupid here and appreciate any help that you're able to offer.

  • 写回答

2条回答 默认 最新

  • donglu9978 2017-10-10 16:56
    关注

    Had a friend take a look at this and he pointed out that gob doesn't let you assign to a nil pointer. From the gob package docs: "Nil pointers are not permitted, as they have no value." It looks like gob reflects on the fields of the struct that is passed in and attempts to assign values from the encoded stream. Changing this:

    var t2 *tester
    

    To this:

    t2 := &tester{}
    

    Makes the test pass.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化