proposal: spec: for int, *E := range *[]E
#69337
Labels
LanguageChange
Suggested changes to the Go language
LanguageChangeReview
Discussed by language change review committee
Proposal
Milestone
Go Programming Experience
Experienced
Other Languages Experience
C, C++, Python, Javascript
Related Idea
Has this idea, or one like it, been proposed before?
Unlike the above proposal, which requires new syntax and is non-orthogonal, this one aims to accomplish the same thing by just adding a new supported type to
range
.Proposal
Currently, ranging over slices and arrays only provides read access since the elements are copied by value. Adding a way to modify them when using
range
would enable loops to omit using index variables entirely for most cases, apart from the rare cases when index arithmetic is actually necessary.This would, among other things, prevent accidentally using the wrong index when writing nested loops.
Language Spec Changes
Informal Change
N/A
Is this change backward compatible?
Unfortunately Go already supports ranging over array pointers (!), so this would change the behavior of such loops. A
gofix
rule should be able to update affected loops:for i, v := range arrayPtr { + v := *v // ... }
Slice pointers are new and therefore backward compatible.
Orthogonality: How does this change interact or overlap with existing features?
This change arguably increases orthogonality (compared to the current range-over-array-pointer), since it more closely follows the convention that taking a pointer of a value should allow for modifying it.
Would this change make Go easier or harder to learn, and why?
N/A
Cost Description
Tools that understand the type of the expression in
range
statements would need to be updated to the new semantics.Changes to Go ToolChain
vet, gopls
Performance Costs
N/A (likely minimal)
Prototype
N/A
The text was updated successfully, but these errors were encountered: