Auto merge of #130829 - Urgau:option_array_transpose, r=ibraheemdev
Add `[Option<T>; N]::transpose` This PR as a new unstable libs API, `[Option<T>; N]::transpose`, which permits going from `[Option<T>; N]` to `Option<[T; N]>`. This new API doesn't have an ACP as it was directly asked by T-libs-api in https://github.com/rust-lang/rust/issues/97601#issuecomment-2372109119: > [..] but it'd be trivial to provide a helper method `.transpose()` that turns array-of-Option into Option-of-array (**and we think that method should exist**; it already does for array-of-MaybeUninit). r? libs
This commit is contained in:
commit
9e3e517446
@ -2543,3 +2543,27 @@ pub const fn flatten(self) -> Option<T> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, const N: usize> [Option<T>; N] {
|
||||
/// Transposes a `[Option<T>; N]` into a `Option<[T; N]>`.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// #![feature(option_array_transpose)]
|
||||
/// # use std::option::Option;
|
||||
///
|
||||
/// let data = [Some(0); 1000];
|
||||
/// let data: Option<[u8; 1000]> = data.transpose();
|
||||
/// assert_eq!(data, Some([0; 1000]));
|
||||
///
|
||||
/// let data = [Some(0), None];
|
||||
/// let data: Option<[u8; 2]> = data.transpose();
|
||||
/// assert_eq!(data, None);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable(feature = "option_array_transpose", issue = "130828")]
|
||||
pub fn transpose(self) -> Option<[T; N]> {
|
||||
self.try_map(core::convert::identity)
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user