Golang-获取结构属性名称

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。

One*_*One 5

您需要操作的TypeValue

func (q *MultiQuestions) StructAttrName() string {
    return reflect.Indirect(reflect.ValueOf(q)).Type().Field(0).Name
}
Run Code Online (Sandbox Code Playgroud)

playground