Does the lifetime in the returned type impose the requirement on the lifetime in the returned value?

Consider this example:

fn borrow<'a>(i:&'a mut i32)->&'a mut i32{
   let v = & /*'r*/ mut *i;  // #1
   v
}

The reborrowing constraint at #1 is 'a:'r. However, for v being returned, is the constraint 'r:'a also imposed on the lifetime 'r? Because Type coercions - The Rust Reference says

Function results—either the final line of a block if it is not semicolon-terminated or any expression in a return statement

To coerce &'r mut i32 to &'a mut i32, the former must be the subtype of the latter, so 'r:'a. Is there a requirement like that imposed on v? So, the final constraints are 'a:'r and 'r:'a, so the 'r must be 'a to satisfies these constraints. Is my understanding right?

Yes.

1 Like

BTW, does the coercion happen even though the source and target types are identical?

My mental model is that an annotated reference return is always a reborrow, so I guess I would say yes.

Would the types be equal if the possibility of coercion or reborrowing was absent? Is there a meaningful distinction between "we would have coerced, but determined it wasn't necessary, so we didn't" and "we determined it was a no-op but coerced anyway"?

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.