Description
I would like to propose add func Must[T any](v T, err error) T
function in Go. The implementation would be like:
func Must[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}
Motivation
Currently, we have some Must
prefix functions in standard libraries. e.g. regexp.MustCompile
, template.Must
, netip.MustParseAddr
, netip.MustParseAddrPort
, etc.
Also, I make a github search to list the functions which with Must
prefix. And not surprisingly, most of Must
/must
functions have similar implementation.
There're two styles Must
function: (Option 1 is what I propose)
func Must(v Type, err error) Type
and
func Must(err error)
Most of them just check if err != nil
then panic directly.
Before Go 1.18, we didn't have generic, so we need to use MustSomething
for each of Something
which we want to panic immediately if we got error. Now, we have generic capability, maybe we could make these functions more clear.
Activity
Jorropo commentedon Jun 16, 2023
@septemhill in which package would it being added,
builtin
?septemhill commentedon Jun 16, 2023
Actually, I have no idea.
After Go 1.18 introduced generic capability, we could simplify so many exist functions.
But these simplification functions (includes this proposal) just like utility.
If we accept the proposal, that means we might have more proposals like this one.
So, before we figure out how to classify these functions, I'll suggest put it under
golang.org/x/somewhere
seankhliao commentedon Jun 16, 2023
Duplicate of #54297