反射 – Golang-获取结构属性名称
发布时间:2020-12-16 09:23:45 所属栏目:大数据 来源:网络整理
导读:我想使用reflect包返回struct属性的名称.到目前为止,我有: type MultiQuestions struct { QuestionId int64 QuestionType string QuestionText string }func (q *MultiQuestions) StructAttrName() string { return reflect.ValueOf(q).Elem().Field(0).Nam
我想使用reflect包返回struct属性的名称.到目前为止,我有:
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 undefined(类型reflect.Value没有字段或方法名称) 我尝试过转换为StructField,但这也没有用.我如何获得Struct的名称? 在这种情况下,我感兴趣的名称是QuestionId,QuestionType和QuestionText. 解决方法
您需要操作Type而不是Value
func (q *MultiQuestions) StructAttrName() string { return reflect.Indirect(reflect.ValueOf(q)).Type().Field(0).Name } playground (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |