Consider the following Rust code using Rc smart pointers. What will be printed?
use std::rc::Rc;
fn main() {
let a = Rc::new(5);
let b = Rc::clone(&a);
println!("{}", Rc::strong_count(&a));
}Think about how many owners the Rc pointer has after cloning.
Cloning an Rc pointer increases the reference count. Here, a and b both own the data, so the count is 2.
What error or output will this Rust code produce?
use std::rc::Rc;
fn main() {
let data = Rc::new(5);
let mut_ref = Rc::get_mut(&mut Rc::clone(&data));
match mut_ref {
Some(v) => *v = 10,
None => println!("Cannot get mutable reference"),
}
}Rc allows mutation only if there is exactly one owner.
Rc::get_mut returns None if there are multiple owners. Here, cloning increases owners, so mutable access is denied.
Examine the Rust code below. Why does it panic at runtime?
use std::cell::RefCell;
fn main() {
let data = RefCell::new(5);
let _borrow1 = data.borrow_mut();
let _borrow2 = data.borrow_mut();
}Think about Rust's borrowing rules enforced at runtime by RefCell.
RefCell enforces borrowing rules at runtime. Two simultaneous mutable borrows cause a panic.
Choose the best explanation of the difference between Box and Rc smart pointers.
Think about ownership and how many owners each pointer type supports.
Box has single ownership and stores data on the heap. Rc allows multiple owners by counting references.
Analyze the following Rust code. What will it print?
use std::rc::Rc;
use std::cell::RefCell;
fn main() {
let data = Rc::new(RefCell::new(10));
let data_clone = Rc::clone(&data);
*data_clone.borrow_mut() += 5;
println!("{}", data.borrow());
}Consider how Rc and RefCell work together to allow mutation.
Rc allows shared ownership, and RefCell allows interior mutability. The value is changed to 15.