【问题标题】:How to use shared variables Rust's Rocket web framework?Rust 的 Rocket Web 框架如何使用共享变量?
【发布时间】:2022-01-14 12:06:32
【问题描述】:
我正在尝试在路由函数中使用共享资源,例如在我的 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!"
}
我如何做到这一点?
【问题讨论】:
标签:
web
rust
web-applications
webserver
rust-rocket
【解决方案1】:
您可以为此使用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!"
}