must

package
v0.14.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2025 License: MIT Imports: 1 Imported by: 0

Documentation

Overview

Package must provides helper functions that wrap calls returning `(T, error)` and panic if the error is non-nil. This is intended to reduce boilerplate code in specific, controlled contexts where an error should never happen.

Warning: Use with Extreme Care

The functions in this package intentionally convert a recoverable error into a non-recoverable panic. This is an anti-pattern in normal Go application code. It should only be used in situations where an error is truly unexpected and indicates a critical, unrecoverable programmer error (e.g., a bug).

Appropriate Use Cases

  1. **Program Initialization:** During startup (e.g., in `init` functions or at the top of `main`), when a failure means the application cannot run at all.

  2. **Test Setup:** When preparing test fixtures, where a failure indicates a broken test environment, not a feature to be tested.

## Example: Compiling a Regular Expression

It is common to compile regular expressions at the package level. Since the pattern is hardcoded, a compilation failure is a programmer error, not a runtime error. `must.Must` simplifies this.

// Before: Verbose error handling for a panic-worthy error.
//
// var wordRegexp *regexp.Regexp
//
// func init() {
// 	var err error
// 	wordRegexp, err = regexp.Compile(`\w+`)
// 	if err != nil {
// 		panic(fmt.Sprintf("failed to compile word regexp: %v", err))
// 	}
// }

// After: Using must.Must for concise, clear initialization.
var wordRegexp = must.Must(regexp.Compile(`\w+`))

Inappropriate Use Cases

NEVER use these functions for regular application logic where errors are expected and should be handled gracefully. This includes, but is not limited to:

- Handling user input. - Processing network requests or responses. - Reading from or writing to files.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Cast

func Cast[T any](v any) T

Cast performs a type assertion and panics if it fails. It provides a more informative panic message than a raw type assertion.

func Do

func Do[T any](v T, err error) T

Do panics if err is not nil, otherwise it returns the value v. It is useful for wrapping function calls that return a value and an error, where the error is not expected.

func Do2

func Do2[T any, U any](v1 T, v2 U, err error) (T, U)

Do2 is similar to Do, but for functions that return two values and an error.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL