must

package module
v0.0.30 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2025 License: MIT Imports: 5 Imported by: 76

README

GitHub Workflow Status (branch) GoDoc Coverage Status Supported Go Versions GitHub Release Go Report Card

must

Simple assertion utilities with panic-on-failure semantics designed to reduce boilerplate code in Go.


CHINESE README

中文说明

Main Features

🎯 Panic-on-Failure Validation: Clean assertions with automatic panic on failure when conditions are violated ⚡ Type-Safe Generics: Comprehensive support with Go generics spanning assertion types 🔄 Stack Frame Adjustment: Precise panic location through intelligent skip configurations 🌍 Structured Logging: Deep integration with zap providing detailed panic context 📋 Domain-Specific Packages: Specialized utilities with numeric, string, slice, and map operations


Installation

go get github.com/yyle88/must

Quick Start

Example 1: Basic Assertions
package main

import (
	"fmt"

	"github.com/yyle88/must"
)

func main() {
	fmt.Println("=== Demo 1: Basic Assertions ===")

	// Boolean assertion
	must.True(checkCondition())
	fmt.Println("✓ Boolean check passed")

	// Validate no errors
	must.Done(performOperation())
	fmt.Println("✓ No error")

	// Non-zero value
	count := getCount()
	must.Nice(count)
	fmt.Printf("✓ Valid count: %d\n", count)

	// Values match
	must.Equals("success", getStatus())
	fmt.Println("✓ Values match")

	// Slice operations
	items := getItems()
	must.Have(items)
	must.Length(items, 3)
	must.In("banana", items)
	fmt.Printf("✓ Slice validated: %v\n", items)

	// Pointer check
	account := getAccount()
	must.Full(account)
	fmt.Printf("✓ Pointer valid: %s\n", account.Name)

	fmt.Println("\n=== All checks passed! ===")
}

type Account struct{ Name string }

func checkCondition() bool    { return true }
func performOperation() error { return nil }
func getStatus() string       { return "success" }
func getCount() int           { return 42 }
func getItems() []string      { return []string{"apple", "banana", "orange"} }
func getAccount() *Account    { return &Account{Name: "test"} }

⬆️ Source: Source


Example 2: Rese Package Functions
package main

import (
	"fmt"

	"github.com/yyle88/must"
)

func main() {
	fmt.Println("=== Demo 2: Rese Package ===")

	// V1 - single value validation
	config := must.V1(readConfig())
	fmt.Printf("✓ Config: %s\n", config)

	// V2 - two-value validation
	width, height := must.V2(getDimensions())
	fmt.Printf("✓ Dimensions: %dx%d\n", width, height)

	// P1 - non-nil data validation
	admin := must.P1(findAdmin())
	fmt.Printf("✓ Admin: %s\n", admin.Name)

	// C1 - non-zero validation
	num := must.C1(getNum())
	fmt.Printf("✓ Num: %d\n", num)

	// Combined validations
	data := getData()
	must.Full(data)
	must.Nice(data.Score)
	must.Same(data.Status, "active")
	fmt.Printf("✓ Data: score=%d, status=%s\n", data.Score, data.Status)

	fmt.Println("\n=== All checks passed! ===")
}

type Admin struct{ Name string }
type Data struct {
	Score  int
	Status string
}

func readConfig() (string, error)      { return "v1.0", nil }
func getDimensions() (int, int, error) { return 1920, 1080, nil }
func findAdmin() (*Admin, error)       { return &Admin{"Alice"}, nil }
func getNum() (int, error)             { return 123, nil }
func getData() *Data                   { return &Data{95, "active"} }

⬆️ Source: Source


Example 3: Advanced Specialized Packages
package main

import (
	"fmt"

	"github.com/yyle88/must"
	"github.com/yyle88/must/mustmap"
	"github.com/yyle88/must/mustnum"
	"github.com/yyle88/must/mustslice"
	"github.com/yyle88/must/muststrings"
)

func main() {
	fmt.Println("=== Demo 3: Advanced Packages ===")

	// Numeric validations
	score := getScore()
	mustnum.Positive(score)
	mustnum.Gt(score, 60)
	fmt.Printf("✓ Score: %d\n", score)

	// Slice validations
	tags := getTags()
	mustslice.Have(tags)
	mustslice.Contains(tags, "go")
	fmt.Printf("✓ Tags: %v\n", tags)

	// Map validations
	config := getConfig()
	mustmap.Have(config)
	timeout := mustmap.Get(config, "timeout")
	fmt.Printf("✓ Timeout: %d\n", timeout)

	// String validations
	filename := getFilename()
	muststrings.HasSuffix(filename, ".pdf")
	muststrings.Contains(filename, "report")
	fmt.Printf("✓ Filename: %s\n", filename)

	// Complex scenario
	data := getAnalytics()
	must.Full(data)
	mustmap.Have(data.Metrics)
	fmt.Printf("✓ Analytics: %d metrics\n", len(data.Metrics))

	fmt.Println("\n=== All checks passed! ===")
}

type Analytics struct {
	Metrics map[string]float64
}

func getScore() int             { return 85 }
func getTags() []string         { return []string{"go", "test"} }
func getConfig() map[string]int { return map[string]int{"timeout": 30} }
func getFilename() string       { return "report.pdf" }
func getAnalytics() *Analytics {
	return &Analytics{Metrics: map[string]float64{"score": 87.5}}
}

⬆️ Source: Source


Core Assertions

Here are the core assertions in must, summarized in a table:

Function Description Example Notes
True(v bool) Panics if v is false. must.True(isValid) Validates if v is true.
Done(err error) Panics if err is not nil. must.Done(err) Ensures no error occurred.
Must(err error) Panics if err is not nil. must.Must(err) Same as Done.
Nice(a V) Panics if a is zero. must.Nice(value) Ensures a is non-zero.
Zero(a V) Panics if a is not zero. must.Zero(value) Ensures a is zero.
None(a V) Panics if a is non-zero. must.None(value) Ensures a is zero.
Null(v any) Panics if v is not nil. must.Null(ptr) Ensures v is nil.
Full(v any) Panics if v is nil. must.Full(value) Ensures v is non-nil.
Equals(a, b V) Panics if a and b are not the same. must.Equals(a, b) Checks if a equals b.
Same(a, b V) Panics if a and b are not the same. must.Same(a, b) Alias of Equals.
SameNice(a, b V) Panics if a and b are not the same, both non-zero. must.SameNice(a, b) Ensures same and non-zero.
Sane(a, b V) Panics if a and b are not the same, both non-zero. must.Sane(a, b) Alias of SameNice.
Diff(a, b V) Panics if a and b are the same. must.Diff(a, b) Ensures values mismatch.
Different(a, b V) Panics if a and b are the same. must.Different(a, b) Alias of Diff.
Is(a, b V) Panics if a and b are not the same. must.Is(a, b) Alias of Equals.
Ise(err, target error) Panics if err does not match target using errors.Is. must.Ise(err, targetErr) Matching like errors.Is function.
Ok(a V) Panics if a is zero. must.Ok(value) Ensures a is non-zero.
OK(a V) Alias of Ok, checks non-zero value. must.OK(value) Same as Ok.
TRUE(v bool) Panics if v is false. must.TRUE(isValid) Alias of True.
FALSE(v bool) Panics if v is true. must.FALSE(isError) Ensures v is false.
False(v bool) Panics if v is true. must.False(isError) Same as FALSE.
Cause(err error) Panics if err is nil, returns the error. must.Cause(err) Ensures error is present.
Wrong(err error) Panics if err is nil. must.Wrong(err) Ensures error is present.
Have(a []T) Panics if a has no elements. must.Have(slice) Ensures a is not vacant.
Length(a []T, n int) Panics if a length is not n. must.Length(slice, 3) Ensures a length is n.
Len(a []T, n int) Alias of Length, ensures a length is n. must.Len(slice, 3) Validates a length.
In(v T, a []T) Panics if v is not in a. must.In(value, slice) Ensures v is in a.
Contains(a []T, v T) Panics if a does not contain v. must.Contains(slice, value) Ensures a contains v.
Boolean Package (mustboolean)
Function Description Example Notes
True(v bool) Panics if v is false. mustboolean.True(isEnabled) Validates if v is true.
Conflict(bs ...bool) Panics if multiple boolean values are true. mustboolean.Conflict(a, b, c) Ensures at most one boolean is true.

Examples

Basic Usage Patterns

Assert non-zero value:

value := 42
must.Nice(value) // Panics if value is zero

Validate no error:

err := someFunction()
must.Done(err) // Panics if err is not nil

Check slice length:

arr := []int{1, 2, 3}
must.Length(arr, 3) // Panics if length is not 3
Common Validation Scenarios

Validate map operations:

config := map[string]int{"port": 8080}
port := mustmap.Get(config, "port")
mustnum.Positive(port)

String validation:

filename := "data.json"
muststrings.HasSuffix(filename, ".json")
muststrings.Contains(filename, "data")

Pointer validation:

account := findAccount(id)
must.Full(account) // Panics if account is nil

Explore more error handling packages in this ecosystem:

Advanced Packages
  • must - Must-style assertions with rich type support and detailed error context (this project)
  • rese - Result extraction with panic, focused on safe value unwrapping
Foundation Packages
  • done - Simple, focused error handling with method chaining
  • sure - Generates code that creates custom validation methods

Each package targets different use cases, from quick prototyping to production systems with comprehensive error handling.


📄 License

MIT License - see LICENSE.


💬 Contact & Feedback

Contributions are welcome! Report bugs, suggest features, and contribute code:

  • 🐛 Mistake reports? Open an issue on GitHub with reproduction steps
  • 💡 Fresh ideas? Create an issue to discuss
  • 📖 Documentation confusing? Report it so we can improve
  • 🚀 Need new features? Share the use cases to help us understand requirements
  • Performance issue? Help us optimize through reporting slow operations
  • 🔧 Configuration problem? Ask questions about complex setups
  • 📢 Follow project progress? Watch the repo to get new releases and features
  • 🌟 Success stories? Share how this package improved the workflow
  • 💬 Feedback? We welcome suggestions and comments

🔧 Development

New code contributions, follow this process:

  1. Fork: Fork the repo on GitHub (using the webpage UI).
  2. Clone: Clone the forked project (git clone https://github.com/yourname/repo-name.git).
  3. Navigate: Navigate to the cloned project (cd repo-name)
  4. Branch: Create a feature branch (git checkout -b feature/xxx).
  5. Code: Implement the changes with comprehensive tests
  6. Testing: (Golang project) Ensure tests pass (go test ./...) and follow Go code style conventions
  7. Documentation: Update documentation to support client-facing changes
  8. Stage: Stage changes (git add .)
  9. Commit: Commit changes (git commit -m "Add feature xxx") ensuring backward compatible code
  10. Push: Push to the branch (git push origin feature/xxx).
  11. PR: Open a merge request on GitHub (on the GitHub webpage) with detailed description.

Please ensure tests pass and include relevant documentation updates.


🌟 Support

Welcome to contribute to this project via submitting merge requests and reporting issues.

Project Support:

  • Give GitHub stars if this project helps you
  • 🤝 Share with teammates and (golang) programming friends
  • 📝 Write tech blogs about development tools and workflows - we provide content writing support
  • 🌟 Join the ecosystem - committed to supporting open source and the (golang) development scene

Have Fun Coding with this package! 🎉🎉🎉


GitHub Stars

Stargazers

Documentation

Overview

Package must provides panic-on-failure assertion utilities with structured logging Implements type-safe validation functions that panic with detailed context when expectations are not met Supports generic types enabling flexible value checking across different data types Integrates with zap logging to provide precise stack trace information

must 提供带结构化日志的 panic-on-failure 断言工具 实现类型安全的验证函数,当期望不满足时 panic 并提供详细上下文 支持泛型类型,在不同数据类型间灵活检查值 与 zap 日志集成,提供精确的堆栈跟踪信息

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func C0

func C0(err error)

C0 validates no error occurred. Panics if error is non-nil. C0 验证没有错误发生。如果错误非 nil 则触发 panic。

func C1

func C1[T1 comparable](v1 T1, err error) T1

C1 validates no error and returns non-zero comparable value. Panics if error is non-nil / value is zero. C1 验证没有错误并返回非零可比较值。如果错误非 nil 或值为零则触发 panic。

func C2

func C2[T1, T2 comparable](v1 T1, v2 T2, err error) (T1, T2)

C2 validates no error and returns two non-zero comparable values. Panics if error is non-nil / any value is zero. C2 验证没有错误并返回两个非零可比较值。如果错误非 nil 或任何值为零则触发 panic。

func Cause added in v0.0.30

func Cause(err error) error

Cause expects an error to be present. Panics if error is nil, returns the error. Cause 期望存在错误。如果错误为 nil,则触发 panic;否则返回该错误。

func Contains

func Contains[T comparable](a []T, v T)

Contains checks if the slice contains the value. Panics if the value is not found. Contains 检查切片是否包含该值。如果未找到该值,则触发 panic。

func Diff added in v0.0.17

func Diff[V comparable](a, b V)

Diff expects the values to be distinct. Panics if the values match. Diff 期望值不同。如果值相同,则触发 panic。

func Different added in v0.0.16

func Different[V comparable](a, b V)

Different expects the values to be distinct. Panics if the values match. Different 期望值不同。如果值相同,则触发 panic。

func Done

func Done(err error)

Done expects no error. Panics if the provided error is non-nil. Done 期望没有错误。如果提供的错误不为 nil,则触发 panic。

func Equals

func Equals[V comparable](a, b V)

Equals expects the values to be the same. Panics if not the same. Equals 期望值相等。如果值不相等,则触发 panic。

func FALSE

func FALSE(v bool)

FALSE expects the value to be false. Panics if the value is true. FALSE 期望值为 false。如果值为 true,则触发 panic。

func False

func False(v bool)

False expects the value to be false. Panics if the value is true. False 期望值为 false。如果值为 true,则触发 panic。

func Full

func Full[T any](v *T) *T

Full expects the value to be non-nil. Panics if the value is nil. Full 期望值为非 nil。如果值为 nil,则触发 panic。

func Have

func Have[T any](a []T) []T

Have checks that the slice is not vacant. Panics if the slice is vacant. Have 检查切片是否为空。如果切片为空,则触发 panic。

func In

func In[T comparable](v T, a []T)

In checks if the value is in the slice. Panics if the value is not found. In 检查值是否在切片中。如果未找到该值,则触发 panic。

func Is

func Is[V comparable](a, b V)

Is expects matching values, not the logic of errors.Is, but the logic of Equals. Panics if the values do not match. Is 期望相等,不是 errors.Is 的逻辑,而是 Equals 的逻辑。如果值不相等,则触发 panic。

func Ise

func Ise(err, target error)

Ise expects the errors to match, using the logic of errors.Is. Panics if not matching. Ise 期望错误相等,类似于 errors.Is 的行为。如果错误不相等,则触发 panic。

func Len

func Len[T any](a []T, n int)

Len is an abbreviation of Length, serving the same purpose. Panics if the length is not n. Len 是 Length 的缩写,功能相同。如果长度不是 n,则触发 panic。

func Length

func Length[T any](a []T, n int)

Length expects the slice to have length n. Panics if the length is not n. Length 期望切片的长度为 n。如果长度不是 n,则触发 panic。

func Must

func Must(err error)

Must expects no error. Panics if the provided error is non-nil. Must 期望没有错误。如果提供的错误不为 nil,则触发 panic。

func Nice

func Nice[V comparable](a V) V

Nice expects a non-zero value. Panics if the value is zero, returns the value if non-zero. Nice 期望一个非零值。如果值为零,则触发 panic;如果值非零,则返回该值。

func None

func None[V comparable](a V)

None expects a zero value (vacant/absent). Panics if the value is non-zero. None 期望值为零(空)。如果值不为零,则触发 panic。

func Null

func Null[T any](v *T)

Null expects the value to be nil. Panics if the value is non-nil. Null 期望值为 nil。如果值不为 nil,则触发 panic。

func OK

func OK[V comparable](a V)

OK expects a non-zero value. Panics if the value is zero. Provides an alternative name based on preference. OK 期望一个非零值。如果值为零,则触发 panic。提供一个偏好的替代名称。

func Ok

func Ok[V comparable](a V)

Ok expects a non-zero value. Panics if the value is zero. Ok 期望一个非零值。如果值为零,则触发 panic。

func P0

func P0(err error)

P0 validates no error occurred. Panics if error is non-nil. P0 验证没有错误发生。如果错误非 nil 则触发 panic。

func P1

func P1[T1 any](v1 *T1, err error) *T1

P1 validates no error and returns non-nil data. Panics if error is non-nil / data is nil. P1 验证没有错误并返回非 nil 指针。如果错误非 nil 或指针为 nil 则触发 panic。

func P2

func P2[T1, T2 any](v1 *T1, v2 *T2, err error) (*T1, *T2)

P2 validates no error and returns two non-nil data. Panics if error is non-nil / any data is nil. P2 验证没有错误并返回两个非 nil 指针。如果错误非 nil 或任何指针为 nil 则触发 panic。

func Same

func Same[V comparable](a, b V)

Same expects the values to be the same. Panics if not the same. Same 期望值相等。如果值不相等,则触发 panic。

func SameNice added in v0.0.18

func SameNice[V comparable](a, b V) V

SameNice expects the values to match and be non-zero. Panics if not matching / when zero. Returns the value when conditions are met. SameNice 期望值相等且非零。如果值不相等/为零,则触发 panic。如果条件满足,则返回该值。

func Sane added in v0.0.19

func Sane[V comparable](a, b V) V

Sane means same && nice Sane 期望值相等且非零。如果值不相等/为零,则触发 panic。如果条件满足,则返回该值。

func TRUE

func TRUE(v bool)

TRUE expects the value to be true. Panics if the value is false. TRUE 期望值为 true。如果值为 false,则触发 panic。

func True

func True(v bool)

True expects the value to be true. Panics if the value is false. True 期望值为 true。如果值为 false,则触发 panic。

func V0

func V0(err error)

V0 validates no error occurred. Panics if error is non-nil. V0 验证没有错误发生。如果错误非 nil 则触发 panic。

func V1

func V1[T1 any](v1 T1, err error) T1

V1 validates no error and returns the value. Panics if error is non-nil. V1 验证没有错误并返回值。如果错误非 nil 则触发 panic。

func V2

func V2[T1, T2 any](v1 T1, v2 T2, err error) (T1, T2)

V2 validates no error and returns two values. Panics if error is non-nil. V2 验证没有错误并返回两个值。如果错误非 nil 则触发 panic。

func Wrong added in v0.0.30

func Wrong(err error)

Wrong expects an error to be present. Panics if error is nil. Wrong 期望存在错误。如果错误为 nil,则触发 panic。

func Zero

func Zero[V comparable](a V)

Zero expects a zero value. Panics if the value is non-zero. Zero 期望值为零。如果值不为零,则触发 panic。

Types

This section is empty.

Directories

Path Synopsis
internal
demos/demo1x command
demos/demo2x command
demos/demo3x command
mustskip/must2
Package must2 provides assertion functions with Skip2 stack frame adjustment Implements panic-on-failure validation with 2-depth skip to produce accurate stack traces Used when assertions are wrapped by one extra function invocation Integrates with zap logging using Skip2 configuration to report correct source location
Package must2 provides assertion functions with Skip2 stack frame adjustment Implements panic-on-failure validation with 2-depth skip to produce accurate stack traces Used when assertions are wrapped by one extra function invocation Integrates with zap logging using Skip2 configuration to report correct source location
mustskip/must3
Package must3 provides assertion functions with Skip3 stack frame adjustment Implements panic-on-failure validation with 3-depth skip to produce accurate stack traces Used when assertions are wrapped by two extra function invocations Integrates with zap logging using Skip3 configuration to report correct source location
Package must3 provides assertion functions with Skip3 stack frame adjustment Implements panic-on-failure validation with 3-depth skip to produce accurate stack traces Used when assertions are wrapped by two extra function invocations Integrates with zap logging using Skip3 configuration to report correct source location
utils
Package utils provides support functions enabling the must assertion packages Implements generic support functions used across different assertion modules Not intended to be used outside this module, serves as support mechanism
Package utils provides support functions enabling the must assertion packages Implements generic support functions used across different assertion modules Not intended to be used outside this module, serves as support mechanism
Package mustmap provides map-specific assertion utilities with panic-on-failure semantics Implements type-safe map validation functions using Go generics and standard maps package Supports comparison operations, length validation, and element existence checking on map types Integrates with zap structured logging to provide detailed context when assertions are not met
Package mustmap provides map-specific assertion utilities with panic-on-failure semantics Implements type-safe map validation functions using Go generics and standard maps package Supports comparison operations, length validation, and element existence checking on map types Integrates with zap structured logging to provide detailed context when assertions are not met
Package mustnum provides numeric-specific assertion utilities with panic-on-failure semantics Implements type-safe validation functions with numeric comparison and state checking Supports numeric types spanning integers and floating-points through generic Num constraint Integrates with zap structured logging to provide detailed context when assertions are not met
Package mustnum provides numeric-specific assertion utilities with panic-on-failure semantics Implements type-safe validation functions with numeric comparison and state checking Supports numeric types spanning integers and floating-points through generic Num constraint Integrates with zap structured logging to provide detailed context when assertions are not met
Package mustsecret provides assertion utilities with panic-on-failure semantics designed to protect sensitive data Implements validation functions that avoid logging data values to prevent information leakage Panic messages exclude data values to prevent leaking secrets in logs Integrates with zap structured logging but omits sensitive value details
Package mustsecret provides assertion utilities with panic-on-failure semantics designed to protect sensitive data Implements validation functions that avoid logging data values to prevent information leakage Panic messages exclude data values to prevent leaking secrets in logs Integrates with zap structured logging but omits sensitive value details
Package mustslice provides slice-specific assertion utilities with panic-on-failure semantics Implements type-safe slice validation functions using Go generics and standard slices package Supports comparison operations, membership testing, and length validation on slice types Integrates with zap structured logging to provide detailed context when assertions are not met
Package mustslice provides slice-specific assertion utilities with panic-on-failure semantics Implements type-safe slice validation functions using Go generics and standard slices package Supports comparison operations, membership testing, and length validation on slice types Integrates with zap structured logging to provide detailed context when assertions are not met
Package muststrings provides string-specific assertion utilities with panic-on-failure semantics Implements validation functions using Go standard strings package Supports length checking, prefix/suffix validation, and substring containment testing Integrates with zap structured logging to provide detailed context when assertions are not met
Package muststrings provides string-specific assertion utilities with panic-on-failure semantics Implements validation functions using Go standard strings package Supports length checking, prefix/suffix validation, and substring containment testing Integrates with zap structured logging to provide detailed context when assertions are not met

Jump to

Keyboard shortcuts

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