Proposal Details
Proposing some syntax sugar to propagate errors, which would be the equivalent of this propagation pattern:
val, err = someFunctionCall()
if err != nil {
return nil, err
}
We already have _
to ignore the error. Proposing syntax of ^
as an indicator that the err should be propagated if not nil.
val, ^ = someFunctionCall()
Other return values should use their default values (0 for int, "" for strings, etc.). This is only to cover the propagation use case. You can always still use if err != nil
block to add more context or when you need to return anything other than the defaults for the other variables, so we don't lose any functionality, we can just clean up some of these cases.
// Ignore the error:
val, _ = someFunctionCall()
// propagate if err != nil
val, ^ = someFunctionCall()
// Handle, create new, or wrap with additional context:
val, err = someFunctionCall()
if err != nil {
return nil, fmt.Errorf("Additional or different context related to the error.")
}
Comment From: ianlancetaylor
Thanks, but per https://go.dev/blog/error-syntax we are not considering proposals for changes to error handling syntax.
Also this proposal has been made several times before in different variations. See #40432.