Shuai Lin | 8 Aug 2012 19:23
Picon
Gravatar

create a value from reflect.Type

The problems is like this: type P implements interface F with pointer receiver, i.e.:

type P struct {}
type I interface {f()}
func (p *P) f() {}

I want to store the type of P, and later use this type to create a variable that implements I

So I do something like this:

pType := reflect.TypeOf(P{})
i := reflect.Zero(pType)
p := i.Interface() // p has dynamic type P, not *P, so it does not implement interface I

Given all this, how can I get a variable that implements interface I?

Shuai Lin | 8 Aug 2012 20:44
Picon
Gravatar

Re: create a value from reflect.Type

I asked the same question in #go-nuts and someone gave me the answer:

reflect.New(procType) would return a reflect.Value with *P as the underlying value

在 2012年8月9日星期四UTC+8上午1时23分33秒,Shuai Lin写道:

The problems is like this: type P implements interface F with pointer receiver, i.e.:

type P struct {}
type I interface {f()}
func (p *P) f() {}

I want to store the type of P, and later use this type to create a variable that implements I

So I do something like this:

pType := reflect.TypeOf(P{})
i := reflect.Zero(pType)
p := i.Interface() // p has dynamic type P, not *P, so it does not implement interface I

Given all this, how can I get a variable that implements interface I?

Gmane