mardi 22 mars 2022

Wrap a reflect.Value with pointer which points to the same element

Here I found the following code -

// ptr wraps the given value with pointer: V => *V, *V => **V, etc.
func ptr(v reflect.Value) reflect.Value {
    pt := reflect.PtrTo(v.Type()) // create a *T type.
    pv := reflect.New(pt.Elem())  // create a reflect.Value of type *T.
    pv.Elem().Set(v)              // sets pv to point to underlying value of v.
    return pv
}

As stated, calling this function on variable V of type reflect.Value, which describes an element of type T that holds data d, returns variable VP of type reflect.Value, which describes an element of type *T that points to data d.

When modifying VP by setting it's data to something other then d, V doesn't change (ie by calling VP.Set(..)).
I need a function that returns VP as described above, but so that modifying the data in VP modifies it in V.

The reason I need this function is that I want to extend this stack overflow answer to initialize strings and ints with default values. I wanted to use this stack overflow answer to do it, but for that I need to have a value of a pointer of a struct, not a value of a struct, when running SetString and SetInt.

Thanks,





Aucun commentaire:

Enregistrer un commentaire