Skip to content

proposal: add Must[T] function #60846

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
septemhill opened this issue Jun 16, 2023 · 3 comments
Closed

proposal: add Must[T] function #60846

septemhill opened this issue Jun 16, 2023 · 3 comments

Comments

@septemhill
Copy link

septemhill commented Jun 16, 2023

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)

  1. func Must(v Type, err error) Type

and

  1. 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.

@gopherbot gopherbot added this to the Proposal milestone Jun 16, 2023
@Jorropo
Copy link
Member

Jorropo commented Jun 16, 2023

@septemhill in which package would it being added, builtin ?

@septemhill
Copy link
Author

septemhill commented Jun 16, 2023

@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

@seankhliao
Copy link
Member

Duplicate of #54297

@seankhliao seankhliao marked this as a duplicate of #54297 Jun 16, 2023
@seankhliao seankhliao closed this as not planned Won't fix, can't repro, duplicate, stale Jun 16, 2023
@golang golang locked and limited conversation to collaborators Jun 15, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants