0

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

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.