How to implement const mapping (like on iterator) on array?

const fn array_map<T, U, const N: usize>(a: [T; N], f: fn(T) -> U) -> [U; N] {
    todo!()
}

It already exists.

The existing array::map is not a const fn.

I don't think we have any way to do this yet. Function pointer calls are not allowed in const context, and we also don't have const trait bounds to try a concrete impl Fn type.

1 Like

Ah, I missed that requirement, my bad.

What if encapsulation into function or method is not required? Or what are the obstacles other than function pointers?

If you're performing a specific operation using concrete types, and only generic length, you may be able to do it something like this:

pub const fn square<const N: usize>(a: [u32; N]) -> [u64; N] {
    let mut b = [0; N];
    let mut i = 0;
    while i < N {
        b[i] = (a[i] as u64).pow(2); // map
        i += 1;
    }
    b
}

If your output type doesn't allow an easy init like [0; N], then you may need to involve MaybeUninit, and I'm not sure all the const pieces are there yet.