pub macro local_cache_once($request:expr, $v:expr $(,)?) {
    ...
}
Expand description

Store and immediately retrieve a value $v in $request’s local cache using a locally generated anonymous type to avoid type conflicts.

The code generated by this macro is expected to be invoked at-most once per-request. This is because while local_cache_once! generates a new type for the macro invocation, that type is the same per run-time invocation. Thus, for a given request, a local_cache_once! invocation always returns the same reference.

To get a unique request-local reference to string-like values, use local_cache! instead.

Example

use rocket::request::local_cache_once;

// The first store into local cache for a given type wins.
assert_eq!(request.local_cache(|| String::from("hello")), "hello");

// The following returns the cached, previously stored value for the type.
assert_eq!(request.local_cache(|| String::from("goodbye")), "hello");

// This shows that we cannot cache different values of the same type;
// we _must_ use a proxy type. To avoid the need to write these manually,
// use `local_cache_once!`, which generates one of the fly.
assert_eq!(local_cache_once!(request, String::from("hello")), "hello");
assert_eq!(local_cache_once!(request, String::from("goodbye")), "goodbye");

// But a macro invocation for the same request always resolves to the
// first reference as the unique type is generated at compile-time.
for i in 1..4 {
    assert_eq!(local_cache_once!(request, i.to_string()), "1");
}