Dagrada
Dagrada

Reputation: 1155

How to get struct field from refect.Value

Given

type Runnable interface {
     Run()
}

type T struct {
    Z struct {
        A int
    }
}

func (t T) Run() {
    t.Z.A = 1
}

func main() {
    t := reflect.TypeOf( T{} )

    var v reflect.Value
    v = reflect.New(t).Elem()

    runnable := v.Interface().(Runnable)
    runnable.Run()

Is there a way, at the end, to retrive Z and its field values as set by the Run() method?

I am implementing an API command pattern, so T could be RegisterCommand, LoginCommand, LogoutCommand etc. Z is the 'output doc' - a JSON doc returned by the API command - which I want to specify declaratively and have written to the network after the command is run.

Upvotes: 1

Views: 59

Answers (1)

Dagrada
Dagrada

Reputation: 1155

Got it! Thank you to synful for the 'pointer' :-)

    z := v.Elem().FieldByName("Z").Interface()

Upvotes: 1

Related Questions