mailru / easyjson

Fast JSON serializer for golang.
MIT License
4.48k stars 421 forks source link

Do not unconditionally do new() to fill embedded struct pointer #161

Open dynaxis opened 6 years ago

dynaxis commented 6 years ago

In the case of encoding/json, if I set Inner of Test struct before unmarshalling, it is kept after unmarshalled. But in the case of easyjson, the generated implementation unconditionally do new(Inner) and assign to the Test.Inner.

If there is no particular reason for doing it unconditionally, it would be good if easyjson works the same way as encoding/json.

Thanks.

package main

import (
    "encoding/json"
    "fmt"
)

type Test struct {
    Dummy int
    *Inner
}

type Inner struct {
    Boo int
}

const data = `
{
    "Dummy": 7,
    "Boo": 3
}
`

func main() {
    t := &Test{}
    i := &Inner{}
    //t.Inner = i

    json.Unmarshal([]byte(data), t)
    fmt.Printf("Check: %v, %v, %v\n", t.Inner == i, t.Inner.Boo, t.Dummy)
}
dynaxis commented 6 years ago

Let me elaborate more on it. In my case, I have a struct and some more fields outside it that should be added only to JSON. So I created an outer struct with the additional fields and the original struct embedded as a pointer. So when I unmarshall it, I set pointer to the original struct to the outer struct and expect the pointer kept in tact filling data from JSON into it.

As a workaround, I'm currently copying the unmarshalled inner-struct to the struct that is passed into unmarshall methods.