lifetime

Rust Mutable references: covariance in borrow duration

A mutable reference permits its outer borrow lifetime to be shortened. This does not imply that the type stored behind it can be changed to a subtype or supertype. Keep the two parameters of a mutable reference separate. Expected output (not executed): 7 Why: The shortened exclusive access ends before stock is read again. Common mistake: Thinking every parameter in a mutable reference is invariant, or that shortening permits simultaneous mutation through the original reference.

Formal Syntax & Structure

rust syntaxrust
&'a mut T

Working Example

Example Snippetrust
fn shorten<'a: 'b, 'b>(value: &'a mut u32, _: &'b str) -> &'b mut u32 {    value}fn main() {    let mut stock = 4;    {        let reason = String::from("delivery");        *shorten(&mut stock, &reason) += 3;    }    println!("{stock}");}
Rust Reference