У меня есть структура Config, которая состоит из поля SliceOfAnotherStruct, содержащего фрагмент указателя на ДругойСтрукт.
Вот как я могу получить тег json для поля Bank в AnotherStruct.
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
Вы ответили тегом: используйте отражение. Это нетривиально. XY проблема? Редизайн?