rust - What is the canonical way to implement is_empty for Iterator? -
i have implements std::iter::iterator
, want know if there > 0
elements. standard way it? count() > 0
looks expensive.
i see 2 candidates: any(|_| true)
, nth(0).is_some()
, 1 should pick future reader can understand on sight i'm checking here?
i write iter.next().is_some()
.
however, need aware doing advances 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 future reader can understand on sight
i'd add method on iterator named is_empty
.
Comments
Post a Comment