Skip to content

proposal: Go 2: operator to cause early function return on error #32601

Closed
@klaidliadon

Description

@klaidliadon

Proposal

This proposal aims to reduce the boilerplate of basic error handling by introducing a new identifier.

We will use ? in this proposal, which will behave as follows: when a error is assigned to ?
the function would return immediately with the error received.

As for the other variables their values would be:

  • if they are not named zero value
  • the value assigned to the named variables otherwise

The use of ? would allow to use += and similar operators on the other value, as if ? was not there.
When ? receives an error the last value of the named value would be returned.

Examples

Anonymous

From:

func foo(path string) (io.ReadCloser, error) {
    f, err := os.Open(path)
    if err != nil {
        return nil, err
    }
    if _, err = fmt.Fprint(f, "foo\n"); err != nil {
        return nil, err
    }
    return f, nil
}

To:

func foo(path string) (io.ReadCloser, error) {
	f, ? := os.Open()
	_, ? = fmt.Fprint(f, "foo\n")
	return f, nil
}

Named

From:

func foo(r io.Reader) (n int, err error) {
    b := make([]byte, 1024)
    for {
        a, err := r.Read()
        n += a
        if err != nil {
            return n, err
        }
    }
}

To:

func foo(r io.Reader) (n int, err error) {
    b := make([]byte, 1024)
    for {
        n, ? += r.Read()
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeLanguageChangeSuggested changes to the Go languageProposalerror-handlingLanguage & library change proposals that are about error handling.v2An incompatible library change

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions