Skip to content

Conversation

@vishruth-thimmaiah
Copy link
Contributor

Closes: #19256

adds an assist that converts a for loop into a while let loop.

@rustbot rustbot added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Mar 3, 2025
@vishruth-thimmaiah vishruth-thimmaiah force-pushed the for_loop_to_while_let branch 2 times, most recently from 691550b to e4c24a8 Compare March 6, 2025 12:33
@vishruth-thimmaiah vishruth-thimmaiah marked this pull request as ready for review March 9, 2025 13:18
Comment on lines 28 to 34
// fn main() {
// let x = vec![1, 2, 3];
// while let Some(v) = x.into_iter().next() {
// let y = v * 2;
// };
// }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, I don't think this is the right conversion for that for-loop.
This will create a new iterator for every while-loop iteration, but as the into_iterator takes ownership of the Vec it'll fail to compile.

Generally, I think the correct way to do the conversion is to instead check if the iterable expression implements IntoIterator and then generate a let statement to hold the iterator. This is closer to the actual desugaring of a for-loop, and by extension would also handle the (1..2), &x, and &mut x cases. (though it'd be nice to keep the &x -> x.iter() and &mut x -> x.iter_mut() transformations if available).

@DropDemBits DropDemBits added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Mar 13, 2025
@DropDemBits DropDemBits added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Mar 14, 2025
Copy link
Contributor

@DropDemBits DropDemBits left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me, thanks!

@Veykril Veykril added this pull request to the merge queue Mar 14, 2025
Merged via the queue into rust-lang:master with commit e3b3d9e Mar 14, 2025
9 checks passed
@vishruth-thimmaiah vishruth-thimmaiah deleted the for_loop_to_while_let branch May 4, 2025 18:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-waiting-on-review Status: Awaiting review from the assignee but also interested parties.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Replace for loop with while let assist

4 participants