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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大