rust - 如何满足 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>>`
解决方案
推荐阅读
- postgresql - 如何使用 Postgres 计算平均日期差
- c# - 如何配置 xUnit 测试以使用 NLog?
- qradar - 使用 API 的 IBM QRadar 搜索事件
- api - 如何从 API 发送自适应卡片
- javascript - vue.esm.js:649 [Vue 警告]:nextTick 中的错误:“TypeError:无法将对象转换为原始值”vue
- javascript - “请求”类型上不存在属性“授权”
- c# - Angular 9 / Typescript 在多个键上合并多个对象数组
- postgresql - 全文搜索:在任意数组项中查找节点值
- matlab - 如何获得两个二维矩阵的元素对之间的最大值?
- c++ - 如何使用 MySQL X Dev API ping