Single element from iterator When I was working in Rust this week, I missed kotlin's fun &lt;T&gt; Sequence&lt;T&gt;.single(): T. Basically, calling this function means that you are asserting that the sequence contains only one element and that you want that one element back. The most common use case is you've filtered a sequence down to one element. It's also clearer than using first() for the same task as it is clear that there is only supposed to be one thing and that if there is more than one you need to crash because your assumptions don't hold anymore.

I wanted it in Rust, so I implemented it and put it on crates.io. Before I go 1.0.0, however, I'd like to ask for review, mostly focusing on usability of the crate (thus design) and style of the code.

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

use std::{fmt, error, result};

type Result&lt;T&gt; = result::Result&lt;T, self::Error&gt;;

/// Trait to extract the element from a single-element iterator.
pub trait Single {
    /// The item type of the wrapped iterator.
    type 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.
    ///
    /// # Examples
    ///
    /// ```
    /// # use single::{ self, Single };
    /// # use std::iter;
    /// assert_eq!(iter::empty::&lt;i32&gt;().single(), Err(single::Error::NoElements));
    /// assert_eq!(iter::once(0).single(), Ok(0));
    /// assert_eq!(iter::repeat(0).single(), Err(single::Error::MultipleElements));
    /// ```
    fn single(self) -&gt; Result&lt;Self::Item&gt;;
}

/// An error in the execution of [`single::Single::single`](trait.Single.html#tymethod.single).
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Error {
    /// Asked empty iterator for single element.
    NoElements,
    /// Asked iterator with multiple elements for single element.
    MultipleElements,
}

impl fmt::Debug for Error {
    fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl fmt::Display for Error {
    fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
        match *self {
            Error::NoElements =&gt; write!(
                f,
                "SingleError::NoElements: {}",
                error::Error::description(self),
            ),
            Error::MultipleElements =&gt; write!(
                f,
                "SingleError::MultipleElements: {}",
                error::Error::description(self),
            ),
        }
    }
}

impl error::Error for Error {
    fn description(&amp;self) -&gt; &amp;str {
        match *self {
            Error::NoElements =&gt; "Asked empty iterator for single element",
            Error::MultipleElements =&gt; "Asked iterator with multiple elements for single element",
        }
    }
    fn cause(&amp;self) -&gt; Option&lt;&amp;error::Error&gt; { None }
}

impl&lt;I&gt; Single for I where I: Iterator {
    type Item = &lt;Self as Iterator&gt;::Item;

    fn single(mut self) -&gt; Result&lt;Self::Item&gt; {
        match self.next() {
            None =&gt; Err(Error::NoElements),
            Some(element) =&gt; if self.next().is_none() {
                Ok(element)
            } else {
                Err(Error::MultipleElements)
            }
        }
    }
}

#[cfg(test)]
mod test {
    use std::iter;
    use super::Single;

    #[test]
    #[should_panic(expected = "Asked empty iterator for single element")]
    fn panic_empty() { let _: i32 = iter::empty().single().unwrap(); }

    #[test]
    #[should_panic(expected = "Asked iterator with multiple elements for single element")]
    fn panic_multiple() { let _ = iter::repeat(0).single().unwrap(); }
}


Future growth by optimization(?) with std::iter::ExactSizeIterator and/or std::iter::TrustedLen may be possible in the future, but would require benchmarking to see if it is worthwhile.
"`panic!`ing" would normally be written as "panicking". Strangely, it doesn't appear your code actually... panics though? Seems your docs are misleading or outdated.
I dislike the common repetition in documentation for an X that starts with an equivalent of "The X is". Try removing those and improving the information density of the docs. We can already see it's an X from the doc tool itself.
Since the crate is so narrowly focused, I'd recommend moving at least one (if not all) the examples from the method to the crate level. This allows users to immediately see what it does and how to use it.
There's no reason to use self:: in the custom Result.
There's never a time where you'd implement this trait for anything but an iterator, so your trait should require Iterator as a supertrait. This has the benefit of unifying the Item types.
The note about "many iterators return references to the elements", seems out-of-place; that's just how iterators work. If someone doesn't understand that, it seems like they should re-read The Rust Programming Language. For similar reasons, I wouldn't explain how to use a trait or how to add dependencies to the Cargo.toml in my crate docs.
Avoid referencing your crate name in the doc prose. A user can choose to import it with whatever name they like.
Consider a nested match in the iterator implementation.
The majority of your code appears to be dealing with the error type. Perhaps a crate like quick-error would help tip the balance back towards the interesting code.
It's strange to have Display and Debug be the same value. Recall that Debug is for programmers; we'd expect to see the variant name. Display is for humans that see the error.
I'd delegate your Display implementation to Error::description as adding the names of the variants doesn't help the humans reading it.
I'm not a fan of multi-line expressions that aren't blocks in a match (like your write! or if). Would promote them to blocks.


//! Provides the `Single` trait for extracting the element from a
//! single-element iterator.

use std::{fmt, error, result};

type Result&lt;T&gt; = result::Result&lt;T, Error&gt;;

/// Extract the element from a single-element iterator.
pub trait Single: Iterator {
    /// Get the single element from a single-element iterator.
    ///
    /// # Examples
    ///
    /// ```
    /// # use single::{ self, Single };
    /// # use std::iter;
    /// assert_eq!(iter::empty::&lt;i32&gt;().single(), Err(single::Error::NoElements));
    /// assert_eq!(iter::once(0).single(), Ok(0));
    /// assert_eq!(iter::repeat(0).single(), Err(single::Error::MultipleElements));
    /// ```
    fn single(self) -&gt; Result&lt;Self::Item&gt;;
}

/// An error in the execution of [`Single::single`](trait.Single.html#tymethod.single).
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Error {
    /// Asked empty iterator for single element.
    NoElements,
    /// Asked iterator with multiple elements for single element.
    MultipleElements,
}

impl fmt::Debug for Error {
    fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl fmt::Display for Error {
    fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
        match *self {
            Error::NoElements =&gt; {
                write!(
                    f, "SingleError::NoElements: {}",
                    error::Error::description(self),
                )
            }
            Error::MultipleElements =&gt; {
                write!(
                    f, "SingleError::MultipleElements: {}",
                    error::Error::description(self),
                )
            }
        }
    }
}

impl error::Error for Error {
    fn description(&amp;self) -&gt; &amp;str {
        match *self {
            Error::NoElements =&gt;
                "Asked empty iterator for single element",
            Error::MultipleElements =&gt;
                "Asked iterator with multiple elements for single element",
        }
    }
    fn cause(&amp;self) -&gt; Option&lt;&amp;error::Error&gt; { None }
}

impl&lt;I&gt; Single for I where I: Iterator {
    fn single(mut self) -&gt; Result&lt;Self::Item&gt; {
        match self.next() {
            None =&gt; Err(Error::NoElements),
            Some(element) =&gt; {
                match self.next() {
                    None =&gt; Ok(element),
                    Some(_) =&gt; Err(Error::MultipleElements),
                }
            }
        }
    }
}

#[cfg(test)]
mod test {
    use std::iter;
    use super::Single;

    #[test]
    #[should_panic(expected = "Asked empty iterator for single element")]
    fn panic_empty() { let _: i32 = iter::empty().single().unwrap(); }

    #[test]
    #[should_panic(expected = "Asked iterator with multiple elements for single element")]
    fn panic_multiple() { let _ = iter::repeat(0).single().unwrap(); }
}