Go 如何在结构中打印结构切片的标记
我有一个struct Config,它由字段sliceofotherstruct组成,其中包含指向 另一个结构 在这里,我如何在另一个结构中获得field Bank的json标记Go 如何在结构中打印结构切片的标记,go,reflection,Go,Reflection,我有一个struct Config,它由字段sliceofotherstruct组成,其中包含指向 另一个结构 在这里,我如何在另一个结构中获得field Bank的json标记 type Config struct { SliceOfAnotherStruct []*AnotherStruct `bson:"anotherStruct" json:"anotherStruct" validate:"required,dive,required"` } t
type Config struct {
SliceOfAnotherStruct []*AnotherStruct `bson:"anotherStruct" json:"anotherStruct" validate:"required,dive,required"`
}
type AnotherStruct struct {
Name string `bson:"name" json:"name" validate:"required"`
Cost string `bson:"cost" json:"cost" validate:"required"`
Bank string `bson:"bank" json:"bank" validate:"required"`
IFSC string `bson:"ifsc" json:"ifsc" validate:"required"`
}
使用
AnotherStruct
创建新变量,然后使用reflect尝试获取Bank
字段,之后您将能够获取它的标记
// new object created from struct AnotherStruct
obj := AnotherStruct{}
// getting `Bank` field information.
// the `FieldByName` function return two variables,
// 1. the field data
// 2. a boolean data, determines whether field is exists or not
bankField, ok := reflect.TypeOf(obj).FieldByName("Bank")
if ok {
// if the field is exists, then get the desired tag
jsonTagValue := bankField.Tag.Get("json")
fmt.Println(jsonTagValue) // bank
}
工作场所:您给出的答案是一个标签:使用反射。这不是小事。XY问题?重新设计?可能重复的