moe*_*sef 5 reflection struct go
我想使用 Reflect 包返回结构属性的名称。到目前为止我有:
type MultiQuestions struct {
QuestionId int64
QuestionType string
QuestionText string
}
func (q *MultiQuestions) StructAttrName() string {
return reflect.ValueOf(q).Elem().Field(0).Name
}
Run Code Online (Sandbox Code Playgroud)
但是,这给了我一个错误reflect.ValueOf(q).Elem().Field(0).Name undefined (type reflect.Value has no field or method Name)
我尝试转换为 StructField 但也不起作用。如何获取 Struct 的名称?
在本例中,我感兴趣的名称是 QuestionId、QuestionType 和 QuestionText。
您需要操作的Type是Value
func (q *MultiQuestions) StructAttrName() string {
return reflect.Indirect(reflect.ValueOf(q)).Type().Field(0).Name
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7517 次 |
| 最近记录: |