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
.