by borrowwhatnow · 11y ago · 0 comments
It seems to me that the borrow checker disallows behavior that I (perhaps naively) wouldn't be concerned about. For example, if I have this C snippet:
{ // Safe C
int *ptr = NULL;
int val = 42;
ptr = &val;
}
Everything is hunky-dory. Translating this to Rust results in this (I think): { // Malformed Rust
let ref: &i32;
let val = 42;
ref = &val;
}
Now the borrow checker tells me that "val" doesn't live long enough, because the reference comes to life before the value. It seems like this should be safe behavior, because the reference isn't bound to the value until after the value comes to life.Can anyone shed some light on this for me? I'm all for safety, but this in particular seems like something that I should be allowed to do.
> That would leave 'ref' dangling, if even for a moment, like here. That'd be bad.
I'm not sure I agree that it would be bad (except maybe from a purity standpoint). Ref is unreachable during the time it is "pointing" to the out-of-scope "val", so nothing can actually reach the out-of-scope value through ref.
Your ref can't be unassigned. There are no null pointers.
let x: i32;
But you have to assign to it before you can use it.But what happens is that variables leave scope in reverse of the order in which they came in, so ref lives for slightly longer than val.
This happens so that the order of destructors can be guaranteed.
This happens because borrow scopes are always lexical. This is a bug, see https://github.com/rust-lang/rfcs/issues/811.
In this case, I think the term is justified.
I did, thanks.