-1

I have struct Config which consist of Field SliceOfAnotherStruct which contained the slice of pointer to AnotherStruct.

Here how could I get the json tag for field Bank in 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"`
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • 1
    You gave the answer as a tag: Use reflection. It is not trivial. XY problem? Redesign? – Volker Oct 31 '18 at 06:17
  • 1
    Possible duplicate of [Golang Reflection: Get Tag from struct field](https://stackoverflow.com/questions/23507033/golang-reflection-get-tag-from-struct-field) – Emile Pels Oct 31 '18 at 06:47

1 Answers1

0

Create new variable using AnotherStruct, then by using reflect try to get the Bank field, after that you'll be able to get it's tag.

// 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
}

Working playground: https://play.golang.org/p/TJDCEVm23Hz

novalagung
  • 10,905
  • 4
  • 58
  • 82