Reflection Golang-获取结构属性名称
我想使用reflect包返回struct属性的名称。到目前为止,我已经:Reflection Golang-获取结构属性名称,reflection,struct,go,Reflection,Struct,Go,我想使用reflect包返回struct属性的名称。到目前为止,我已经: type MultiQuestions struct { QuestionId int64 QuestionType string QuestionText string } func (q *MultiQuestions) StructAttrName() string { return reflect.ValueOf(q).Elem().Field(0).N
type MultiQuestions struct {
QuestionId int64
QuestionType string
QuestionText string
}
func (q *MultiQuestions) StructAttrName() string {
return reflect.ValueOf(q).Elem().Field(0).Name
}
但是,这给了我一个错误reflect.ValueOf(q).Elem().Field(0).Name未定义(reflect.Value类型没有字段或方法名)
我试着在StructField上选角,但也没用。如何获取Struct的名称
在本例中,我感兴趣的名称是QuestionId、QuestionType和QuestionText。您需要对
类型进行操作,而不是对值进行操作
func (q *MultiQuestions) StructAttrName() string {
return reflect.Indirect(reflect.ValueOf(q)).Type().Field(0).Name
}
使用以下类型:
package main
import (
"fmt"
"reflect"
)
type MultiQuestions struct {
QuestionId int64
QuestionType string
QuestionText string
}
func (q *MultiQuestions) StructAttrName() string {
return reflect.TypeOf(q).Elem().Field(0).Name
}
func main() {
fmt.Println((&MultiQuestions{}).StructAttrName())
}
您也可以考虑定义在函数中的实用函数,比如在指针或对象上工作的函数,包括<代码>结构> <代码>结构> <代码> >
package main
import (
"fmt"
"reflect"
"github.com/fatih/structure"
)
type MultiQuestions struct {
QuestionId int64
QuestionType string
QuestionText string
SubMQ SubMultiQuestions
}
type SubMultiQuestions struct{}
func (q *MultiQuestions) StructAttrName() string {
return reflect.Indirect(reflect.ValueOf(q)).Type().Field(0).Name
}
func main() {
fmt.Println((&MultiQuestions{}).StructAttrName())
fmt.Println(Fields(&MultiQuestions{}))
fmt.Println(Fields(MultiQuestions{}))
}
输出:
SubMQ
[QuestionId QuestionType QuestionText SubMQ]
[QuestionId QuestionType QuestionText SubMQ]
请参阅本文中的完整示例