async fn in Trait 稳定化
核心概念
Rust 1.75(2023 年 12 月)稳定了 async fn in trait(AFIT),允许在 trait 定义中直接使用 async fn,并在 impl 块中用 async fn 实现。这是 Rust 异步编程历程中的重大里程碑——在此之前,trait 中的异步方法需要借助 async-trait 第三方 crate 通过 Box 动态分发来实现,带来额外的堆分配开销。
AFIT 的稳定让零成本异步抽象成为现实。编译器直接为每个实现类型生成对应的 Future 类型,没有堆分配,没有动态分发,完全是编译时确定的静态分发。
// Rust 1.75+ 稳定的 async fn in trait
// 在 trait 中直接定义 async fn
trait HttpClient {
async fn get(&self, url: &str) -> Result<String, String>;
async fn post(&self, url: &str, body: &str) -> Result<String, String>;
}
// 在 impl 中直接实现 async fn
struct SimpleClient;
impl HttpClient for SimpleClient {
async fn get(&self, url: &str) -> Result<String, String> {
// 模拟异步请求
println!("GET {}", url);
Ok(format!("Response from {}", url))
}
async fn post(&self, url: &str, body: &str) -> Result<String, String> {
println!("POST {} with body: {}", url, body);
Ok("Created".to_string())
}
}
#[tokio::main]
async fn main() {
let client = SimpleClient;
let result = client.get("https://example.com").await;
println!("{:?}", result);
}之前的写法(async-trait crate)
// 稳定化之前的写法需要 async-trait crate
// 这种写法会在每次调用时进行堆分配(Box<dyn Future>)
// 旧写法:
// #[async_trait::async_trait]
// trait HttpClient {
// async fn get(&self, url: &str) -> Result<String, String>;
// }
//
// #[async_trait::async_trait]
// impl HttpClient for SimpleClient {
// async fn get(&self, url: &str) -> Result<String, String> {
// Ok("response".to_string())
// }
// }
// async-trait 宏实际展开为:
// trait HttpClient {
// fn get(&self, url: &str) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send + '_>>;
// }
// 每次调用都有 Box 堆分配
fn main() {
println!("原生 async fn in trait 不需要 Box,零成本抽象");
}| 特性 | async-trait crate(旧) | 原生 AFIT(1.75+) |
|---|---|---|
| 堆分配 | 每次调用都有 Box 分配 | 零分配 |
| 动态分发 | 是(dyn Future) | 否(静态分发) |
| Send 约束 | 默认添加 Send | 不自动添加 |
| dyn Trait 支持 | 支持 | 有限制(见下文) |
| 额外依赖 | 需要 async-trait crate | 不需要 |
| 性能 | 有运行时开销 | 零成本 |
AFIT 的限制
// === 限制 1:dyn Trait 不直接支持 ===
// 含有 async fn 的 trait 默认不是 object-safe 的
// 因为每个实现返回不同大小的 Future
trait AsyncProcessor {
async fn process(&self, data: &[u8]) -> Vec<u8>;
}
// 以下代码编译失败:
// fn use_processor(p: &dyn AsyncProcessor) { ... }
// 因为 async fn 返回的 Future 类型和大小因实现而异
// === 解决方案:使用泛型约束代替 dyn ===
async fn process_with<P: AsyncProcessor>(processor: &P, data: &[u8]) -> Vec<u8> {
processor.process(data).await
}
// === 限制 2:Send 约束需要显式声明 ===
// AFIT 不自动为返回的 Future 添加 Send
// 如果需要跨线程使用,需要额外约束
// 方式一:使用 return-position impl trait bound
// trait SendProcessor: Send {
// fn process(&self, data: &[u8]) -> impl Future<Output = Vec<u8>> + Send;
// }
// 方式二:在调用处添加 Send 约束
// fn spawn_process<P>(p: P) where P: AsyncProcessor + Send + 'static { ... }
struct MyProcessor;
impl AsyncProcessor for MyProcessor {
async fn process(&self, data: &[u8]) -> Vec<u8> {
data.to_vec()
}
}
fn main() {
println!("AFIT 的 Future 默认不是 Send 的");
}返回位置 impl Trait(RPITIT)
// Rust 1.75 同时稳定了 return-position impl Trait in traits
// 这是 AFIT 的基础——async fn 实际上就是返回 impl Future 的语法糖
trait Converter {
// 返回 impl Trait 的方法
fn convert(&self, input: &str) -> impl Iterator<Item = char> + '_;
}
struct UpperConverter;
impl Converter for UpperConverter {
fn convert(&self, input: &str) -> impl Iterator<Item = char> + '_ {
input.chars().map(|c| c.to_uppercase().next().unwrap_or(c))
}
}
struct FilterConverter {
allowed: Vec<char>,
}
impl Converter for FilterConverter {
fn convert(&self, input: &str) -> impl Iterator<Item = char> + '_ {
input.chars().filter(|c| self.allowed.contains(c))
}
}
// async fn in trait 等价于:
// trait AsyncTrait {
// fn method(&self) -> impl Future<Output = T> + '_;
// }
fn main() {
let upper = UpperConverter;
let result: String = upper.convert("hello").collect();
println!("大写: {}", result);
let filter = FilterConverter {
allowed: vec!['a', 'e', 'i', 'o', 'u'],
};
let vowels: String = filter.convert("hello world").collect();
println!("元音: {}", vowels);
}基本示例
use std::collections::HashMap;
// 定义一个异步键值存储 trait
trait AsyncKvStore {
async fn get(&self, key: &str) -> Option<String>;
async fn set(&mut self, key: &str, value: &str);
async fn delete(&mut self, key: &str) -> bool;
}
// 内存实现
struct MemoryStore {
data: HashMap<String, String>,
}
impl MemoryStore {
fn new() -> Self {
MemoryStore {
data: HashMap::new(),
}
}
}
impl AsyncKvStore for MemoryStore {
async fn get(&self, key: &str) -> Option<String> {
// 模拟异步操作
self.data.get(key).cloned()
}
async fn set(&mut self, key: &str, value: &str) {
self.data.insert(key.to_string(), value.to_string());
}
async fn delete(&mut self, key: &str) -> bool {
self.data.remove(key).is_some()
}
}
// 使用泛型约束来接受任意实现
async fn populate_store<S: AsyncKvStore>(store: &mut S) {
store.set("name", "Rust").await;
store.set("version", "1.94").await;
store.set("year", "2026").await;
}
async fn read_store<S: AsyncKvStore>(store: &S) {
if let Some(name) = store.get("name").await {
println!("name = {}", name);
}
if let Some(version) = store.get("version").await {
println!("version = {}", version);
}
}
#[tokio::main]
async fn main() {
let mut store = MemoryStore::new();
populate_store(&mut store).await;
read_store(&store).await;
let deleted = store.delete("year").await;
println!("删除 year: {}", deleted);
println!("year 存在: {}", store.get("year").await.is_some());
}常见问题
问题一:现在还需要 async-trait crate 吗?
如果你的代码需要 dyn Trait(trait object)形式的异步 trait,仍然需要 async-trait。如果只用泛型约束(静态分发),原生 AFIT 更好——零成本、无额外依赖。
问题二:AFIT 返回的 Future 是 Send 的吗?
默认不是。如果 async fn 中持有非 Send 类型的引用,返回的 Future 就不是 Send 的。需要 Send 时,可以在 trait 定义中使用 fn method(&self) -> impl Future<Output = T> + Send 的写法。
问题三:什么版本开始可以用 AFIT?
Rust 1.75.0(2023 年 12 月 28 日)稳定了 async fn in trait 和 return-position impl Trait in traits。
问题四:AFIT 和 GATs 有什么关系?
GATs(Generic Associated Types,1.65 稳定)是 AFIT 的底层基础。async fn 在 trait 中的 Future 返回类型实际上依赖于 GAT 来为每个实现关联不同的 Future 类型。
适用场景
- 异步服务抽象:数据库、缓存、消息队列的统一接口
- 中间件模式:异步请求处理链
- 插件系统:异步插件接口
- 测试 mock:为异步 trait 提供测试实现
注意事项
- AFIT 返回的 Future 默认不是 Send
- 含 async fn 的 trait 不是 object-safe 的
- 使用泛型约束(静态分发)而非 dyn Trait
- 需要 dyn 支持时仍可使用 async-trait crate
- RPITIT 是 AFIT 的基础
- 迁移时注意 Send 约束的差异
总结
async fn in trait 在 Rust 1.75 稳定,允许 trait 中直接定义和实现 async fn,实现零成本异步抽象。与旧的 async-trait crate 相比,原生 AFIT 无需堆分配和动态分发。主要限制是 AFIT 返回的 Future 默认不是 Send 的,且含 async fn 的 trait 不能作为 trait object 使用。使用泛型约束替代 dyn Trait 是推荐方式。RPITIT(return-position impl Trait in traits)同时稳定,允许 trait 方法返回 impl Trait。对于需要 dyn Trait 的场景,async-trait crate 仍然有用。