Menu
Coddy logo textTech

Button Component

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

challenge icon

Challenge

Easy

Let's continue building our Document System by adding a second UI component: a Button. Just like the TextField, this component will implement the Draw trait, demonstrating how different types can share a common interface.

You'll expand your project with another module file:

  • draw.rs: Keep your Draw trait from the previous challenges.
  • text_field.rs: Keep your TextField struct and its Draw implementation.
  • button.rs: Create a Button struct with two public fields: label (a String) and width (a u32). Implement the Draw trait for Button so that calling draw() prints the button in this format: Button: {label} (width: {width})
  • main.rs: Bring in all three modules. Create both a TextField and a Button, then call draw() on each to render both components.

Your button module will need to access the Draw trait using crate::draw::Draw, just like you did with TextField.

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 the text field first, then the button, each on its own line:

Text: Welcome
Button: Submit (width: 100)

Try it yourself

mod draw;
mod text_field;
mod button;

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

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 text_field = TextField { content };
    text_field.draw();

    // TODO: Create a Button with `label` and `width`, then call draw()
    
}

All lessons in Object Oriented Programming