Menu
Coddy logo textTech

Recap - Smart Pointer Mock

Part of the Object Oriented Programming section of Coddy's Rust journey — lesson 58 of 61.

challenge icon

Challenge

Easy

Let's build a smart pointer mock called SmartBox that demonstrates how Rust's actual smart pointers work under the hood! Your wrapper will be generic, provide access to its inner value, and automatically announce when it's being cleaned up.

You'll organize your code across two files:

  • smart_box.rs: Define a public generic struct SmartBox<T> with a single field value of type T. Implement a new associated function that creates a SmartBox and prints a creation message. Add a get method that returns a reference to the inner value. Finally, implement the Drop trait to print a cleanup message when the SmartBox goes out of scope.
  • main.rs: Bring in your smart_box module and demonstrate your SmartBox with two different types. Create a SmartBox<i32> holding a number and a SmartBox<String> holding text (both from provided inputs). Print the values using your get method. The Drop messages will appear automatically when the boxes go out of scope at the end of main.

When a SmartBox is created, it should print:

SmartBox created

When accessing the value, print it in this format:

Value: {value}

When a SmartBox is dropped, it should print:

SmartBox dropped

For example, with inputs 42 and Hello:

SmartBox created
SmartBox created
Value: 42
Value: Hello
SmartBox dropped
SmartBox dropped

Notice how both boxes are created first, then their values are accessed, and finally both are dropped in reverse order (last created, first dropped) when main ends.

You will receive two inputs: an integer value (parse as i32) and a string value.

Try it yourself

mod smart_box;

use smart_box::SmartBox;

fn main() {
    // Read inputs
    let mut input1 = String::new();
    std::io::stdin().read_line(&mut input1).expect("Failed to read line");
    let number: i32 = input1.trim().parse().expect("Failed to parse number");
    
    let mut input2 = String::new();
    std::io::stdin().read_line(&mut input2).expect("Failed to read line");
    let text = input2.trim().to_string();
    
    // TODO: Create a SmartBox<i32> holding the number
    
    // TODO: Create a SmartBox<String> holding the text
    
    // TODO: Print the values using the get method
    // Format: "Value: {value}"
    
    // The Drop messages will appear automatically when main ends
}

All lessons in Object Oriented Programming