pub const fn try_into_array<T, const N: usize>(
slice: &[T],
) -> Result<&[T; N], TryIntoArrayError>
Expand description
Tries to convert from &[T]
to &[T; N]
.
Returns an Err(TryIntoArrayError{..})
when the slice doesn’t match the expected length.
§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]);