Skip to content

Commit 5ed9a62

Browse files
committed
Create structs with embedded fields; create instance from field values
1 parent 3f4bf7d commit 5ed9a62

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

builder.go

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,13 @@ type (
6969
//
7070
New() interface{}
7171

72+
// New provides new instance of defined dynamic struct, and assigns to
73+
// its fields the values `fieldValues` in field order.
74+
//
75+
// value := dStruct.NewWithValues("hello", 123)
76+
//
77+
NewWithValues(fieldValues ...interface{}) interface{}
78+
7279
// NewSliceOfStructs provides new slice of defined dynamic struct, with 0 length and capacity.
7380
//
7481
// value := dStruct.NewSliceOfStructs()
@@ -103,7 +110,6 @@ type (
103110
// for defining fresh dynamic struct.
104111
//
105112
// builder := dynamicstruct.NewStruct()
106-
//
107113
func NewStruct() Builder {
108114
return &builderImpl{
109115
fields: []*fieldConfigImpl{},
@@ -114,7 +120,6 @@ func NewStruct() Builder {
114120
// returns new instance of Builder interface.
115121
//
116122
// builder := dynamicstruct.MergeStructs(MyStruct{})
117-
//
118123
func ExtendStruct(value interface{}) Builder {
119124
return MergeStructs(value)
120125
}
@@ -123,7 +128,6 @@ func ExtendStruct(value interface{}) Builder {
123128
// returns new instance of Builder interface.
124129
//
125130
// builder := dynamicstruct.MergeStructs(MyStructOne{}, MyStructTwo{}, MyStructThree{})
126-
//
127131
func MergeStructs(values ...interface{}) Builder {
128132
builder := NewStruct()
129133

@@ -142,6 +146,10 @@ func MergeStructs(values ...interface{}) Builder {
142146
}
143147

144148
func (b *builderImpl) AddField(name string, typ interface{}, tag string) Builder {
149+
if name == "" {
150+
typ_ := reflect.TypeOf(typ)
151+
return b.addField(typ_.Name(), typ_.PkgPath(), typ, tag, true)
152+
}
145153
return b.addField(name, "", typ, tag, false)
146154
}
147155

@@ -216,6 +224,14 @@ func (ds *dynamicStructImpl) New() interface{} {
216224
return reflect.New(ds.definition).Interface()
217225
}
218226

227+
func (ds *dynamicStructImpl) NewWithValues(fieldValues ...interface{}) interface{} {
228+
n := reflect.Zero(ds.definition)
229+
for i, v := range fieldValues {
230+
n.Field(i).Set(reflect.ValueOf(v))
231+
}
232+
return n.Interface()
233+
}
234+
219235
func (ds *dynamicStructImpl) NewSliceOfStructs() interface{} {
220236
return reflect.New(reflect.SliceOf(ds.definition)).Interface()
221237
}

0 commit comments

Comments
 (0)