Surprising behavior of `'label: for`
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
Consider the following code:
fn main() {
let mut s = 0;
'label: for i in 0..100 {
println!("s: {s}, i: {i}");
s += 1;
if i == 3 {
continue 'label;
}
}
}
The expectation was that it would work like the following C code:
#include <stdio.h>
int main() {
int s = 0;
label: for (int i = 0; i < 100; i++) {
printf("s: %d, i: %d\n", s++, i);
if (i == 3) {
goto label;
}
}
}
Instead, the continuation at the for just advances the loop counter of the for, running the expression inside it. This is surprising behavior to anyone who is familiar with this C idiom, as while goto is... not exactly equal to continue, for many purposes we make continue and break a "controlled goto" exactly so that we can support these idioms. The code that achieves this idiom is, instead:
fn main() {
let mut s = 0;
'label: loop {
for i in 0..100 {
println!("{s}, {i}");
s += 1;
if i == 3 {
continue 'label;
}
}
break;
}
}
This "continue 'label but it's equal to continue" pattern could be recognized and linted on as it is almost never what is wanted, much as we warn about other useless syntax.
Meta
rustc --version --verbose:
rustc 1.82.0-nightly (cefe1dcef 2024-07-22)
binary: rustc
commit-hash: cefe1dcef0e21f4d0c8ea856ad61c1936dfb7913
commit-date: 2024-07-22
host: x86_64-unknown-linux-gnu
release: 1.82.0-nightly
LLVM version: 18.1.7
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the Rust and C examples with the rustc 1.82.0-nightly version reported in the issue, then compare the continue 'label behavior with the proposed loop workaround. Trace the compiler's lint handling for labeled for loops; done means the surprising pattern has a well-defined diagnostic and coverage for the reported example.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100