【问题标题】:Blanket implementation returning reference fails with "the parameter type `T` may not live long enough"返回引用的一揽子实现失败,并显示“参数类型 `T` 可能寿命不够长”
【发布时间】: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>> {
   |           ++++

我模糊地理解我必须以某种方式告诉它 BaseOnBase 的生命周期应该相同,但即使我将 'a 添加到所有特征和引用中,它也会失败。

是否有可能以某种方式使其编译?

附言- 如果 get_a 返回普通的A,它就会工作。

pps - 在真实的应用程序中,它应该是一种委托给它封装的任何 impl 的策略

playground

【问题讨论】:

  • 注意不可能用T = dyn OnBase来实现Base,因为它必须是Sized

标签: rust lifetime borrow-checker


【解决方案1】:

这可能是你真正想要的,而不是T = dyn OnBase&lt;T = T&gt;

trait Base {
    type T;

    fn get_p(&self) -> &Self::T;
}

trait OnBase: Base {
    fn get_a(&self) -> &A;
}

impl<S> OnBase for S
where
    S: Base,
    <S as Base>::T: OnBase,
{
    fn get_a(&self) -> &A {
        self.get_p().get_a()
    }
}

struct A;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    • 2015-06-26
    相关资源
    最近更新 更多