Ben McCormack
Ben McCormack

Reputation: 33078

How do I create a Go type derived from string that matches a pattern?

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

Answers (1)

dev.bmax
dev.bmax

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

Related Questions