[英]How to use shared variables Rust's Rocket web framework?
我正在嘗試在路由功能中使用共享資源,例如在我的 hello() function 中訪問變量“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!"
}
我如何實現這一目標?
您可以為此使用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!"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.