rust - 从 Option<Rc<RefCell<T>>> 解包并访问 T

标签 rust smart-pointers dereference

我正在尝试用 Rust 解决一些 Leetcode 问题。然而,我在 LeetCode 的 TreeNode 上遇到了一些困难。执行。

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

// TreeNode data structure
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
    pub val: i32,
    pub left: Option<Rc<RefCell<TreeNode>>>,
    pub right: Option<Rc<RefCell<TreeNode>>>,
}

impl TreeNode {
    #[inline]
    pub fn new(val: i32) -> Self {
        TreeNode {
            val,
            left: None,
            right: None,
        }
    }
}

如果我想进行中序遍历,如何解包TreeNodeOption<Rc<RefCell<TreeNode>>>对象,访问它的 .val .left .right并将它们作为输入传递给递归函数?

我试过:

pub struct Solution;

impl Solution {
    pub fn inorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
        let mut ret: Vec<i32> = vec![];
        match root {
            Some(V) => Solution::helper(&Some(V), &mut ret),
            None => (),
        }

        ret
    }

    fn helper(node: &Option<Rc<RefCell<TreeNode>>>, ret: &mut Vec<i32>) {
        match node {
            None => return,
            Some(V) => {
                // go to the left branch
                Solution::helper(
                    (*Rc::try_unwrap(Rc::clone(V)).unwrap_err())
                        .into_inner()
                        .left,
                    ret,
                );
                // push root value on the vector
                ret.push(Rc::try_unwrap(Rc::clone(V)).unwrap_err().into_inner().val);
                // go right branch
                Solution::helper(
                    (*Rc::try_unwrap(Rc::clone(V)).unwrap_err())
                        .into_inner()
                        .right,
                    ret,
                );
            }
        }
    }
}

fn main() {}

( Playground )

编译器提示:

error[E0308]: mismatched types
  --> src/lib.rs:42:21
   |
42 | /                     (*Rc::try_unwrap(Rc::clone(V)).unwrap_err())
43 | |                         .into_inner()
44 | |                         .left,
   | |_____________________________^ expected reference, found enum `std::option::Option`
   |
   = note: expected type `&std::option::Option<std::rc::Rc<std::cell::RefCell<TreeNode>>>`
              found type `std::option::Option<std::rc::Rc<std::cell::RefCell<TreeNode>>>`
help: consider borrowing here
   |
42 |                     &(*Rc::try_unwrap(Rc::clone(V)).unwrap_err())
43 |                         .into_inner()
44 |                         .left,
   |

但如果我尝试这个建议,它也会提示:

error[E0507]: cannot move out of an `Rc`
  --> src/lib.rs:42:22
   |
42 |                     &(*Rc::try_unwrap(Rc::clone(V)).unwrap_err())
   |                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot move out of an `Rc`

error[E0507]: cannot move out of data in a `&` reference
  --> src/lib.rs:42:22
   |
42 |                     &(*Rc::try_unwrap(Rc::clone(V)).unwrap_err())
   |                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |                      |
   |                      cannot move out of data in a `&` reference
   |                      cannot move

最佳答案

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

真的不想尝试从 Option 中删除值, RcRefCell通过unwrap/try_unwrap/into_inner .相反,Option 上的模式匹配然后调用borrowRefCell 上获得对 T 的引用.

另外:

  1. 使用if let而不是 match当您只关心一只 ARM 时的声明。
  2. 变量使用snake_case . V不是一个合适的名字。
  3. 这里不需要使用结构,也不需要公开定义辅助函数。普通函数和嵌套函数更简单,公开的细节也更少。
  4. 构造 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
}

就个人而言,我不喜欢被迫构建 Some ,所以我可能会重新组织代码,这也允许我将它作为一种方法粘贴在 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
    }
}

另见:

关于rust - 从 Option<Rc<RefCell<T>>> 解包并访问 T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54012660/

相关文章:

C++11 使用带有自定义删除器的 unique_ptr

c++ - 如何通过唯一指针获得多态行为?

将 char* 转换为 int

c++ - `copy`实现示例中的运算符优先级

* 和 -> 之间的 C++ 指针区别

rust - 有没有办法创建 std::slice::Iter 的类型别名?

rust - 用特征别名替换特征绑定(bind)说 "the size for values cannot be known at compilation time"

rust - 如何在不运行的情况下构建 Rust 示例

来自工厂函数的 Rust 闭包

c++ - 保持 shared_ptr use_count() 为 1