RefCell

Cell's semantics of moving the stored data value in and out of the cell are not always convenient to work with, and for large data values, moving them can be an expensive operation that we don't want to keep repeating over and over without need. RefCell to the rescue!

The RefCell type supports RefCell::new, replace, and into_inner, just as Cell does, but it also has functions that allow us to borrow the contained value, either mutably or immutably.

Let's give RefCell a whirl:

 let refcell = RefCell::new("It's a string".to_string());

match refcell.try_borrow() {
Ok(x) => { println!("Borrowed: {}", x); }
Err(_) => { println!("Couldn't borrow first try"); }
};

let borrowed_mutably = refcell.try_borrow_mut()?;

match refcell.try_borrow() {
Ok(x) => { println!("Borrowed: {}", x); }
Err(_) => { println!("Couldn't borrow second try"); }
};

println!("Mutable borrow is still alive: {}", borrowed_mutably);

First, we created a new RefCell, containing a text string. After that, we used the try_borrow function to retrieve an immutable borrow of the contained data value. The rules about borrowing are still enforced, meaning we can't borrow a value if it's mutably borrowed, and we can't mutably borrow a value if the value is already borrowed at all, which means that try_borrow might not actually succeed. Therefore, we have to handle the possibility that it fails, which we're doing here by using a match expression.

Next, we retrieve a mutable borrow and store it in a local variable. The previous borrow's lifetime ended at the end of the chosen block in the match expression, so there are no live borrows and we expect the try_borrow_mut to succeed, but we still need to handle the possibility of failure. In this case, we're using ? to handle the returned Result, which will extract the value of a success, or return a failure to the function that called our current function. If the try_borrow_mut succeeds as expected, that leaves the borrowed_mutably variable containing a mutable reference to refcell's contained data value.

Then we again try to borrow the contained data value, immutably. Since immutable borrows are not compatible with mutable borrows, and our mutable borrow is still around, we expect this attempt to fail.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.179.85