Skip to content

Instantly share code, notes, and snippets.

@klaidliadon
Created June 13, 2019 09:27
Show Gist options
  • Save klaidliadon/27abf69952ca24eeb01c08e8150cb034 to your computer and use it in GitHub Desktop.
Save klaidliadon/27abf69952ca24eeb01c08e8150cb034 to your computer and use it in GitHub Desktop.
Go error handling

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 returns 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()
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment