Macro array_macro::array

source ·
macro_rules! array {
    [$expr:expr; $count:expr] => { ... };
    [$i:pat => $e:expr; $count:expr] => { ... };
}
Expand description

Creates an array containing the arguments.

This macro provides a way to repeat the same macro element multiple times without requiring Copy implementation as array expressions require.

There are two forms of this macro.

  • Create an array from a given element and size. This will Clone the element.

    use array_macro::array;
    assert_eq!(array![vec![1, 2, 3]; 2], [[1, 2, 3], [1, 2, 3]]);

    Unlike array expressions this syntax supports all elements which implement Clone.

  • Create an array from a given expression that is based on index and size. This doesn’t require the element to implement Clone.

    use array_macro::array;
    assert_eq!(array![x => x * 2; 3], [0, 2, 4]);

    This form can be used for declaring const variables.

    use array_macro::array;
    const ARRAY: [String; 3] = array![_ => String::new(); 3];
    assert_eq!(ARRAY, ["", "", ""]);

Limitations

When using a form with provided index it’s not possible to use break or continue without providing a label. This won’t compile.

use array_macro::array;
loop {
    array![_ => break; 1];
}

To work-around this issue you can provide a label.

use array_macro::array;
'label: loop {
    array![_ => break 'label; 1];
}