【发布时间】:2023-02-05 18:29:58
【问题描述】:
此 sn-p 的编译:
trait Base {
type T;
fn get_p(&self) -> &Self::T;
}
trait OnBase: Base {
fn get_a(&self) -> &A;
}
impl<S, T> OnBase for S
where
S: Base<T = dyn OnBase<T = T>>,
{
fn get_a(&self) -> &A {
self.get_p().get_a()
}
}
struct A {}
失败:
error[E0311]: the parameter type `T` may not live long enough
--> src/blanket_with_ref.rs:17:9
|
17 | self.get_p().get_a()
| ^^^^^^^^^^^^
|
note: the parameter type `T` must be valid for the anonymous lifetime defined here...
--> src/blanket_with_ref.rs:16:14
|
16 | fn get_a(&self) -> &A {
| ^^^^^
note: ...so that the type `T` will meet its required lifetime bounds
--> src/blanket_with_ref.rs:17:9
|
17 | self.get_p().get_a()
| ^^^^^^^^^^^^
help: consider adding an explicit lifetime bound...
|
14 | impl <S, T: 'a> OnBase for S where S:Base<T=dyn OnBase<T=T>> {
| ++++
我模糊地理解我必须以某种方式告诉它 Base 和 OnBase 的生命周期应该相同,但即使我将 'a 添加到所有特征和引用中,它也会失败。
是否有可能以某种方式使其编译?
附言- 如果 get_a 返回普通的A,它就会工作。
pps - 在真实的应用程序中,它应该是一种委托给它封装的任何 impl 的策略
【问题讨论】:
-
注意不可能用
T = dyn OnBase来实现Base,因为它必须是Sized。
标签: rust lifetime borrow-checker