Reputation: 33078
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)
Upvotes: 0
Views: 221
Reputation: 10581
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
Upvotes: 4