DEV Community

Thiago Massari Guedes
Thiago Massari Guedes

Posted on

Quick tip: Type of tokio spawn return

When I was implementing the metrics task using tokio, I wanted to save the result JoinHandle in a struct and I saw the type being displayed by the IDE: JoinHandle<?>

What does it mean?

When I looked the definition of the function spawn, that's the code:

pub fn spawn<F>(future: F) -> JoinHandle<F::Output>  
where  
    F: Future + Send + 'static,  
    F::Output: Send + 'static,  
{
// ...
Enter fullscreen mode Exit fullscreen mode

In the Future trait, F::Output refers to the return value of the input function.

Now, the piece of code I have is a long running task. That is the piece of code.

let receiver_task = tokio::spawn(async move {  
    println!("Starting metrics receiver");  
    while let Some(event) = rx.recv().await {  
        if let Err(e) = metrics.add(&event.post_name, &event.origin) {  
            error!("Error writing access metric for {}: {}", &event.post_name, e);  
        } else {  
            debug!("Metric event written for {}", &event.post_name);  
        }  
    }  
});
Enter fullscreen mode Exit fullscreen mode

As this function returns nothing, the type is Unit, hence for this lambda I can declare my struct as:

pub struct MetricHandler {  
    receiver_task: JoinHandle<()>,  
    //...
}
Enter fullscreen mode Exit fullscreen mode

And now you can do:

let receiver_task = tokio::spawn(async move {
// ...
MetricHandler {
    receiver_task,
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay