Error about borrowed values after the move

The area function takes ownership of the Rectangle instance, calculates the area, and returns the result. In the next line, I am trying to print the Rectangle instance but I am getting a value borrowed error on compiling the code.

I agree that the area function doesn't need the ownership but The Rectangle contains types u32 that implement the Copy trait. When I create a new variable using an assignment (like let rect1 = ...), the data is copied for types that implement Copy(?), which makes rect1 a separate copy of the Rectangle data, and the area function takes ownership of it shouldn't affect the original rect1. I should be able to use rect1 after calling the area(rect1) right?

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };

    println!("The area of the rectangle is {} square pixels.",area(rect1));

    println!("{:?}",rect1);
}

fn area(rectangle: Rectangle) -> u32 {
    rectangle.width * rectangle.height
}

This is wrong. If you want Rectangle to be copyable, you have to specify that.

#[derive(Clone, Copy, Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}
2 Likes

thank you for pointing it out.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.