Как реализовать асинхронные задачи в Rust? - PullRequest
0 голосов
/ 01 октября 2019

Я пытаюсь реализовать задачи в Rust 1.40.0-nightly (8431f261d 2019-09-29), и я не могу заставить мой код скомпилироваться.

У меня есть следующий код, который я хотел быхотел бы упростить:

use async_std::task;
use std::time::Duration;

pub fn main() {
    let mut v = Vec::new();
    v.push(task::spawn(async {
        task::sleep(Duration::from_millis(1000)).await;
        println!("Hello, world!");
    }));
    v.push(task::spawn(async {
        task::sleep(Duration::from_millis(2000)).await;
        println!("Hello, world 2!");
    }));
    for t in &mut v {
        task::block_on(t);
    }
}

Я хотел бы реализовать структуру Scope так, чтобы предыдущий код выглядел следующим образом:

pub fn main() {
    let mut s = Scope::new();
    s.push(async {
        task::sleep(Duration::from_millis(1000)).await;
        println!("Hello, world 1!");
    });
    s.push(async {
        task::sleep(Duration::from_millis(2000)).await;
        println!("Hello, world 2!");
    });
}

Текущая реализация, которую я имею:

struct Scope<T>
where
    T: std::future::Future + std::marker::Unpin,
{
    v: Vec<T>,
}

impl<T> Scope<T>
where
    T: std::future::Future + std::marker::Unpin,
{
    fn new() -> Scope<T> {
        Scope { v: Vec::new() }
    }
    fn push(&mut self, t: T) {
        self.v.push(t);
    }
}

impl<T> Drop for Scope<T>
where
    T: std::future::Future + std::marker::Unpin,
{
    fn drop(&mut self) {
        for t in &mut self.v {
            task::block_on(t);
        }
    }
}

pub fn main() {
    let mut s = Scope::new();
    s.push(async {
        task::sleep(Duration::from_millis(1000)).await;
        println!("Hello, world 1!");
    });
    s.push(async {
        task::sleep(Duration::from_millis(2000)).await;
        println!("Hello, world 2!");
    });
}

Но компиляция не удалась со следующей ошибкой:

error[E0277]: the trait bound `std::future::GenFuture<[static generator@src/main.rs:36:18: 39:6 _]>: std::marker::Unpin` is not satisfied in `impl std::future::Future`
  --> src/main.rs:36:7
   |
36 |     s.push(async {
   |       ^^^^ within `impl std::future::Future`, the trait `std::marker::Unpin` is not implemented for `std::future::GenFuture<[static generator@src/main.rs:36:18: 39:6 _]>`
   |
   = help: the following implementations were found:
             <std::future::GenFuture<T> as std::marker::Unpin>
   = note: required because it appears within the type `impl std::future::Future`

error[E0599]: no method named `push` found for type `Scope<impl std::future::Future>` in the current scope
  --> src/main.rs:40:7
   |
4  | / struct Scope<T>
5  | | where
6  | |     T: std::future::Future + std::marker::Unpin,
7  | | {
8  | |     v: Vec<T>,
9  | | }
   | |_- method `push` not found for this
...
40 |       s.push(async {
   |         ^^^^ method not found in `Scope<impl std::future::Future>`
   |
   = note: the method `push` exists but the following trait bounds were not satisfied:
           `impl std::future::Future : std::marker::Unpin`

Как мне исправить эти проблемы компиляции?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...