How can I pass a variable initialized in main to a Rocket route handler?

前端 未结 1 947
滥情空心
滥情空心 2021-01-12 11:49

I have a variable that gets initialized in main (line 9) and I want to access a reference to this variable inside of one of my route handlers.

#         


        
相关标签:
1条回答
  • 2021-01-12 12:33

    Please read the Rocket documentation, specifically the section on state.

    Use State and Rocket::manage to have shared state:

    #![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();
    }
    

    If you want to mutate the value inside the State, you will need to wrap it in a Mutex or other type of thread-safe interior mutability.

    See also:

    • Compiler says that data cannot be shared between threads safely even though the data is wrapped within a Mutex
    • Need holistic explanation about Rust's cell and reference counted types
    • Share i32 mutably between threads

    this problem would be solvable by using global variables.

    See also:

    • How do I create a global, mutable singleton?
    0 讨论(0)
提交回复
热议问题