I am learning Rust' lifetime, and write some code to understand the topic. But now, I need help,The code will report an error if I uncomment a line in code.
The code follows:
use std::collections::HashMap;
#[derive(Debug)]
pub struct EDocument<'a>{
tables:Vec<ETable<'a>>,
}
#[derive(Debug)]
pub struct ETable<'b>{
column_index:HashMap<String, usize>,
records:Vec<ERecord<'b>>,
}
#[derive(Debug)]
pub struct ERecord<'a>{
cols:&'a HashMap<String, usize>,
}
fn main(){
let mut doc = EDocument{tables:Vec::new()};
for i in 0..10{
let t = ETable{column_index:HashMap::new(), records:Vec::new()};
doc.tables.push(t);
}
{
let doc_mut = &mut doc;
for t in doc_mut.tables.iter_mut(){
for i in 0..10{
let r = ERecord{cols:&t.column_index};
t.records.push(r); // ERROR
}
}
}
for t in doc.tables.iter_mut(){
t.column_index.insert("xxx".to_string(), 3);
for i in t.records.iter(){
println!("{:?}", i);
}
}
}
My understanding is t.records.push(r)
expands the lifetime range 'a, but I fail to change code to fix the error.
How could I fix it?