如何使用一个FnOnce封闭的参考?

时间:2019-02-02 09:20:46

标签: rust closures

我有需要递归地传递一个闭合参数的函数

use std::cell::RefCell;
use std::rc::Rc;

pub struct TreeNode {
    val: i32,
    left: Option<Rc<RefCell<TreeNode>>>,
    right: Option<Rc<RefCell<TreeNode>>>,
}

pub fn pre_order<F>(root: Option<Rc<RefCell<TreeNode>>>, f: F)
where
    F: FnOnce(i32) -> (),
{
    helper(&root, f);

    fn helper<F>(root: &Option<Rc<RefCell<TreeNode>>>, f: F)
    where
        F: FnOnce(i32),
    {
        match root {
            Some(node) => {
                f(node.borrow().val);
                helper(&node.borrow().left, f);
                helper(&node.borrow().right, f);
            }
            None => return,
        }
    }
}

这不起作用:

error[E0382]: use of moved value: `f`
  --> src/lib.rs:23:45
   |
22 |                 f(node.borrow().val);
   |                 - value moved here
23 |                 helper(&node.borrow().left, f);
   |                                             ^ value used here after move
   |
   = note: move occurs because `f` has type `F`, which does not implement the `Copy` trait

error[E0382]: use of moved value: `f`
  --> src/lib.rs:24:46
   |
23 |                 helper(&node.borrow().left, f);
   |                                             - value moved here
24 |                 helper(&node.borrow().right, f);
   |                                              ^ value used here after move
   |
   = note: move occurs because `f` has type `F`, which does not implement the `Copy` trait

如果我尝试改变的类型ff: Ff: &F我得到的编译器错误

error[E0507]: cannot move out of borrowed content
  --> src/lib.rs:22:17
   |
22 |                 f(node.borrow().val);
   |                 ^ cannot move out of borrowed content

我该如何解决?

我打电话的功能是这样的:

let mut node = TreeNode::new(15);
node.left = Some(Rc::new(RefCell::new(TreeNode::new(9))));

let node_option = Some(Rc::new(RefCell::new(node)));
pre_order(node_option, |x| {
    println!("{:?}", x);
});

1 个答案:

答案 0 :(得分:3)

FnOnce是最通用的函数约束。但是,这意味着您的代码必须适用于所有可能的功能,包括那些消耗其环境的功能。这就是为什么它被称为FnOnce的原因:您唯一了解的是它至少可以被称为一次 -但不一定要称为它。在pre_order内部,我们只能假设一切可能的情况 F的正确之处:它只能被调用一次。

如果将其更改为FnFnMut,以排除占用其环境的闭包,则可以多次调用它。 FnMut是第二个最通用的函数特征,因此最好接受它而不是Fn,以确保您可以接受最多的函数:

pub fn pre_order<F>(root: Option<Rc<RefCell<TreeNode>>>, mut f: F)
where
    F: FnMut(i32),
{
    helper(&root, &mut f);

    fn helper<F>(root: &Option<Rc<RefCell<TreeNode>>>, 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,
        }
    }
}