Macro konst::array::from_fn

source ·
macro_rules! from_fn {
    ($type:tt => $($closure:tt)*) => { ... };
    ($($closure:tt)*) => { ... };
}
Expand description

Const equivalent of array::from_fn.

§Warning

This macro leaks the initialized part of the array if the closure passed to this macro panics or returns early.

note: this warning is not relevant if the elements don’t need dropping(e.g: by implementing Copy).

§Limitations

When the array type is annotated, the array type must be one of:

  • Square brackets (e.g: from_fn!([usize; 10] => |i| i))
  • A parenthesized type (e.g: from_fn!((foo::ArrayAlias) => |i| i * 2))
  • A single identifier (e.g: from_fn!(ArrayAlias => |i| func(i)))

§Example

use konst::array;

{
    const POWERS: [u64; 5] = array::from_fn!(|i| 2u64.pow(i as u32));

    assert_eq!(POWERS, [1, 2, 4, 8, 16]);
}

// Annotating the array type
assert_eq!(
    array::from_fn!([&str; 6] => |i| konst::string::str_up_to("hello", i)),
    ["", "h", "he", "hel", "hell", "hello"],
);