0
0
Rustprogramming~20 mins

Box pointer in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Box 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 Rust code using Box pointer?
Consider the following Rust program that uses a Box pointer. What will it print when run?
Rust
fn main() {
    let b = Box::new(5);
    println!("{}", *b + 10);
}
ACompilation error
B5
C10
D15
Attempts:
2 left
💡 Hint
Remember that Box stores the value on the heap and you need to dereference it to get the value.
Predict Output
intermediate
2:00remaining
What happens when you try to move a Box pointer?
What will be the output or result of this Rust code?
Rust
fn main() {
    let b1 = Box::new(7);
    let b2 = b1;
    println!("{}", *b1);
    println!("{}", *b2);
}
A7
BRuntime panic
CCompilation error due to use of moved value
D0
Attempts:
2 left
💡 Hint
Box pointers have ownership semantics. Moving them invalidates the original variable.
🔧 Debug
advanced
2:00remaining
Why does this Box pointer code cause a compilation error?
Identify the error in this Rust code and what causes it.
Rust
fn main() {
    let b = Box::new(10);
    let r1 = &b;
    let r2 = &mut b;
    println!("{} {}", r1, r2);
}
ACannot borrow `b` as mutable because it is also borrowed as immutable
BCannot borrow `b` as immutable because it is also borrowed as mutable
CBox pointer cannot be borrowed
DNo error, prints '10 10'
Attempts:
2 left
💡 Hint
Rust enforces borrowing rules: you cannot have mutable and immutable borrows at the same time.
Predict Output
advanced
2:00remaining
What is the output of this recursive Box pointer example?
What will this Rust program print?
Rust
enum List {
    Cons(i32, Box<List>),
    Nil,
}

fn main() {
    let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
    match list {
        List::Cons(x, box List::Cons(y, box List::Nil)) => println!("{} {}", x, y),
        _ => println!("No match"),
    }
}
ANo match
B1 2
CCompilation error
DRuntime panic
Attempts:
2 left
💡 Hint
Pattern matching with Box requires unboxing with `box` keyword.
🧠 Conceptual
expert
2:00remaining
Why use Box pointer in Rust for recursive types?
Which is the main reason to use Box pointer for recursive data types in Rust?
ATo allocate recursive data on the heap and have a known size for the enum
BTo improve runtime speed by avoiding heap allocation
CTo allow multiple ownership of the recursive data
DTo automatically clone the recursive data when copied
Attempts:
2 left
💡 Hint
Rust needs to know the size of types at compile time. Recursive types without indirection have unknown size.