Skip to content

proposal: add Must[T] function #60846

Not planned
Not planned
@septemhill

Description

@septemhill

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.

Activity

added this to the Proposal milestone on Jun 16, 2023
Jorropo

Jorropo commented on Jun 16, 2023

@Jorropo
Member

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

septemhill

septemhill commented on Jun 16, 2023

@septemhill
Author

@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

seankhliao commented on Jun 16, 2023

@seankhliao
Member

Duplicate of #54297

locked and limited conversation to collaborators on Jun 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @septemhill@gopherbot@seankhliao@Jorropo

        Issue actions

          proposal: add `Must[T]` function · Issue #60846 · golang/go