我有一个名为
但我不知道如何在 Rust 中表达它。
我已阅读了为什么无法在同一结构体中存储值和对该值的引用?,我理解为什么不能传递对所拥有值的引用。然而,在我的情况下,我传递的是指向箱化值的引用,它不会被移动,因此对它的引用必须是稳定的。
以下是不工作的原型:
Engine
的东西,它拥有 Worker
,我想让 Engine
作为 trait 的引用提供一些 API 给 Worker
使用。API 的实现是使用 Box
分配的,并由 Engine
拥有,因此只要 worker 存在,对它的引用就是稳定和有效的。但我不知道如何在 Rust 中表达它。
我已阅读了为什么无法在同一结构体中存储值和对该值的引用?,我理解为什么不能传递对所拥有值的引用。然而,在我的情况下,我传递的是指向箱化值的引用,它不会被移动,因此对它的引用必须是稳定的。
以下是不工作的原型:
trait EngineApi {
fn foo(&self);
}
struct Worker<'a> {
api: &'a EngineApi,
}
impl<'a> Worker<'a> {
fn new(engine_api: &'a EngineApi) -> Self {
Worker { api: engine_api }
}
}
struct Api;
impl EngineApi for Api {
fn foo(&self) {}
}
struct Engine<'a> {
api: Box<Api>,
worker: Box<Worker<'a>>,
}
impl<'a> Engine<'a> {
fn new() -> Self {
let api = Box::new(Api);
let worker = Box::new(Worker::new(api.as_ref()));
Engine { api: api, worker: worker }
}
}
fn main() {
let engine = Engine::new();
}
错误:
test.rs:27:37: 27:40 error: `api` does not live long enough
test.rs:27 let worker = Box::new(Worker::new(api.as_ref()));
^~~
test.rs:25:19: 29:3 note: reference must be valid for the lifetime 'a as defined on the block at 25:18...
test.rs:25 fn new() -> Self {
test.rs:26 let api = Box::new(Api);
test.rs:27 let worker = Box::new(Worker::new(api.as_ref()));
test.rs:28 Engine { api: api, worker: worker }
test.rs:29 }
test.rs:26:27: 29:3 note: ...but borrowed value is only valid for the block suffix following statement 0 at 26:26
test.rs:26 let api = Box::new(Api);
test.rs:27 let worker = Box::new(Worker::new(api.as_ref()));
test.rs:28 Engine { api: api, worker: worker }
test.rs:29 }
error: aborting due to previous error