Expand description
Request guard to retrieve managed state.
This type can be used as a request guard to retrieve the state Rocket is
managing for some type T
. This allows for the sharing of state across any
number of handlers. A value for the given type must previously have been
registered to be managed by Rocket via
Rocket::manage()
. The type being managed must be
thread safe and sendable across thread boundaries. In other words, it must
implement Send
+ Sync
+ 'static
.
Example
Imagine you have some configuration struct of the type MyConfig
that you’d
like to initialize at start-up and later access it in several handlers. The
following example does just this:
use rocket::State;
// In a real application, this would likely be more complex.
struct MyConfig {
user_val: String
}
#[get("/")]
fn index(state: State<MyConfig>) -> String {
format!("The config value is: {}", state.user_val)
}
#[get("/raw")]
fn raw_config_value<'r>(state: State<'r, MyConfig>) -> &'r str {
// use `inner()` to get a lifetime longer than `deref` gives us
state.inner().user_val.as_str()
}
fn main() {
let config = MyConfig {
user_val: "user input".to_string()
};
rocket::ignite()
.mount("/", routes![index, raw_config_value])
.manage(config)
.launch();
}
Within Request Guards
Because State
is itself a request guard, managed state can be retrieved
from another request guard’s implementation. In the following code example,
Item
retrieves the MyConfig
managed state in its FromRequest
implementation using the Request::guard()
method.
use rocket::State;
use rocket::request::{self, Request, FromRequest};
struct Item(String);
impl<'a, 'r> FromRequest<'a, 'r> for Item {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<Item, ()> {
request.guard::<State<MyConfig>>()
.map(|my_config| Item(my_config.user_val.clone()))
}
}
Testing with State
When unit testing your application, you may find it necessary to manually
construct a type of State
to pass to your functions. To do so, use the
State::from()
static method:
use rocket::State;
struct MyManagedState(usize);
#[get("/")]
fn handler(state: State<MyManagedState>) -> String {
state.0.to_string()
}
let rocket = rocket::ignite().manage(MyManagedState(127));
let state = State::from(&rocket).expect("managing `MyManagedState`");
assert_eq!(handler(state), "127");
Implementations
sourceimpl<'r, T> State<'r, T>where
T: 'static + Send + Sync,
impl<'r, T> State<'r, T>where
T: 'static + Send + Sync,
sourcepub fn inner(&self) -> &'r T
pub fn inner(&self) -> &'r T
Retrieve a borrow to the underlying value with a lifetime of 'r
.
Using this method is typically unnecessary as State
implements
Deref
with a Deref::Target
of T
. This means Rocket will
automatically coerce a State<T>
to an &T
as required. This method
should only be used when a longer lifetime is required.
Example
use rocket::State;
struct MyConfig {
user_val: String
}
// Use `inner()` to get a lifetime of `'r`
fn handler1<'r>(config: State<'r, MyConfig>) -> &'r str {
&config.inner().user_val
}
// Use the `Deref` implementation which coerces implicitly
fn handler2(config: State<MyConfig>) -> String {
config.user_val.clone()
}
sourcepub fn from(rocket: &'r Rocket) -> Option<State<'r, T>>
pub fn from(rocket: &'r Rocket) -> Option<State<'r, T>>
Returns the managed state value in rocket
for the type T
if it is
being managed by rocket
. Otherwise, returns None
.
Example
use rocket::State;
#[derive(Debug, PartialEq)]
struct Managed(usize);
#[derive(Debug, PartialEq)]
struct Unmanaged(usize);
let rocket = rocket::ignite().manage(Managed(7));
let state: Option<State<Managed>> = State::from(&rocket);
assert_eq!(state.map(|s| s.inner()), Some(&Managed(7)));
let state: Option<State<Unmanaged>> = State::from(&rocket);
assert_eq!(state, None);
Trait Implementations
sourceimpl<'a, 'r, T> FromRequest<'a, 'r> for State<'r, T>where
T: 'static + Send + Sync,
impl<'a, 'r, T> FromRequest<'a, 'r> for State<'r, T>where
T: 'static + Send + Sync,
sourceimpl<'r, T> Ord for State<'r, T>where
T: 'static + Ord + Send + Sync,
impl<'r, T> Ord for State<'r, T>where
T: 'static + Ord + Send + Sync,
1.21.0 · sourcefn max(self, other: Self) -> Selfwhere
Self: Sized,
fn max(self, other: Self) -> Selfwhere
Self: Sized,
1.21.0 · sourcefn min(self, other: Self) -> Selfwhere
Self: Sized,
fn min(self, other: Self) -> Selfwhere
Self: Sized,
1.50.0 · sourcefn clamp(self, min: Self, max: Self) -> Selfwhere
Self: Sized + PartialOrd<Self>,
fn clamp(self, min: Self, max: Self) -> Selfwhere
Self: Sized + PartialOrd<Self>,
sourceimpl<'r, T> PartialEq<State<'r, T>> for State<'r, T>where
T: 'static + PartialEq<T> + Send + Sync,
impl<'r, T> PartialEq<State<'r, T>> for State<'r, T>where
T: 'static + PartialEq<T> + Send + Sync,
sourceimpl<'r, T> PartialOrd<State<'r, T>> for State<'r, T>where
T: 'static + PartialOrd<T> + Send + Sync,
impl<'r, T> PartialOrd<State<'r, T>> for State<'r, T>where
T: 'static + PartialOrd<T> + Send + Sync,
sourcefn partial_cmp(&self, other: &State<'r, T>) -> Option<Ordering>
fn partial_cmp(&self, other: &State<'r, T>) -> Option<Ordering>
1.0.0 · sourcefn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
self
and other
) and is used by the <=
operator. Read moreimpl<'r, T> Eq for State<'r, T>where
T: 'static + Eq + Send + Sync,
impl<'r, T> StructuralEq for State<'r, T>where
T: 'static + Send + Sync,
impl<'r, T> StructuralPartialEq for State<'r, T>where
T: 'static + Send + Sync,
Auto Trait Implementations
impl<'r, T> RefUnwindSafe for State<'r, T>where
T: RefUnwindSafe,
impl<'r, T> Send for State<'r, T>
impl<'r, T> Sync for State<'r, T>
impl<'r, T> Unpin for State<'r, T>
impl<'r, T> UnwindSafe for State<'r, T>where
T: RefUnwindSafe,
Blanket Implementations
sourceimpl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
sourceimpl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
impl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
sourcefn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key
and return true
if they are equal.impl<T> IntoCollection<T> for T
impl<T> IntoCollection<T> for T
fn into_collection<A>(self) -> SmallVec<A>where
A: Array<Item = T>,
fn into_collection<A>(self) -> SmallVec<A>where
A: Array<Item = T>,
self
into a collection.