首页 > 解决方案 > 如何满足 Rust 编译器对拥有的 trait 对象的“静态生命周期要求”?

问题描述

我有一个由容器容器组成的文件格式。我已经对该文件进行了内存映射,并且每个子结构都包含对该内存映射中字节的引用。我正在尝试实现一个Filterable特征,该特征允许我连续解析容器并提取子容器的向量。

我试图在下面的简化版本中捕捉行为。一切都引用相同的生命周期'mmap,所以我不明白为什么编译器坚持我有一个额外的'static生命周期。

use memmap::MmapOptions; // 0.7.0
use std::fs::File;

type Filtered<'mmap> = Box<dyn Filterable<'mmap>>;
type Collection<'mmap> = Vec<Filtered<'mmap>>;

struct Foo<'mmap> {
    body: &'mmap [u8],
}
struct Bar<'mmap> {
    body: &'mmap [u8],
}

trait Filterable<'mmap> {
    fn filtered(&'mmap self) -> Collection<'mmap>;
}

impl<'mmap> Filterable<'mmap> for Foo<'mmap> {
    fn filtered(&'mmap self) -> Collection<'mmap> {
        let bytes: &'mmap [u8] = self.body;
        vec![Box::new(Bar { body: self.body }) as Filtered<'mmap>]
    }
}

impl<'mmap> Filterable<'mmap> for Bar<'mmap> {
    fn filtered(&'mmap self) -> Collection<'mmap> {
        vec![]
    }
}

fn main() {
    let file = File::open("any_file_will_do").unwrap();
    let mmap = unsafe { MmapOptions::new().map(&file).unwrap() };

    let foo = Foo { body: &mmap };
    let bars = foo.filtered();
}
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'mmap` due to conflicting requirements
  --> src/main.rs:21:23
   |
21 |         vec![Box::new(Bar { body: self.body }) as Filtered<'mmap>]
   |                       ^^^
   |
note: first, the lifetime cannot outlive the lifetime `'mmap` as defined on the impl at 18:6...
  --> src/main.rs:18:6
   |
18 | impl<'mmap> Filterable<'mmap> for Foo<'mmap> {
   |      ^^^^^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:21:35
   |
21 |         vec![Box::new(Bar { body: self.body }) as Filtered<'mmap>]
   |                                   ^^^^^^^^^
   = note: but, the lifetime must be valid for the static lifetime...
note: ...so that the expression is assignable
  --> src/main.rs:21:14
   |
21 |         vec![Box::new(Bar { body: self.body }) as Filtered<'mmap>]
   |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   = note: expected `Box<(dyn Filterable<'mmap> + 'static)>`
              found `Box<dyn Filterable<'mmap>>`

标签: rust

解决方案


推荐阅读