Rust編程進階:040、弱引用

弱引用Weak<T>
特點:
(1)弱引用通過Rc::downgrade傳遞Rc實例的引用,調用Rc::downgrade會得到Weak<T>類型的智能指針,同時將weak_count加1(不是將strong_count加1)。
(2)區別在於 weak_count 無需計數爲 0 就能使 Rc 實例被清理。只要strong_count爲0就可以了。
(3)可以通過Rc::upgrade方法返回Option<Rc<T>>對象。
示例:

#[derive(Debug)]
enum List {
    // Cons(i32, RefCell<Rc<List>>),
    Cons(i32, RefCell<Weak<List>>),
    Nil,
}

impl List {
    fn tail(&self) -> Option<&RefCell<Weak<List>>> {
        match self {
            Cons(_, item) => Some(item),
            Nil => None,
        }
    }
}

use crate::List::{Cons, Nil};
use std::cell::RefCell;
use std::rc::Rc;
use std::rc::Weak;

fn main() {
    let a = Rc::new(Cons(5, RefCell::new(Weak::new())));
    println!(
        "1, a strong count = {}, weak count = {}",
        Rc::strong_count(&a),
        Rc::weak_count(&a)
    );
    println!("1, a tail = {:?}", a.tail());

    let b = Rc::new(Cons(10, RefCell::new(Weak::new())));
    if let Some(link) = b.tail() {
        *link.borrow_mut() = Rc::downgrade(&a);
    }
    println!(
        "2, a strong count = {}, weak count = {}",
        Rc::strong_count(&a),
        Rc::weak_count(&a)
    );
    println!(
        "2, b strong count = {}, weak count = {}",
        Rc::strong_count(&b),
        Rc::weak_count(&b)
    );
    println!("2, b tail = {:?}", b.tail());

    if let Some(link) = a.tail() {
        *link.borrow_mut() = Rc::downgrade(&b);
    }
    println!(
        "3, a strong count = {}, weak count = {}",
        Rc::strong_count(&a),
        Rc::weak_count(&a)
    );
    println!(
        "3, b strong count = {}, weak count = {}",
        Rc::strong_count(&b),
        Rc::weak_count(&b)
    );
    println!("3, a tail = {:?}", a.tail());
}

本節全部源代碼:
https://github.com/anonymousGiga/learn_rust/blob/master/learn_loop_ref2/src/main.rs

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章