'A lifetime issue pops up after a seemingly ineffectual change

#![allow(dead_code)]
#![allow(unused_variables)]

use std::cell::Cell;

pub struct Foo<'a> {
    pub x1: &'a i32,
    pub x2: &'a i32,
    pub data: Cell<&'a i32>,
}

fn test<'a>(foo: &Foo<'a>) {
    let x1 = 1;
    let data = Cell::new(foo.data.get());
    // UNCOMMENT THE NEXT LINE
    // let data = foo.data.clone();
    Foo {
        x1: &x1,
        x2: foo.x2,
        data,
    };
}

The above code compiles, but if you uncomment the line I marked in the code (and optionally comment out the line before it), you will see the following error (I use Rust 1.58.1):

error[E0597]: `x1` does not live long enough
  --> src/lib.rs:18:13
   |
12 | fn test<'a>(foo: &Foo<'a>) {
   |         -- lifetime `'a` defined here
...
18 |         x1: &x1,
   |             ^^^
   |             |
   |             borrowed value does not live long enough
   |             this usage requires that `x1` is borrowed for `'a`
...
22 | }
   | - `x1` dropped here while still borrowed

For more information about this error, try `rustc --explain E0597`.

The line that causes error when uncommented strongly seems to have the same effect as the line before it - I basically inlined the clone implementation; quote from the rust stdlib source:

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Copy> Clone for Cell<T> {
    #[inline]
    fn clone(&self) -> Cell<T> {
        Cell::new(self.get())
    }
}

Question: where the difference comes from?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source