惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

PCI Perspectives
PCI Perspectives
J
Java Code Geeks
阮一峰的网络日志
阮一峰的网络日志
V
Visual Studio Blog
博客园 - 聂微东
雷峰网
雷峰网
The Cloudflare Blog
V
V2EX
Hacker News: Ask HN
Hacker News: Ask HN
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Hacker News - Newest:
Hacker News - Newest: "LLM"
爱范儿
爱范儿
NISL@THU
NISL@THU
T
The Exploit Database - CXSecurity.com
Project Zero
Project Zero
腾讯CDC
罗磊的独立博客
Simon Willison's Weblog
Simon Willison's Weblog
博客园 - 【当耐特】
Hugging Face - Blog
Hugging Face - Blog
S
Security Affairs
S
SegmentFault 最新的问题
月光博客
月光博客
P
Privacy International News Feed
Last Week in AI
Last Week in AI
博客园 - Franky
C
Cisco Blogs
宝玉的分享
宝玉的分享
Forbes - Security
Forbes - Security
WordPress大学
WordPress大学
博客园 - 叶小钗
L
LINUX DO - 最新话题
博客园_首页
Spread Privacy
Spread Privacy
大猫的无限游戏
大猫的无限游戏
S
Secure Thoughts
IT之家
IT之家
人人都是产品经理
人人都是产品经理
I
Intezer
W
WeLiveSecurity
C
CERT Recently Published Vulnerability Notes
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Cyberwarzone
Cyberwarzone
有赞技术团队
有赞技术团队
酷 壳 – CoolShell
酷 壳 – CoolShell
S
Security @ Cisco Blogs
L
Lohrmann on Cybersecurity
美团技术团队

Rust Blog

Security Advisory for Cargo (CVE-2026-5223) | Rust Blog Security Advisory for Cargo (CVE-2026-5222) | Rust Blog Project goals update — April 2026 (end of 2025H2) | Rust Blog Rust is participating in Outreachy | Rust Blog Raising the baseline for the `nvptx64-nvidia-cuda` target | Rust Blog Announcing Google Summer of Code 2026 selected projects | Rust Blog Announcing Rust 1.95.0 | Rust Blog docs.rs: building fewer targets by default | Rust Blog Changes to WebAssembly targets and handling undefined symbols | Rust Blog Announcing Rust 1.94.1 | Rust Blog Security advisory for Cargo | Rust Blog What we heard about Rust's challenges | Rust Blog Call for Testing: Build Dir Layout v2 | Rust Blog Announcing rustup 1.29.0 | Rust Blog Announcing Rust 1.94.0 | Rust Blog 2025 State of Rust Survey Results | Rust Blog Rust debugging survey 2026 | Rust Blog Update on the October 15, 2018 incident on crates.io Announcing Rust 1.29.2 Announcing Rust 1.29 Announcing Rust 1.28 What is Rust 2018? Announcing Rust 1.27.2 Announcing Rust 1.27.1 Security Advisory for rustdoc Announcing Rust 1.27 Announcing Rust 1.26.2 Announcing Rust 1.26.1 Rust turns three Announcing Rust 1.26 The Rust Team All Hands in Berlin: a Recap Increasing Rust’s Reach 2018 Announcing Rust 1.25 Rust's 2018 roadmap Announcing Rust 1.24.1 Announcing Rust 1.24 The 2018 Rust Event Lineup Announcing Rust 1.23 New Year's Rust: A Call for Community Blogposts Rust in 2017: what we achieved Announcing Rust 1.22 (and 1.22.1) Fearless Concurrency in Firefox Quantum Announcing Rust 1.21 impl Future for Rust Rust 2017 Survey Results Announcing Rust 1.20 Announcing Rust 1.19 The 2017 Rust Conference Lineup Rust's 2017 roadmap, six months in Increasing Rust’s Reach Announcing Rust 1.18 Two years of Rust The Rust Libz Blitz Launching the 2017 State of Rust Survey Announcing Rust 1.17 Announcing Rust 1.16 Rust's language ergonomics initiative Announcing Rust 1.15.1 Rust's 2017 roadmap Announcing Rust 1.15 Announcing Rust 1.14 Announcing the First Underhanded Rust Contest Announcing Rust 1.13 Announcing Rust 1.12.1 Announcing Rust 1.12 Incremental Compilation Announcing Rust 1.11 Shape of errors to come The 2016 Rust Conference Lineup Announcing Rust 1.10 State of Rust Survey 2016 Announcing Rust 1.9 One year of Rust Taking Rust everywhere with rustup Launching the 2016 State of Rust Survey Cargo: predictable dependency management Introducing MIR Announcing Rust 1.8 Announcing Rust 1.7 Announcing Rust 1.6 Announcing Rust 1.5 Announcing Rust 1.4 Announcing Rust 1.3 Rust in 2016 Announcing Rust 1.2 Rust 1.1 stable, the Community Subteam, and RustCamp Announcing Rust 1.0 Abstraction without overhead: traits in Rust Rust Once, Run Everywhere Mixing matching, mutation, and moves in Rust Fearless Concurrency with Rust Announcing Rust 1.0 Beta Announcing Rust 1.0.0.alpha.2 Rust 1.0: status report and final timeline Announcing Rust 1.0 Alpha Rust 1.0: Scheduling the trains Yehuda Katz and Steve Klabnik are joining the Rust Core Team Cargo: Rust's community crate host Stability as a Deliverable Road to Rust 1.0
Async fn in trait MVP comes to nightly | Inside Rust Blog
Tyler Mandry on behalf of The Rust Async Working Group · 2022-11-17 · via Rust Blog

The async working group is excited to announce that async fn can now be used in traits in the nightly compiler. You can now write code like this:

#![feature(async_fn_in_trait)]

trait Database {
    async fn fetch_data(&self) -> String;
}

impl Database for MyDb {
    async fn fetch_data(&self) -> String { ... }
}

A full working example is available in the playground. There are some limitations we'll cover, as well as a few known bugs to be worked out, but we think it is ready for some users to try. Read on for the specifics.

Recap: How async/await works in Rust

async and .await were a major improvement in the ergonomics of writing async code in Rust. In Rust, an async fn returns a Future, which is some object that represents an ongoing asynchronous computation.

The type of the future does not actually appear in the signature of an async fn. When you write an async function like this:

async fn fetch_data(db: &MyDb) -> String { ... }

The compiler rewrites it to something like this:

fn fetch_data<'a>(db: &'a MyDb) -> impl Future<Output = String> + 'a {
    async move { ... }
}

This "desugared" signature is something you can write yourself, and it's useful for examining what goes on under the hood. The impl Future syntax here represents some opaque type that implements Future.

The future is a state machine responsible for knowing how to continue making progress the next time it wakes up. When you write code in an async block, the compiler generates a future type specific to that async block for you. This future type does not have a name, so we must instead use an opaque type in the function signature.

The historic problem of async fn in trait

Traits are the fundamental mechanism of abstraction in Rust. So what happens if you want to put an async method in a trait? Each async block or function creates a unique type, so you would want to express that each implementation can have a different Future for the return type. Thankfully, we have associated types for this:

trait Database {
    type FetchData<'a>: Future<Output = String> + 'a where Self: 'a;
    fn fetch_data<'a>(&'a self) -> FetchData<'a>;
}

Notice that this associated type is generic. Generic associated types haven't been supported in the language... until now! Unfortunately though, even with GATs, you still can't write a trait implementation that uses async:

impl Database for MyDb {
    type FetchData<'a> = /* what type goes here??? */;
    fn fetch_data<'a>(&'a self) -> FetchData<'a> { async move { ... } }
}

Since you can't name the type constructed by an async block, the only option is to use an opaque type (the impl Future we saw earlier). But those are not supported in associated types!1

Workarounds available in the stable compiler

So to write an async fn in a trait we need a concrete type to specify in our impl. There are a couple ways of achieving this today.

Runtime type erasure

First, we can avoid writing the future type by erasing it with dyn. Taking our example from above, you would write your trait like this:

trait Database {
    fn fetch_data(&self)
    -> Pin<Box<dyn Future<Output = String> + Send + '_>>;
}

This is significantly more verbose, but it achieves the goal of combining async with traits. What's more, the async-trait proc macro crate rewrites your code for you, allowing you to simply write

#[async_trait]
trait Database {
    async fn fetch_data(&self) -> String;
}

#[async_trait]
impl Database for MyDb {
    async fn fetch_data(&self) -> String { ... }
}

This is an excellent solution for the people who can use it!

Unfortunately, not everyone can. You can't use Box in no_std contexts. Dynamic dispatch and allocation come with overhead that can be overwhelming for highly performance-sensitive code. Finally, it bakes a lot of assumptions into the trait itself: allocation with Box, dynamic dispatch, and the Send-ness of the futures. This makes it unsuitable for many libraries.

Besides, users expect to be able to write async fn in traits, and the experience of adding an external crate dependency is a papercut that gives async Rust a reputation for being difficult to use.

Manual poll implementations

Traits that need to work with zero overhead or in no_std contexts have another option: they can take the concept of polling from the Future trait and build it directly into their interface. The Future::poll method returns Poll::Ready(Output) if the future is complete and Poll::Pending if the future is waiting on some other event.

You can see this pattern, for example, in the current version of the unstable AsyncIterator trait. The signature of AsyncIterator::poll_next is a cross between Future::poll and Iterator::next.

pub trait AsyncIterator {
    type Item;

    fn poll_next(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>
    ) -> Poll<Option<Self::Item>>;
}

Before async/await, it was very common to write manual poll implementations. Unfortunately, they proved challenging to write correctly. In the vision document process we underwent last year, we received a number of reports on how this was extremely difficult and a source of bugs for Rust users.

In fact, the difficulty of writing manual poll implementations was a primary reason for adding async/await to the core language in the first place.

What's supported in nightly

We've been working to support async fn directly in traits, and an implementation recently landed in nightly! The feature still has some rough edges, but let's take a look at what you can do with it.

First, as you might expect, you can write and implement traits just like the above.

#![feature(async_fn_in_trait)]

trait Database {
    async fn fetch_data(&self) -> String;
}

impl Database for MyDb {
    async fn fetch_data(&self) -> String { ... }
}

One thing this will allow us to do is standardize new traits we've been waiting on this feature for. For example, the AsyncIterator trait from above is significantly more complicated than its analogue, Iterator. With the new support, we can simply write this instead:

#![feature(async_fn_in_trait)]

trait AsyncIterator {
    type Item;
    async fn next(&mut self) -> Option<Self::Item>;
}

There's a decent chance that the trait in the standard library will end up exactly like this! For now, you can also use the one in the async_iterator crate and write generic code with it, just like you would normally.

async fn print_all<I: AsyncIterator>(mut count: I)
where
    I::Item: Display,
{
    while let Some(x) = count.next().await {
        println!("{x}");
    }
}

Limitation: Spawning from generics

There is a catch! If you try to spawn from a generic function like print_all, and (like the majority of async users) you use a work stealing executor that requires spawned tasks to be Send, you'll hit an error which is not easily resolved.2

fn spawn_print_all<I: AsyncIterator + Send + 'static>(mut count: I)
where
    I::Item: Display,
{
    tokio::spawn(async move {
        //       ^^^^^^^^^^^^
        // ERROR: future cannot be sent between threads safely
        while let Some(x) = count.next().await {
            //              ^^^^^^^^^^^^
            // note: future is not `Send` as it awaits another future which is not `Send`
            println!("{x}");
        }
    });
}

You can see that we added an I: Send bound in the function signature, but that was not enough. To satisfy this error we need to say that the future returned by next() is Send. But as we saw at the beginning of this post, async functions return anonymous types. There's no way to express bounds on those types.

There are potential solutions to this problem that we'll be exploring in a follow-up post. But for now, there are a couple things you can do to get out of a situation like this.

Hypothesis: This is uncommon

First, you may be surprised to find that this situation just doesn't occur that often in practice. For example, we can spawn a task that invokes the above print_all function without any problem:

async fn do_something() {
    let iter = Countdown::new(10);
    executor::spawn(print_all(iter));
}

This works without any Send bounds whatsoever! This works because do_something knows the concrete type of our iterator, Countdown. The compiler knows that this type is Send, and that print_all(iter) therefore produces a future that is Send.3

One hypothesis is that while people will hit this problem, they will encounter it relatively infrequently, because most of the time spawn won't be called in code that's generic over a trait with async functions.

We would like to start gathering data on people's actual experiences with this. If you have relevant experience to share, please comment on this issue.

When it does happen

Eventually you probably will want to spawn from a context that's generic over an async trait that you call. What then!?

For now it's possible to use another new nightly-only feature, return_position_impl_trait_in_trait, to express the bound you need directly in your trait:

#![feature(return_position_impl_trait_in_trait)]

trait SpawnAsyncIterator: Send + 'static {
    type Item;
    fn next(&mut self) -> impl Future<Output = Option<Self::Item>> + Send + '_;
}

Here we've desugared our async fn to a regular function returning impl Future + '_, which works just like normal async fns do. It's more verbose, but it gives us a place to put a + Send bound! What's more, you can continue to use async fn in an impl of this trait.

The downside of this approach is that the trait becomes less generic, making it less suitable for library code. If you want to maintain two separate versions of a trait, you can do that, and (perhaps) provide macros to make it easier to implement both.

This solution is intended to be temporary. We'd like to implement a better solution in the language itself, but since this is a nightly-only feature we prefer to get more people trying it out as soon as possible.

Limitation: Dynamic dispatch

There's one final limitation: You can't call an async fn with a dyn Trait. Designs to support this exist4, but are in the earlier stages. If you need dynamic dispatch from a trait, you're better off using the async_trait macro for now.

Path to stabilization

The async working group would like to get something useful in the hands of Rust users, even if it doesn't do everything they might want. That's why despite having some limitations, the current version of async fn in traits might not be far off from stabilization.5 You can follow progress by watching the tracking issue.

There are two big questions to answer first:

  • Do we need to solve the "spawning from generics" (Send bound) problem first? Please leave feedback on this issue.
  • What other bugs and quality issues exist? Please file new issues for these. You can view known issues here.

If you're an async Rust enthusiast and are willing to try experimental new features, we'd very much appreciate it if you gave it a spin!

If you use #[async_trait], you can try removing it from some traits (and their impls) where you don't use dynamic dispatch. Or if you're writing new async code, try using it there. Either way, you can tell us about your experience at the links above.

Conclusion

This work was made possible thanks to the efforts of many people, including

  • Michael Goulet
  • Santiago Pastorino
  • Oli Scherer
  • Eric Holk
  • Dan Johnson
  • Bryan Garza
  • Niko Matsakis
  • Tyler Mandry

In addition it was built on top of years of compiler work that enabled us to ship GATs as well as other fundamental type system improvements. We're deeply grateful to all those who contributed; this work would not be possible without you. Thank you!

To learn more about this feature and the challenges behind it, check out the Static async fn in traits RFC and why async fn in traits are hard. Also stay tuned for a follow-up post where we explore language extensions that make it possible to express Send bounds without a special trait.

Thanks to Yoshua Wuyts, Nick Cameron, Dan Johnson, Santiago Pastorino, Eric Holk, and Niko Matsakis for reviewing a draft of this post.

  1. This feature is called "type alias impl trait".

  2. The actual error message produced by the compiler is a bit noisier than this, but that will be improved.

  3. Auto traits such as Send and Sync are special in this way. The compiler knows that the return type of print_all is Send if and only if the type of its argument Send, and unlike with regular traits, it is allowed to use this knowledge when type checking your program.

  4. See Async fn in dyn trait on the initiative website, as well as posts 8 and 9 in this series.

  5. When? Possibly sometime in the next six months or so. But don't hold me to it :)