Skip to content

Commit a7d53da

Browse files
committed
Auto merge of rust-lang#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 rust-lang#97601 (comment): > [..] 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
2 parents 7c896fc + 0580e66 commit a7d53da

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

core/src/option.rs

+24
Original file line numberDiff line numberDiff line change
@@ -2543,3 +2543,27 @@ impl<T> Option<Option<T>> {
25432543
}
25442544
}
25452545
}
2546+
2547+
impl<T, const N: usize> [Option<T>; N] {
2548+
/// Transposes a `[Option<T>; N]` into a `Option<[T; N]>`.
2549+
///
2550+
/// # Examples
2551+
///
2552+
/// ```
2553+
/// #![feature(option_array_transpose)]
2554+
/// # use std::option::Option;
2555+
///
2556+
/// let data = [Some(0); 1000];
2557+
/// let data: Option<[u8; 1000]> = data.transpose();
2558+
/// assert_eq!(data, Some([0; 1000]));
2559+
///
2560+
/// let data = [Some(0), None];
2561+
/// let data: Option<[u8; 2]> = data.transpose();
2562+
/// assert_eq!(data, None);
2563+
/// ```
2564+
#[inline]
2565+
#[unstable(feature = "option_array_transpose", issue = "130828")]
2566+
pub fn transpose(self) -> Option<[T; N]> {
2567+
self.try_map(core::convert::identity)
2568+
}
2569+
}

0 commit comments

Comments
 (0)