英文:
How to access the embedded struct inside the Slice of Pointers field of a Struct
问题
我想要添加一个功能,当数据是[]*struct
时,取第一个元素。
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)
}
}
}
在这段代码中,当数据是[]*Struct
时,我需要添加功能。以下是要传递给此函数的结构类型。
type Customer struct {
Name string `json:"name" bson:"name"`
Acnumber int64 `json:"acnumber" bson:"acnumber,encr"`
Number int64 `json:"number" bson:"number,encr"`
Address []*Address `json:"address" bson:"address"`
}
type Address struct {
Mail string `json:"mail" bson:"mail,encr"`
}
谢谢您的支持。
英文:
I want to add functionality to take the first element when the data is []*struct
.
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)
}
}
In this code I need to add functionality when the data is []*Struct
. Here is the struct type to be passed in this function.
type Customer struct {
Name string `json:"name" bson:"name"`
Acnumber int64 `json:"acnumber" bson:"acnumber,encr"`
Number int64 `json:"number" bson:"number,encr"`
Address []*Address `json:"address" bson:"address"`
}
type Address struct {
Mail string `json:"mail" bson:"mail,encr"`
}
Thank you for your support
答案1
得分: 3
通过指针,可以像遍历数组、切片和映射一样深入查看。
func getEncFields(t reflect.Type, list map[string]int) {
for t.Kind() == reflect.Ptr || t.Kind() == reflect.Slice || t.Kind() == reflect.Array || t.Kind() == reflect.Map {
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)
}
}
}
你可以在这里查看代码示例:https://go.dev/play/p/1msFGC89NX-
英文:
Drill down through arrays, slices and maps as you do for pointers.
func getEncFields(t reflect.Type, list map[string]int) {
for t.Kind() == reflect.Ptr || t.Kind() == reflect.Slice || t.Kind() == reflect.Array || t.Kind() == reflect.Map {
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)
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论