Rust programming video tutorial (Advanced) – 013 using RC reference counting smart pointer

Time:2021-10-17

Video address

Headline address:https://www.ixigua.com/i677586170644791348…
Station B address:https://www.bilibili.com/video/av81202308/

Source address

GitHub address:https://github.com/anonymousGiga/learn_rus…

Explanation content

1. Consider needs
Rust programming video tutorial (Advanced) - 013 using RC reference counting smart pointer
B and C share the ownership of A. how to realize it
Example 1: using box implementation

enum List {
    Cons(i32, Box<List>),
    Nil,
}
use crate::List::{Cons, Nil};
fn main() {
    let a = Cons(5,
        Box::new(Cons(10,
            Box::new(Nil))));
    let b = Cons(3, Box::new(a));
    let c = Cons(4, Box::new(a));
}

This implementation reports an error. The prompt has been moved.

Example 2: implementation using RC

enum List {
    Cons(i32, Rc<List>),
    Nil,
}
use crate::List::{Cons, Nil};
use std::rc::Rc;
fn main() {
    let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
    let b = Cons(3, Rc::clone(&a));   // It is also OK to use A. clone () here
    let c = Cons(4, Rc::clone(&a));
}

2. Cloning RC increases the reference count

fn main() {
    let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
    println!("count after creating a = {}", Rc::strong_count(&a));
    let b = Cons(3, Rc::clone(&a));
    println!("count after creating b = {}", Rc::strong_count(&a));
    {
        let c = Cons(4, Rc::clone(&a));
        println!("count after creating c = {}", Rc::strong_count(&a));
    }
    println!("count after c goes out of scope = {}", Rc::strong_count(&a));
}

Through RC:: strong_ The count function prints the reference count divided by.

3. RC allows read-only data sharing between multiple parts of the program, because multiple variable references in the same location may cause data competition and inconsistency.

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Linghu rushed

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]