Description
Go Programming Experience
Intermediate
Other Languages Experience
Python, JS, Rust
Related Idea
- Has this idea, or one like it, been proposed before?
- Does this affect error handling?
- Is this about generics?
- Is this change backward compatible? Breaking the Go 1 compatibility guarantee is a large cost and requires a large benefit
Has this idea, or one like it, been proposed before?
I believe many ideas around this topic have been proposed but I wasn't able to find this exact suggestion.
Does this affect error handling?
Yes it would add a new operator that would make handling the most common error cases easy.
Is this about generics?
No
Proposal
Adding a new operator to the syntax ?
.
This operator, heavily inspired by the rust version , would be appended to expressions where at least one result is of type error and return that error if is is != nil
.
For other result parameters the operator will return:
- The default "zero" values for unnamed parameters
- The current value for named parameters
Example
This function
func Foo() (string, error) {
x, err := SomeFunc()
if err != nil {
return "", err
}
y, err := SomethingWithX(x)
if err != nil {
return "", err
}
return y, nil
}
Could be rewritten like this
func Foo() (string, error) {
x, _ := SomeFunc()?
y, _ := SomethingWithX(x)?
return y, nil
}
I'm torn on whether this operator should allow the error return value ignore to be omitted or not. Not sure if it would make it to difficult to understand that it does return and error value but maybe the ?
on the end is the replacement for that.
Advantages
- Still explicit error handling
- Does not add any extra syntax in the way of what the code is doing
- Does not break the currently existing language.
- Simple to understand for new developers
Language Spec Changes
An operator would be added to the spec that can follow an expression.
Informal Change
When you have a function that can return an error so far we have been creating an full if statement to check that error and return it to the caller if it did. Instead we can replace this whole if statement with a single ?
at the end of the function call and it will do the exact same thing.
Is this change backward compatible?
I believe so since it is not changing any existing patters or structures only adding a syntax sugar for common error handling.
Orthogonality: How does this change interact or overlap with existing features?
No response
Would this change make Go easier or harder to learn, and why?
No response
Cost Description
No response
Changes to Go ToolChain
No response
Performance Costs
No response
Prototype
No response