Consider the following Rust code using Rc. What will it print?
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 Rc pointers point to the same data.
Both a and b point to the same data, so the strong count is 2.
Choose the correct statement about Rc pointers in Rust.
Think about whether Rc can be shared across threads.
Rc allows multiple ownership but is not safe to share between threads. For thread-safe reference counting, Arc is used.
What error will this Rust code produce?
use std::rc::Rc;
fn main() {
let a = Rc::new(10);
let b = a;
println!("{}", Rc::strong_count(&a));
}Consider what happens when you assign a to b without cloning.
Assigning a to b moves the Rc pointer, so a is no longer valid. Using a after move causes a compile error.
Which of the following lines correctly clones an Rc pointer rc_val?
use std::rc::Rc;
fn main() {
let rc_val = Rc::new(42);
// Which line correctly clones rc_val?
}Remember the recommended way to clone an Rc pointer.
The recommended way is to use Rc::clone(&rc_val). Option B also compiles but is less explicit. Option B tries to create a new Rc from an Rc which is invalid. Option B uses a method that does not exist.
After running this Rust code, how many strong references to the value exist?
use std::rc::Rc;
fn main() {
let x = Rc::new(100);
let y = Rc::clone(&x);
{
let z = Rc::clone(&y);
println!("Inside block: {}", Rc::strong_count(&x));
}
println!("Outside block: {}", Rc::strong_count(&x));
}Count how many Rc pointers exist inside and outside the inner block.
Inside the block, x, y, and z all point to the value, so count is 3. After the block, z is dropped, so count is 2.