asomers / mockall

A powerful mock object library for Rust
Apache License 2.0
1.5k stars 62 forks source link

Cannot mock a trait that introduces a method with a new generic parameter #434

Closed Pet3ris closed 1 year ago

Pet3ris commented 1 year ago

The following code is not compiling due to lifetime issues with &C:

trait Zen {
    fn zen<C>(c: &C) -> bool;
}

mock! {
    pub Z {}
    impl Zen for Z {
        fn zen<C>(c: &C) -> bool;
    }
}

I've tried a couple of ways to add 'static in the mock! macro but they didn't work. Any way around this?

Tested with mockall = "0.11.2".

Detailed error

error[E0310]: the parameter type `C` may not live long enough
   --> src/commands/run.rs:312:9
    |
312 | /         mock! {
313 | |             pub Z {}
314 | |             impl Zen for Z {
315 | |                 fn zen<C>(c: &C) -> bool;
    | |                        - help: consider adding an explicit lifetime bound...: `C: 'static`
316 | |             }
317 | |         }
    | |_________^ ...so that the type `__zen::Expectations<C>` will meet its required lifetime bounds
Pet3ris commented 1 year ago

Possibly related to: https://github.com/asomers/mockall/issues/422, https://github.com/asomers/mockall/issues/299

asomers commented 1 year ago

It's a documented limitation that all generic types must be 'static. See https://github.com/asomers/mockall/blob/master/mockall/tests/mock_generic_and_reference_arguments.rs .

asomers commented 1 year ago

Closing, on the theory that your emoji indicates resolution.