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 Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay