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

Builder to allow add field and build in different statement #12

Closed dharmjit closed 4 years ago

dharmjit commented 4 years ago

I tried below and the dynamic struct at the end is empty.

instance := dynamicstruct.NewStruct() //empty dynamic struct
for _, attr := range Attributes {
instance.AddField(strings.Title(attr.Name), "", `json:"`+attr.MappedTo+`"`) //add fields
}
instance.Build().New() //build in the end
Ompluscator commented 4 years ago

Hi. Thank you for submitting!

I've tried to reproduce the issue you experience, but I could not manage it. This is an example I use: https://play.golang.org/p/RcI1qND76tW

In this case, which I've created, it gives me expected result.

Integralist commented 4 years ago

Ah I was going to ask the same thing as splitting up...

    instance := NewStruct().
        AddField("Integer", 0, `json:"int"`).
        AddField("Text", "", `json:"someText"`).
        AddField("Float", 0.0, `json:"double"`).
        AddField("Boolean", false, "").
        AddField("Slice", []int{}, "").
        AddField("Anonymous", "", `json:"-"`).
        Build().
        New()

...over multiple lines like:

instance := NewStruct()
i1 := instance.AddField("Integer", 0, `json:"int"`)
i2 := i1.AddField("Text", "", `json:"someText"`).
...
i6.Build().New()

would result in output similar to this...

&{fields:map[Anonymous:0xc0000a6260 Boolean:0xc0000a61c0 Float:0xc0000a6180 Integer:0xc0000a60c0 Slice:0xc0000a6220 Text:0xc0000a6140]}

UPDATE

I tried the playground linked to and I realized I was doing it wrong. 👍