Skip to content
Discussion options

You must be logged in to vote

Yeah, that tradeoff is annoying, but it’s also the part that keeps this sound.

The problem isn’t just “async Rust likes clones”. It’s that once you hit .await, the current future can be suspended, and the task-local scope may no longer be the same when it resumes. So holding a borrowed &str from LocalKey across .await would let the future keep a reference to something Tokio can’t guarantee is still alive.

For this case I’d probably make the task-local value cheap to clone instead of trying to borrow it across awaits:

use std::sync::Arc;

tokio::task_local! {
    static NAME: Arc<str>;
}

async fn greet(delay: Duration) -> String {
    let name = NAME.get().clone();
    wait_a_while_and_greet

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@inklesspen
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by inklesspen
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants