-
-
Notifications
You must be signed in to change notification settings - Fork 614
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add must.Do utility function (#6955)
This can take two values (typically the return values of a two-value function) and panic if the error is non-nil, returning the interesting value. This is particularly useful for cases where we statically know the call will succeed. Thanks to @mcpherrinm for the idea!
- Loading branch information
Showing
6 changed files
with
48 additions
and
35 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
package must | ||
|
||
// Do panics if err is not nil, otherwise returns t. | ||
// It is useful in wrapping a two-value function call | ||
// where you know statically that the call will succeed. | ||
// | ||
// Example: | ||
// | ||
// url := must.Do(url.Parse("http://example.com")) | ||
func Do[T any](t T, err error) T { | ||
if err != nil { | ||
panic(err) | ||
} | ||
return t | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
package must | ||
|
||
import ( | ||
"net/url" | ||
"testing" | ||
) | ||
|
||
func TestDo(t *testing.T) { | ||
url := Do(url.Parse("http://example.com")) | ||
if url.Host != "example.com" { | ||
t.Errorf("expected host to be example.com, got %s", url.Host) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters