With that code, anytime someone visits the index, the counter would increase by 1.
\nBy using the .manage() method on your Rocket builder, you make your struct (or whatever) available anywhere State can be retrieved (eg. request guards, etc).
Note that State is Send + Sync, so if you want mutable access to data, you have to use interior mutability (eg. Mutex, RwLock).
","upvoteCount":1,"url":"https://github.com/rwf2/Rocket/discussions/2301#discussioncomment-3293085"}}}-
|
How to create global variables with State? |
Beta Was this translation helpful? Give feedback.
-
|
If you mean data you can access with // main.rs
use rocket::State;
use std::sync::Mutex;
struct Counter {
pub inner: Mutex<u32>,
}
impl Counter {
pub fn new() -> Self {
Counter {
inner: Mutex::new(0),
}
}
}
#[get("/")]
async fn index(counter: &State<Counter>) -> String {
let mut counter = counter.inner.lock().unwrap();
*counter += 1;
format!("{}", counter)
}
#[launch]
fn rocket() -> _ {
rocket::build()
.manage(Counter::new())
.mount("/", routes![index])
}With that code, anytime someone visits the index, the counter would increase by 1. By using the Note that State is Send + Sync, so if you want mutable access to data, you have to use interior mutability (eg. Mutex, RwLock). |
Beta Was this translation helpful? Give feedback.
-
|
Hello @SergioBenitez , |
Beta Was this translation helpful? Give feedback.
If you mean data you can access with
&State<T>, this is a rough example:With that code, anytime someone visits the index, the counter would increase by 1.
By using the
.manage()method on your Roc…