From 5a7353945dd210ab97ff57e969652171b068726e Mon Sep 17 00:00:00 2001 From: Maxim Lebedev Date: Tue, 9 Apr 2024 05:16:27 +0500 Subject: [PATCH] :technologist: Created function package with Must utility --- function/must.go | 16 ++++++++++++++++ function/must_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 function/must.go create mode 100644 function/must_test.go 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) + } +}