0

That was a mouthful of a title, let me explain more. Assuming I have a struct of all pointers (don't know of what type)

type A struct {
  S *string
  I *int
}

I want to write a function that takes a pointer to that struct and given a fieldName sets that field to a pointer to the Zero/empty value of that pointer. For example:

func setZeroForField(i any, fieldName string) {
  // do stuff
}

a := A{}
setZeroForField(&a, "S")
setZeroForField(&a, "I")

// *a.S == ""
// *a.I == 0

Is there any way to do it using reflect? I know how to get the types of the fields of A but I can't use reflect.Indirect because it just returns a Zero value which in this case is a nil pointer, not the empty string or 0.

strikerdude10
  • 663
  • 6
  • 15

1 Answers1

0
func setZeroForField(i any, fieldName string) {
    rv := reflect.ValueOf(i).Elem()
    fv := rv.FieldByName(fieldName)
    fv.Set(reflect.New(fv.Type().Elem()))
}

https://go.dev/play/p/7clmztF5uaa

mkopriva
  • 35,176
  • 4
  • 57
  • 71