Skip to content
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

proposal: builtin: add must function #70902

Closed
fjl opened this issue Dec 18, 2024 · 2 comments
Closed

proposal: builtin: add must function #70902

fjl opened this issue Dec 18, 2024 · 2 comments
Labels
Milestone

Comments

@fjl
Copy link

fjl commented Dec 18, 2024

Proposal Details

For library APIs which return an error and a value, it is commonplace to provide Must* variants of the corresponding function. The Must* variant usually wraps the non-Must function, panicking when an error is returned. Here is an example from the standard library:

package regexp

// Compile parses a regular expression...
func Compile(expr string) (*Regexp, error) {
    ...
}

// MustCompile is like [Compile] but panics if the expression cannot be parsed.
func MustCompile(str string) *Regexp {
    ...
}

With the introduction of generics, this pattern becomes unnecessary, since one can write a must function:

func must[T any](v T, err error) T {
    if err != nil {
        panic(err)
    }
    return v
}

With this function, and the 'call shortcut', one can write:

must(regexp.Compile("[a-z]+")).FindString(input)

While one could always define this function in an external package, it only really becomes useful if it's just available by default. So here is the rationale for making it builtin:

  • Similar to builtins min and max, the use of this function will likely become pervasive, especially in tests. See also cmp: new package with Ordered, Compare, Less; min, max as builtins #59488 (comment)
  • If defined in an external package, it'd have to be defined as Must. Having to prefix every use of must with a package name really takes away from the appeal of the function, as does using it with an uppercase identifier. The call to must should not steal attention from the call of the inner function, just change the semantics of that call.
  • Finally, defining it as a builtin would make it possible to support any number of return values (where the last type is error). This isn't possible in a user-defined function because they must always declare a specific number of parameters and return values.
@fjl fjl added the Proposal label Dec 18, 2024
@gopherbot gopherbot added this to the Proposal milestone Dec 18, 2024
@fjl
Copy link
Author

fjl commented Dec 18, 2024

Aww, looks like this is already tracked in #21419 and #54297. must.Do is a pretty good alternative though.

@fjl fjl closed this as completed Dec 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants