Closed
Description
The try
proposal #32437 was recently declined. This is an alternate proposal to achieve the goal of simplifying error handling. It has two parts:
- 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 toEXPRESSION != 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)
}
}
- 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.