【问题标题】:How can I pass a variable initialized in main to a Rocket route handler?如何将 main 中初始化的变量传递给 Rocket 路由处理程序?
【发布时间】:2019-08-18 10:24:08
【问题描述】:

我有一个在 main(第 9 行)中初始化的变量,我想在我的一个路由处理程序中访问对这个变量的引用。

#[get("/")]
fn index() -> String {
    return fetch_data::fetch(format!("posts"), &redis_conn).unwrap(); // How can I get redis_conn?
}

fn main() {
    let redis_conn = fetch_data::get_redis_connection(); // initialized here

    rocket::ignite().mount("/", routes![index]).launch();
}

在其他语言中,这个问题可以通过使用全局变量来解决。

【问题讨论】:

    标签: rust rust-rocket


    【解决方案1】:

    请阅读Rocket documentation,特别是section on state

    使用StateRocket::manage 共享状态:

    #![feature(proc_macro_hygiene, decl_macro)]
    
    #[macro_use]
    extern crate rocket; // 0.4.2
    
    use rocket::State;
    
    struct RedisThing(i32);
    
    #[get("/")]
    fn index(redis: State<RedisThing>) -> String {
        redis.0.to_string()
    }
    
    fn main() {
        let redis = RedisThing(42);
    
        rocket::ignite()
            .manage(redis)
            .mount("/", routes![index])
            .launch();
    }
    

    如果您想改变 State 中的值,您需要将其包装在 Mutex 或其他类型的线程安全内部可变性中。

    另见:

    这个问题可以通过使用全局变量来解决。

    另见:

    【讨论】:

      猜你喜欢
      • 2010-10-17
      • 1970-01-01
      • 2022-07-19
      • 2015-03-16
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      相关资源
      最近更新 更多