How to escape a backtick inside a Go struct tag

Viewed 946

I want to escape a backtick inside a Go struct tag. For example in the code below:

type User struct {
   email string `validate: "regexp=`"`
   password string `validate: "min=8"`

}

1 Answers

You can use regular quotes. You'll just have to escape more characters, especially the quotes around the value part of the struct tag.

type User struct {
   Email string "validate:\"regexp=`\""
   Password string `validate:"min=8"`
}

And verify the tag value with reflection:

func main() {
  s := reflect.ValueOf(&User{}).Elem()
  fmt.Println(s.Type().Field(0))
}

Outputs:

{Email  string validate:"regexp=`" 0 [0] false}
Related