Text Component
Part of the Object Oriented Programming section of Coddy's Rust journey. Lesson 50 of 61.
Challenge
EasyBuilding 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 yourDrawtrait from the previous challenge.text_field.rs: Create aTextFieldstruct with a publiccontentfield (aString). Implement theDrawtrait forTextFieldso that callingdraw()prints the text in a specific format:Text: {content}main.rs: Bring in both modules and create aTextFieldinstance. Call itsdraw()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 WorldTry 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
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 MockPractice on your own: Online Rust compiler