[Rust] Intro Lifetimes
The following code has compiler error:
fn jazz(years: &[i64]) -> Releases {
let eighties: [i64] = &years[0..2];
let nineties: [i64] = &years[2..4];
Releases {
years,
eighties,
nineties,
}
}
let releases = {
let all_years: Vec<i64> = vec![
1980, 1985, 1990, 2000, 2005
];
jazz(&all_years)
}; //dealloc(all_years)
let eighties = releases.eighties;
Mainly due to after calling jazz(&all_years)
, Rust dealloc all_years
, later when we try to refer to releases.eighties
, it doesn't exist anymore.
To resolve the problem, we need to intro lifetime to help us to analysis the code:
// Named lifetime as all_years
fn jazz<'all_years>(years: &'all_years [i64]) -> Releases<'all_years> {
let eighties: &'all_years [i64] = &years[0..2];
let nineties: &'all_years [i64] = &years[2..4];
Releases {
years,
eighties,
nineties,
}
}
// lifetime to struct
struct Releases<'years> {
years: &'years [i64],
eighties: &'years [i64],
nineties: &'years [i64],
}
let releases = {
let all_years: Vec<i64> = vec![
1980, 1985, 1990, 2000, 2005
];
jazz(&all_years)
}; //dealloc(all_years)
let eighties = releases.eighties;