Let valuePtr
and value
be two interface{}
. Knowing that valuePtr
is a pointer of the type of value
, how to make valuePtr
points on value
?
The "trick" I'm using currently works with the reflect
package and a type switch:
switch value.(type) {
case string:
ptr := reflect.ValueOf(valuePtr).Elem().Addr().Interface().(*string)
*ptr = value.(string)
case ...:
[...]
}
This requires one case for each type that can be given to the function. However, I am using interface{}
to make things universal. Thus, this technic will eventually lead to a situation where dozens of types will be listed.
What I am trying to do is something like:
ptr := valuePtr.(*type(value))
Did you face this issue? What did you do?
Based on the code in the question, it looks like your goal is to set a pointer element to a value. Use this code:
reflect.ValueOf(valuePtr).Elem().Set(reflect.ValueOf(value))
As an aside, the code ptr := reflect.ValueOf(valuePtr).Elem().Addr().Interface().(*string)
can be written more directly as ptr := valuePtr.(*string)
.