Debian Codegraph @

td/must_118.go

raw
1 // Copyright (c) 2026, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 //go:build go1.18
8 // +build go1.18
9
10 package td
11
12 // Must panics if err is non-nil. Otherwise it returns ret.
13 //
14 // fn := func() (int, error) { … }
15 // value := td.Must(fn())
16 //
17 // It typically avoids to use 2 lines for the mostly same effect than:
18 //
19 // value, err := fn()
20 // td.Require(t).CmpNoError(err)
21 //
22 // except that in case of error a panic occurs instead of a clean
23 // [testing.T.Fatal] error like. Starting go1.27, you should prefer to
24 // use [T.Must] which does not panic but calls [testing.T.Fatal].
25 //
26 // See also [T.Must], [T.Must2], [T.Must3], [Must2], [Must3],
27 // [CmpNoError] and [T.CmpNoError].
28 func Must[X any](ret X, err error) X {
29 if err != nil {
30 panic("Must: " + err.Error())
31 }
32 return ret
33 }
34
35 // Must2 panics if err is non-nil. Otherwise it returns ret1, ret2.
36 //
37 // fn := func() (int, string, error) { … }
38 // value1, value2 := td.Must2(fn())
39 //
40 // It typically avoids to use 2 lines for the mostly same effect than:
41 //
42 // value1, value2, err := fn()
43 // td.Require(t).CmpNoError(err)
44 //
45 // except that in case of error a panic occurs instead of a clean
46 // [testing.T.Fatal] error. Starting go1.27, you should prefer to
47 // use [T.Must2] which does not panic but calls [testing.T.Fatal].
48 //
49 // See also [T.Must2], [T.Must], [T.Must3], [Must], [Must3],
50 // [CmpNoError] and [T.CmpNoError].
51 func Must2[X, Y any](ret1 X, ret2 Y, err error) (X, Y) {
52 if err != nil {
53 panic("Must2: " + err.Error())
54 }
55 return ret1, ret2
56 }
57
58 // Must3 panics if err is non-nil. Otherwise it returns ret1, ret2, ret3.
59 //
60 // fn := func() (int, string, bool, error) { … }
61 // value1, value2, value3 := td.Must3(fn())
62 //
63 // It typically avoids to use 2 lines for the mostly same effect than:
64 //
65 // value1, value2, value3, err := fn()
66 // td.Require(t).CmpNoError(err)
67 //
68 // except that in case of error a panic occurs instead of a clean
69 // [testing.T.Fatal] error. Starting go1.27, you should prefer to
70 // use [T.Must3] which does not panic but calls [testing.T.Fatal].
71 //
72 // See also [T.Must3], [T.Must], [T.Must2], [Must], [Must2],
73 // [CmpNoError] and [T.CmpNoError].
74 func Must3[X, Y, Z any](ret1 X, ret2 Y, ret3 Z, err error) (X, Y, Z) {
75 if err != nil {
76 panic("Must3: " + err.Error())
77 }
78 return ret1, ret2, ret3
79 }