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.
#[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();
}
In other languages, this problem would be solvable by using global variables.
Please read the Rocket documentation, specifically the section on state.
Use
State
andRocket::manage
to have shared state:If you want to mutate the value inside the
State
, you will need to wrap it in aMutex
or other type of thread-safe interior mutability.See also:
See also: