Unwrap and access T from an Option>>

后端 未结 1 1573
情书的邮戳
情书的邮戳 2021-01-15 12:21

I am trying to solve some Leetcode problems with Rust. However, I ran into some difficulties with LeetCode\'s TreeNode implementation.

use std:         


        
相关标签:
1条回答
  • 2021-01-15 13:22

    Unwrap and access T from an Option<Rc<RefCell<T>>>

    You really don't want to try to remove the value from the Option, the Rc or the RefCell via unwrap / try_unwrap / into_inner. Instead, pattern match on the Option and then call borrow on the RefCell to get a reference to the T.

    Additionally:

    1. Use if let instead of a match statement when you only care about one arm.
    2. Variables use snake_case. V is not an appropriate name.
    3. There's no need to use a struct here, or to define the helper function publicly. A plain function and a nested function are simpler and exposes less detail.
    4. There's no need to provide an explicit type when constructing ret.
    pub fn inorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
        fn helper(node: &Option<Rc<RefCell<TreeNode>>>, ret: &mut Vec<i32>) {
            if let Some(v) = node {
                let v = v.borrow();
    
                helper(&v.left, ret);
                ret.push(v.val);
                helper(&v.right, ret);
            }
        }
    
        let mut ret = vec![];
    
        if let Some(v) = root {
            helper(&Some(v), &mut ret);
        }
    
        ret
    }
    

    Personally, I'm not a fan of being forced to construct the Some, so I'd probably reorganize the code, which also allows me to stick it as a method on TreeNode:

    impl TreeNode {
        pub fn inorder_traversal(&self) -> Vec<i32> {
            fn helper(node: &TreeNode, ret: &mut Vec<i32>) {
                if let Some(ref left) = node.left {
                    helper(&left.borrow(), ret);
                }
    
                ret.push(node.val);
    
                if let Some(ref right) = node.right {
                    helper(&right.borrow(), ret);
                }
            }
    
            let mut ret = vec![];
            helper(self, &mut ret);
            ret
        }
    }
    

    See also:

    • Why does Arc::try_unwrap() cause a panic?
    0 讨论(0)
提交回复
热议问题