N
N
Nikita2020-12-15 19:17:50
go
Nikita, 2020-12-15 19:17:50

How to pass the value of a constant to a struct tag?

There is a code:

const (
  MIN = 60 * 10
  MAX = 60 * 24 * 24 * 30
)

type Item struct {
  Seconds int `valid:"required,range(MIN|MAX)"`
}

func NewItem(seconds int) (*Item, error) {
  item := &Item{
    Seconds: seconds,
  }

  _, err := govalidator.ValidateStruct(item)
  if err != nil {
    return nil, fmt.Errorf(err.Error())
  }

  return item, nil
}

play.golang.org

Is it possible to pass the value of constants (MIN,MAX) to the "valid" tag?
Something like this:
Seconds int `valid:"required,range(${MIN}|${MAX})"`


UPD
https://github.com/golang/go/issues/4740#issuecomm...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pavlyuk, 2020-12-15
@somebug

No, structure tag is a string literal.
https://golang.org/ref/spec#Struct_types

A
Anatoly Evladov, 2020-12-16
@Visteras

Unless through the generator to make the generation already with the specified values, but it will still be a simple string literal. So only through the generator if there are many similar values.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question