【问题标题】:Ignore case in golang reflection FieldByName在golang反射FieldByName中忽略大小写
【发布时间】:2019-06-04 18:54:09
【问题描述】:

我正在尝试使用 golang 中的反射从结构中读取,但我想知道如何忽略字段名称的大小写。

我有以下代码

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())
}

上面的函数返回<invalid-value>,因为字段名是小写的

有没有办法可以忽略此案?

【问题讨论】:

  • 我认为不会,因为您可以在结构中拥有不同的字段,名称相同但大小写不同。
  • 据我所知,Golang 也不支持属性别名。

标签: go reflection reflect


【解决方案1】:

在查找字段时使用Value.FieldByNameFuncstrings.ToLower 忽略大小写:

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 })
}

像这样使用它:

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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多