It's not just changing `k` inside the loop body that makes the transformation invalid -- your observation also applies to modifying `i` inside the loop body. Modifying either variable inside the loop body is extremely rare in my experience and doing so warrants a "dragons be here" comment. Still, your point is valid and anyone applying such a transformation should carefully evaluate the body of each loop to see if either variable might be modified by the loop body. Obviously it would be nice if a tool automated that analysis and transformation but I'm not going to hold my breath waiting for someone to implement that tool.
On Fri, Feb 16, 2024 at 11:06 PM Patrick Smith <pat42sm...@gmail.com> wrote: > On Fri, Feb 16, 2024 at 10:27 PM Amnon <amno...@gmail.com> wrote: > >> But now it is out, I think it is great, and have run >> perl -pi -e 's/for (\w+) := 0; \1 < ([\w()]+); \1\+\+/for \1 := >> range \2/' $(git grep -l for) over my entire codebase to use it >> everywhere. >> > > You know your own codebase, and maybe this was safe for you to do. But in > general, blindly applying such a blanket change has the potential to cause > bugs, as these two are not always equivalent: > > for i := range k > for i := 0; i < k; i++ > > In particular, if k is changed inside the loop they may be very different. > https://go.dev/play/p/kAHcmu7377I > > (Yes, many people, myself included, would consider changing k inside such > a loop to be bad coding style. But "bad style" doesn't mean it's not going > to be done.) > > -- > You received this message because you are subscribed to the Google Groups > "golang-nuts" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to golang-nuts+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/golang-nuts/CAADvV_trGNxeLUma722wk-JOGnz42fJqM8%3DVZ36TKpr5s-%3DmOQ%40mail.gmail.com > <https://groups.google.com/d/msgid/golang-nuts/CAADvV_trGNxeLUma722wk-JOGnz42fJqM8%3DVZ36TKpr5s-%3DmOQ%40mail.gmail.com?utm_medium=email&utm_source=footer> > . > -- Kurtis Rader Caretaker of the exceptional canines Junior and Hank -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CABx2%3DD9Hyjj_N9KjY6XfFH0ZUt55f27VCcZQSj_DyX36gzrX1g%40mail.gmail.com.