gpt4 book ai didi

rust - 如果外部包装箱明确要求静态生命周期,该怎么办?

转载 作者:行者123 更新时间:2023-12-03 11:41:45 27 4
gpt4 key购买 nike

我正在使用seanmonstar/warp构建我的休息服务,并遇到了与生命周期相关的问题。这是我的应用程序启动代码的样子:

struct MyModelStruct {
//...
}

struct Database {
//...
}

impl Database {
fn connect(/* ommited */) -> Database {
//...
}
}

fn start_app(db: &Database) -> () {
let route = warp::post()
.and(warp::path!("action" / u32))
.and(warp::body::json::<MyModelSctruct>())
.map(|_, _| {
//use db
})
warp::serve(route).run(/* address */);
}
我得到了错误:
error[E0621]: explicit lifetime required in the type of `db`
--> src/application.rs:69:5
|
46 | fn start_app(db: &Database) -> (){
| -------- help: add explicit lifetime `'static` to the type of `db`: `&'static db::Database`
...
69 | warp::serve(route);
| ^^^^^^^^^^^ lifetime `'static` required
这是因为 warp::serve 函数定义为
/// Create a `Server` with the provided `Filter`.
pub fn serve<F>(filter: F) -> Server<F>
where
F: Filter + Clone + Send + Sync + 'static,
F::Extract: Reply,
F::Error: IsReject,
{
Server {
pipeline: false,
filter,
}
}
因此,明确要求 'static生存期。问题是它被用作
let db = Database::connect(...);
start_app(&db);
因此,db的生存期不是 static。有办法解决此问题吗?

最佳答案

'static生存期意味着在删除函数本身之前,保证该函数不会引用任何可能删除的数据。因为您当前正在传递&Database,所以您的函数不能是'static(除非您以某种方式传递了&'static Database,这将需要显式创建内存泄漏)。
解决此问题的唯一方法是让您传递DatabaseArc<Database>或允许访问的内容,以便该功能对Database的强大引用,并可以确保只要该功能存在,DB就将继续存在。

关于rust - 如果外部包装箱明确要求静态生命周期,该怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63106684/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com