Skip to content

feature req: defaults for type pointersΒ #14

Open
@nergdron

Description

@nergdron

I'd love it if this library also handled type pointers, so something like this:

type test struct {
  Name *string `default:"test"`
}

now obviously a string pointer isn't the most useful thing in the world, but handling it generically should allow us to specify nested struct pointers with their own defaults, and then this library would correctly initialize the whole data tree. I've written a little bit of wrapper code to do this myself (which actually doesn't even handle the string pointer case), but I'd love it if this was something the library just did itself:

setDefaults(reflect.ValueOf(test))

[...]

func setDefaults(v reflect.Value) {
  if v.Kind() != reflect.Ptr { return }
  if v.IsNil() {
    if v.CanSet() {
      v.Set(reflect.New(v.Type().Elem()))
    } else {
      return
    }
  }
  if v.Elem().Kind() != reflect.Struct { return }
  defaults.SetDefaults(v.Interface())
  v = v.Elem()

  for i := 0; i < v.NumField(); i++ {
    field := v.Field(i)
    if field.Type().Kind() == reflect.Ptr {
      setDefaults(field)
    }
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions