typestar

The Must pattern in Go

For values that cannot fail at run time, panic at start-up instead.

func Must[T any](value T, err error) T {
    if err != nil {
        panic(err)
    }
    return value
}

var pattern = Must(regexp.Compile(`^[a-z][a-z0-9_-]{1,31}$`))

func validSlug(slug string) bool {
    return pattern.MatchString(slug)
}

How it works

  1. Must wraps a call that returns a value and an error.
  2. Only use it for package-level initialization.
  3. Generics let one Must serve every type.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
218
Tokens
56
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 32 seconds.

Type this snippet

Step 2 of 2 in Your own errors, step 9 of 15 in Errors.

← Previous Next →