macro_rules! task_local {
() => { ... };
($(#[$attr:meta])* $vis:vis static const $name:ident: $t:ty; $($rest:tt)*) => { ... };
($(#[$attr:meta])* $vis:vis static const $name:ident: $t:ty) => { ... };
($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty; $($rest:tt)*) => { ... };
($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty) => { ... };
}Expand description
Declares task-local storage keys.
This macro is similar to thread_local! but creates storage that is
scoped to async tasks rather than OS threads. Task-locals are useful
for storing context that needs to be available throughout a task’s
execution without explicitly passing it through function parameters.
§Syntax
The macro supports two types of task-locals:
- Mutable:
static NAME: TYPE- Can be read and modified - Immutable:
static const NAME: TYPE- Can only be set via scoping
Multiple task-locals can be declared in a single macro invocation.
§Examples
§Basic Usage
use some_executor::task_local;
task_local! {
static COUNTER: u32;
static const USER_ID: u64;
}
async fn example() {
// Mutable task-local
COUNTER.scope(0, async {
COUNTER.set(1);
assert_eq!(COUNTER.get(), 1);
COUNTER.replace(2);
assert_eq!(COUNTER.get(), 2);
}).await;
// Immutable task-local
USER_ID.scope(12345, async {
assert_eq!(USER_ID.get(), 12345);
// USER_ID.set(99999); // This would not compile!
}).await;
}§Multiple Declarations
task_local! {
static REQUEST_ID: String;
static TRACE_ID: String;
static const ENVIRONMENT: String;
static const REGION: String;
}§With Attributes
task_local! {
/// The current user's session ID
#[allow(dead_code)]
pub static SESSION_ID: String;
/// Application configuration
pub static const CONFIG: String;
}§Differences from thread_local!
- Scoping: Task-locals must be explicitly scoped using the
scopemethod - Inheritance: Task-locals are not inherited by spawned tasks
- Lifetime: Values are automatically cleaned up when the scope ends
- Access: Values may not be set outside of a scope
§Generated Types
- Mutable task-locals generate a
LocalKey<T> - Immutable task-locals generate a
LocalKeyImmutable<T>