我有结构Config,它由Field SliceOfAnotherStruct组成,其中包含指向AnotherStruct的指针切片。
在这里,我如何获取AnotherStruct中字段Bank的json标签。
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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句