So I'm doing this years advent of code and I've come across a borrowing problem:
How to have a struct that accepts closures calling methods from another variable? Here's a minimum example I've managed to come up with. The borrow checker doesn't like that the two closures both borrow values.
If I have a mutex around values then it seems to work but I was hoping for a more elegant solution.
Essentially, I want to have different Brains with different input/output functions where one might just print outputs and another might be adding outputs to a vec.
struct Brain<I, O>
where
I: Fn() -> i32,
O: FnMut(i32),
{
input: I,
output: O,
}
impl<I, O> Brain<I, O>
where
I: Fn() -> i32,
O: FnMut(i32),
{
fn new(input: I, output: O) -> Self {
Brain { input, output }
}
}
fn runner() {
let mut values = Vec::new();
let request_input = || *values.last().unwrap();
let add_output = |v| values.push(v);
let _ = Brain::new(request_input, add_output);
}