A trivial package to provide a collection of functions shortcuts error returns to panics.
This is handy when doing small programs, or script-like programs in Go, where any failure should just panic.
It defines:
func M(err error) {
if err != nil {
panic(err)
}
}
func M1[T any](value T, err error) T {
M(err)
return value
}
// And similarly it defines functions M2 ... to ... M9.
Example of usage:
package main
import . "github.com/janpfeifer/must"
func main() {
fName := "my_file.txt"
contents := M1(os.ReadFile(fName))
M(os.Remove(fName))
}
Or, if using a Go Jupyter Notebook with GoNB:
import . "github.com/janpfeifer/must"
%%
fName := "my_file.txt"
contents := M1(os.ReadFile(fName))
M(os.Remove(fName))
Notice you can also redefine M
, and all other functions will automatically follow suit:
import . "github.com/janpfeifer/must"
func init() {
M = func(err error) {
if err != nil {
log.Fatalf("Interrupted with error: %+v", err)
}
}
}
%%
contents := M1(os.ReadFile("my_file")) // This will fail with log.Fatalf if err != nil.
Note
panic
is like an exception, and it can be caught (with recover
), if you need it at some point in the "script".
- What if I don't want to
panic
but do something else ?
See example of reassigningM
to however you want errors to be handled. - What if I don't like
M
as the name for these functions, and want something else ?
If it's something generic, just create an issue, I'll quickly create a subpackage with your favourite naming convention.