Need clarification on the Rust Nomicon section on (co)variance of `Box`, `Vec` and other collections
I think that section could use some work to make it clearer.
I'm slightly confused as to what the mutable reference is to. Is it a mutable reference to the Box / Vec?
No. It means, if you store values in an existing Box
, you'd have to do that via a mutable reference to the data, for example using Box::borrow_mut()
.
The main idea this section is trying to convey is that you can't modify the contents of a Box
while there is another reference to the contents. That's guaranteed because the Box
owns its contents. In order to change the contents of a Box
, you have to do it by taking a new mutable reference.
This means that — even if you did overwrite the contents with a shorter-lived value — it wouldn't matter because no one else could be using the old value. The borrow checker wouldn't allow it.
This is different from function arguments because a function has a code block which can actually do things with its arguments. In the case of a Box
or Vec
, you have to get the contents out, by mutably borrowing them, before you can do anything to them.