Can anyone explain to me why this error occurs?
Below I wrote a simple code sample that does not work.
I’m new to the Rust and I do not understand much about this yet. I will be very grateful to you if you can explain to me the reason of this error.
use std::ops::Index;
#[derive(Debug)]
struct TestChild<'a> {
name: &'a str,
}
impl<'a> TestChild<'a> {
fn new(name: &'a str) -> Self {
Self { name }
}
}
#[derive(Debug)]
struct Parent<'a> {
children: Vec<TestChild<'a>>,
}
impl<'a> Parent<'a> {
fn new() -> Self {
let init = TestChild::new("Init child");
Self {
children: vec![init],
}
}
fn add_child(&mut self, child: TestChild<'a>) {
self.children.push(child);
println!("Parent {:?}", self);
}
fn get_lat(&self) -> &TestChild<'a> {
self.children.index(self.children.len() - 1)
}
fn test(&mut self, name: &'a str) {
let last = self.get_lat();
println!("Last child is {:?}", last);
let child = TestChild::new(name);
self.add_child(child);
}
}
fn main() {
let mut p = Parent::new();
p.test("Foo");
p.test("Bar");
}