美文网首页RUST编程
Rust 编程视频教程(进阶)——015_3 查看 strong

Rust 编程视频教程(进阶)——015_3 查看 strong

作者: 令狐壹冲 | 来源:发表于2020-02-08 11:09 被阅读0次

    视频地址

    头条地址:https://www.ixigua.com/i6775861706447913485
    B站地址:https://www.bilibili.com/video/av81202308/

    源码地址

    github地址:https://github.com/anonymousGiga/learn_rust

    讲解内容

    通过例子查看strong_count和weak_count的改变

    例子:

    use std::rc::{Rc, Weak};
    use std::cell::RefCell;
    
    #[derive(Debug)]
    struct Node {
        value: i32,
        parent: RefCell<Weak<Node>>,
        children: RefCell<Vec<Rc<Node>>>,
    }
    fn main() {
        let leaf = Rc::new(Node {
            value: 3,
            parent: RefCell::new(Weak::new()),
            children: RefCell::new(vec![]),
        });
    
        println!(
            "leaf strong = {}, weak = {}",
            Rc::strong_count(&leaf),
            Rc::weak_count(&leaf),
        );
    
        {
            let branch = Rc::new(Node {
                value: 5,
                parent: RefCell::new(Weak::new()),
                children: RefCell::new(vec![Rc::clone(&leaf)]),
            });
    
            *leaf.parent.borrow_mut() = Rc::downgrade(&branch);
    
            println!(
                "branch strong = {}, weak = {}",
                Rc::strong_count(&branch),
                Rc::weak_count(&branch),
            );
    
            println!(
                "leaf strong = {}, weak = {}",
                Rc::strong_count(&leaf),
                Rc::weak_count(&leaf),
            );
        }
    
        println!("leaf parent = {:?}", leaf.parent.borrow().upgrade());
        println!(
            "leaf strong = {}, weak = {}",
            Rc::strong_count(&leaf),
            Rc::weak_count(&leaf),
        );
    }
    

    相关文章

      网友评论

        本文标题:Rust 编程视频教程(进阶)——015_3 查看 strong

        本文链接:https://www.haomeiwen.com/subject/cxtixhtx.html