diff --git a/function/must.go b/function/must.go new file mode 100644 index 0000000..25b2d36 --- /dev/null +++ b/function/must.go @@ -0,0 +1,16 @@ +package function + +// Must initiates a panic if the function provided in it returns an error. +// +// See [regexp.MustCompile] as an example of how to use it. +// +// WARN(toby3d): this utility should only be used for data provided by the +// developer side. Any data from other sources should be handled in the regular +// way. +func Must[T any](v T, err error) T { + if err != nil { + panic(err) + } + + return v +} diff --git a/function/must_test.go b/function/must_test.go new file mode 100644 index 0000000..ceab015 --- /dev/null +++ b/function/must_test.go @@ -0,0 +1,33 @@ +package function_test + +import ( + "fmt" + "strconv" + "strings" + "testing" + + "source.toby3d.me/toby3d/hacks/function" +) + +func TestMust(t *testing.T) { + t.Parallel() + + testFunc := func(input string) (result [2]float64, err error) { + coords := strings.Split(input, ",") + if len(coords) < 2 { + return result, fmt.Errorf("got '%s', want input in format '9.999,9.999'", input) + } + + for i := 0; i < 2; i++ { + if result[i], err = strconv.ParseFloat(coords[i], 64); err != nil { + return result, fmt.Errorf("cannot parse coordinate '%s': %w", coords[i], err) + } + } + + return result, nil + } + + if actual := function.Must(testFunc("1.23,9.87")); len(actual) != 2 { + t.Errorf("want 2 lenght float array, got %v", actual) + } +}