添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I'm trying to write a regex in Go to verify that a string only has alphanumerics, periods, and underscores. However, I'm running into an error that I haven't seen before and have been unsuccessful at Googling.

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 a constant" mean and how do I fix this?

This happens when you're trying to assign to a constant that has a type that can't be constant (like for example, Regexp). Only basic types likes int, string, etc. can be constant. 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 have to declare it as a 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_\.]+`)

In Go declaration context, assignment with a simple = creates a constant, not a variable. (Outside of a declaration, it's an assignment to a variable that must already exist.)

But a constant initialization has to include only constants - not calls like regexp.MustCompile() - so pattern can't be a constant in this case, even if you don't plan on changing its value later. (In fact, even if you could somehow initialize it without calling anything, a Regexp can't be a constant in Go; only basic types can be.)

That means you need to make it a variable by either putting it inside a var statement or declaring it inside a function with := instead of =:

var (
   pattern = ...
var pattern = ...
func something() {
   pattern := ...
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.