< 返回版块

fengqi2019 发表于 2021-01-19 14:02

Tags:asyc,trait,impl

最近在看《Asynchronous Programming in Rust》中第2.3章《Applied: Build an Executor》里面关于Spawner的实现:

impl Spawner {
    fn spawn(&self, future: impl Future<Output = ()> + 'static + Send) {
        let future = future.boxed();
        let task = Arc::new(Task {
            future: Mutex::new(Some(future)),
            task_sender: self.task_sender.clone(),
        });
        self.task_sender.send(task).expect("too many tasks queued");
    }
}
use {
    futures::{
        future::{BoxFuture, FutureExt},
        task::{waker_ref, ArcWake},
    },
    std::{
        future::Future,
        sync::mpsc::{sync_channel, Receiver, SyncSender},
        sync::{Arc, Mutex},
        task::{Context, Poll},
        time::Duration,
    },
    // The timer we wrote in the previous section:
    timer_future::TimerFuture,
};
pub trait FutureExt: Future {
...

Spawner 实现的第三行future.boxed();明明future只是实现Future的类型,但boxed方法却是futures_util::future::future::FutureExt的方法,请问为什么程序还能运行,编译器也不会报错?

解答: 关键在于

impl<T: ?Sized> FutureExt for T where T: Future {}

评论区

写评论
作者 fengqi2019 2021-01-19 22:30

嗯嗯,多谢多谢!

--
👇
Ryan-Git: Extension traits

Ryan-Git 2021-01-19 19:42

Extension traits

1 共 2 条评论, 1 页