Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature req: defaults for type pointers #14

Open
nergdron opened this issue May 3, 2021 · 2 comments
Open

feature req: defaults for type pointers #14

nergdron opened this issue May 3, 2021 · 2 comments

Comments

@nergdron
Copy link

nergdron commented May 3, 2021

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)
    }
  }
}
@kevin-lindsay-1
Copy link

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.

@nf-brentsaner
Copy link

nf-brentsaner commented Aug 29, 2023

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants