I have something that implements std::iter::Iterator
and I want to know if there are > 0
elements. What is the standard way to do it? count() > 0
looks too expensive.
I see two candidates: any(|_| true)
and nth(0).is_some()
, but which one should I pick so a future reader can understand on sight what I'm checking here?
I would write iter.next().is_some()
.
However, you need to be aware that doing this advances the iterator.
fn main() {
let scores = [1, 2, 3];
let mut iter = scores.iter();
println!("{}", iter.next().is_some()); // true
println!("{}", iter.next().is_some()); // true
println!("{}", iter.next().is_some()); // true
println!("{}", iter.next().is_some()); // false
}
In many cases I'd use Peekable
:
fn main() {
let scores = [1, 2, 3];
let mut iter = scores.iter().peekable();
println!("{}", iter.peek().is_some()); // true
println!("{}", iter.peek().is_some()); // true
println!("{}", iter.peek().is_some()); // true
println!("{}", iter.peek().is_some()); // true
}
so a future reader can understand on sight
I'd add a method on iterator named is_empty
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With