Skip to content

proposal: Go 2: use symbol or function call in assignment for error handling #33150

Closed
@ctlod

Description

@ctlod

The final form of this proposal can be found further down in #33150 (comment)


Use ! (or some other symbol) as special symbol in assignment for error handling

My issues with a built-in function try as proposed is 4 fold.

  1. Excess of function calls all over the place.
  2. Allows chaining, exasperating the above point.
  3. defers should not be required to decorate an error.
  4. I don't use go full time, and the example code I've seen just felt messy.
func MyFunc() (error) {
  f, err := os.Open(filename)
  if err != nil {
    return …, err  // zero values for other results, if any
  }
}

can be simplified to

func MyFunc() (error) {
  f, ! := os.Open(filename)
}

This resembles the _ key symbol, but is only applicable to errors.

HandlerFunctions: func myHandler([...]) error
Takes at least 1 argument compatible with the type of error returned.

eg:

func myHandler(err error, x string) error {
  return fmt.Errorf("copy %s : %v", x, err)
}

And used as so:

func MyFunc() (error) {
  filename := "myFile"
  f, myHandler(!, filename) := os.Open(filename)
}

this is equivalent to:

func MyFunc() (error) {
  f, err := os.Open(filename)
  if err != nil {
    return myHandler(err, filename)
  }
}

Although, in this simple case, it would suffice to do:

func MyFunc() (error) {
  filename := "myFile"
  f, fmt.Errorf("copy %s : %v", filename, !) := os.Open(filename)
}

With support for error with return values:

func MyFunc() (error) {
  filename := "myFile"
  f, myHandler(!, f) := os.Open(filename)
}

I'd expect most function calls using ! to remain rather compact.

Special case, but probably marginal.

func MyFunc() (error) {
  f, panic(!) := os.Open(filename)
}

And of course for the cases where an error doesn't imply an immediate return, then the existing "if err != nil" remains appropriate, as flow is continuing after the function call statement, and the error is treated as nothing more than a variable.

Thanks for your time parsing this late and naive suggestion.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions