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.
#
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:
this problem would be solvable by using global variables.
See also: