[英]How to print tag for slice of struct within a struct
我有 struct 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
创建新变量,然后使用反射尝试获取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
}
工作游乐场: https : //play.golang.org/p/TJDCEVm23Hz
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.