You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I would like to propose add func Must[T any](v T, err error) T function in Go. The implementation would be like:
funcMust[Tany](vT, errerror) T {
iferr!=nil {
panic(err)
}
returnv
}
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.
The text was updated successfully, but these errors were encountered:
@septemhill in which package would it being added, builtin ?
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
I would like to propose add
func Must[T any](v T, err error) T
function in Go. The implementation would be like: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 ofMust
/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 ofSomething
which we want to panic immediately if we got error. Now, we have generic capability, maybe we could make these functions more clear.The text was updated successfully, but these errors were encountered: