Function konst::slice::try_into_array [−][src]
pub const fn try_into_array<T, const N: usize>(
slice: &[T]
) -> Result<&[T; N], TryIntoArrayError>
This is supported on crate feature
deref_raw_in_fn
only.Expand description
Tries to convert from &[T]
to &[T; N]
, usable in const fn
s. Requires Rust nightly.
Returns an Err(TryIntoArrayError{..})
when the slice doesn’t match the expected length.
For an alternative that works on stable Rust, there is the try_into_array
macro,
but it can only be used in const
s, not in const fn
s .
Features
This is not enabled by default,
you need to enable the "deref_raw_in_fn"
feature to use it,
which requires Rust nightly.
Example
use konst::{ slice::{TryIntoArrayError, try_into_array}, result, unwrap_ctx, }; const fn arr_5() -> Option<&'static [u64; 5]> { let slice: &[u64] = &[1, 10, 100, 1000, 10000]; // Passing the length explicitly to the function result::ok!(try_into_array::<_, 5>(slice)) } assert_eq!(arr_5(), Some(&[1, 10, 100, 1000, 10000])); const fn err() -> Result<&'static [u64; 5], TryIntoArrayError> { let slice: &[u64] = &[]; // Letting the function infer the length of the array, try_into_array(slice) } assert!(err().is_err()); const fn arr_3() -> &'static [u64; 3] { let slice: &[u64] = &[3, 5, 8]; let array = unwrap_ctx!(try_into_array(slice)); // You can destructure the array into its elements like this let [a, b, c] = *array; array } assert_eq!(arr_3(), &[3, 5, 8]);