Menu
Coddy logo textTech

The Draw Trait

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

challenge icon

Challenge

Easy

Let's begin building a Document System! In this project, you'll create a flexible framework for rendering UI components using trait objects. The foundation starts with defining a Draw trait in its own module file.

You'll create two files to organize your code:

  • draw.rs: Define a public Draw trait with a single method called draw that takes &self and prints output. This trait will serve as the contract that all UI components must fulfill.
  • main.rs: Bring in your draw module and create a simple struct called Label with a public text field (a String). Implement the Draw trait for Label so that calling draw() prints the label's text.

In your main function, create a Label instance and call its draw() method to display the text.

The following input will be provided:

  • A string representing the label's text

Your output should be exactly the label's text on a single line.

Try it yourself

mod draw;

use draw::Draw;

// TODO: Define a public struct called Label with a public text field (String)

// TODO: Implement the Draw trait for Label
// The draw method should print the label's text

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

    // TODO: Create a Label instance with the input text
    // TODO: Call the draw() method on the label
}

All lessons in Object Oriented Programming