박준호
박준호

Reputation: 1

How to use go-amino library with private variables in struct

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?

Upvotes: 0

Views: 65

Answers (1)

Zak
Zak

Reputation: 5898

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.

Upvotes: 2

Related Questions