go - 制作自定义结构类型的常量全局变量

标签 go types constants

我想创建一个“类”来处理输入验证。我首先创建一个 Input 类型,它是一个用于存储用户输入的字符串,以及一个 REGP 类型,它存储正则表达式模式和模式的描述。我创建了两个常量实例 REGP_LOGINNAMEREGP_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
}

错误信息:

/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.

最佳答案

Go 中的常量只能是标量值(例如。2true3.14“and more”) 或任何仅由常量组成的表达式(例如 1 + 2"hello "+ "world"2 * math.Pi * 1i).

这意味着不能将非标量值的结构类型(例如您的 REGP_LOGINNAME)分配给常量。相反,使用变量:

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",
    }
)

延伸阅读

旁白:当然,我不知道您的用例,但我真的真的怀疑您是否真的需要或想要使用正则表达式来验证用户密码.相反,考虑通过 OpaqueString profile of PRECIS 传递它(用于处理和加强 unicode 字符串安全性的框架;不透明字符串配置文件旨在处理密码)。同样,UsernameCaseMapped 和 UsernameCasePreserved 配置文件(也在链接包中实现)可用于用户名,以确保您最终不会得到两个看起来相同但具有不同 unicode 字符的用户名。当然也可以做进一步的验证。

关于go - 制作自定义结构类型的常量全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38542588/

相关文章:

function - 绑定(bind)到结构的 Golang 函数类型?

go - 将文件放入 Go 中的 amazon s3 后如何获取文件 url?

json - 如何覆盖 Go 结构中的 json 标签?

variables - 通过尽可能多地定义常量而不是变量在 Swift 中有什么好处吗?

c++ - const数组更改c++的问题

c++ - 静态常量 std::vector

go - 了解测试覆盖率

c# - 如何将值四舍五入到小数点后三位?

typescript - 如何使用类型来强制执行特定的参数对?

Haskell 函数接受一个类型和一个值并检查值是否具有该类型