Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow creating an embedded struct field; create a new instance with field values #31

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 19 additions & 3 deletions builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,13 @@ type (
//
New() interface{}

// New provides new instance of defined dynamic struct, and assigns to
// its fields the values `fieldValues` in field order.
//
// value := dStruct.NewWithValues("hello", 123)
//
NewWithValues(fieldValues ...interface{}) interface{}

// NewSliceOfStructs provides new slice of defined dynamic struct, with 0 length and capacity.
//
// value := dStruct.NewSliceOfStructs()
Expand Down Expand Up @@ -103,7 +110,6 @@ type (
// for defining fresh dynamic struct.
//
// builder := dynamicstruct.NewStruct()
//
func NewStruct() Builder {
return &builderImpl{
fields: []*fieldConfigImpl{},
Expand All @@ -114,7 +120,6 @@ func NewStruct() Builder {
// returns new instance of Builder interface.
//
// builder := dynamicstruct.MergeStructs(MyStruct{})
//
func ExtendStruct(value interface{}) Builder {
return MergeStructs(value)
}
Expand All @@ -123,7 +128,6 @@ func ExtendStruct(value interface{}) Builder {
// returns new instance of Builder interface.
//
// builder := dynamicstruct.MergeStructs(MyStructOne{}, MyStructTwo{}, MyStructThree{})
//
func MergeStructs(values ...interface{}) Builder {
builder := NewStruct()

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

func (b *builderImpl) AddField(name string, typ interface{}, tag string) Builder {
if name == "" {
typ_ := reflect.TypeOf(typ)
return b.addField(typ_.Name(), typ_.PkgPath(), typ, tag, true)
}
return b.addField(name, "", typ, tag, false)
}

Expand Down Expand Up @@ -216,6 +224,14 @@ func (ds *dynamicStructImpl) New() interface{} {
return reflect.New(ds.definition).Interface()
}

func (ds *dynamicStructImpl) NewWithValues(fieldValues ...interface{}) interface{} {
n := reflect.Zero(ds.definition)
for i, v := range fieldValues {
n.Field(i).Set(reflect.ValueOf(v))
}
return n.Interface()
}

func (ds *dynamicStructImpl) NewSliceOfStructs() interface{} {
return reflect.New(reflect.SliceOf(ds.definition)).Interface()
}
Expand Down