英文:
Setting field using reflect.Set
问题
我已经翻译了你的代码,如下所示:
var t reflect.Type = LaunchController(route.controller)
// 创建控制器指针
var appControllerPtr reflect.Value = reflect.New(t)
fmt.Println(appControllerPtr) // => <**controller.AppController Value>
var appController reflect.Value = appControllerPtr.Elem()
// 创建并配置基础控制器
var c *Controller = &Controller{
Request: r,
Writer: w,
Name: t.Name(),
}
// 这将在应用程序控制器中分配*goninja.Controller字段
var controllerField reflect.Value = reflect.ValueOf(appController).Field(0)
controllerField.Elem().Set(reflect.ValueOf(c))
我正在尝试反射的结构如下:
type AppController struct {
*goninja.Controller
}
然而,当我尝试使用以下代码分配该字段时:
controllerField.Elem().Set(reflect.ValueOf(c))
我遇到了以下错误:
reflect: reflect.Value.Set using value obtained using unexported field
我做错了什么?另外,我不明白为什么我的reflect.New(t)
返回带有两个星号**
的reflect.Value
。
英文:
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
得分: 2
你没有提供完整的代码,所以我只能猜测一下,但我怀疑AppController
结构体的Controller
字段是小写的。对吗?这是我根据你的代码尝试创建一个最小示例:working(字段名为大写)和non-working(字段名为小写)。
另外,在你写的reflect.ValueOf(appController).Field(0)
中,appController
已经是reflect.Value
类型,所以不需要使用ValueOf
。你可以像我上面链接的示例代码中那样直接写appController.Field(0)
。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论