How to create global variables with State? #2301
-
How to create global variables with State? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
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…