Macro const_arr

Source
macro_rules! const_arr {
    ([$TYPE:ty; $SIZE:literal], $func_name:ident) => { ... };
    ([$TYPE:ty; $SIZE:literal], |$name:ident| $body:expr) => { ... };
    ([$TYPE:ty; $SIZE:literal], |_| $body:expr ) => { ... };
    () => { ... };
    ([$type:ty; $size:literal]) => { ... };
    ([$type:ty; $size:literal], ) => { ... };
    ([$type:ty; $size:literal], ||) => { ... };
    ([$type:ty; $size:literal], || $_wha:tt) => { ... };
    ([$type:ty; $size:literal], $num:literal) => { ... };
    ($type:ty) => { ... };
    ($type:ty, ) => { ... };
    ($type:ty,$size:literal) => { ... };
    ($type:ty,$size:literal, $_:tt) => { ... };
    ($type:ty,$size:literal, |$_:tt| $_n2:tt) => { ... };
}
Expand description

§Macro used to initialize arrays in constant context

§Supports both closure syntax and const fn initialization.

Usage:

const ARR: [TYPE; SIZE] = const_arr!([TYPE; SIZE], CONST_INIT_FN);
  • CONST_INIT_FN is const function or const-like closure from array index(usize) to TYPE

§Examples:

use const_array_init::const_arr;
 
const ARR1: [i32; 5] = const_arr!([i32; 5], |i| i as i32 + 1);
assert_eq!(ARR1, [1, 2, 3, 4, 5]);
 
const fn to_i32_plus_one(n: usize) -> i32 {
    n as i32 + 1
}
 
const ARR2: [i32; 5] = const_arr!([i32; 5], to_i32_plus_one);
assert_eq!(ARR2, [1, 2, 3, 4, 5]);

You have to specify array type in const context, even if compiler can infer it.

This is good quick-fix opportunity for your language server.

const ARR = const_arr!([i32; 5], |i| i as i32);
//    ^^^ help: provide a type for the constant: `: [i32; 5]`
const ARR: [i32; 5] = const_arr!([i32; 5], |i| i as i32);

But if you don’t want to specify type twice you can use

  • make_const_arr!(NAME, [TYPE; SIZE], INIT_FN) macro.
use const_array_init::make_const_arr;
 
make_const_arr!(ARR, [i32; 5], |i| i as i32 + 1);
 
assert_eq!(ARR, [1, 2, 3, 4, 5]);