Rust static lifetime conflicting anonymous

Viewed 84

I'm trying to mock a trait for testing, but ATM not able to implement a function.
I use the crate mockall.

Error msg is:

cannot infer an appropriate lifetime due to conflicting requirements
but, the lifetime must be valid for the static lifetime...
expected `&mut __get_mapping::Expectation<'_>`
   found `&mut __get_mapping::Expectation<'static>`

I'm aware that the problem is, a lifetime conflict. But the item passed to the closure already has an anonymous lifetime, even if I do not state it explicitly.

I tried to find some examples with a solution or hints.... But I could not find a solution.

Is there a way to specify that the returning item has a lifetime other than static? I also tried specifying the lifetime of the return type of the closure, but the error was still the same.

My code so far is:

#[mockall::automock]
pub trait Analyzer {
    //...
    fn get_mapping<'a>(&'a self, old: &Item) -> Option<&'a Item>;
    //...
}



fn test() {
    let mut analyzer = MockAnalyzer::new();
    analyzer.expect_get_mapping().returning(|item:&'_ Item| Some(item));
    // also tried ... returning(|item:&'_ Item| -> Option<&'_ Item> {Some(item)})
    // my initial code was ... returning(|item| Some(item))
    //...
}

1 Answers

If your Item is Clone, you might get away with the following:

analyzer
    .expect_get_mapping()
    .returning(|item: &'_ Item| Some(Box::leak(Box::new(item.clone()))));

This does indeed leak heap memory, so if your test code executes this more than a few 10 million times, it may cause trouble.

Related