这里有一个解决方案来自于如何将`impl Trait`类型的变量存储在结构体中,建议创建一个`Future` trait对象。但在我的实际代码中这样做会生成一个错误,提示该类型不是 `Send` 类型,但工作和非工作版本之间唯一的区别是是否存在向`dyn Future`强制转换。
为什么编译器认为它们是不同的,我应该如何解决这个问题?
下面是一个简化版的问题:
use std::future::Future;
fn uses_impl_trait() -> impl Future<Output = i32> {
async { 42 }
}
fn uses_trait_object() -> Box<dyn Future<Output = i32>> {
Box::new(async { 42 })
}
fn requires_send<T: Send>(_: T) {}
fn example() {
requires_send(uses_impl_trait()); // Works
requires_send(uses_trait_object()); // Fails
}
error[E0277]: `dyn std::future::Future<Output = i32>` cannot be sent between threads safely
--> src/lib.rs:15:19
|
11 | fn requires_send<T: Send>(_: T) {}
| ------------- ---- required by this bound in `requires_send`
...
15 | requires_send(uses_trait_object());
| ^^^^^^^^^^^^^^^^^^^ `dyn std::future::Future<Output = i32>` cannot be sent between threads safely
|
= help: the trait `std::marker::Send` is not implemented for `dyn std::future::Future<Output = i32>`
= note: required because of the requirements on the impl of `std::marker::Send` for `std::ptr::Unique<dyn std::future::Future<Output = i32>>`
= note: required because it appears within the type `std::boxed::Box<dyn std::future::Future<Output = i32>>`
我已经知道从在Rust中在线程之间发送trait对象,我可以将trait对象更改为Box<dyn Future<Output = i32> + Send>
,但是为什么存在这种差异呢?