konst::array

Macro map

Source
macro_rules! map {
    ($array:expr, $($closure:tt)* ) => { ... };
}
Expand description

Superceeded by [map_], const version of array::map.

§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

This macro supports mapping from non-Copy arrays if any of these conditions are met about the parameter of the passed-in closure:

  1. it’s a pattern that only copies Copy fields of each array element
  2. it’s a ref pattern

examples of both of the above conditions below

§Example

§Basic

use konst::array;

const TRIMMED: [&str; 3] = array::map!(["  foo", "bar  ", "  baz  "], konst::string::trim);
assert_eq!(TRIMMED, ["foo", "bar", "baz"]);

const LENGTHS: [usize; 3] = array::map!(["foo", "hello", "bar baz"], |s| s.len());
assert_eq!(LENGTHS, [3, 5, 7]);

const SQUARED: [u32; 6] = array::map!([1, 2, 3, 4, 5, 6], |x: u32| x.pow(2));
assert_eq!(SQUARED, [1, 4, 9, 16, 25, 36]);

{
    let input = [3, 5, 8];
    let output = array::map!(input, |x| -> u64 { x + 2 });
    assert_eq!(output, [5, 7, 10]);
}

§Map from non-Copy array

Demonstrates both ways to map from a non-Copy array.

use konst::array;

struct NonCopy(u32, u32);

const PRIME_SUMS: [u32; 3] = {
    let input = [NonCopy(2, 3), NonCopy(5, 7), NonCopy(11, 13)];
     
    // demonstrates the first way to map from non-Copy elements
    array::map!(input, |NonCopy(l, r)| l + r)
};
assert_eq!(PRIME_SUMS, [5, 12, 24]);

const FIBB_SUMS: [u32; 3] = {
    let input = [NonCopy(2, 3), NonCopy(5, 8), NonCopy(13, 21)];
     
    // demonstrates the second way to map from non-Copy elements
    array::map!(input, |ref nc| nc.0 + nc.1)
};
assert_eq!(FIBB_SUMS, [5, 13, 34]);