The Rust Nomicon has an entire section on variance which I more or less understand except this little section in regards to Box<T>
and Vec<T>
being (co)variant over T
.
Box
andVec
are interesting cases because they're variant, but you can definitely store values in them! This is where Rust gets really clever: it's fine for them to be variant because you can only store values in them via a mutable reference! The mutable reference makes the whole type invariant, and therefore prevents you from smuggling a short-lived type into them.
What confuses me is the following line:
it's fine for them to be variant because you can only store values in them via a mutable reference!
My first question is that I'm slightly confused as to what the mutable reference is to. Is it a mutable reference to the Box
/ Vec
?
If so, how does the fact that I can only store values in them via a mutable reference justify their (co)variance? I understand what (co)variance is and the benefits of having it for Box<T>
, Vec<T>
etc., but I am struggling to see the link between only being able to store values via mutable references and the justification of (co)variance.
Also, when we initialize a Box
, aren't values moved into the box without involving an mutable reference? Doesn't this contradict the statement that we can only store values in them via mutable reference?
And finally, under what context is this 'mutable reference' borrowed? Do they mean that when you call methods that modify the Box
or Vec
you implicitly take an &mut self
? Is that the mutable reference mentioned?
Update 2nd May 2018:
Since I have yet to receive a satisfactory answer to this question, I take it that the nomicon's explanation is genuinely confusing. So as promised in a comment thread below, I have opened an issue in the Rust Nomicon repository. You can track any updates there.