我正在尝试使用golang中的反射功能从结构中读取数据,但是我想知道该怎么做才能忽略字段名的大小写。

我有以下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
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())
}

由于字段名称的小写,上面的函数对两者都返回

有没有办法我可以忽略这种情况?

  • 我不这么认为,因为您可以在具有相同名称的结构中使用不同的大小写。
  • 据我所知,Golang还不支持属性别名。

查找字段时,请使用Value.FieldByNameFunc和strings.ToLower忽略大小写:

1
2
3
4
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 })
}

像这样使用它:

1
2
3
4
5
6
7
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())
}

在操场上运行它。