Ompluscator / dynamic-struct

Golang package for editing struct's fields during runtime and mapping structs to other structs.
MIT License
683 stars 81 forks source link

fix: Support embedded struct #21

Closed mtt0 closed 1 year ago

mtt0 commented 3 years ago

With this fix, the following code will output the expected result, tested on MaxOS and Linux:

go get -u github.com/mtt0/dynamic-struct@0e75835bc641757dac062453629f1300ea57678c

go 1.13

require github.com/mtt0/dynamic-struct v1.3.1-0.20220614084457-0e75835bc641 // indirect


- main.go
```go
package main

import (
    "encoding/json"
    "fmt"
    "log"

    //dynamicstruct "github.com/Ompluscator/dynamic-struct"
    dynamicstruct "github.com/mtt0/dynamic-struct"
)

type A struct {
    B
    String string `json:"str"`
}

type B struct {
    Name string `json:"name"`
}

func main() {
    instance := dynamicstruct.ExtendStruct(A{}).
        Build().
        New()
    data := []byte(`
{
    "str": "string in a",
    "name": "string in b"
}
`)
    err := json.Unmarshal(data, &instance)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(instance)
    // Out:
    // &{{} string in a}
    //
    // Expected:
    // &{{string in b} string in a}

    data, err = json.Marshal(instance)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(data))
    // Out:
    // {"B":{"name":""},"str":"string in a"}
    //
    // Expected:
    // {"name":"string in b","str":"string in a"}
}