For the Nth Prime Rust exercise on exercism.io, I found that some solutions choose to filter() over a range with no upper limit.
Here's an example:
pub fn nth(n: u32) -> u32 {
let mut primes = Vec::with_capacity((n as usize) + 1);
(2..)
.filter(|candidate| {
if !primes.iter().any(|i| candidate % i == 0) {
primes.push(*candidate);
true
} else {
false
}
})
.nth(n as usize)
.unwrap()
}
I'm wondering when Rust stops iterating over the range in such a scenario. Does it perhaps iterate until the maximum value of the type, or could it figure out when it can stop iterating by checking code that follows the iterator (e.g. by checking when .unwrap() doesn't panic in the example)?