How to init 2D array using function

I want to initialize a fixed-size 2D array using a function - something like:

    let init = |x, y| { /* do something and return value */ };
    let a = [[init; 10]; 10];

init could be a regular function, too.

I found this article:
https://www.joshmcguigan.com/blog/array-initialization-rust/
which lists some good options for 1D arrays, but there doesn't seem to be a 2D equivalent. Does anyone know of one?

let init = |x: usize, y: usize| x + y;
let arr = array::from_fn(|y| array::from_fn(|x| init(x, y)));
assert_eq!(arr, [[0, 1, 2], [1, 2, 3], [2, 3, 4]]);
3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.