must.go - Error Assertion
Overview
must.go provides error assertion utilities that simplify error handling flow by providing panic-based error checking. These functions are designed for initialization and critical operations where failure should halt program execution.
Functions
MustOk()
Assert second return value is true.
Parameters:
value- Return valueok- Success flag
Returns:
- Returns
valueifokis true - Panics with message "is not ok" if
okis false
Example:
Notes:
- Use this function when second return value indicates success/failure
- Panic will halt program execution if assertion fails
- Generic type
Tallows any return type - Commonly used with map lookups and type assertions
MustSuccess()
Assert error is nil.
Parameters:
err- Error to check
Behavior:
- Does nothing if
erris nil - Panics with formatted error message if
erris not nil
Example:
Notes:
- Commonly used for initialization and setup operations
- Panic message includes error details for debugging
- Use for operations that must succeed for the program to continue
Must()
Combine validation function that checks error status and returns value.
Parameters:
value- Return valueerr- Error
Returns:
- Returns
valueiferris nil - Panics if
erris not nil
Example:
Notes:
- Most commonly used function in must module
- Combines error checking and value extraction
- Generic type
Tallows any return type - Ideal for functions that return
(T, error)
Ignore()
Forcefully ignore any parameter.
Parameters:
value- Value to return_- Ignored parameter
Returns:
- Returns
value
Example:
Notes:
- Used when you need to suppress linter warnings about ignored values
- The second parameter is explicitly ignored
- Useful for maintaining clean code without linter warnings
- Does not actually handle the error, just suppresses warnings
Usage Patterns
Initialization Chain
File Operations
Map Operations
Configuration Loading
Best Practices
When to Use Must Functions
Use Must() when:
- The operation is critical to program startup
- Failure should halt program execution
- Error recovery is not possible or meaningful
- You're in initialization code (main, init)
Avoid Must() when:
- Handling user input
- Network requests that may fail
- File operations that may not exist
- Any operation that can reasonably fail
Error Handling vs Panic
Related Documentation
- orm.go - Database operations
- validator - Data validation
- API Documentation
- Module Overview