1
0
Fork 0

🧑‍💻 Created function package with Must utility

This commit is contained in:
Maxim Lebedev 2024-04-09 05:16:27 +05:00
parent 97ff2563df
commit 5a7353945d
Signed by: toby3d
GPG Key ID: 1F14E25B7C119FC5
2 changed files with 49 additions and 0 deletions

16
function/must.go Normal file
View File

@ -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
}

33
function/must_test.go Normal file
View File

@ -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)
}
}