Rust programming video tutorial (Advanced) — 014refcell and internal variability

Time:2021-1-16

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. Internal variability: allows data to be changed when using immutable references.

2. By checking borrowing rules at run time (usually at compile time) by refcell, refcell represents the unique ownership of its data.
Similar to RC, refcell can only be used in single threaded scenarios.

3. Reasons for choosing box, RC or refcell:
RC allows multiple owners for the same data; box and refcell have a single owner.
Box allows immutable or variable borrowing check at compile time; RC only allows immutable borrowing check at compile time; refcell allows immutable or variable borrowing check at run time.
Because refcell allows variable borrowing check at run time, we can modify the internal value of refcell even if it is immutable.

4. Internal variability: variable borrowing of immutable values
example:

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

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

fn main() {
    let value = Rc::new(RefCell::new(5)); 

    let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil)));

    Let B = cons (RC:: new (refcell:: new (6)), RC:: Clone (& A)); // immutable reference
    Let C = cons (RC:: new (refcell:: new (10)), RC:: Clone (& A)); // immutable reference

    * value.borrow_ Mut() + = 10; // variable, variable reference at runtime

    println!("a after = {:?}", a);
    println!("b after = {:?}", b);
    println!("c after = {:?}", c);
}

In the above example, we can have a seemingly immutable list through refcell, but we can modify the data when necessary by providing an internal variability method in refcell.
Results of operation:

a after = Cons(RefCell { value: 15 }, Nil)
b after = Cons(RefCell { value: 6 }, Cons(RefCell { value: 15 }, Nil))
c after = Cons(RefCell { value: 10 }, Cons(RefCell { value: 15 }, Nil))

This work adoptsCC agreementReprint must indicate the author and the link of this article

Linghu Yichong

Recommended Today

New JavaScript syntax “double question mark syntax” and “optional chain syntax”

Double question mark grammar Double question mark grammarThe concept is to return the value on the right when the value on the left is null or undefined let Form = undefined ?? true; //Form = true Alternative chain syntax ? optional chain //Optional chain let body = { value: { a: ‘123321’ } } let […]