Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a new struct with reflect from type defined by a nil pointer

Tags:

reflection

go

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 ?

like image 709
yageek Avatar asked Dec 05 '14 13:12

yageek


1 Answers

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

like image 188
Ainar-G Avatar answered Nov 07 '22 09:11

Ainar-G