Why is this code wrong?

I'm going through the rust programming language book. I found this error particulary interesting.
I was under the impression that rust's ownership model handles heap allocated objects.(Much like malloc in C). So I'm a little bit confused about why the compiler is complaining about the variable rect being moved to the function area.

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

fn main() {

    let rect = Rectangle{
        width: 10,
        height: 10,
    };

    let pair = (1, 2);

    let result1 = area(rect);
    let result2 = sum(pair);
    println!("Area: {}", result1);
    println!("sum: {}", result2);
    println!("orginal 1: {:?}", rect); // Compiler error
    println!("original 2: {:?}", pair); // This is okay


}

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

fn sum(pair: (u32, u32)) -> u32 {
    pair.0 + pair.1
}

I was under the impression that the variable rect would be allocated in the stack. If its indeed allocated in the stack, what makes it different from the other tuple named pair I created? The compiler doesnt complain about it being moved to the function sum.

The ownership model applies to all values, whether heap or stack allocated. Since the area function declares that it takes rect by value, and since Rectangle does not implement Copy, ownership will be moved from main to the area function.
Two possible solutions: Make area take a borrow, or make Rectangle implement Copy.
The tuple implements Copy implicitly, since all its members implement Copy.

1 Like

That rect is not allocated on the heap. It's just a variable on the stack.

1 Like

Aah thanks for the quick reply mate. Sorry if the question was stupid. :smile:

No, it certainly wasn't! :smiley: The fact that tuples implicitly implement Copy (if possible) but structs don't is not obvious.

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.