Can 2 fields in struct have same struct tags in Go

157 Views Asked by At

I have Struct Type for binding SQL data to my struct variable. It has 2 Feilds as CenterCode and ActualCenterCode

type LearnerModel struct {
    CenterCode dbr.NullString  `json:"centerCode" db:"LEARNINGCENTERCODE"`
    ActualCenterCode dbr.NullString  `json:"actualCenterCode" db:"LEARNINGCENTERCODE"`
    SomeOtherFeild dbr.NullString  `json:"someOtherFeild" db:"SOMEOTHERFEILD"`
}
  • The ActualCenterCode would be the same as CenterCode if SomeOtherFeild is Null.
  • Else ActualCenterCode will be set to SomeOtherFeild.

My question is when I bind this data using

"github.com/gocraft/dbr"

session.Select(selectQuery).From(tableName).Where("LearnerID IN ?", learnerIDs).Load(&learnerModelObj)

I get CenterCode as the data in Database but the ActualCenterCode is set to null. I have to send this data to another server via API where I can handle this condition, but is there a way to handle this via struct

1

There are 1 best solutions below

0
mleko On

Yes, multiple fields can have same struct tags, how they will be interpreted though is up to the libraries using those tags.

In this case it seems that library you use, ignores duplicate mappings. In my opinion this makes sense as otherwise there would ambiguity which data to save if it would happen that CenterCode and ActualCenterCode contain different values during save.

If I understand correctly your intention, I would rather add accessor method containing logic you described.

Something like

type LearnerModel struct {
    CenterCode dbr.NullString  `json:"centerCode" db:"LEARNINGCENTERCODE"`
    SomeOtherFeild dbr.NullString  `json:"someOtherFeild" db:"SOMEOTHERFEILD"`
}

func (m *LearnerModel) ActualCenterCode() dbr.NullString {
  if m.SomeOtherFeild != nil {
    return m.SomeOtherFeild
  }
  return m.CenterCode
}

This way there is no ambiguity.