[][src]Struct tokio::task::LocalKey

pub struct LocalKey<T: 'static> { /* fields omitted */ }

A key for task-local data.

This type is generated by the task_local! macro.

Unlike std::thread::LocalKey, tokio::task::LocalKey will not lazily initialize the value on first access. Instead, the value is first initialized when the future containing the task-local is first polled by a futures executor, like Tokio.

Examples

tokio::task_local! {
    static NUMBER: u32;
}

NUMBER.scope(1, async move {
    assert_eq!(NUMBER.get(), 1);
}).await;

NUMBER.scope(2, async move {
    assert_eq!(NUMBER.get(), 2);

    NUMBER.scope(3, async move {
        assert_eq!(NUMBER.get(), 3);
    }).await;
}).await;

Implementations

impl<T: 'static> LocalKey<T>[src]

pub async fn scope<F>(&'static self, value: T, f: F) -> F::Output where
    F: Future
[src]

Sets a value T as the task-local value for the future F.

On completion of scope, the task-local will be dropped.

Examples

tokio::task_local! {
    static NUMBER: u32;
}

NUMBER.scope(1, async move {
    println!("task local value: {}", NUMBER.get());
}).await;

pub fn with<F, R>(&'static self, f: F) -> R where
    F: FnOnce(&T) -> R, 
[src]

Accesses the current task-local and runs the provided closure.

Panics

This function will panic if not called within the context of a future containing a task-local with the corresponding key.

pub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError> where
    F: FnOnce(&T) -> R, 
[src]

Accesses the current task-local and runs the provided closure.

If the task-local with the accociated key is not present, this method will return an AccessError. For a panicking variant, see with.

impl<T: Copy + 'static> LocalKey<T>[src]

pub fn get(&'static self) -> T[src]

Returns a copy of the task-local value if the task-local value implements Copy.

Trait Implementations

impl<T: 'static> Debug for LocalKey<T>[src]

Auto Trait Implementations

impl<T> RefUnwindSafe for LocalKey<T>[src]

impl<T> Send for LocalKey<T>[src]

impl<T> Sync for LocalKey<T>[src]

impl<T> Unpin for LocalKey<T>[src]

impl<T> UnwindSafe for LocalKey<T>[src]

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.