I have a type
type SpecialString *string
I have two reflect values, aVal
and bVal
(just to be clear aVal
and bVal
are of type reflect.Value
) where
aVal.Type() // *SpecialString
bVal.Type() // *string
In regular code I can create c
, a pointer to a special string like so:
a := "foo"
b := SpecialString(&a)
c := &b
How can I achieve the same using reflection?
aval.Set(bVal) // does not work: "reflect.Set: value of type *string is not assignable to type *SpecialString"
You need to convert the types and pay attention to what you can and cannot set. Something like:
type SpecialString string
var s string = "source regular string"
var ss SpecialString
// Get the reflect.Value of the thing &ss pointing at.
ssv := reflect.ValueOf(&ss).Elem()
// You need to convert string to SpecialString explicitly
ssv.Set(reflect.ValueOf(s).Convert(ssv.Type()))
fmt.Printf("ss = %T %+#v
", ss, ss)