5 ms·
After reading this bit: // Vec is our growable heap-allocated array type. // This is just a handy way to make one with some fixed data. let mut v = vec![
by enjoy-your-stay 12y ago
After reading this bit:
// Vec is our growable heap-allocated array type.
// This is just a handy way to make one with some fixed data.
let mut v = vec![1i32, 2, 3, 4, 5];
let x = v.get(2);
v.push(6); // oops, sorry x!
I really hope that the Rust compiler has some really good error messages explaining what the problem is because I couldn't see what was wrong with this fragment until I read the explanation.
Saying that, after reading the explanation it became a bit more obvious, and I really like the way of describing the relationship to the pointer as a 'view' and 'loan', which as a c++ programmer (though clearly spending too much time with GC languages) I can understand.
- veddan 12y ago> I really hope that the Rust compiler has some really good error messages explaining what the problem is because I couldn't see what was wrong with this fragment until I read the explanation. They're not always perfect, but in this case it's quite good. err.rs:4:9: 4:10 error: cannot borrow `v` as mutable because it is also borrowed as immutable err.rs:4 v.push(6); // oops, sorry x! ^ err.rs:3:17: 3:18 note: previous borrow of `v` occurs here; the immutable borrow prevents subsequent moves or mutable borrows of `v` until the borrow ends err.rs:3 let x = v.get(2); ^ err.rs:5:6: 5:6 note: previous borrow ends here err.rs:1 fn main() { err.rs:2 let mut v = vec![1i32, 2, 3, 4, 5]; err.rs:3 let x = v.get(2); err.rs:4 v.push(6); // oops, sorry x! err.rs:5 } ^ If you want to try out code examples, the Rust playpen is nice: http://play.rust-lang.org http://play.rust-lang.org
- renox 12y agoI'm quite surprised by Rust behaviour here: if x isn't used after 'v.push(6);' (doesn't seem too difficult to know by the compiler) then I would have expected the compiler to allow this code and to reject it only if x is used after the 'v.push(6)'.. Sure as he explained you can do "let mut v = vec![1i32, 2, 3, 4, 5]; { let x = v.get(2); <work with x> } v.push(6);" but this must be quite annoying..
- kibwen 12y agoI think this might be more difficult than it seems, given that Rust allows you to store references in structs. I'll ask the developers sometime.
- Jweb_Guru 12y agoCurrently, borrows last for block scope, which is why this doesn't work. There is a feature in the making called SEME (single entry, multiple exit) which will resolve this and other annoying borrow hazards. It at least at one point was considered a priority for 1.0.