如何表达闭包的生命周期限制以匹配特征有界生命周期?

问题描述 投票:0回答:2

我有一个特征,该特征会返回附加到其生命周期的借阅:

trait SomeTrait {
    fn do<'a>(&'a self, other: &AnonymousLifetime) -> &'a Output;
}

如何在闭包的where clause中表达相同的限制,以便SomeTrait可以impl From<Closure>

示例

方案的minimal, reproducible exampleplayground):

// The traits
trait Context {
    fn give(&self) -> usize;
}
trait ContextDecider {
    fn decide<'a>(&'a self, context: &dyn Context) -> &'a str;
}

// A concrete implementation example
// As expected, works OK
struct SomeDecider(Vec<String>);
impl ContextDecider for SomeDecider {
    fn decide<'a>(&'a self, context: &dyn Context) -> &'a str {
        let some_context = context.give();
        if some_context > self.0.len() {
            panic!("Oh no!");
        }

        &self.0[some_context]
    }
}

// An implemetation for a closure
// Help here!!
impl<'a, F> ContextDecider for F
where
    F: 'a + Fn(&dyn Context) -> &'a str,
{
    fn decide<'b>(&'b self, giver: &dyn Context) -> &'b str {
        self(giver)
    }
}

无法编译:

error[E0312]: lifetime of reference outlives lifetime of borrowed content...
  --> src/lib.rs:30:9
   |
30 |         self(giver)
   |         ^^^^^^^^^^^
   |
note: ...the reference is valid for the lifetime `'b` as defined on the method body at 29:15...
  --> src/lib.rs:29:15
   |
29 |     fn decide<'b>(&'b self, giver: &dyn Context) -> &'b str {
   |               ^^
note: ...but the borrowed content is only valid for the lifetime `'a` as defined on the impl at 25:6
  --> src/lib.rs:25:6
   |
25 | impl<'a, F> ContextDecider for F
   |      ^^

在示例中,我无法在闭包范围内表达特征施加的限制,并且编译器不满意。编译器没有帮助我使用应该使我将两个生存期锁定在一起的语法。

我有一个特征,该特征返回附加到其自身生命周期的借项:特征SomeTrait {fn do(&'a self,other:&AnonymousLifetime)->&'a Output; }这怎么可能...

rust closures traits lifetime
2个回答
2
投票

您可以应用绑定到ContextDecider的终生特征吗? (这样您就可以得到ContextDeciderinstead of having the lifetime only ondecide`。)


0
投票

您可以通过另一个特征将Fn穿入隧道,如下所示:

© www.soinside.com 2019 - 2024. All rights reserved.