I have trouble to find a solution to the lifetime issue of function parameters not living long enough.
In the following example I measure the runtime (very broadly, I know) and have a testcase struct which just stores the function and its runtime. The data for the function passes just through and is not required after the function has run, but the compiler complains it does not live long enough.
I also wonder, why I cannot declare the lifetime of the function 'static, as the function itself does not change.
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
struct Testcase<'a, 'b> {
// Does not work. Why? Function is compiled and address is fixed during runtime, or not?
// func: &'static dyn Fn(&'b [Point]) -> Vec<&'b Point>,
func: &'a dyn Fn(&'b [Point]) -> Vec<&'b Point>,
name: &'static str,
duration_ms: f64,
}
impl<'a,'b> Testcase<'a,'b> {
pub fn do_test(&'a self, points: &'b [Point]) -> Vec<&'b Point> {
(self.func)(points)
}
}
fn gift_wrapping(points: &[Point]) -> Vec<&Point> {
let mut vec = Vec::new();
vec.push(&points[0]);
vec
}
fn graham_scan(points: &[Point]) -> Vec<&Point> {
let mut vec = Vec::new();
vec.push(&points[0]);
vec
}
fn main() {
let mut testcases = [
Testcase {
func: &gift_wrapping,
name: "gift wrapping",
duration_ms: 0.0,
},
Testcase {
func: &graham_scan,
name: "graham scan",
duration_ms: 0.0,
},
];
// This works, but I explicitly want new data for each test case
// let points = get_random_points();
for testcase in &mut testcases {
let points = get_random_points();
let convex_hull = testcase.do_test(&points); // <-- borrowed value does not live long enough
testcase.duration_ms = 42.0;
println!("{} = {}, first: {:?}", testcase.name, testcase.duration_ms, convex_hull[0]);
}
}
fn get_random_points() -> Vec<Point> {
let mut points = Vec::new();
let p = Point { x: 10, y: 10 };
points.push(p);
points
}