Cas*_*per 3 types constants go
我想创建一个“类”来处理输入验证。我首先创建一个类型,Input其中一个是用于存储用户输入的字符串,另一个是REGP存储正则表达式模式和模式描述的类型。我创建了两个常量实例REGP_LOGINNAME和REGP_PASSWORD. 但我得到const initializer REGP literal is not a constant. 为什么?
package aut
import "regexp"
type Input string
type REGP struct {
pattern string
Descr string
}
const REGP_LOGINNAME = REGP{ //const initializer REGP literal is not a constant
"regex pattern 1",
"regex description 1",
}
const REGP_PASSWORD = REGP{ //const initializer REGP literal is not a constant
"regex pattern 2",
"regex description 2",
}
func (i Input) isMatch(regp REGP) bool {
isMatchREGP, _ := regexp.MatchString(regp.pattern, string(i))
return isMatchREGP
}
Run Code Online (Sandbox Code Playgroud)
错误信息:
/usr/local/go/bin/go build -i [/home/casper/gopath/codespace_v2.6.6/dev/server_side/golang/go_codespace_v2.1/server/lib/aut]
# _/home/casper/gopath/codespace_v2.6.6/dev/server_side/golang/go_codespace_v2.1/server/lib/aut
./validation.go:15: const initializer REGP literal is not a constant
./validation.go:20: const initializer REGP literal is not a constant
Error: process exited with code 2.
Run Code Online (Sandbox Code Playgroud)
Go 中的常量只能是标量值(例如2、true、3.14、"and more")或任何仅由常量组成的表达式(例如1 + 2、"hello " + "world"、 或2 * math.Pi * 1i)。
这意味着REGP_LOGINNAME不能将诸如 your 之类的非标量值的结构类型分配给常量。相反,使用一个变量:
var (
REGP_LOGINNAME = REGP{
pattern: `/^(?=^.{6,20}$)^[a-zA-Z][a-zA-Z0-9]*[._-]?[a-zA-Z0-9]+$/`,
Descr: "regex description 1",
}
REGP_PASSWORD = REGP{
pattern: `/^(?=^.{8,}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s)[0-9a-zA-Z!@#$%^&*()]*$/`,
Descr: "regex description 2",
}
)
Run Code Online (Sandbox Code Playgroud)
旁白:当然,我不知道您的用例,但我真的很怀疑您是否真的需要或想要使用正则表达式来验证用户密码。相反,请考虑通过PRECIS的OpaqueString 配置文件(用于处理和实施 unicode 字符串安全的框架;不透明字符串配置文件旨在处理密码)。同样,UsernameCaseMapped 和 UsernameCasePreserved 配置文件(也在链接包中实现)可用于用户名,以确保您不会得到两个看起来相同但其中包含不同 unicode 字符的用户名。当然,也可以进行进一步的验证。