proposal: Go 2: default values for named return parameters #44396
Labels
FrozenDueToAge
LanguageChange
Suggested changes to the Go language
Proposal
Proposal-FinalCommentPeriod
v2
An incompatible library change
Milestone
Experienced.
Many functional programming languages, C, Perl, JS/TS, and lots of others.
This would add a bit of complexity, but it wouldn’t make Go any harder to learn because novice developers don’t use named return parameters that often.
I didn’t find anything.
It helps developers and reviewers understand what value will be returned by a function most of the time.
Go has the ability to give names to return parameters. It is a great feature, as it gives some kind of documentation to the reader, and allows developers to better clarify their intent if they’re writing a long function.
However, named return parameters are always zero initialised. Although this is great for consistency, I feel like an explicit default value can help in readability.
Think of it as the
default
case of a switch. It could also represent a contract with a default value if the function succeeds, and that contract can be understood just by reading the function’s prototype.Other syntax proposals:
=
, like aconst
definition:There should be restrictions on the type of expression you can write. This shouldn’t be allowed IMO:
Maybe allow only const expressions or a single variable name?
This change is backward compatible.
Here’s the piece of code that gave me the idea for this proposal (this function represents a state of a parser):
This function could be rewritten as:
Here, I understand that the next state of the parser is likely going to be
pRaw
.This proposal would affect a lot of tools, but the implementation cost isn’t big.
The compile time cost should be negligible.
No runtime cost.
I made a quick & dirty proof of concept here.
The Signature section of the language spec should be the only one affected by this proposal.
This extends the named return parameter feature.
Thank you for reading this proposal. This can seem useless, as one could just assign to the return parameter on the first line, but I think the readability is worth it.
The text was updated successfully, but these errors were encountered: