简体   繁体   English

Rust – 从 trait 方法返回 trait 对象时无法推断出适当的生命周期

[英]Rust – cannot infer an appropriate lifetime when returning trait object from trait method

I'm trying to make something like immutable Dictionary trait that can be added new items (references) into and used without affecting the previous version.我正在尝试制作类似于不可变 Dictionary 特征的东西,可以将新项目(引用)添加到并使用而不影响以前的版本。 Minimal example:最小的例子:

#[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);
}

The error message is following:错误消息如下:

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>>`

As far as I understand, the new SetOfValues should have the lifetime of the passed vector ('b), but this part据我了解,新的 SetOfValues 应该具有传递向量('b)的生命周期,但这部分

first, the lifetime cannot outlive the lifetime 'b as defined here...首先,生命周期不能超过此处定义的生命周期'b ...

as I see, suggests that the new instance of SetOfValues has another lifetime ('static ?) that is supposed to live longer than 'b.如我所见,表明 SetOfValues 的新实例具有另一个生命周期('静态?),它应该比'b. I don't quite understand how I can restrict this lifetime.我不太明白我怎么能限制这一生。 What can I do to make this code work?我该怎么做才能使此代码正常工作?

This is because dyn Trait is actually dyn Trait + 'static .这是因为dyn Trait实际上是dyn Trait + 'static Thus, dyn TheSetAccessor<'b> is actually dyn TheSetAccessor<'b> + 'static , and cannot contain any non- 'static lifetime, so it requires 'b: 'static .因此, dyn TheSetAccessor<'b>实际上是dyn TheSetAccessor<'b> + 'static ,并且不能包含任何非'static生命周期,因此它需要'b: 'static

To relax this bound add a lifetime to the trait: dyn TheSetAccessor<'b> + 'b .为了放宽这个限制,给特征添加一个生命周期: dyn TheSetAccessor<'b> + 'b Note this may not be the best solution, depending on your use case.请注意,这可能不是最佳解决方案,具体取决于您的用例。

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

Playground . 游乐场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么Rust不能推断出我的特质方法的适当生命周期? - Why can't Rust infer an appropriate lifetime for my trait method? 无法推断生命周期参数克隆特征对象的适当生命周期 - Cannot infer an appropriate lifetime for lifetime parameter cloning trait object 在实现Deref特征时无法推断生命周期参数的适当生命周期 - Cannot infer an appropriate lifetime for lifetime parameter while implementing Deref trait 将结构转换为具有生存期的特征得到“由于需求冲突,无法为生存期参数&#39;a&#39;推断适当的生存期” - casting struct to trait with lifetime got “cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements” 无法推断闭包的寿命,该闭包返回包含引用的盒装特征 - Cannot infer a lifetime for a closure returning a boxed trait that contains a reference 从迭代器返回切片时无法推断适当的生命周期 - Cannot infer an appropriate lifetime when returning a slice from an iterator 特征方法中的 Rust Lifetime 不匹配 - Rust Lifetime mismatch in trait method Rust:在默认方法实现中返回特征 object - Rust: returning trait object in default method implementation 尝试在返回迭代器的闭包内改变状态时,Rust 错误“无法推断借用表达式的适当生命周期” - Rust error "cannot infer an appropriate lifetime for borrow expression" when attempting to mutate state inside a closure returning an Iterator `由于需求冲突,无法为 autoref 推断适当的生命周期`,但由于特征定义约束,无法更改任何内容 - `cannot infer an appropriate lifetime for autoref due to conflicting requirements` but can't change anything due to trait definition constraints
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM