Single Build Status

This crate exposes a Single trait for extracting the element from a single-element iterator (or panic!ing if that precondition is false).

License

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.

Trait single::Single

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; }

Associated Types

type Item

The item type of the wrapped iterator.

Required Methods

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

Panics if the iterator is empty or has more than one element.

Examples

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.

Examples

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.

Examples

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)

Implementors

rust impl<I> Single for I where I: Iterator