golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
122.68k stars 17.49k forks source link

proposal: Go 2: OR operator on error return #41539

Closed Codebreaker101 closed 3 years ago

Codebreaker101 commented 3 years ago

Sometimes I have a function that does two or more things and I need to return an error if something failed in the function.

To do that I have to do the following:

func do() error {
    if err := doSomething1(); err != nil {
        return err
    }

    if err := doSomething2(); err != nil {
        return err
    }

    if err := doSomething3(); err != nil {
        return err
    }
}

Wouldn't it be nice if once can do this insted:

func do() error {
    err1 := doSomething1()
    err2 := doSomething2()
    err3 := doSomething3()
    return err1 || err2 || err3
    /* OR */
    return doSomething1() || doSomething2() || doSomething3()
}

Opinions?

earthboundkid commented 3 years ago

See https://github.com/golang/go/issues/37165 which would work this way.

zigo101 commented 3 years ago
func AnyError(errs ...error) error {
   for _, e := range errs {
      if e != nil {
         return e
      }
   }
   return nil
}
...

return AnyError(err1, err2, err3)

return AnyError(doSomething1(args), doSomething2(args), doSomething3(args))

It would be greater if lazy evalutaion is supported.

martisch commented 3 years ago

For language change proposals, please fill out the template at https://go.googlesource.com/proposal/+/refs/heads/master/go2-language-changes.md .

When you are done, please reply to the issue with @gopherbot please remove label WaitingForInfo.

Thanks!

martisch commented 3 years ago

See https://github.com/golang/go/issues/40432 for past error handling proposals and associated design problems.

Codebreaker101 commented 3 years ago

As mentioned above, there are open issues that describes this proposal, in one way or another. Closing this.