rust 从trait方法返回trait对象时无法推断适当的生存期

eqqqjvef  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(135)

我试图使一些东西像不可变的字典trait,可以添加新的项目(引用)到和使用,而不影响以前的版本。最小的例子:

#[derive(Clone)]
pub struct SetOfValues<'a> {
    value: Vec<&'a i32>,
}

pub trait TheSetAccessor<'b> {
    fn with_additional_values(&self, new_set: Vec<&'b i32>) -> Box<dyn TheSetAccessor<'b>>;
    fn get_from_set(&self, index: usize) -> &i32;
}

impl<'a, 'b : 'a> TheSetAccessor<'b> for SetOfValues<'a> {
    fn with_additional_values(&self, new_set: Vec<&'b i32>) -> Box<dyn TheSetAccessor<'b>> {
        Box::new(SetOfValues { value: new_set } )
    }

    fn get_from_set(&self, index: usize) -> &i32 {
        self.value[index]
    }
}

fn usage() {
    let a = 0;
    let set = SetOfValues {
        value: vec![&a]
    };

    // ...

    let b = 1;
    let extended_set = set.with_additional_values(vec![&a, &b]);

    // ...

    let got_b = extended_set.get_from_set(1);
}

字符串
错误消息如下:

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
  --> src/test.rs:13:18
   |
13 |         Box::new(SetOfValues { value: new_set } )
   |                  ^^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the lifetime `'b` as defined here...
  --> src/test.rs:11:10
   |
11 | impl<'a, 'b : 'a> TheSetAccessor<'b> for SetOfValues<'a> {
   |          ^^
note: ...so that the expression is assignable
  --> src/test.rs:13:39
   |
13 |         Box::new(SetOfValues { value: new_set } )
   |                                       ^^^^^^^
   = note: expected `Vec<&i32>`
              found `Vec<&'b i32>`
   = note: but, the lifetime must be valid for the static lifetime...
note: ...so that the types are compatible
  --> src/test.rs:13:9
   |
13 |         Box::new(SetOfValues { value: new_set } )
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   = note: expected `Box<(dyn TheSetAccessor<'b> + 'static)>`
              found `Box<dyn TheSetAccessor<'b>>`


据我所知,新的SetOfValues应该具有传递的vector('b)的生命周期,但这部分
首先,生命周期不能超过这里定义的生命周期'b.
正如我所看到的,建议SetOfValues的新示例具有另一个生命周期('static?),该生命周期应该比'B更长。我不太理解如何限制此生命周期。我可以做些什么来使此代码工作?

5cg8jx4n

5cg8jx4n1#

这是因为dyn Trait实际上是dyn Trait + 'static。因此,dyn TheSetAccessor<'b>实际上是dyn TheSetAccessor<'b> + 'static,并且不能包含任何非'static的生存期,因此它需要'b: 'static
要放宽这个限制,请为trait添加一个生存期:dyn TheSetAccessor<'b> + 'b。注意,根据您的用例,这可能不是最佳解决方案。

fn with_additional_values(&self, new_set: Vec<&'b i32>) -> Box<dyn TheSetAccessor<'b> + 'b>;

字符串
Playground的一个。

相关问题