Home  >  Article  >  Backend Development  >  Get the field names in the structure

Get the field names in the structure

WBOY
WBOYforward
2024-02-06 08:25:03982browse

Get the field names in the structure

Question content

I wrote a program to retrieve the field names within a structure and it works perfectly. However, it doesn't work when it comes to the struct pointer inside the struct.

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

When checking the type pointer structure, it shows "Ptr" using reflection package, but when I do Elem(), it says is there any way to fix this?

I just want to get every field name in MAP that is marked with "encr".


Correct answer


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

The calling method is as follows:

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

https://www.php.cn/link/761213bcd999998a5b22d22b13db075f

The above is the detailed content of Get the field names in the structure. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete