Masterminds / sprig

Useful template functions for Go templates.
http://masterminds.github.io/sprig/
MIT License
4.25k stars 436 forks source link

use of "must" functions is backwards from expectations #338

Open ghostsquad opened 2 years ago

ghostsquad commented 2 years ago

Typically a function prefixed with Must indicates that should a problem occur, the program will panic rather than return an error. Functions with the must prefix are usually used in one of the following situations:

  1. use of constant-like behavior, but cannot be defined as a constant (such as regex parse). The pattern string may be constant, and a single test is enough to assert that no panic will ever occur.

  2. unrecoverable operation, error handling would just add extra boilerplate, and likely not very useful. This is common during application startup.

Examples of use of must:

https://pkg.go.dev/regexp#MustCompile

MustCompile is like Compile but panics if the expression cannot be parsed. It simplifies safe initialization of global variables holding compiled regular expressions.

https://pkg.go.dev/text/template#Must

Must is a helper that wraps a call to a function returning (*Template, error) and panics if the error is non-nil. It is intended for use in variable initializations such as

MustHaveGoBuild https://go.dev/src/internal/testenv/testenv.go

This is similar in that, there's no "handling" of the condition. If the condition is not met, control is not returned to the caller. The test is just skipped.

I sprig I see:

regexFind panics if there is a problem and mustRegexFind returns an error to the template engine if there is a problem.