Recap - Rectangle Actions
Part of the Object Oriented Programming section of Coddy's Rust journey — lesson 7 of 61.
Challenge
EasyCreate a Rectangle struct with two fields: width (u32) and height (u32).
Add an implementation block for Rectangle with the following:
new— an associated function that takeswidth: u32andheight: u32and returns a newRectanglearea— takes&selfand returns the area asu32scale— takes&mut selfand afactor: u32, multiplies both width and height by the factor
You will receive three inputs:
- First line: the width (u32)
- Second line: the height (u32)
- Third line: the scale factor (u32)
Create a mutable Rectangle using Rectangle::new with the provided dimensions. Print the initial area, then scale the rectangle by the given factor, and print the new area.
Expected output format:
{initial_area}
{scaled_area}Try it yourself
use std::io;
// TODO: Define the Rectangle struct here
// TODO: Add the implementation block for Rectangle with:
// - new: associated function that takes width and height, returns Rectangle
// - area: method that takes &self, returns u32
// - scale: method that takes &mut self and factor, multiplies width and height
fn main() {
let mut input = String::new();
// Read width
io::stdin().read_line(&mut input).expect("Failed to read line");
let width: u32 = input.trim().parse().expect("Invalid number");
input.clear();
// Read height
io::stdin().read_line(&mut input).expect("Failed to read line");
let height: u32 = input.trim().parse().expect("Invalid number");
input.clear();
// Read scale factor
io::stdin().read_line(&mut input).expect("Failed to read line");
let factor: u32 = input.trim().parse().expect("Invalid number");
// TODO: Create a mutable Rectangle using Rectangle::new
// TODO: Print the initial area
// TODO: Scale the rectangle by the factor
// TODO: Print the new area
}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