Skip to content
This repository was archived by the owner on May 1, 2024. It is now read-only.

Commit 5a73539

Browse files
committed
🧑‍💻 Created function package with Must utility
1 parent 97ff256 commit 5a73539

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

function/must.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package function
2+
3+
// Must initiates a panic if the function provided in it returns an error.
4+
//
5+
// See [regexp.MustCompile] as an example of how to use it.
6+
//
7+
// WARN(toby3d): this utility should only be used for data provided by the
8+
// developer side. Any data from other sources should be handled in the regular
9+
// way.
10+
func Must[T any](v T, err error) T {
11+
if err != nil {
12+
panic(err)
13+
}
14+
15+
return v
16+
}

function/must_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package function_test
2+
3+
import (
4+
"fmt"
5+
"strconv"
6+
"strings"
7+
"testing"
8+
9+
"source.toby3d.me/toby3d/hacks/function"
10+
)
11+
12+
func TestMust(t *testing.T) {
13+
t.Parallel()
14+
15+
testFunc := func(input string) (result [2]float64, err error) {
16+
coords := strings.Split(input, ",")
17+
if len(coords) < 2 {
18+
return result, fmt.Errorf("got '%s', want input in format '9.999,9.999'", input)
19+
}
20+
21+
for i := 0; i < 2; i++ {
22+
if result[i], err = strconv.ParseFloat(coords[i], 64); err != nil {
23+
return result, fmt.Errorf("cannot parse coordinate '%s': %w", coords[i], err)
24+
}
25+
}
26+
27+
return result, nil
28+
}
29+
30+
if actual := function.Must(testFunc("1.23,9.87")); len(actual) != 2 {
31+
t.Errorf("want 2 lenght float array, got %v", actual)
32+
}
33+
}

0 commit comments

Comments
 (0)