Skip to content

How to create global variables with State? #2301

Discussion options

You must be logged in to vote

If you mean data you can access with &State<T>, this is a rough example:

// 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 .manage() method on your Roc…

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
2 replies
@779505388
Comment options

@SergioBenitez
Comment options

Answer selected by 779505388
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
4 participants