【发布时间】:2019-09-04 20:57:06
【问题描述】:
我有一个通用函数创建一个本地对象并采用一个特征来指定如何处理该对象。 trait 获取对对象的引用并在其生命周期内保存它(以避免一次又一次地将它传递给每个函数调用)。它在
之前死去fn do_stuff<'a, T>()
where T : BigBorrower<'a>
{
let borrowee = Borrowed{ data : 1 };
{
let _borrowee = T::new(&borrowee);
}
}
这是函数调用。因为 trait 的生命周期必须在函数声明中指定,这使得编译器认为生命周期延长了 _borrowee 的生命周期。
|
24 | fn do_stuff<'a, T>()
| -- lifetime `'a` defined here
...
29 | let _borrowee = T::new(&borrowee);
| -------^^^^^^^^^-
| | |
| | borrowed value does not live long enough
| argument requires that `borrowee` is borrowed for `'a`
30 | }
31 | }
| - `borrowee` dropped here while still borrowed
【问题讨论】:
-
直接问题类似于How do I write the lifetimes for references in a type constraint when one of them is a local reference? 在
T上放置HRTB 会提醒您SomeBigBorrower<'_>不满足约束条件。您可以使用a "family" trait 将'a的选择推迟到do_stuff内部来使其工作(但您可能应该寻找其他解决方案)。