Create a new structure with reflection from the type defined by the nil pointer

I would like to know if it is possible to extract a structure from the type indicated by the nil pointer 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 can I do it?

+6
source share
1 answer

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 the comments below indicated that you can get the structure without unsafe.Pointer 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

+8
source

Source: https://habr.com/ru/post/979171/


All Articles