Menu
Coddy logo textTech

Recap - Rectangle Actions

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

challenge icon

Challenge

Easy

Create 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 takes width: u32 and height: u32 and returns a new Rectangle
  • area — takes &self and returns the area as u32
  • scale — takes &mut self and a factor: 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