dozc58418381 2019-01-09 22:55
浏览 551
已采纳

忽略golang反射中的大小写FieldByName

I am trying read from a struct using reflection in golang which I was able to do successfully but I am wondering what can I do to ignore case of a field name.

I have the below code

type App struct{
    AppID        string
    Owner        string
    DisplayName  string
}

func Extract(app *App){
appData := reflect.ValueOf(app)
appid := reflect.Indirect(appData).FieldByName("appid")
fmt.Println(appid.String())
owner:=reflect.Indirect(appData).FieldByName("owner")
fmt.Println(owner.String())
}

The above function returns <invalid-value> for both and its because of the lower case of the field name

Is there a way I could ignore the case?

  • 写回答

1条回答 默认 最新

  • doupi4649 2019-01-10 01:54
    关注

    Use Value.FieldByNameFunc and strings.ToLower to ignore case when finding a field:

    func caseInsenstiveFieldByName(v reflect.Value, name string) reflect.Value {
        name = strings.ToLower(name)
        return v.FieldByNameFunc(func(n string) bool { return strings.ToLower(n) == name })
    }
    

    Use it like this:

    func Extract(app *App) {
        appData := reflect.ValueOf(app)
        appid := caseInsenstiveFieldByName(reflect.Indirect(appData), "appid")
        fmt.Println(appid.String())
        owner := caseInsenstiveFieldByName(reflect.Indirect(appData), "owner")
        fmt.Println(owner.String())
    }
    

    Run it on the Playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝