This crate exposes a Single
trait for extracting the element from a
single-element iterator (or panic!
ing if that precondition is false).
You may use this crate under the MIT license or the Apache License (Version 2) at your discretion. This crate is dual-licensed for compatibility with rust itself.
rust
pub trait Single {
type Item;
fn single(self) -> Self::Item;
fn single_or(self, default: Self::Item) -> Self::Item;
fn single_or_else<F>(self, default_fn: F) -> Self::Item
where F: FnOnce() -> Self::Item;
}
type Item
The item type of the wrapped iterator.
fn single(self) -> Self::Item
Get the single element from a single-element iterator.
Note that many iterators return references to the elements, so this method will as well if the backing iterator does.
Panics if the iterator is empty or has more than one element.
An emtpy iterator panics:
iter::empty().single();
An iterator with multiple elements panics:
iter::repeat(0).single();
An iterator with a single element returns that element:
assert_eq!(iter::once(0).single(), 0);
fn single_or(self, default: Self::Item) -> Self::Item
Get the single element from an iterator or a default fallback value.
Note that many iterators return references to the elements, so this method will as well if the backing iterator does.
An empty iterator will return the fallback:
assert_eq!(iter::empty().single_or(5), 5)
An iterator with multiple elements will return the fallback:
assert_eq!(iter::repeat(0).single_or(5), 5)
An iterator with a single element returns that element:
assert_eq!(iter::once(0).single_or(5), 0)
fn single_or_else(self, default_fn: F) -> Self::Item where F: FnOnce() -> Self::Item
Get the single element from an iterator or from a default provider.
Note that many iterators return references to the elements, so this method will as well if the backing iterator does.
An empty iterator will return the fallback:
assert_eq!(iter::empty().single_or_else(|| 5), 5)
An iterator with multiple elements will return the fallback:
assert_eq!(iter::repeat(0).single_or_else(|| 5), 5)
An iterator with a single element returns that element:
assert_eq!(iter::once(0).single_or_else(|| 5), 0)
rust
impl<I> Single for I
where I: Iterator