I'm very new to rust and recently I came across reference lifetime
.I was learning this topic and wrote below code. Here I'm trying to have a reference to 'Bar' in 'Foo' struct.
struct Foo<'a>{
a:i32,b:i32,bar:&'a Bar,
}
#[derive(Debug)]
struct Bar{
s:String,
}
impl Foo<'a>{
fn setup<'a>(&mut self) {
println!("{} {} {:?}",self.a,self.b,self.bar);
}
}
fn main() {
let bar = Bar{s:String::from("hello\n")};
Foo{a:1,b:2,bar}.setup();
}
getting below error when i compile the code
Compiling playground v0.0.1 (/playground)
error[E0261]: use of undeclared lifetime name `'a`
--> src/main.rs:12:10
|
12 | impl Foo<'a>{
| - ^^ undeclared lifetime
| |
| help: consider introducing lifetime `'a` here: `<'a>`
For more information about this error, try `rustc --explain E0261`.
error: could not compile `playground` due to previous error
What's the correct way of having a reference inside a struct
which also has impl block