Menu
Coddy logo textTech

Running the Screen

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

challenge icon

Challenge

Easy

Congratulations on reaching the final step of the Document System project! You've built all the individual pieces—the Draw trait, TextField, Button, and Screen. Now it's time to give your Screen the ability to render all its components at once with a single method call.

You'll complete your project by adding a run method to the Screen struct. This method will iterate through all the components stored in the screen and call draw() on each one, bringing your entire document system to life.

Your project files:

  • draw.rs: Your Draw trait with the draw method.
  • text_field.rs: Your TextField component that prints Text: {content}.
  • button.rs: Your Button component that prints Button: {label} (width: {width}).
  • screen.rs: Your Screen struct with new and add methods. Add a run method that takes &self and calls draw() on every component in the collection.
  • main.rs: Bring everything together—create a Screen, add your components, and call run() to render the entire screen in one go.

The run method encapsulates the rendering logic inside the Screen, making your main function clean and simple. Instead of manually iterating through components in main, you just call screen.run().

The following inputs will be provided:

  • First line: the text field's content
  • Second line: the button's label
  • Third line: the button's width (as a number)

Your output should display each component on its own line, in the order they were added:

Text: Dashboard
Button: Save (width: 120)

Try it yourself

mod draw;
mod text_field;
mod button;
mod screen;

use draw::Draw;
use text_field::TextField;
use button::Button;
use screen::Screen;

pub struct Label {
    pub text: String,
}

impl Draw for Label {
    fn draw(&self) {
        println!("{}", self.text);
    }
}

fn main() {
    let mut input1 = String::new();
    std::io::stdin().read_line(&mut input1).expect("Failed to read line");
    let content = input1.trim().to_string();

    let mut input2 = String::new();
    std::io::stdin().read_line(&mut input2).expect("Failed to read line");
    let label = input2.trim().to_string();

    let mut input3 = String::new();
    std::io::stdin().read_line(&mut input3).expect("Failed to read line");
    let width: u32 = input3.trim().parse().expect("Failed to parse width");

    let mut screen = Screen::new();

    let text_field = TextField { content };
    screen.add(Box::new(text_field));

    let button = Button { label, width };
    screen.add(Box::new(button));

    // TODO: Replace the manual iteration below with a single call to screen.run()
    for component in &screen.components {
        component.draw();
    }
}

All lessons in Object Oriented Programming