E0141
Error
break with a value in a loop that has none
ErrorOnly a loop gives a value through break. A break with a value in a for, a while or a while let is an error.
Why
A for, a while and a while let also end when their header says so: the source runs out, or the condition is false. That end gives no value, so the loop as a whole has none, and a value given by break would have nowhere to go. A loop ends only through a break, so each of its breaks can give the value. To keep a value found in another loop, assign it to a variable declared before the loop, then break.
Broken
fn main() {
let words = ["a", "bb", "ccc"]
for w in words {
if w.len() > 1 {
break w
}
}
}
What sisu says
error[E0141]: `break` with a value in a `for` --> E0141.sisu:5:19 | 3 | for w in words { | --- this `for` has no value 4 | if w.len() > 1 { 5 | break w | ^ | = help: only `loop` gives a value through `break`; assign to a variable declared before the loop instead sisu: 1 error sisu: for more on a code, run `sisu explain <code>`: E0141
Fixed
fn main() {
let words = ["a", "bb", "ccc"]
let mut found = ""
for w in words {
if w.len() > 1 {
found = w
break
}
}
print(found)
}
Sisu