Skip to content

Commit

Permalink
Merge pull request #24 from mmpereira2github/master
Browse files Browse the repository at this point in the history
Set the default value for a pointers (non-struct) when it is nil only.
  • Loading branch information
creasty authored Aug 27, 2021
2 parents 0e0a326 + beee52b commit b261feb
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
8 changes: 6 additions & 2 deletions defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ func setField(field reflect.Value, defaultVal string) error {
return nil
}

defaultValueSet := false
if isInitialValue(field) {
defaultValueSet = true
switch field.Kind() {
case reflect.Bool:
if val, err := strconv.ParseBool(defaultVal); err == nil {
Expand Down Expand Up @@ -153,8 +155,10 @@ func setField(field reflect.Value, defaultVal string) error {

switch field.Kind() {
case reflect.Ptr:
setField(field.Elem(), defaultVal)
callSetter(field.Interface())
if defaultValueSet || field.Elem().Kind() == reflect.Struct {
setField(field.Elem(), defaultVal)
callSetter(field.Interface())
}
case reflect.Struct:
if err := Set(field.Addr().Interface()); err != nil {
return err
Expand Down
24 changes: 24 additions & 0 deletions defaults_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,12 @@ type Sample struct {
Float64 float64 `default:"1.64"`
BoolTrue bool `default:"true"`
BoolFalse bool `default:"false"`
BoolPtr *bool `default:"true"`
String string `default:"hello"`
Duration time.Duration `default:"10s"`

IntOct int `default:"0o1"`
IntOctPtr *int `default:"0o1"`
Int8Oct int8 `default:"0o10"`
Int16Oct int16 `default:"0o20"`
Int32Oct int32 `default:"0o40"`
Expand Down Expand Up @@ -258,13 +260,19 @@ func TestInit(t *testing.T) {
if sample.BoolFalse != false {
t.Errorf("it should initialize bool (false)")
}
if *sample.BoolPtr != true {
t.Errorf("it should initialize bool (true)")
}
if sample.String != "hello" {
t.Errorf("it should initialize string")
}

if sample.IntOct != 0o1 {
t.Errorf("it should initialize int with octal literal")
}
if *sample.IntOctPtr != 0o1 {
t.Errorf("it should initialize int with octal literal")
}
if sample.Int8Oct != 0o10 {
t.Errorf("it should initialize int8 with octal literal")
}
Expand Down Expand Up @@ -580,6 +588,22 @@ func TestPointerStructMember(t *testing.T) {
}
}

func TestPointerNonStructMember(t *testing.T) {
falseVal := false
intVal := 10
m := Sample{
IntOctPtr: &intVal,
BoolPtr: &falseVal,
}
MustSet(&m)
if *m.BoolPtr != false {
t.Errorf("BoolPtr with valid value should not be modified by Set")
}
if *m.IntOctPtr != 10 {
t.Errorf("IntOctPtr with valid value should not be modified by Set")
}
}

type Main struct {
MainInt int `default:"-"`
*Other `default:"{}"`
Expand Down

0 comments on commit b261feb

Please sign in to comment.