blob: 6450f27aef37bb437527a1bcbca1b3273a26a92c [file] [log] [blame]
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="generator" content="rustdoc"><meta name="description" content="github crates-io docs-rs"><meta name="keywords" content="rust, rustlang, rust-lang, async_trait"><title>async_trait - Rust</title><link rel="preload" as="font" type="font/woff2" crossorigin href="../SourceSerif4-Regular.ttf.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../FiraSans-Regular.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../FiraSans-Medium.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../SourceCodePro-Regular.ttf.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../SourceSerif4-Bold.ttf.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../SourceCodePro-Semibold.ttf.woff2"><link rel="stylesheet" href="../normalize.css"><link rel="stylesheet" href="../rustdoc.css" id="mainThemeStyle"><link rel="stylesheet" href="../ayu.css" disabled><link rel="stylesheet" href="../dark.css" disabled><link rel="stylesheet" href="../light.css" id="themeStyle"><script id="default-settings" ></script><script src="../storage.js"></script><script defer src="../crates.js"></script><script defer src="../main.js"></script><noscript><link rel="stylesheet" href="../noscript.css"></noscript><link rel="alternate icon" type="image/png" href="../favicon-16x16.png"><link rel="alternate icon" type="image/png" href="../favicon-32x32.png"><link rel="icon" type="image/svg+xml" href="../favicon.svg"></head><body class="rustdoc mod crate"><!--[if lte IE 11]><div class="warning">This old browser is unsupported and will most likely display funky things.</div><![endif]--><nav class="mobile-topbar"><button class="sidebar-menu-toggle">&#9776;</button><a class="sidebar-logo" href="../async_trait/index.html"><div class="logo-container"><img class="rust-logo" src="../rust-logo.svg" alt="logo"></div></a><h2></h2></nav><nav class="sidebar"><a class="sidebar-logo" href="../async_trait/index.html"><div class="logo-container"><img class="rust-logo" src="../rust-logo.svg" alt="logo"></div></a><h2 class="location"><a href="#">Crate async_trait</a></h2><div class="sidebar-elems"><ul class="block"><li class="version">Version 0.1.68</li><li><a id="all-types" href="all.html">All Items</a></li></ul><section><ul class="block"><li><a href="#attributes">Attribute Macros</a></li></ul></section></div></nav><main><div class="width-limiter"><nav class="sub"><form class="search-form"><div class="search-container"><span></span><input class="search-input" name="search" autocomplete="off" spellcheck="false" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"><div id="help-button" title="help" tabindex="-1"><a href="../help.html">?</a></div><div id="settings-menu" tabindex="-1"><a href="../settings.html" title="settings"><img width="22" height="22" alt="Change settings" src="../wheel.svg"></a></div></div></form></nav><section id="main-content" class="content"><div class="main-heading"><h1 class="fqn">Crate <a class="mod" href="#">async_trait</a><button id="copy-path" onclick="copy_path(this)" title="Copy item path to clipboard"><img src="../clipboard.svg" width="19" height="18" alt="Copy item path"></button></h1><span class="out-of-band"><a class="srclink" href="../src/async_trait/lib.rs.html#1-343">source</a> · <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">[<span class="inner">&#x2212;</span>]</a></span></div><details class="rustdoc-toggle top-doc" open><summary class="hideme"><span>Expand description</span></summary><div class="docblock"><p><a href="https://github.com/dtolnay/async-trait"><img src="https://img.shields.io/badge/github-8da0cb?style=for-the-badge&amp;labelColor=555555&amp;logo=github" alt="github" /></a><a href="https://crates.io/crates/async-trait"><img src="https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&amp;labelColor=555555&amp;logo=rust" alt="crates-io" /></a><a href="https://docs.rs/async-trait"><img src="https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&amp;labelColor=555555&amp;logo=docs.rs" alt="docs-rs" /></a></p>
<br>
<h5>Type erasure for async trait methods</h5>
<p>The initial round of stabilizations for the async/await language feature in
Rust 1.39 did not include support for async fn in traits. Trying to include
an async fn in a trait produces the following error:</p>
<div class="example-wrap compile_fail"><div class='tooltip'></div><pre class="rust rust-example-rendered"><code><span class="kw">trait </span>MyTrait {
<span class="kw">async fn </span>f() {}
}</code></pre></div>
<div class="example-wrap"><pre class="language-text"><code>error[E0706]: trait fns cannot be declared `async`
--&gt; src/main.rs:4:5
|
4 | async fn f() {}
| ^^^^^^^^^^^^^^^</code></pre></div>
<p>This crate provides an attribute macro to make async fn in traits work.</p>
<p>Please refer to <a href="https://smallcultfollowing.com/babysteps/blog/2019/10/26/async-fn-in-traits-are-hard/"><em>why async fn in traits are hard</em></a> for a deeper
analysis of how this implementation differs from what the compiler and
language hope to deliver in the future.</p>
<br>
<h2 id="example"><a href="#example">Example</a></h2>
<p>This example implements the core of a highly effective advertising platform
using async fn in a trait.</p>
<p>The only thing to notice here is that we write an <code>#[async_trait]</code> macro on
top of traits and trait impls that contain async fn, and then they work.</p>
<div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">use </span>async_trait::async_trait;
<span class="attribute">#[async_trait]
</span><span class="kw">trait </span>Advertisement {
<span class="kw">async fn </span>run(<span class="kw-2">&amp;</span><span class="self">self</span>);
}
<span class="kw">struct </span>Modal;
<span class="attribute">#[async_trait]
</span><span class="kw">impl </span>Advertisement <span class="kw">for </span>Modal {
<span class="kw">async fn </span>run(<span class="kw-2">&amp;</span><span class="self">self</span>) {
<span class="self">self</span>.render_fullscreen().<span class="kw">await</span>;
<span class="kw">for _ in </span><span class="number">0</span>..<span class="number">4u16 </span>{
remind_user_to_join_mailing_list().<span class="kw">await</span>;
}
<span class="self">self</span>.hide_for_now().<span class="kw">await</span>;
}
}
<span class="kw">struct </span>AutoplayingVideo {
media_url: String,
}
<span class="attribute">#[async_trait]
</span><span class="kw">impl </span>Advertisement <span class="kw">for </span>AutoplayingVideo {
<span class="kw">async fn </span>run(<span class="kw-2">&amp;</span><span class="self">self</span>) {
<span class="kw">let </span>stream = connect(<span class="kw-2">&amp;</span><span class="self">self</span>.media_url).<span class="kw">await</span>;
stream.play().<span class="kw">await</span>;
<span class="comment">// Video probably persuaded user to join our mailing list!
</span>Modal.run().<span class="kw">await</span>;
}
}</code></pre></div>
<p><br><br></p>
<h2 id="supported-features"><a href="#supported-features">Supported features</a></h2>
<p>It is the intention that all features of Rust traits should work nicely with
#[async_trait], but the edge cases are numerous. Please file an issue if
you see unexpected borrow checker errors, type errors, or warnings. There is
no use of <code>unsafe</code> in the expanded code, so rest assured that if your code
compiles it can’t be that badly broken.</p>
<blockquote>
<p>☑ Self by value, by reference, by mut reference, or no self;<br>
☑ Any number of arguments, any return value;<br>
☑ Generic type parameters and lifetime parameters;<br>
☑ Associated types;<br>
☑ Having async and non-async functions in the same trait;<br>
☑ Default implementations provided by the trait;<br>
☑ Elided lifetimes;<br>
☑ Dyn-capable traits.<br></p>
</blockquote>
<br>
<h2 id="explanation"><a href="#explanation">Explanation</a></h2>
<p>Async fns get transformed into methods that return <code>Pin&lt;Box&lt;dyn Future + Send + 'async&gt;&gt;</code> and delegate to a private async freestanding function.</p>
<p>For example the <code>impl Advertisement for AutoplayingVideo</code> above would be
expanded as:</p>
<div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">impl </span>Advertisement <span class="kw">for </span>AutoplayingVideo {
<span class="kw">fn </span>run&lt;<span class="lifetime">&#39;async</span>&gt;(
<span class="kw-2">&amp;</span><span class="lifetime">&#39;async </span><span class="self">self</span>,
) -&gt; Pin&lt;Box&lt;<span class="kw">dyn </span>core::future::Future&lt;Output = ()&gt; + Send + <span class="lifetime">&#39;async</span>&gt;&gt;
<span class="kw">where
</span><span class="self">Self</span>: Sync + <span class="lifetime">&#39;async</span>,
{
<span class="kw">async fn </span>run(_self: <span class="kw-2">&amp;</span>AutoplayingVideo) {
<span class="comment">/* the original method body */
</span>}
Box::pin(run(<span class="self">self</span>))
}
}</code></pre></div>
<p><br><br></p>
<h2 id="non-threadsafe-futures"><a href="#non-threadsafe-futures">Non-threadsafe futures</a></h2>
<p>Not all async traits need futures that are <code>dyn Future + Send</code>. To avoid
having Send and Sync bounds placed on the async trait methods, invoke the
async trait macro as <code>#[async_trait(?Send)]</code> on both the trait and the impl
blocks.</p>
<br>
<h2 id="elided-lifetimes"><a href="#elided-lifetimes">Elided lifetimes</a></h2>
<p>Be aware that async fn syntax does not allow lifetime elision outside of <code>&amp;</code>
and <code>&amp;mut</code> references. (This is true even when not using #[async_trait].)
Lifetimes must be named or marked by the placeholder <code>'_</code>.</p>
<p>Fortunately the compiler is able to diagnose missing lifetimes with a good
error message.</p>
<div class="example-wrap compile_fail"><div class='tooltip'></div><pre class="rust rust-example-rendered"><code><span class="kw">type </span>Elided&lt;<span class="lifetime">&#39;a</span>&gt; = <span class="kw-2">&amp;</span><span class="lifetime">&#39;a </span>usize;
<span class="attribute">#[async_trait]
</span><span class="kw">trait </span>Test {
<span class="kw">async fn </span>test(not_okay: Elided, okay: <span class="kw-2">&amp;</span>usize) {}
}</code></pre></div>
<div class="example-wrap"><pre class="language-text"><code>error[E0726]: implicit elided lifetime not allowed here
--&gt; src/main.rs:9:29
|
9 | async fn test(not_okay: Elided, okay: &amp;usize) {}
| ^^^^^^- help: indicate the anonymous lifetime: `&lt;&#39;_&gt;`</code></pre></div>
<p>The fix is to name the lifetime or use <code>'_</code>.</p>
<div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="attribute">#[async_trait]
</span><span class="kw">trait </span>Test {
<span class="comment">// either
</span><span class="kw">async fn </span>test&lt;<span class="lifetime">&#39;e</span>&gt;(elided: Elided&lt;<span class="lifetime">&#39;e</span>&gt;) {}
<span class="comment">// or
</span><span class="kw">async fn </span>test(elided: Elided&lt;<span class="lifetime">&#39;_</span>&gt;) {}
}</code></pre></div>
<p><br><br></p>
<h2 id="dyn-traits"><a href="#dyn-traits">Dyn traits</a></h2>
<p>Traits with async methods can be used as trait objects as long as they meet
the usual requirements for dyn – no methods with type parameters, no self
by value, no associated types, etc.</p>
<div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="attribute">#[async_trait]
</span><span class="kw">pub trait </span>ObjectSafe {
<span class="kw">async fn </span>f(<span class="kw-2">&amp;</span><span class="self">self</span>);
<span class="kw">async fn </span>g(<span class="kw-2">&amp;mut </span><span class="self">self</span>);
}
<span class="kw">impl </span>ObjectSafe <span class="kw">for </span>MyType {...}
<span class="kw">let </span>value: MyType = ...;
<span class="kw">let </span>object = <span class="kw-2">&amp;</span>value <span class="kw">as </span><span class="kw-2">&amp;</span><span class="kw">dyn </span>ObjectSafe; <span class="comment">// make trait object</span></code></pre></div>
<p>The one wrinkle is in traits that provide default implementations of async
methods. In order for the default implementation to produce a future that is
Send, the async_trait macro must emit a bound of <code>Self: Sync</code> on trait
methods that take <code>&amp;self</code> and a bound <code>Self: Send</code> on trait methods that
take <code>&amp;mut self</code>. An example of the former is visible in the expanded code
in the explanation section above.</p>
<p>If you make a trait with async methods that have default implementations,
everything will work except that the trait cannot be used as a trait object.
Creating a value of type <code>&amp;dyn Trait</code> will produce an error that looks like
this:</p>
<div class="example-wrap"><pre class="language-text"><code>error: the trait `Test` cannot be made into an object
--&gt; src/main.rs:8:5
|
8 | async fn cannot_dyn(&amp;self) {}
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</code></pre></div>
<p>For traits that need to be object safe and need to have default
implementations for some async methods, there are two resolutions. Either
you can add Send and/or Sync as supertraits (Send if there are <code>&amp;mut self</code>
methods with default implementations, Sync if there are <code>&amp;self</code> methods with
default implementations) to constrain all implementors of the trait such that
the default implementations are applicable to them:</p>
<div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="attribute">#[async_trait]
</span><span class="kw">pub trait </span>ObjectSafe: Sync { <span class="comment">// added supertrait
</span><span class="kw">async fn </span>can_dyn(<span class="kw-2">&amp;</span><span class="self">self</span>) {}
}
<span class="kw">let </span>object = <span class="kw-2">&amp;</span>value <span class="kw">as </span><span class="kw-2">&amp;</span><span class="kw">dyn </span>ObjectSafe;</code></pre></div>
<p>or you can strike the problematic methods from your trait object by
bounding them with <code>Self: Sized</code>:</p>
<div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="attribute">#[async_trait]
</span><span class="kw">pub trait </span>ObjectSafe {
<span class="kw">async fn </span>cannot_dyn(<span class="kw-2">&amp;</span><span class="self">self</span>) <span class="kw">where </span><span class="self">Self</span>: Sized {}
<span class="comment">// presumably other methods
</span>}
<span class="kw">let </span>object = <span class="kw-2">&amp;</span>value <span class="kw">as </span><span class="kw-2">&amp;</span><span class="kw">dyn </span>ObjectSafe;</code></pre></div>
</div></details><h2 id="attributes" class="small-section-header"><a href="#attributes">Attribute Macros</a></h2><div class="item-table"><div class="item-row"><div class="item-left module-item"><a class="attr" href="attr.async_trait.html" title="async_trait::async_trait attr">async_trait</a></div></div></div></section></div></main><div id="rustdoc-vars" data-root-path="../" data-current-crate="async_trait" data-themes="ayu,dark,light" data-resource-suffix="" data-rustdoc-version="1.66.0-nightly (5c8bff74b 2022-10-21)" ></div></body></html>