У меня есть черта, которая возвращает заем, привязанный к его собственному времени жизни:
trait SomeTrait {
fn do<'a>(&'a self, other: &AnonymousLifetime) -> &'a Output;
}
Как это же ограничение может быть выражено в выражении для замыкания, так что SomeTrait
can impl From<Closure>
?
Пример
A минимальный, воспроизводимый пример для сценария ( детская площадка ):
// 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
| ^^
В этом примере мне не удается express в закрытии ограничивает ограничение, накладываемое признаком, и компилятор не удовлетворен.
Компилятор не помогая мне с тем, какой синтаксис мне следует использовать, что позволит мне соединить две жизни вместе.