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
Mustwraps a call that returns a value and an error.- Only use it for package-level initialization.
- Generics let one Must serve every type.
Keywords and builtins used here
anyboolerrorfuncifpanicreturnstringvar
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.
Step 2 of 2 in Your own errors, step 9 of 15 in Errors.