4

Sometimes when writing a function with multiple input lifetimes, I encounter an error like:

error[E0623]: lifetime mismatch
 --> src/main.rs:4:27
  |
3 | fn use_ref_ref<'a, 'b>(_ra: &'a Box<()>, _rb: &'a mut &'b mut ()) {
  |                             -----------               ----------
  |                             |
  |                             these two types are declared with different lifetimes...
4 |     use_same_ref_ref(_ra, _rb);
  |                           ^^^ ...but data from `_ra` flows into `_rb` here

Note the phrasing: "...but data from _ra flows into _rb here". The code to produce that looks like:

fn use_same_ref_ref<'c>(_ra: &'c Box<()>, _rb: &'c mut &'c mut ()) {}

fn use_ref_ref<'a, 'b>(_ra: &'a Box<()>, _rb: &'a mut &'b mut ()) {
    use_same_ref_ref(_ra, _rb);
}

fn main() {
    let mut ra = Box::new(());
    let mut rb = &mut ();
    use_ref_ref(&mut ra, &mut rb);
}

The underlying reason for this error is explained extremely well in Why does linking lifetimes matter only with mutable references? I am not asking about the reason this is an error! I would like to know why the error message talks about data "flowing" from one reference into another, and how to interpret that.

The first few times I read it I found it extremely confusing. It even occurs with a single reference (as per the linked question) which is even more confusing ("data from x flows into x" - well, sure it does, who cares?).

What is the link between the compiler's "flowing" explanation and the aliasing constraints being enforced here?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
detly
  • 29,332
  • 18
  • 93
  • 152

0 Answers0