go-defaults icon indicating copy to clipboard operation
go-defaults copied to clipboard

feature req: defaults for type pointers

Open nergdron opened this issue 3 years ago • 2 comments

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)
    }
  }
}

nergdron avatar May 03 '21 09:05 nergdron

I agree with this; it's become quite common for pointers on structs to be used in order be able to explicitly check the nil case, and this library doesn't currently seem to support it.

kevin-lindsay-1 avatar Aug 15 '22 17:08 kevin-lindsay-1

Checking in a year later and this issue is still present...

Why hasn't #22 been merged yet? Pointer values are, by far, the most simple and commonplace way of denoting "this field was not provided/is not explicitly the zero-value for this type", and structs get nested deeper and deeper in projects.

I personally find it puzzling why this wasn't even implemented on v0, but given that there's a PR now, what ETA can we expect for merging/having this functionality added?

nf-brentsaner avatar Aug 29 '23 12:08 nf-brentsaner