Omkar Chavan
Omkar Chavan

Reputation: 94

Can 2 fields in struct have same struct tags in Go

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"`
}

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

Upvotes: -1

Views: 235

Answers (1)

mleko
mleko

Reputation: 12233

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.

Upvotes: 1

Related Questions