簡體   English   中英

如何使用共享變量 Rust 的 Rocket web 框架?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM