Rust mock function returning reference using `mockall`

Viewed 101

The code that I'm trying to mock is similar to this (this is just a minimal example):

use std::any::Any;

struct Foo {
    data: Box<dyn Any>,
}

impl Foo {
    pub fn bar<T: 'static>(&self) -> Option<&T> {
        self.data.downcast_ref()
    }
}
// (other impls for `Foo`)

and it compiled, no errors.

I tried to mock it like so:

use mockall::mock;

mock! {
    pub Foo {
        pub fn bar<T: 'static>(&self, index: usize) -> Option<&T>;
    }
}

but I got an error:

error[E0637]: `&` without an explicit lifetime name cannot be used here
 --> src/main.rs:6:63
  |
6 |         pub fn bar<T: 'static>(&self, index: usize) -> Option<&T>;
  |                                                               ^ explicit lifetime name needed here

error[E0106]: missing lifetime specifier
 --> src/main.rs:6:63
  |
6 |         pub fn bar<T: 'static>(&self, index: usize) -> Option<&T>;
  |                                                               ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value with an elided lifetime, but the lifetime cannot be derived from the arguments
  = note: for more information on higher-ranked polymorphism, visit https://doc.rust-lang.org/nomicon/hrtb.html
help: consider making the bound lifetime-generic with a new `'a` lifetime
  |
4 ~ for<'a> mock! {
5 |     pub Foo {
6 ~         pub fn bar<T: 'static>(&self, index: usize) -> Option<&'a T>;
  |
help: consider using the `'static` lifetime
  |
6 |         pub fn bar<T: 'static>(&self, index: usize) -> Option<&'static T>;
  |                                                               ~~~~~~~~

I tried adding the 'static lifetime and it compiled but I don't think that's what I want because https://doc.rust-lang.org/rust-by-example/scope/lifetime/static_lifetime.html says that

As a reference lifetime 'static indicates that the data pointed to by the reference lives for the entire lifetime of the running program.

and I don't think thats what I want because I don't see any reason for the returned reference to have to live for the lifetime of the entire program.

Also, now bar on the new mock type is slightly different to bar on the original type. I feel like this could cause some problems elsewhere where I'm using lifetimes.

0 Answers
Related