本文介绍了正则表达式“不是恒定的".编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Go中编写一个正则表达式,以验证字符串仅包含字母数字,句点和下划线.但是,我遇到了一个以前从未见过的错误,并且在Googling上失败了.

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.

这是正则表达式:

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

这是错误:

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

什么不是常数"?是什么意思,我该如何解决?

What does "not a constant" mean and how do I fix this?

推荐答案

当您尝试分配给一个类型不能为常数的常量(例如 Regexp ).只有基本类型(例如 int string 等)可以是常量.有关更多详细信息,请参见此处.

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.

示例:

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

要使其正常工作,必须将其声明为 var :

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_\.]+`)

这篇关于正则表达式“不是恒定的".编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 06:16