Skip to content
\n

With that code, anytime someone visits the index, the counter would increase by 1.

\n

By using the .manage() method on your Rocket builder, you make your struct (or whatever) available anywhere State can be retrieved (eg. request guards, etc).

\n

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"}}}
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
@zgangguoguo
Comment options

@SergioBenitez
Comment options

Answer selected by zgangguoguo
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