Skip to content

Instantly share code, notes, and snippets.

@yossan
Created March 2, 2021 15:13
Show Gist options
  • Save yossan/1bb23f3b47648790c76401ade115b170 to your computer and use it in GitHub Desktop.
Save yossan/1bb23f3b47648790c76401ade115b170 to your computer and use it in GitHub Desktop.
Rust Lifetime problems
#[derive(Debug)]
struct Value(i32);
#[derive(Debug)]
struct Shared<'a> { val: &'a Value }
#[derive(Debug)]
struct A<'a> {
shared: &'a mut Shared<'a>,
}
struct B<'a> {
shared: &'a mut Shared<'a>,
}
impl<'a> A<'a> {
fn new(shared: &'a mut Shared<'a>) -> Self {
A {
shared: shared,
}
}
}
impl<'a> B<'a> {
fn new(shared: &'a mut Shared) -> Self {
B {
shared: shared,
}
}
fn make_a(&mut self) -> A {
let a = A::new(self.shared);
a
}
}
fn main() {
let v = Value(5);
let mut shared = Shared { val: &v };
let mut b = B::new(&mut shared);
b.make_a();
}
/*
error[E0621]: explicit lifetime required in the type of `shared`
--> /Users/yossan/testcodes/rust/garbage/reference_reference.rs:27:21
|
25 | fn new(shared: &'a mut Shared) -> Self {
| -------------- help: add explicit lifetime `'a` to the type of `shared`: `&'a mut Shared<'a>`
26 | B {
27 | shared: shared,
| ^^^^^^ lifetime `'a` required
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
--> /Users/yossan/testcodes/rust/garbage/reference_reference.rs:32:17
|
32 | let a = A::new(self.shared);
| ^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 31:5...
--> /Users/yossan/testcodes/rust/garbage/reference_reference.rs:31:5
|
31 | fn make_a(&mut self) -> A {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that the expression is assignable
--> /Users/yossan/testcodes/rust/garbage/reference_reference.rs:33:9
|
33 | a
| ^
= note: expected `A<'_>`
found `A<'_>`
note: but, the lifetime must be valid for the lifetime `'a` as defined on the impl at 24:6...
--> /Users/yossan/testcodes/rust/garbage/reference_reference.rs:24:6
|
24 | impl<'a> B<'a> {
| ^^
note: ...so that the expression is assignable
--> /Users/yossan/testcodes/rust/garbage/reference_reference.rs:32:24
|
32 | let a = A::new(self.shared);
| ^^^^^^^^^^^
= note: expected `&mut Shared<'_>`
found `&mut Shared<'a>`
error: aborting due to 2 previous errors
Some errors have detailed explanations: E0495, E0621.
For more information about an error, try `rustc --explain E0495`.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment