dongrao9454 2014-08-04 21:35 采纳率: 100%
浏览 1265

Golang-获取结构属性名称

I want to return the name of a struct attribute using the reflect package. So far I have:

type MultiQuestions struct {
    QuestionId      int64  
    QuestionType    string 
    QuestionText    string 
}
func (q *MultiQuestions) StructAttrName() string {
    return reflect.ValueOf(q).Elem().Field(0).Name
}

However, this gives me a error reflect.ValueOf(q).Elem().Field(0).Name undefined (type reflect.Value has no field or method Name)

I tried casting to StructField but that didn't work either. How do I get at the name of Struct?

In this case, the names I am interested in are QuestionId, QuestionType and QuestionText.

  • 写回答

3条回答 默认 最新

  • dongyuan2388 2014-08-04 22:10
    关注

    You need to operate on the Type not the Value

    func (q *MultiQuestions) StructAttrName() string {
        return reflect.Indirect(reflect.ValueOf(q)).Type().Field(0).Name
    }
    

    <kbd>playground</kbd>

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分