英文:
How do I create a Go type derived from string that matches a pattern?
问题
我正在尝试创建一个新的Go类型,它基于string
,但需要匹配一个模式(Slack用户名,例如@ben
)。
在使用时,该类型应该类似于:
var user SlackUser
user = SlackUser("@ben")
fmt.Println(user) // 这应该打印出:@ben
如果匹配了模式,NewSlackUser
将正常工作。如果不匹配,将抛出一个错误。
要匹配的模式基于这里,模式为:
^@[a-z0-9][a-z0-9._-]*$
(我对Go非常陌生,所以非常感谢对我的方法的任何纠正)
英文:
I'm trying to create a new Go type that's based on string
but is required to match a pattern (Slack username, e.g. @ben
).
When used, the type would look something like:
var user SlackUser
user = SlackUser("@ben")
fmt.Println(user) //This should print: @ben
If it matches the pattern, NewSlackUser
will work. If it doesn't, it will throw an error.
The pattern to match, which is based on this, is:
^@[a-z0-9][a-z0-9._-]*$
(I'm very new to Go, so any correction to my approach is much appreciated)
答案1
得分: 4
使用结构体类型:
type SlackUser struct {
username string
}
编译正则表达式:
var (
pattern = regexp.MustCompile("^@[a-z0-9][a-z0-9._-]*$")
)
构造函数:
func NewSlackUser(username string) (*SlackUser, error) {
if !pattern.MatchString(username) {
return nil, errors.New("Invalid username.")
}
return &SlackUser{username}, nil
}
Stringer:
func (s *SlackUser) String() string {
return s.username
}
完整示例:点击此处
英文:
Use a struct type:
type SlackUser struct {
username string
}
Compile the regular expression:
var (
pattern = regexp.MustCompile("^@[a-z0-9][a-z0-9._-]*$")
)
Constructor:
func NewSlackUser(username string) (*SlackUser, error) {
if !pattern.MatchString(username) {
return nil, errors.New("Invalid username.")
}
return &SlackUser{ username }, nil
}
Stringer:
func (s *SlackUser) String() string {
return s.username
}
Full example
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论