Get the field names in the structure

WBOY
Release: 2024-02-06 08:25:03
forward
894 people have browsed it

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) } } }
Copy after login

The calling method is as follows:

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

//m.sbmmt.com/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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!