Rust impl block
Created By: chatGPT
Rust allows you to define methods and associated functions within an
impl
block. This is a way to associate functions with a specific type, which can be a struct, enum, or trait. The impl
block is a fundamental concept in Rust for organizing functionality related to data types. Here’s how to define an impl
block: struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
// Associated function
fn area(&self) -> u32 {
self.width * self.height
}
// Method to create a new Rectangle
fn new(width: u32, height: u32) -> Rectangle {
Rectangle { width, height }
}
}
fn main() {
let rect = Rectangle::new(30, 50);
println!("Area of the rectangle: {}", rect.area());
}
Inside the
impl
block for the Rectangle
struct, we've defined a method called area
, which calculates the area of the rectangle. We also have an associated function called new
, which is used for creating a new instance of Rectangle
. This way, we encapsulate the functionality related to Rectangle
neatly. let rect = Rectangle::new(30, 50);
println!("Area of the rectangle: {}", rect.area());