macro_rules! try_into_array {
($slice:expr, $len:expr$(,)*) => { ... };
($slice:expr $(,)*) => { ... };
}
Expand description
Tries to convert from &[T]
to &[T; N]
, usable in const
s, but not in const fn
s.
Evaluates to an Err(TryIntoArrayError{..})
when the slice doesn’t match the expected length.
For an alternative that can be used in const fn
s, there is the try_into_array
function,
but it can only be used with the nightly compiler.
§Features
By default you need to pass the length of the returned array.
To infer the length of the array you need to enable the "rust_1_51"
feature,
which requires Rust 1.51.0
§Example
§Explicit length
use konst::{
slice::{TryIntoArrayError, try_into_array},
result,
};
const ARR_5: Option<&[u64; 5]> = {
let slice: &[u64] = &[1, 10, 100, 1000, 10000];
result::ok!(try_into_array!(slice, 5))
};
assert_eq!(ARR_5, Some(&[1, 10, 100, 1000, 10000]));
const ERR: Result<&[u64; 5], TryIntoArrayError> = {
let slice: &[u64] = &[];
try_into_array!(slice, 5)
};
assert!(ERR.is_err());
§Slice constant to Array
use konst::{slice, unwrap_ctx};
const SLICE: &[u8] = b"Hello world!";
static ARRAY: [u8; SLICE.len()] = *unwrap_ctx!(slice::try_into_array!(SLICE, SLICE.len()));
assert_eq!(ARRAY, *b"Hello world!")
§Length inference
try_into_array
can infer the length of the array with the
"rust_1_51"
feature, which requires Rust 1.51.0.
use konst::{slice::try_into_array, unwrap_ctx};
const ARR_3: &[u64; 3] = {
let slice: &[u64] = &[3, 5, 8];
// Letting the macro infer the length of the array,
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]);