首页 > 解决方案 > 无法模拟返回 Option<&String> 的特征

问题描述

我正在尝试使用mockall板条箱模拟一个特征:

#[automock]
trait Foo {
  fn foo(input: &Vec<String>) -> Option<&String>;
}

但是,我收到以下错误:

error[E0637]: `&` without an explicit lifetime name cannot be used here
  --> src/names_matcher.rs:79:51
   |
79 |             fn foo(input: &Vec<String>) -> Option<&String>;
   |                                                   ^ explicit lifetime name needed here

error[E0623]: lifetime mismatch
  --> src/names_matcher.rs:77:9
   |
77 |         #[automock]
   |         ^^^^^^^^^^^
   |         |
   |         ...but data from `input` is returned here
78 |         trait Foo {
79 |             fn foo(input: &Vec<String>) -> Option<&String>;
   |                           ------------ this parameter and the return type are declared with different lifetimes...

我要实现的函数将返回 None 或 Some 并引用输入中向量的元素之一。如果我尝试在考虑到这一点的情况下定义生命周期:

#[automock]
trait Foo {
  fn foo<'r>(input: &'r Vec<String>) -> Option<&'r String>;
}

我得到以下信息:

error[E0261]: use of undeclared lifetime name `'r`
  --> src/names_matcher.rs:79:20
   |
79 |             fn foo<'r>(input: &'r Vec<String>) -> Option<&'r String>;
   |                    ^^ undeclared lifetime
   |
help: consider introducing lifetime `'r` here
   |
77 |         #[automock]<'r>
   |                    ^^^^
help: consider introducing lifetime `'r` here
   |
77 |         'r, #[automock]
   |         ^^^

但是这些建议都不起作用,它们会产生语法错误。有没有办法像我上面定义的那样模拟一个特征?

标签: rust

解决方案


推荐阅读