Button Component
Part of the Object Oriented Programming section of Coddy's Rust journey — lesson 51 of 61.
Challenge
EasyLet'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 yourDrawtrait from the previous challenges.text_field.rs: Keep yourTextFieldstruct and itsDrawimplementation.button.rs: Create aButtonstruct with two public fields:label(aString) andwidth(au32). Implement theDrawtrait forButtonso that callingdraw()prints the button in this format:Button: {label} (width: {width})main.rs: Bring in all three modules. Create both aTextFieldand aButton, then calldraw()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
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