Rc+RefCell解释

1 Rc(Reference Counted)

Rc(Reference Counted):是Rust标准库中,用于处理引用计数智能指针。用来突破单一所有权的限制。其基本操作是通过clone()增加引用计数。

Reference Counted
// Rc会把对应的数据结构创建在堆上
// 堆上的数据才适合被用来在多个函数调用栈帧中共享
let i1 = Rc::new(1);
// 复制引用计数
let i2 = i1.clone();
let i3 = i1.clone();
// 现在引用计数值为3
println!("{}", Rc::strong_count(&i1)); //3
println!("{}", Rc::strong_count(&i2)); //3
println!("{}", Rc::strong_count(&i3)); //3

Rc的使用

use std::rc::Rc;

fn main() {
    let i1 = Rc::new(13);
    let i2 = i1.clone();

    println!("{}", i1); 
    println!("{}", i2);
}

13
13

2 内外可变性

2.1 外部可变性

简单来说,mut关键字注明的可修改性就是外部可变性

Rust中提供了两种引用/借用类型:

  • &:只读引用,只读引用不允许修改被引用的对象。
  • &mut:可变引用,可变引用才有修改权限。

在编译阶段,Rust会检查,同一作用域内,对于某一个对象的引用,只允许存在两种情况:

要么只有一个活跃的可变引用,要么同时存在多个只读引用

2.2 RefCell和内部可变性

RefCell,提供内部包装类型的内部可变性,用来突破mut变量才能被修改(外部可变性)的限制

//Rc是线程内部以只读的方式共享数据
//RefCell提供内部可变性
let cell = RefCell::new(10);
{// 运行时会检查借用规则,所以这里必须加大括号
 // 将可写借用跟后面的只读借用隔离开来
    let mut mut_ref = cell.borrow_mut();
    *mut_ref += 1;
}
println!("{}", cell.borrow());//11

其中,

  • borrow()方法返回内部包装对象的只读引用。
  • borrow_mut()返回内部包装对象的可写引用。

代码在运行时,会动态检查RefCell对象的借用规则,以保证:在同一作用域内,要么只存在一个可写借用,要么只存在1到多个只读借用

3 Rust表达二叉树

// Definition for a binary tree node.
// #[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
//     }
//   }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
    fn dfs(root:&Option<Rc<RefCell<TreeNode>>>, ans:&mut Vec<i32>){
        if root.is_none(){
            return;
        }
        let node=root.as_ref().unwrap().borrow();
        Self::dfs(&node.left,ans);
        ans.push(node.val);
        Self::dfs(&node.right,ans);
    }
    pub fn inorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
        let mut ans=vec![];
        Self::dfs(&root,&mut ans);
        ans
    }
}

 

posted @ 2024-03-11 20:56  ImreW  阅读(27)  评论(0编辑  收藏  举报