Skip to main content

core/
unit.rs

1use crate::intrinsics::type_id;
2
3/// Collapses all unit items from an iterator into one.
4///
5/// This is more useful when combined with higher-level abstractions, like
6/// collecting to a `Result<(), E>` where you only care about errors:
7///
8/// ```
9/// use std::io::*;
10/// let data = vec![1, 2, 3, 4, 5];
11/// let res: Result<()> = data.iter()
12///     .map(|x| writeln!(stdout(), "{x}"))
13///     .collect();
14/// assert!(res.is_ok());
15/// ```
16#[stable(feature = "unit_from_iter", since = "1.23.0")]
17impl FromIterator<()> for () {
18    fn from_iter<I: IntoIterator<Item = ()>>(iter: I) -> Self {
19        iter.into_iter().for_each(|()| {})
20    }
21}
22
23pub(crate) trait IsUnit {
24    const IS_UNIT: bool;
25}
26
27impl<T: ?Sized> IsUnit for T {
28    // `type_id` erases lifetimes, but that's OK here because "is it ()" never depends on lifetimes
29    const IS_UNIT: bool = type_id::<Self>() == type_id::<()>();
30}