Golang中的正则表达“不是常量”错误
发布时间:2020-12-16 19:26:03 所属栏目:大数据 来源:网络整理
导读:我正在尝试在Golang中编写一个正则表达式来验证字符串是否只有字母数字,句点和下划线.但是,我遇到了一个我以前没有见过的错误,并且在Googling上没有成功. 这是正则表达式: pattern = regexp.MustCompile(`^[A-Za-z0-9_.]+`) 这是错误: const initializer
我正在尝试在Golang中编写一个正则表达式来验证字符串是否只有字母数字,句点和下划线.但是,我遇到了一个我以前没有见过的错误,并且在Googling上没有成功.
这是正则表达式: pattern = regexp.MustCompile(`^[A-Za-z0-9_.]+`) 这是错误: const initializer regexp.MustCompile("^[A-Za-z0-9_.]+") is not a constant 什么“不是常数”是什么意思,我该如何解决这个问题?
当您尝试分配具有不能为常量的类型的包级变量时(例如,Regexp),通常会发生这种情况.只有基本类型如int,string等可以是常量.有关详细信息,请参见
here.
例: pattern = regexp.MustCompile(`^[A-Za-z0-9_.]+`) // which translates to: const pattern = regexp.MustCompile(`^[A-Za-z0-9_.]+`) 你必须将它声明为var才能工作: var pattern = regexp.MustCompile(`^[A-Za-z0-9_.]+`) 另外,我通常会说明变量被视为常量: var /* const */ pattern = regexp.MustCompile(`^[A-Za-z0-9_.]+`) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |