How to use a reference to a FnOnce closure?

前端 未结 1 1869
温柔的废话
温柔的废话 2021-01-23 19:34

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         


        
1条回答
  •  礼貌的吻别
    2021-01-23 20:26

    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,
            }
        }
    }
    

    0 讨论(0)
提交回复
热议问题