在结构体内获取字段名称

huangapple go评论82阅读模式
英文:

Getting Field name inside a struct

问题

我已经编写了一个程序来获取结构体内部字段的名称,它运行得非常好。然而,当涉及到结构体内部的结构体指针时,它就无法正常工作。

在检查结构体指针类型时,使用反射包显示为"Ptr",但当我使用Elem()时,它显示为""。有没有办法解决这个问题?

我只想获取带有"encr"标签的每个字段名称在MAP中。

英文:

I have written a program to retrieve the names of fields inside a struct, and it works perfectly fine. However, when it comes to a pointer of struct inside a struct, it doesn't work.

https://go.dev/play/p/pHrNRhfZSM4

while checking type pointer struct its shows "Ptr" using reflect package but when I do Elem() it says <invalid reflect.Value> is there any way to solve this?

I just want to get every field name with "encr" tag in MAP.

答案1

得分: 3

使用类型而不是值进行操作:

func getEncFields(t reflect.Type, list map[string]int) {
    // 解引用指针类型。
    for t.Kind() == reflect.Ptr {
        t = t.Elem()
    }
    // 在结构体字段中查找标签。
    if t.Kind() == reflect.Struct {
        for i := 0; i < t.NumField(); i++ {
            field := t.Field(i)
            tag := field.Tag.Get("bson")
            if containsTag(tag, "encr") {
                list[getFieldName(field, tag)]++
            }
            getEncFields(field.Type, list)
        }
    }
}

这是如何调用它的示例:

listOfEncTags := make(map[string]int)
getEncFields(reflect.TypeOf(Gadget{}), listOfEncTags)
fmt.Println(listOfEncTags)

点击此处查看示例代码

英文:

Work with types instead of values:

func getEncFields(t reflect.Type, list map[string]int) {
    // Dereference pointer types.
	for t.Kind() == reflect.Ptr {
		t = t.Elem()
	}
    // Look for tags in struct fields.
	if t.Kind() == reflect.Struct {
		for i := 0; i &lt; t.NumField(); i++ {
			field := t.Field(i)
			tag := field.Tag.Get(&quot;bson&quot;)
			if containsTag(tag, &quot;encr&quot;) {
				list[getFieldName(field, tag)]++
			}
			getEncFields(field.Type, list)
		}
	}
}

Here's how to call it:

listOfEncTags := make(map[string]int)
getEncFields(reflect.TypeOf(Gadget{}), listOfEncTags)
fmt.Println(listOfEncTags)

https://go.dev/play/p/5JsOil-P-RH

huangapple
  • 本文由 发表于 2023年4月27日 23:09:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76121986.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定