Search code examples
go

Built-in helper for "Must" pattern in Go


Is there a more built-in wrapper to make a function that returns (X, error) successfully execute or abort, like regexp.MustCompile?

I'm talking about something like this, but more "built-in".


Solution

  • Since Go 1.18 we can define typed Must instead of interface{}:

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

    How to use: https://go.dev/play/p/ajQAjfro0HG

    func success() (int, error) {
        return 0, nil
    }
    
    func fail() (int, error) {
        return -1, fmt.Errorf("Failed")
    }
    
    func main() {
        n1 := Must(success())
        fmt.Println(n1)
        var n2 int = Must(fail())
        fmt.Println(n2)
    }
    

    Must fails inside main, when fail() returns non-nil error

    You can even define Mustn for more than 1 return parameter, e.g.

    func Must2[T1 any, T2 any](obj1 T1, obj2 T2, err error) (T1, T2) {
        if err != nil {
            panic(err)
        }
        return obj1, obj2
    }