I would like know if it is possible to allocate a struct from a type specified by a nil
pointer by using reflect.New()
type SomeType struct{
A int
}
sometype := (*SomeType)(nil)
v := reflect.valueOf(sometype)
// I would like to allocate a new struct based on the type defined by the pointer
// newA := reflect.New(...)
//
newA.A = 3
How should I do this ?
Use reflect.Type.Elem()
:
s := (*SomeType)(nil)
t := reflect.TypeOf(s).Elem()
v := reflect.New(t)
sp := (*SomeType)(unsafe.Pointer(v.Pointer()))
sp.A = 3
Playground: http://play.golang.org/p/Qq8eo-W2yq
EDIT: Elwinar in comments below pointed out that you can get the struct without unsafe.Pointer
by using reflect.Indirect()
:
s := (*SomeType)(nil)
t := reflect.TypeOf(s).Elem()
ss := reflect.Indirect(reflect.New(t)).Interface().(SomeType)
ss.A = 3
Playground: http://play.golang.org/p/z5xgEMR_Vx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With