Skip to content

proposal: Go 2: simplify error handling with ? and ... #33152

Closed
@earthboundkid

Description

@earthboundkid

The try proposal #32437 was recently declined. This is an alternate proposal to achieve the goal of simplifying error handling. It has two parts:

  1. Make EXPRESSION? return a bool, true if the expression is a non-blank value, false is the expression equals the blank value. So, for interface types, it would be equivalent to EXPRESSION != nil.

Usage:

func CopyFile(src, dst string) error {
	r, err := os.Open(src)
	if err? {
		return fmt.Errorf("copy %s %s: %v", src, dst, err)
	}
	defer r.Close()

	w, err := os.Create(dst)
	if err? {
		return fmt.Errorf("copy %s %s: %v", src, dst, err)
	}

	if _, err := io.Copy(w, r); err? {
		w.Close()
		os.Remove(dst)
		return fmt.Errorf("copy %s %s: %v", src, dst, err)
	}

	if err := w.Close(); err? {
		os.Remove(dst)
		return fmt.Errorf("copy %s %s: %v", src, dst, err)
	}
}
  1. Make return ..., EXPRESSION fill in as many blank values as needed to fulfill the signature of the function.

Usage:

return ..., err

return ..., fmt.Errorf("something went wrong: %v")

Rationale:

Given the design goals for improving error handling, it is difficult to imagine any proposal that doesn't end up being non-orthogonal with if and defer. This makes it simpler for text editors to insert the correct boilerplate for an early return automatically, and it saves a few characters for programmers who type the whole thing out manually.

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