Skip to content

Commit

Permalink
feat: add MustSet function and its test
Browse files Browse the repository at this point in the history
  • Loading branch information
BoynChan committed Aug 14, 2020
1 parent 8240537 commit c2889d7
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
8 changes: 8 additions & 0 deletions defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,14 @@ func Set(ptr interface{}) error {
return nil
}

// MustSet function is a wrapper of Set function
// It will call Set and panic if err not equals nil.
func MustSet(ptr interface{}) {
if err := Set(ptr); err != nil {
panic(err)
}
}

func setField(field reflect.Value, defaultVal string) error {
if !field.CanSet() {
return nil
Expand Down
18 changes: 18 additions & 0 deletions defaults_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,24 @@ type Emmbeded struct {
Int int `default:"1"`
}

func TestMustSet(t *testing.T) {
sample := &Sample{
NonInitialString: "string",
NonInitialSlice: []int{1, 2, 3},
NonInitialStruct: Struct{Foo: 123},
NonInitialStructPtr: &Struct{Foo: 123},
DeepSliceOfStructsWithNoTag: [][][]Struct{{{{Foo: 123}}}},
}

MustSet(sample)
go func() {
if err := recover(); err != nil {
t.Fatalf("it should not panic error: %v", err)
}
}()
t.Log("it works.")
}

func TestInit(t *testing.T) {
sample := &Sample{
NonInitialString: "string",
Expand Down

0 comments on commit c2889d7

Please sign in to comment.