ACP: Add try_from_slice
constructor to core::array
. · Issue #496 · rust-lang/libs-team (original) (raw)
Proposal
Problem statement
In Rust, you can convert a slice &[T]
to an array [T; N]
using <[T; N] as TryFrom<&[T]>>::try_from
. The main issue with this is that it depends on a trait function, and trait functions are not allowed in constant expressions (e.g. const fn
).
I propose adding a try_from_slice
function to the core::array
module for this scenario. The module in question already defines other constructors such as from_fn
and from_ref
.
Solution sketch
The following function should be added to the standard library:
// core::array
pub const fn try_from_slice<T, const N: usize>(slice: &[T]) -> Result<[T; N], TryFromSliceError> where T: Copy;
Alternatives
The main alternative to adding this feature (with regard to const
) would be to allow trait functions in constant expressions. This is already covered by const_trait_impl.
I still do believe adding this function can improve clarity in some code. Other areas of the standard library already define similar patterns, e.g. String
implements Into<Box<str>>
whilst also defining the into_boxed_str
destructor.
Links and related work
Initial, unstable implementation: #133439