-
Notifications
You must be signed in to change notification settings - Fork 18.1k
proposal: spec: for/else block #73857
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
@Mizommz is that supposed to be a reference to a different issue? |
I think in Go where errors are values, the typical pattern is to use those directly rather than using an extra condition variable. Given it's a python only syntax, it's not even clearer to the reader: on seeing it I thought it was only run of the for loop didn't execute at all. |
how do you find these tickets so quickly? searching "for else" gave me 20 pages |
oh, it's a bot. |
Yeah, I wasn't a fan of the It is sparingly used, but is very handy when available. (But I suppose maybe there are better ways of writing code if no other language has implemented it) |
Uh oh!
There was an error while loading. Please reload this page.
Go Programming Experience
Intermediate
Other Languages Experience
Go, Python, JS, Lua
Related Idea
Has this idea, or one like it, been proposed before?
I could not find one similar
Does this affect error handling?
No.
Is this about generics?
No.
Proposal
Python has a "for/else" block, which will only run the "else" block if the for-loop hasn't been broken out of. I am not a fan of the "else" keyword, but the pattern of only running some code if a loop doesn't break is incredibly handy, so you don't have to keep track of a "success" variable
Language Spec Changes
https://go.dev/ref/spec#For_statements
changes to
(perhaps we could use the "default" keyword)
Informal Change
No response
Is this change backward compatible?
I believe so, but you can double check
Before:
After:
One such case is some sort of lookup in an array of structs, and creating a new such struct if one does not exist. Eg, editing an article. If an article does not exist, immediately create a new one and render the same edit page.
Orthogonality: How does this change interact or overlap with existing features?
It's mainly just syntactic sugar got managing a variable yourself
Would this change make Go easier or harder to learn, and why?
Coming from Python, it's easier, since it mirrors Py's existing syntax. Otherwise, no, because not many languages feature for/else blocks.
Cost Description
Intermediate, as now the compiler will have to keep track of an implicit variable before running the "else" block
Changes to Go ToolChain
minimal; gopls: same scope; gofmt: another indent block & follows if {} else {} chain; goimports: unchanged
Performance Costs
Minimal
Prototype
No response
The text was updated successfully, but these errors were encountered: