Skip to content

Commit e2e9406

Browse files
author
Hǎiliàng Wáng
committed
support non-pointer marshaling
1 parent ec810c4 commit e2e9406

2 files changed

Lines changed: 20 additions & 4 deletions

File tree

binary.go

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -104,10 +104,8 @@ func (b *Encoder) Encode(v interface{}) (err error) {
104104
l := rv.NumField()
105105
n := 0
106106
for i := 0; i < l; i++ {
107-
if v := rv.Field(i); v.CanSet() && t.Field(i).Name != "_" {
108-
// take the address of the field, so structs containing structs
109-
// are correctly encoded.
110-
if err = b.Encode(v.Addr().Interface()); err != nil {
107+
if v := rv.Field(i); t.Field(i).Name != "_" {
108+
if err = b.Encode(v.Interface()); err != nil {
111109
return
112110
}
113111
n++

binary_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,24 @@ func TestSliceOfStructWithStruct(t *testing.T) {
258258

259259
}
260260

261+
func TestMarshalNonPointer(t *testing.T) {
262+
type S struct {
263+
A int
264+
}
265+
s := S{A: 1}
266+
data, err := Marshal(s)
267+
if err != nil {
268+
t.Fatal(err)
269+
}
270+
var res S
271+
if err := Unmarshal(data, &res); err != nil {
272+
t.Fatal(err)
273+
}
274+
if !reflect.DeepEqual(res, s) {
275+
t.Fatalf("expect %v got %v", s, res)
276+
}
277+
}
278+
261279
func BenchmarkEncodeStructI1(b *testing.B) {
262280
type Struct struct {
263281
S struct {

0 commit comments

Comments
 (0)