Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the canonical way to implement is_empty for Iterator?

Tags:

rust

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?

like image 993
user1244932 Avatar asked Aug 18 '17 16:08

user1244932


1 Answers

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.

like image 71
Shepmaster Avatar answered Oct 16 '22 13:10

Shepmaster