在通用返回值的生存期与参数绑定在一起的情况下,如何进行闭包处理?

时间:2019-07-04 00:25:39

标签: rust

我正在尝试实现一个使用通用返回值的闭包的方案。我想将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的迭代器的情况下,该生命周期太长了。

0 个答案:

没有答案