Rust Program: Rectangle area calculation
Write a Rust program that defines a struct Rectangle with fields width and height. Write a function to calculate the area of a rectangle instance.
Sample Solution:
Rust Code:
// Define a struct named 'Rectangle' with fields 'width' and 'height'
struct Rectangle {
width: f64,
height: f64,
}
// Implementation block for the 'Rectangle' struct
impl Rectangle {
// Define a method named 'area' that calculates the area of a rectangle instance
fn area(&self) -> f64 {
self.width * self.height // Calculate the area by multiplying the width and height
}
}
fn main() {
let rect1 = Rectangle { width: 5.0, height: 10.0 }; // Create an instance of 'Rectangle'
// Call the 'area' method on 'rect1' to calculate its area
let area_of_rect1 = rect1.area();
// Print the calculated area
println!("Area of the rectangle: {}", area_of_rect1);
}
Output:
Area of the rectangle: 50
Explanation:
Here is a brief explanation of the above Rust code:
- struct Rectangle { ... }: Defines a struct named "Rectangle" with two fields: 'width' and 'height', both of type 'f64'.
- impl Rectangle { ... }: Begins an implementation block for the "Rectangle" struct.
- fn area(&self) -> f64 { ... }: Defines a method named "area" that takes a reference to 'self' (an instance of "Rectangle") and returns the calculated area as a 'f64'. The method does not take ownership of 'self', so it can be called on immutable references to "Rectangle" instances.
- Inside the "area" method:
- The rectangle's area is calculated by multiplying its 'width' and 'height' fields.
- In the main function,
- An instance of "Rectangle" named 'rect1' is created with 'width' 5.0 and 'height' 10.0.
- The "area" method is called on 'rect1' to calculate its area, and the result is stored in 'area_of_rect1'.
- The calculated area is printed to the console.
Rust Code Editor:
Previous: Rust Structs and Enums Exercises.
Next: Rust Program: Enum Direction.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics