Regex is not a permanent bug in Golang

I am trying to write a regular expression in Golang to make sure that the string contains only alphanumeric characters, periods, and underscores. However, I encountered an error that I had not seen before, and was not unsuccessful on Google.

Here's the regex:

pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`) 

Here is the error:

 const initializer regexp.MustCompile("^[A-Za-z0-9_\\.]+") is not a constant 

What does “not permanent” mean and how can I fix it?
Thanks.

+3
source share
3 answers

This usually happens when you try to assign a package level variable that is of a type that cannot be constant (like Regexp ). Only basic types int , string , etc. May be permanent. See here for more details.

Example:

 pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`) // which translates to: const pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`) 

You must declare it as var for it to work:

 var pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`) 

In addition, I usually put a note to say that the variable is treated as a constant:

 var /* const */ pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`) 
+9
source

The error is pretty clear. If you are trying to do it globally ...

Do not execute:

 const pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`) 

Instead, run:

 var pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`) 

Or if you really want a template in constant:

 const pattern = `^[A-Za-z0-9_\.]+` var alphaNum = regexp.MustCompile(pattern) 
+5
source

In the context of a Go declaration, assigning with a simple = creates a constant, not a variable. (Outside of the declaration, this is a variable assignment that must already exist.)

But constant initialization should only include constants - not calls like regexp.MustCompile() - so pattern cannot be a constant in this case, even if you do not plan to change its value later. (In fact, even if you somehow initialized it without invoking anything, Regexp cannot be a constant in Go, there can only be basic types.)

This means that you need to make it a variable, either by placing it in the var statement, or by declaring it inside the function with := instead of = :

 var ( pattern = ... ) 

or

 var pattern = ... 

or

 func something() { pattern := ... } 
+4
source

Source: https://habr.com/ru/post/1272025/


All Articles