【问题标题】:Static lifetime requirements for managed state [duplicate]托管状态的静态生命周期要求 [重复]
【发布时间】:2020-03-08 00:20:22
【问题描述】:

我在管理 StateRocket 时遇到问题。此状态包含数据库连接和该数据库上的游标集合。每一篇论文都有一个关于数据库的参考。

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

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

#![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

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

非常感谢!

【问题讨论】:

    标签: rust lifetime rust-rocket


    【解决方案1】:

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

    原因是当Controller 被移动时,其cursors 成员中对数据库的引用将变得无效,因为其database 成员的内存位置发生了变化。

    最好的前进方式可能是退后一步,考虑一个不是自我参照的设计。一种可能的解决方案是将数据库设为static variable,然后您的游标可以存储&amp;'static Database 引用。

    如果失败,上面的链接会提到rental crate,但它似乎不太好用。

    【讨论】:

    • 这就是我想要的线索。我有点知道那里出了点问题,但现在我得到了确认。此外,通过知道问题名称(自引用结构),我可以做更多的研究。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多