E4211#
Compiler diagnostic name: control_in_list_comprehension.
return, break, continue, and error-producing calls are not allowed inside
a list comprehension whose result type is Iter.
An Iter comprehension is lazy: its body runs later, when the iterator is
consumed. Control-flow operations that jump out of the surrounding function or
loop, or calls that need immediate error propagation, cannot be preserved safely
across that lazy boundary.
Erroneous example#
fn values() -> Iter[Int] {
let xs : Iter[Int] = [ for _ in 0..<3 => { return Iter::empty() } ]
xs
}
Suggestion#
Keep the comprehension body as a normal value-producing expression. If you need early exit, use an eager collection target or write an explicit loop around the iterator consumption.
fn values() -> Iter[Int] {
[ for i in 0..<3 => i ]
}
test {
let mut sum = 0
values().each(x => sum = sum + x)
inspect(sum, content="3")
}