dousi1970 2018-07-19 07:39
浏览 244

如何在结构体中使用带有私有变量的Go-amino库

I'd like to use amino marshal when I have private variables in the structure.

In test2 package, test.go :

type Lnt struct {
    Neg bool
    abs string // this variable
}

func NewLnt() Lnt {
    return Lnt{
        Neg: true,
        abs: "abcdefef",
    }
}

testing go file :

func TestAbc(t *testing.T) {
    s := test2.NewLnt()
    t.Log("s=", s)

    cdc := amino.NewCodec()

    b, err := cdc.MarshalBinary(s)
    assert.Nil(t, err)
    t.Log("b=",b)

    var s2 test2.Lnt
    err = cdc.UnmarshalBinary(b, &s2)
    assert.Nil(t, err)
    assert.Equal(t, s, s2)

    t.Log("s2=", s2)
}

result :

encoding_test.go:39: s= {true abcdefef}
encoding_test.go:55: 
        Error Trace:    encoding_test.go:55
        Error:          Not equal: 
                        expected: test2.Lnt{Neg:true, abs:"abcdefef"} 
                        actual  : test2.Lnt{Neg:true, abs:""} // error

                        Diff:
                        --- Expected
                        +++ Actual
                        @@ -2,3 +2,3 @@
                          Neg: (bool) true,
                        - abs: (string) (len=8) "abcdefef"
                        + abs: (string) ""
                         }
        Test:           TestAbc
encoding_test.go:57: s2= {true }

Private variable "abs" is lost..

Is it not supported, or is there another way to use it in this case?

  • 写回答

1条回答 默认 最新

  • doujiang7258 2018-07-19 07:48
    关注

    The short answer is you can't.

    What's happening here is you are marshalling all the exported values into the binary format, but the unexported values are not included because the marshaler doesn't have access to them.

    The binary data is the unmarshalled into a new struct, and because the unexported field was not in the binary data, it's impossible for the struct to get initialised with that value. (also, it cannot have a value set because it's unexported).

    You will need to export the struct field (make public) if you want this test to pass, or accept that that data is lost on marshalling.

    评论

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘