如何创建一个从字符串派生的 Go 类型,该类型与某个模式匹配?

huangapple go评论86阅读模式
英文:

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

huangapple
  • 本文由 发表于 2017年2月8日 20:16:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/42112907.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定