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 #[ferrocene::prevalidated]
19 fn from_iter<I: IntoIterator<Item = ()>>(iter: I) -> Self {
20 iter.into_iter().for_each(|()| {})
21 }
22}
23
24pub(crate) trait IsUnit {
25 const IS_UNIT: bool;
26}
27
28impl<T: ?Sized> IsUnit for T {
29 // `type_id` erases lifetimes, but that's OK here because "is it ()" never depends on lifetimes
30 const IS_UNIT: bool = type_id::<Self>() == type_id::<()>();
31}