How to use async traits in Rust

Define traits with async fn methods to share non-blocking behavior across types in Rust.

Use async traits by defining a trait with async fn methods and implementing them for your types, ensuring the return type is an impl Future.

use trpl::Html;

trait Fetcher {
    async fn fetch(&self, url: &str) -> Option<String>;
}

struct MyFetcher;

impl Fetcher for MyFetcher {
    async fn fetch(&self, url: &str) -> Option<String> {
        let response_text = trpl::get(url).await.text().await;
        Html::parse(&response_text)
            .select_first("title")
            .map(|title| title.inner_html())
    }
}

Note: You may need the async-trait crate or Rust 2024 edition features to support async fn in traits directly.