英文:
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 < t.NumField(); i++ {
field := t.Field(i)
tag := field.Tag.Get("bson")
if containsTag(tag, "encr") {
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论