我正在尝试实现一个使用通用返回值的闭包的方案。我想将R
的生存期绑定到F
的参数,以便该函数可以返回对Foobar
中项目的引用,但是我看不到这样做的方法。这是我的代码:
struct Foobar {
first: String,
second: String,
third: String,
}
fn grab_first(foobar: &Foobar) -> &str {
&foobar.first
}
fn go<F, R: PartialEq>(lhs: Foobar, rhs: Foobar, f: F) -> bool
where
F: Fn(&Foobar) -> R,
{
f(&lhs) == f(&rhs)
}
fn main() {
dbg!(go(
Foobar {
first: "alpha".to_owned(),
second: "beta".to_owned(),
third: "gamma".to_owned()
},
Foobar {
first: "alpha".to_owned(),
second: "delta".to_owned(),
third: "epsilon".to_owned()
},
grab_first
));
}
编译器说:
error[E0271]: type mismatch resolving `for<'r> <for<'s> fn(&'s Foobar) -> &'s str {grab_first} as std::ops::FnOnce<(&'r Foobar,)>>::Output == _`
--> src/main.rs:19:10
|
19 | dbg!(go(
| ^^ expected bound lifetime parameter, found concrete lifetime
|
note: required by `go`
--> src/main.rs:11:1
|
11 | / fn go<F, R: PartialEq>(lhs: Foobar, rhs: Foobar, f: F) -> bool
12 | | where
13 | | F: Fn(&Foobar) -> R,
14 | | {
15 | | f(&lhs) == f(&rhs)
16 | | }
| |_^
我可以为go
函数添加一个生存期,但是这个生存期将持续整个go
函数。在我要遍历Foobar
的迭代器的情况下,该生命周期太长了。