Borrow checker treating logically immutable reference as mutable
rustminded: i needed to read a mutable reference to an object's Vec, and reuse that reference later in case the data is good. you cannot re-"use" a reference. you need to re-"borrow" the data. rust references are more than just a pointer (as pointers in C) to the data. we don't have discontinous borrows (this is a lie if you consider disjoint flow control paths), i.e. between the creation of the reference and the point of "reuse later", the reference is live and must not overlap with other exclusive reference. in other words, there's no "gap" in the lifetime. rustminded: presumably because it takes the same lifetime as the now out-of-scope mutable reference (x_ref_mut). the variable x_ref_mut can get out of scope, but the lifetime in the type of the reference is NOT tied to the scope of the variable. this is the premise of NLL: Non-Lexical Lifetimes. rustminded: but it would be nice if rust could recognize this situation for me. if you could provide more details about "this" situation. but the borrow checker does consider control flow paths. this modified version should compile, if you can fit your use case to this pattern: fn main() { let mut x: i32 = 5; let x_ref: &i32; { let x_ref_mut = &mut x; x_ref = &*x_ref_mut; } let some_condition: bool = todo!(); if some_condition { &x; } else { x_ref; } }
Take Your Experience to the Next Level
NewDownload our mobile app for a faster and better experience.
Comments
0U
Join the discussion
Sign in to leave a comment