0
0
Rustprogramming~20 mins

Ownership with smart pointers in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Rust Smart Pointer Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Rust code using Rc?

Consider the following Rust code using Rc smart pointers. What will be printed?

Rust
use std::rc::Rc;

fn main() {
    let a = Rc::new(5);
    let b = Rc::clone(&a);
    println!("{}", Rc::strong_count(&a));
}
A1
BCompilation error
C2
D0
Attempts:
2 left
💡 Hint

Think about how many owners the Rc pointer has after cloning.

Predict Output
intermediate
2:00remaining
What happens when you try to mutate data inside an Rc without RefCell?

What error or output will this Rust code produce?

Rust
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"),
    }
}
ACannot get mutable reference
BCompilation error due to mutability
CProgram panics at runtime
DValue is changed to 10
Attempts:
2 left
💡 Hint

Rc allows mutation only if there is exactly one owner.

🔧 Debug
advanced
2:00remaining
Why does this code cause a runtime panic with RefCell?

Examine the Rust code below. Why does it panic at runtime?

Rust
use std::cell::RefCell;

fn main() {
    let data = RefCell::new(5);
    let _borrow1 = data.borrow_mut();
    let _borrow2 = data.borrow_mut();
}
ABecause multiple mutable borrows are not allowed simultaneously
BBecause RefCell does not allow any borrows
CBecause the data is immutable
DBecause borrow_mut returns an error that is not handled
Attempts:
2 left
💡 Hint

Think about Rust's borrowing rules enforced at runtime by RefCell.

🧠 Conceptual
advanced
2:00remaining
What is the main difference between Box and Rc in Rust?

Choose the best explanation of the difference between Box and Rc smart pointers.

ABox automatically clones data; Rc does not
BBox allows multiple owners; Rc allows only one owner
CBox is for stack allocation; Rc is for heap allocation
DBox provides single ownership and heap allocation; Rc provides shared ownership with reference counting
Attempts:
2 left
💡 Hint

Think about ownership and how many owners each pointer type supports.

Predict Output
expert
3:00remaining
What is the output of this code mixing Rc and RefCell?

Analyze the following Rust code. What will it print?

Rust
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());
}
A10
B15
CCompilation error due to borrow rules
DRuntime panic due to multiple mutable borrows
Attempts:
2 left
💡 Hint

Consider how Rc and RefCell work together to allow mutation.