0

I want to set tag dynamically in struct fields in Go.

For example, I have a struct like this,

type user struct {
  Name  string  
  Email  string `valid:"MaxSize(1)"` characters.
}

Now during execution, I want to set same tags for name field as well.

I am trying something like this,

    switch {
    case isStruct(objT):
    case isStructPtr(objT):
        objT = objT.Elem()
    default:
        //err = fmt.Errorf("%v must be a struct or a struct pointer", model)
        return
    }

    for i := 0; i < objT.NumField(); i++ {
        // ... and start using structtag by parsing the tag
        fmt.Println(objT.Field(i))
        objT.Field(i).Tag = `valid:"MaxSize(1)"`
    }

But I am unable to assign tag like this. can Somebody help?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Ameer Hamza
  • 586
  • 3
  • 16
  • you cannot do that. re think your approach. –  Nov 22 '19 at 07:20
  • actually I want to set default max size for all string fields in struct. So that is the approach I thought of. Can you help me in this i.e I want to set default length of a string even if does not contain any valid tags ? – Ameer Hamza Nov 22 '19 at 07:23
  • state your problem using a small reproducible example of your goals and make a new question. –  Nov 22 '19 at 07:24
  • Dublicate of https://stackoverflow.com/questions/42546519/how-do-i-dynamically-change-the-structs-json-tag – sontags Nov 22 '19 at 07:44
  • No, this is not i am looking for. – Ameer Hamza Nov 22 '19 at 07:47

0 Answers0