Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement FromIterator for (impl Default + Extend, impl Default + Extend) #107462

Merged
merged 2 commits into from
Apr 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions library/core/src/iter/traits/collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,39 @@ pub trait FromIterator<A>: Sized {
fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self;
}

/// This implementation turns an iterator of tuples into a tuple of types which implement
/// [`Default`] and [`Extend`].
///
/// This is similar to [`Iterator::unzip`], but is also composable with other [`FromIterator`]
/// implementations:
///
/// ```rust
/// # fn main() -> Result<(), core::num::ParseIntError> {
/// let string = "1,2,123,4";
///
/// let (numbers, lengths): (Vec<_>, Vec<_>) = string
/// .split(',')
/// .map(|s| s.parse().map(|n: u32| (n, s.len())))
/// .collect::<Result<_, _>>()?;
///
/// assert_eq!(numbers, [1, 2, 123, 4]);
/// assert_eq!(lengths, [1, 1, 3, 1]);
/// # Ok(()) }
/// ```
#[stable(feature = "from_iterator_for_tuple", since = "CURRENT_RUSTC_VERSION")]
impl<A, B, AE, BE> FromIterator<(AE, BE)> for (A, B)
where
A: Default + Extend<AE>,
B: Default + Extend<BE>,
{
fn from_iter<I: IntoIterator<Item = (AE, BE)>>(iter: I) -> Self {
let mut res = <(A, B)>::default();
res.extend(iter);

res
}
}

/// Conversion into an [`Iterator`].
///
/// By implementing `IntoIterator` for a type, you define how it will be
Expand Down
Loading