10

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 ?

1 Answer 1

12

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

Sign up to request clarification or add additional context in comments.

3 Comments

Is it the only possibility ? Is there a way without using the unsafe package ?
To prevent having to use the unsafe package, you should use the reflect.Indirect method. One-liner : reflect.Indirect(reflect.New(reflect.TypeOf(sometype).Elem())).Interface().(SomeType)
Is it the same operation to proceed but starting with an interface ? I mean you have an object A implementing the I interface. I start from the interface I and I would like to create the same underlying object that implement the interface I using reflect ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.