I read that memory in Rust is allocated on the stack by default, unless explicitly telling the compiler to use the heap by using a Box
or some other method.
I understand that the ownership is moved between function calls, but where is the memory for the structs actually allocated? If it was on the stack, what happens when the function exits?
#[derive(Debug)]
struct Foo(i32);
#[derive(Debug)]
struct Bar(Foo);
fn foo() -> Foo {
Foo(42)
}
fn bar() -> Bar {
let f = foo();
Bar(f)
}
fn main() {
let bar = bar();
println!("{:?}", bar);
}
For example, on line 12, there's a Foo
struct allocated in the stack frame of the bar()
function. When bar()
exits, the stack is unwound and the memory is reclaimed. Since the struct does not implement Copy
the memory is not copied, so where does it go?
I think there's a fundamental idea here I don't understand.