array of closures in Rust
The following Rust code tries to store a closure of zero arguments in an array and call the function.
fn main() {
println!("The answer is: {}", solution_fns[0]());
}
const solution_fns: [fn() -> isize] =
[|| (1..=999).filter(|e| divides(3, e) || divides(5, e)).sum()];
fn divides(d: usize, n: usize) -> bool {
n % d == 0
}
Link to Rust playground. Unfortunately it does not compile:
error[E0277]: the size for values of type
[fn() -> isize]
cannot be known at compilation time --> src/main.rs:5:21 | 5 | const solution_fns: [fn() -> isize] = |
^^^^^^^^^^^^^^^ doesn't have a size known at compile-time | = help: the traitSized
is not implemented for[fn() -> isize]
I understand that you cannot constuct an array (or Vec) of things of which the size is not known at compile-time. However I understand the type [fn() -> isize]
to be array of function pointers, and I don't see why a function pointer should not have a known size. Sticking the closure in a Box does not seem to help:
const solution_fns: [Box<fn() -> isize>] = [Box::new(|| {
(1..=999).filter(|e| divides(3, e) || divides(5, e)).sum()
})];
How then can I store an array of closures?
The problem is not in the fn pointer, but that your array doesnt have a size. It is simply solved by adding the expected size to the array declaration:
const solution_fns: [fn() -> usize; 1] =
[|| (1..=999usize).filter(|&e| divides(3, e) || divides(5, e)).sum()];
Playground