@@ -11,6 +11,7 @@ Main features:
1111* Removing existing fields from struct
1212* Modifying fields' types and tags
1313* Easy reading of dynamic structs
14+ * Mapping dynamic struct with set values to existing struct
1415
1516Works out-of-the-box with:
1617* https://github.com/go-playground/form
@@ -210,25 +211,31 @@ import (
210211" github.com/ompluscator/dynamic-struct"
211212)
212213
214+ type DataOne struct {
215+ Integer int ` json:"int"`
216+ Text string ` json:"someText"`
217+ Float float64 ` json:"double"`
218+ }
219+
220+ type DataTwo struct {
221+ Boolean bool
222+ Slice []int
223+ Anonymous string ` json:"-"`
224+ }
225+
213226func main () {
214- instance := dynamicstruct.NewStruct ().
215- AddField (" Integer" , 0 , ` json:"int"` ).
216- AddField (" Text" , " " , ` json:"someText"` ).
217- AddField (" Float" , 0.0 , ` json:"double"` ).
218- AddField (" Boolean" , false , " " ).
219- AddField (" Slice" , []int {}, " " ).
220- AddField (" Anonymous" , " " , ` json:"-"` ).
227+ instance := dynamicstruct.MergeStructs (DataOne{}, DataTwo{}).
221228Build ().
222229New ()
223230
224231data := []byte (`
225232{
226- "int": 123,
227- "someText": "example",
228- "double": 123.45,
229- "Boolean": true,
230- "Slice": [1, 2, 3],
231- "Anonymous": "avoid to read"
233+ "int": 123,
234+ "someText": "example",
235+ "double": 123.45,
236+ "Boolean": true,
237+ "Slice": [1, 2, 3],
238+ "Anonymous": "avoid to read"
232239}
233240` )
234241
@@ -237,20 +244,30 @@ func main() {
237244log.Fatal (err)
238245}
239246
240- value := dynamicstruct.NewReader (instance)
241- fmt.Println (" Integer" , value.GetField (" Integer" ).Int ())
242- fmt.Println (" Text" , value.GetField (" Text" ).String ())
243- fmt.Println (" Float" , value.GetField (" Float" ).Float64 ())
244- fmt.Println (" Boolean" , value.GetField (" Boolean" ).Bool ())
245- fmt.Println (" Slice" , value.GetField (" Slice" ).Interface ().([]int ))
246- fmt.Println (" Anonymous" , value.GetField (" Anonymous" ).String ())
247+ reader := dynamicstruct.NewReader (instance)
248+
249+ fmt.Println (" Integer" , reader.GetField (" Integer" ).Int ())
250+ fmt.Println (" Text" , reader.GetField (" Text" ).String ())
251+ fmt.Println (" Float" , reader.GetField (" Float" ).Float64 ())
252+ fmt.Println (" Boolean" , reader.GetField (" Boolean" ).Bool ())
253+ fmt.Println (" Slice" , reader.GetField (" Slice" ).Interface ().([]int ))
254+ fmt.Println (" Anonymous" , reader.GetField (" Anonymous" ).String ())
255+
256+ var dataOne DataOne
257+ err = reader.ToStruct (&dataOne)
258+ fmt.Println (err, dataOne)
247259
260+ var dataTwo DataTwo
261+ err = reader.ToStruct (&dataTwo)
262+ fmt.Println (err, dataTwo)
248263// Out:
249264// Integer 123
250265// Text example
251266// Float 123.45
252267// Boolean true
253268// Slice [1 2 3]
254269// Anonymous
270+ // <nil> {123 example 123.45}
271+ // <nil> {true [1 2 3] }
255272}
256273```
0 commit comments