3 ms·
So, sorry for being not bright. But if I may ask, if I have a Vec<B> A, then, it has I have a mutable reference to it in the form of A. Now, I take a const iter
by kretin45 9y ago
So, sorry for being not bright. But if I may ask, if I have a Vec<B> A, then, it has I have a mutable reference to it in the form of A. Now, I take a const iterator to an object in A, say it, then, though the iterator is const for object of type B, it is a mutable reference for the Vec<B> A, and hence, I now cannot reallocate A till all the iterators have died(most probably because of scope). Is that true?
- Manishearth 9y agoI don't really understand the scenario you're putting out. Why would the iterator be a mutable reference? (there are mutable iterators but you explicitly said const). Basically, in Rust, this happens: let x = vec![1,2,3,4]; let iterator = vec.iter(); vec.push(5); // will not compile, until iterator goes out of scope
- kretin45 9y agoYes. So I'm asking the logic behind this in context of ownership model. How can you derive the above behavior from the principle that only one mutable reference is allowed? If const iterator is not a mutable reference to a Vec, then A itself is the only mutable reference, and push back should be allowed.
- viraptor 9y agoBecause vec.push has signature push(&mut self, value) https://doc.rust-lang.org/std/vec/struct.Vec.html#method.push https://doc.rust-lang.org/std/vec/struct.Vec.html#method.pus... That means you can think of it as push(&mut vec, 5) - you need to pass a mutable reference to the vec as the first a argument and the iterator is already holding one of them. So you're not allowed to.
- Manishearth 9y agoYou are allowed at most one mutable reference or multiple immutable references. Additionally, taking an immutable reference locks the object from mutation (and taking a mutable one locks it for reading from anywhere other than that reference). The iterator is an immutable reference. push() is a mutating method. These don't work together. Rust is "aliasing XOR mutability"
- kretin45 9y agoNevermind, I think I've got it, basically, all references to an object should die before an object is changed.