make a class in rust

In Rust, classes are not a native feature. Instead, you can use structs and implement methods for them using the impl block. Here's an example of how to create a struct and add methods to it:

main.rs
// Define a struct
struct Rectangle {
    width: u32,
    height: u32,
}

// Implement methods for the struct
impl Rectangle {
    // Method to calculate the area of the rectangle
    fn area(&self) -> u32 {
        self.width * self.height
    }

    // Method to determine if the rectangle can fit inside another rectangle
    fn can_fit_inside(&self, other: &Rectangle) -> bool {
        self.width < other.width && self.height < other.height
    }

    // Method to create a new rectangle with the specified width and height
    fn create(width: u32, height: u32) -> Rectangle {
        Rectangle {
            width,
            height,
        }
    }
}

// Usage example
fn main() {
    let rect1 = Rectangle::create(10, 20);
    let rect2 = Rectangle { width: 5, height: 15 };
    println!("Area of rect1: {}", rect1.area());
    println!("Can rect1 fit inside rect2? {}", rect1.can_fit_inside(&rect2));
}
914 chars
35 lines

In this example, we defined a Rectangle struct with width and height fields. Then, inside an impl block, we implemented several methods for that struct. We have a method to calculate the area of the rectangle, a method to determine if the rectangle can fit inside another rectangle, and a static method to create a new rectangle with the specified width and height.

Finally, in the main function, we created two Rectangle instances using the create method and the struct literal syntax. Then, we printed the area of the first rectangle and determined if it can fit inside the second rectangle using the can_fit_inside method.

related categories

gistlibby LogSnag