2

I have code

var t reflect.Type = LaunchController(route.controller)

    // create controller ptr .
    var appControllerPtr reflect.Value = reflect.New(t)
    fmt.Println(appControllerPtr) //#=> <**controller.AppController Value>
    var appController reflect.Value = appControllerPtr.Elem()
    // Create and configure base controller
    var c *Controller = &Controller{
            Request: r,
            Writer: w,
            Name: t.Name(),
        }

    //this should assign *goninja.Controller field in application controllers
    var controllerField reflect.Value = reflect.ValueOf(appController).Field(0)
    controllerField.Elem().Set(reflect.ValueOf(c))

This creates pointer to element, and afterwards trying to assign value, into 0 field of this struct.

My struct, that i'm trying to reflect looks like

type AppController struct {
  *goninja.Controller
}

However when I'm trying to assign this field with code

controllerField.Elem().Set(reflect.ValueOf(c))

I'm facing following error

reflect: reflect.Value.Set using value obtained using unexported field

What am i doin wrong? Also I cant understand why my reflect.New(t) returns reflect.Value with 2 asterisks in beginning **

1 Answer 1

2

You don't give your complete code, so I have to guess a bit, but I suspect that the Controller field of the AppController structure has a lower-case name. Right? Here is my attempt to produce a minimal example from your code: working (with upper-case field name) and non-working (with lower-case fieldname).

Also: where you write reflect.ValueOf(appController).Field(0), the appController is already of type reflect.Value, so the ValueOf is not required. You can just write appController.Field(0) as in the example code I linked above.

3
  • Controller field of my struct AppController is just embedded field. I've checked if I have any unexporting fields, and none avaialble. Also reason why am i doing 2 times ValueOf - because otherwise i have error reflect: call of reflect.Value.FieldByName on ptr Value. Updated code with comment
    – Avdept
    Commented Jun 8, 2015 at 20:26
  • Can you provide complete code (e.g. on play.golang.org) which shows the error message(s)?
    – jochen
    Commented Jun 8, 2015 at 21:25
  • Not sure how can i do that, since i have few different modules
    – Avdept
    Commented Jun 9, 2015 at 6:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.