Skip to content

Commit

Permalink
Merge pull request #6 from creasty/fix_pointer_initializations
Browse files Browse the repository at this point in the history
Fix pointer initialization
  • Loading branch information
creasty authored Feb 17, 2018
2 parents 6c4fe17 + 6c5d7ef commit 046b42c
Showing 2 changed files with 23 additions and 12 deletions.
15 changes: 5 additions & 10 deletions defaults.go
Original file line number Diff line number Diff line change
@@ -45,7 +45,7 @@ func setField(field reflect.Value, defaultVal string) {
return
}

if isEquivalentToInitialValue(field.Kind(), defaultVal) {
if !shouldInitializeField(field.Kind(), defaultVal) {
return
}

@@ -154,18 +154,13 @@ func isInitialValue(field reflect.Value) bool {
return reflect.DeepEqual(reflect.Zero(field.Type()).Interface(), field.Interface())
}

func isEquivalentToInitialValue(kind reflect.Kind, tag string) bool {
func shouldInitializeField(kind reflect.Kind, tag string) bool {
switch kind {
case reflect.Bool,
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Uintptr,
reflect.Float32, reflect.Float64,
reflect.String:
return (tag == "")
case reflect.Struct:
return true
}

return false
return (tag != "")
}

// CanUpdate returns true when the given value is an initial value of its type
20 changes: 18 additions & 2 deletions defaults_test.go
Original file line number Diff line number Diff line change
@@ -80,7 +80,11 @@ type Sample struct {

NoDefault *string `default:"-"`
NoDefaultStruct Struct `default:"-"`
StructWithNoTag Struct

MapWithNoTag map[string]int
SliceWithNoTag []string
StructPtrWithNoTag *Struct
StructWithNoTag Struct

NonInitialString string `default:"foo"`
NonInitialSlice []int `default:"[123]"`
@@ -294,10 +298,22 @@ func TestInit(t *testing.T) {
}
})

t.Run("opt-out", func(t *testing.T) {
t.Run("no tag", func(t *testing.T) {
if sample.MapWithNoTag != nil {
t.Errorf("it should not initialize pointer type (map)")
}
if sample.SliceWithNoTag != nil {
t.Errorf("it should not initialize pointer type (slice)")
}
if sample.StructPtrWithNoTag != nil {
t.Errorf("it should not initialize pointer type (struct)")
}
if sample.StructWithNoTag.WithDefault != "foo" {
t.Errorf("it should automatically recurse into a struct even without a tag")
}
})

t.Run("opt-out", func(t *testing.T) {
if sample.NoDefault != nil {
t.Errorf("it should not be set")
}

0 comments on commit 046b42c

Please sign in to comment.