The Draw Trait
Part of the Object Oriented Programming section of Coddy's Rust journey — lesson 49 of 61.
Challenge
EasyLet'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 publicDrawtrait with a single method calleddrawthat takes&selfand prints output. This trait will serve as the contract that all UI components must fulfill.main.rs: Bring in yourdrawmodule and create a simple struct calledLabelwith a publictextfield (aString). Implement theDrawtrait forLabelso that callingdraw()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
1Methods and Behavior
Intro Implementation BlocksThe Self ParameterMutable MethodsAssociated FunctionsMultiple Implementation BlocksMethod ChainingRecap - Rectangle Actions4Project: Virtual Pet
Defining the PetFeeding the Pet7Standard Traits
The Debug TraitThe Display TraitClone and CopyEquality TraitsRecap - Printable Point10Project: Document System
The Draw TraitText Component2Encapsulation and Modules
Modules BasicsThe Public KeywordPrivate FieldsGettersSettersRecap - Secure Locker5Generics
Generic StructsGeneric MethodsMultiple Generic TypesGeneric FunctionsRecap - Coordinate Point8Traits as Bounds
Trait Bounds SyntaxMultiple BoundsThe Where ClauseReturning Types with TraitsRecap - Generic Printer11Design Patterns in Rust
Newtype PatternCompositionThe Drop TraitFrom and IntoRecap - Smart Pointer Mock