I have a function which needs to pass a closure argument recursively
use std::cell::RefCell;
use std::rc::Rc;
pub struct TreeNode {
val: i32,
left: Opti
FnOnce
is the most most general function constraint. However, that means your code must work for all possible functions, including those that consume their environment. That's why it's called FnOnce
: the only thing you know about it is that it can be called it at least once - but not necessarily more. Inside pre_order
we can only assume what is true of every possible F
: it can be called once.
If you change this to Fn
or FnMut
, to rule out closures that consume their environments, you will be able to call it multiple times. FnMut
is the next most general function trait, so it is preferred to accept that instead of Fn
, to make sure you can accept the most functions:
pub fn pre_order(root: Option>>, mut f: F)
where
F: FnMut(i32),
{
helper(&root, &mut f);
fn helper(root: &Option>>, f: &mut F)
where
F: FnMut(i32),
{
match root {
Some(node) => {
f(node.borrow().val);
helper(&node.borrow().left, f);
helper(&node.borrow().right, f);
}
None => return,
}
}
}