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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more