Menu
Coddy logo textTech

Text Component

Part of the Object Oriented Programming section of Coddy's Rust journey. Lesson 50 of 61.

challenge icon

Challenge

Easy

Building on the Draw trait you created in the previous lesson, let's add our first real UI component: a TextField. This component will represent a text display element in our document system.

You'll expand your project with a new module file:

  • draw.rs: Keep your Draw trait from the previous challenge.
  • text_field.rs: Create a TextField struct with a public content field (a String). Implement the Draw trait for TextField so that calling draw() prints the text in a specific format: Text: {content}
  • main.rs: Bring in both modules and create a TextField instance. Call its draw() method to render the component.

Remember that your text_field module needs to use the Draw trait from the draw module. You can access it with crate::draw::Draw since both modules are part of the same crate.

The following input will be provided:

  • A string representing the text field's content

Your output should follow this exact format:

Text: Hello World

Try it yourself

mod draw;
mod text_field;

use draw::Draw;

pub struct Label {
    pub text: String,
}

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

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

    // TODO: Create a TextField instance and call draw() on it
}

All lessons in Object Oriented Programming

Practice on your own: Online Rust compiler