Skip to content

Commit

Permalink
Auto merge of #107462 - WaffleLapkin:from_iterator_for_tuple, r=dtolnay
Browse files Browse the repository at this point in the history
Implement `FromIterator` for `(impl Default + Extend, impl Default + Extend)`

Similarly to how #85835 implemented `Extend` for `(impl Extend, impl Extend)`:
```rust
impl<A, B, AE, BE> FromIterator<(AE, BE)> for (A, B)
where
    A: Default + Extend<AE>,
    B: Default + Extend<BE>,
{ ... }
```
  • Loading branch information
bors committed Apr 14, 2024
2 parents 7ab5eb8 + 7b5af57 commit f3c6608
Showing 1 changed file with 33 additions and 0 deletions.
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

0 comments on commit f3c6608

Please sign in to comment.