Skip to content
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

Convert for loops to range $int when Go 1.22 becomes the minimum acceptable version #1766

Open
krader1961 opened this issue Feb 17, 2024 · 1 comment

Comments

@krader1961
Copy link
Contributor

krader1961 commented Feb 17, 2024

When Go version 1.22 becomes the minimum acceptable version (probably when Go 1.23 is released) it would be nice to run something like the following over the code base and commit the resulting changes to take advantage of the simpler range syntax for iterating over a sequence of integers from zero to n:

perl -pi -e 's/for (\w+) := 0; \1 < ([\w()]+); \1\+\+/for \1 := range \2/' (git grep -l for)

It is important that every change created by the above command be carefully reviewed. If the loop body modifies the loop var or the value tested against the loop var the transformation may be invalid. Here is a contrived, silly, example that illustrates both pitfalls:

var done int = 10
for i := 0; i < done; i += 1 {
    if i+2 > done {
        i -= 1
        done += 1
    }
}

I couldn't find any Elvish code that modifies either loop value in the loop body at the time I opened this issue but each change still needs to be carefully evaluated when this transformation is made.

@marco-m
Copy link

marco-m commented Mar 25, 2024

@krader1961 FYI gofmt allows automatic rewrite with full syntax tree awareness, see https://go.dev/blog/gofmt#mechanical-source-transformation (and, mentioned in the same place, gofix).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants