Understanding Rust Error E0571
Overview
Rust Error E0571 indicates that a break statement with an argument has appeared in a non-loop loop. In Rust, break statements can take an argument only in loop loops; using an argument in break statements inside for, while, or while let loops will result in this error.
Erroneous Code Example
#![allow(unused)]
fn main() {
let mut i = 1;
fn satisfied(n: usize) -> bool { n % 23 == 0 }
let result = while true {
if satisfied(i) {
break 2 * i; // error: `break` with value from a `while` loop
}
i += 1;
};
}
In the code above, the break statement has an argument (2 * i) inside a while loop, which is incorrect and will result in Rust error E0571.
Solution
To fix this error, you need to replace the incorrect loop construct with a loop loop, allowing the break statement to have an argument. The corrected code should now look like this:
#![allow(unused)]
fn main() {
let mut i = 1;
fn satisfied(n: usize) -> bool { n % 23 == 0 }
let result = loop { // This is now a "loop" loop.
if satisfied(i) {
break 2 * i; // ok!
}
i += 1;
};
}
In this corrected example, the break statement with the argument (2 * i) now appears inside a loop loop, and Rust Error E0571 will no longer be triggered.
Conclusion
Rust Error E0571 arises when you attempt to use a break statement with an argument in a non-loop loop. To fix this error, ensure that you use break arguments only inside loop loops. By understanding and applying the correct loop construct as demonstrated in this article, you can resolve Rust Error E0571 and have your code compile and run without issues.