我试图在路由函数中使用共享资源,比如访问hello()函数中的变量"shared_resource“
#[launch]
fn rocket() -> _ {
let shared_resource = SharedResource::new()
rocket::build().mount("/", routes![hello])
}
#[get("/")]
fn hello() -> &'static str {
let _ = shared_resource.some_method()
"Hello, world!"
}我怎样才能做到这一点?
发布于 2021-12-09 16:57:57
您可以为此使用rocket::State。
只要SharedResource实现Send + Sync + 'static并在启动时初始化,它就能工作。
示例
#[launch]
fn rocket() -> _ {
let shared_resource = SharedResource::new()
rocket::build()
.mount("/", routes![hello])
.manage(shared_resource)
}
#[get("/")]
fn hello(shared_resource: State<SharedResource>) -> &'static str {
let _ = shared_resource.some_method()
"Hello, world!"
}https://stackoverflow.com/questions/70293644
复制相似问题