Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape a backtick inside a Go struct tag

Tags:

go

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

}

like image 434
Victor Timofei Avatar asked May 08 '20 15:05

Victor Timofei


People also ask

What is Backtick Golang?

Backtick strings are analogues of any multiline raw string within Python or else Scala: r""" text""" or within JavaScript: String. raw`Hello\u000A!` They are useful: For keeping huge text inside. For regular expressions, while you own many of backslashes.

What are the use s for tags in Go?

In the Go Language Specification, it mentions a brief overview of tags: A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration. The tags are made visible through a reflection interface but are otherwise ignored.


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}
like image 114
Marc Avatar answered Dec 03 '22 08:12

Marc