0
0
Rustprogramming~20 mins

Rc pointer in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Rc Pointer Mastery
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 Rc pointer code?

Consider the following Rust code using Rc. What will it print?

Rust
use std::rc::Rc;

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

Think about how many Rc pointers point to the same data.

🧠 Conceptual
intermediate
1:30remaining
Which statement about Rc pointers is true?

Choose the correct statement about Rc pointers in Rust.

A<code>Rc</code> allows multiple ownership but is not thread-safe.
B<code>Rc</code> allows multiple ownership and is thread-safe.
C<code>Rc</code> allows only single ownership and is thread-safe.
D<code>Rc</code> allows only single ownership and is not thread-safe.
Attempts:
2 left
💡 Hint

Think about whether Rc can be shared across threads.

🔧 Debug
advanced
2:00remaining
What error does this Rc code produce?

What error will this Rust code produce?

Rust
use std::rc::Rc;

fn main() {
    let a = Rc::new(10);
    let b = a;
    println!("{}", Rc::strong_count(&a));
}
APrints 2
BRuntime panic: null pointer dereference
CCompilation error: use of moved value 'a'
DPrints 1
Attempts:
2 left
💡 Hint

Consider what happens when you assign a to b without cloning.

📝 Syntax
advanced
1:30remaining
Which option correctly clones an Rc pointer?

Which of the following lines correctly clones an Rc pointer rc_val?

Rust
use std::rc::Rc;

fn main() {
    let rc_val = Rc::new(42);
    // Which line correctly clones rc_val?
}
Alet rc_clone = rc_val.clone();
Blet rc_clone = Rc::clone(&rc_val);
Clet rc_clone = Rc::new(rc_val);
Dlet rc_clone = rc_val.copy();
Attempts:
2 left
💡 Hint

Remember the recommended way to clone an Rc pointer.

🚀 Application
expert
2:30remaining
How many strong references exist after this code?

After running this Rust code, how many strong references to the value exist?

Rust
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));
}
AInside block: 1, Outside block: 1
BInside block: 2, Outside block: 1
CInside block: 3, Outside block: 3
DInside block: 3, Outside block: 2
Attempts:
2 left
💡 Hint

Count how many Rc pointers exist inside and outside the inner block.