mcuadros / go-defaults

Go structures with default values using tags

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

feature req: defaults for type pointers

nergdron opened this issue · 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)
    }
  }
}

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.

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?