In C++, the answer would be that the scope of
A is only within the parentheses, so it is created just before
B is created and passed into B, but then at the end of the call to create
A goes out of scope and is no longer valid to use. This, of course, is before
B goes out of scope at the end of the function. So if anything inside
B tried to use its reference to
A, it would actually be using stack space that could have been reused by some other variable. Moving
A out to a
let on a separate line gives it the same scope as B, so it all works out.
I’m a Rust newbie, but I think Rust has the same scoping rules here, and that’s why it flags this as an error.
I’ve encountered very similar bugs in the past when writing C++, where the compiler would reuse stack space from an object that had been created and gone out of scope, but other objects still held a reference to those objects. The tricky thing there is that they often don’t bite you right away, but then you change something unrelated in the function later, suddenly it blows up. So it’s nice that Rust catches this.
EDIT: I realize my description above may be a bit obtuse. Let me know if this doesn’t make sense and I’ll try to explain it in a different way.