1

我在State使用Rocket. 此状态包含数据库连接和该数据库上的游标集合。每一篇论文都有关于数据库的参考。

对该状态的其中一项操作需要在数据库上创建一个新游标并保留它以供以后使用。不幸的是,我遇到了一辈子的问题。通常,我处理这些没有问题,但现在,我没有想法......

我在一个简短的示例中重新创建了下面的问题。

#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket;

use rocket::State;

struct Database;

impl Database {
    fn create_cursor(&self) -> Cursor {
        Cursor { database: self }
    }
}

struct Cursor<'a> {
    database: &'a Database
}

struct Controller<'a> {
    database: Database,
    cursors: Vec<Cursor<'a>>,
}

impl<'a> Controller<'a> {
    fn do_work(&'a mut self) {
        let cursor = self.database.create_cursor();
        self.cursors.push(cursor)
    }
}

fn main() {
    let database = Database;
    let controller = Controller { database, cursors: Vec::new() };

    rocket::ignite()
        .manage(controller)
        .launch();
}

#[get("/")]
pub fn do_work_route(
    mut controller: State<'static, Controller<'static>>
) -> &'static str {
    controller.do_work();
    "Something..."
}
error[E0621]: explicit lifetime required in the type of `__req`
  --> src/main.rs:42:9
   |
40 | #[get("/")]
   | ----------- help: add explicit lifetime `'static` to the type of `__req`: `&'_b rocket::Request<'static>`
41 | pub fn do_work_route(
42 |     mut controller: State<'static, Controller<'static>>
   |         ^^^^^^^^^^ lifetime `'static` required

任何线索将不胜感激。与此同时,我会继续挖掘。

非常感谢!

4

1 回答 1

1

Controller所写的结构是自引用的,这是不可能的:https ://users.rust-lang.org/t/how-to-write-software-without-self-referential-structs/13819

The reason is that when a Controller gets moved, the references to the database in its cursors member would become invalid, because the memory location of its database member changed.

The best way forward is probably to step back and think about a design that is not self-referential. A possible solution is to make the database a static variable, then your cursors could store &'static Database references.

If that fails, the link above mentions the rental crate, but it doesn't seem to be easy to use.

于 2020-03-08T12:20:36.793 回答