must

package
v0.20.2 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2025 License: MIT Imports: 1 Imported by: 0

README

Must Package

Package must provide a set of helper functions which panic on error. Functions are designed to simplify error handling in test code by panicking on errors, reducing boilerplate, and error checking in test cases.

Documentation

Overview

Package must provide a set of helper functions which panic on error.

Functions are designed to simplify error handling in test code by panicking on errors, reducing boilerplate, and error checking in test cases.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func First

func First[T any](s []T, err error) T

First returns the first element in the slice or T's zero value if the slice is empty. It panics with the value of the "err" if it is not nil.

Example

nolint:unparam

package main

import (
	"fmt"

	"github.com/ctx42/testing/pkg/must"
)

func main() {
	type Row struct{ Name string }

	// Query to a database returning rows.
	query := func() ([]Row, error) {
		return []Row{{"a"}, {"b"}}, nil
	}

	have := must.First(query())

	fmt.Println(have)
}
Output:

{a}

func Nil

func Nil(err error)

Nil is a helper function that panics if an error is not nil.

func Single

func Single[T any](s []T, err error) T

Single returns the first element in the slice or T's zero value if the slice is empty. It panics with the value of "err" if it is not nil or with the value of errExpSingle if slices have more than one element.

Example

nolint:unparam

package main

import (
	"fmt"

	"github.com/ctx42/testing/pkg/must"
)

func main() {
	type Row struct{ Name string }

	// Query to a database returning rows.
	query := func() ([]Row, error) {
		return []Row{{"a"}}, nil
	}

	// Will panic if a database returned more than one error.
	have := must.Single(query())

	fmt.Println(have)
}
Output:

{a}

func Value

func Value[T any](val T, err error) T

Value is a helper for functions returning (T, error) panicking if the returned error is not nil. Example:

fil := Value(os.Open("file.txt"))

func Values

func Values[T, TT any](val0 T, val1 TT, err error) (T, TT)

Values is a helper for functions returning (T1, T2, error) panicking if the returned error is not nil.

Example:

t1, t2 := Values(DoSomething())

Types

This section is empty.

Jump to

Keyboard shortcuts

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