fasterthanlime / feedback

An issue tracker for articles/series/videos at https://fasterthanli.me/
13 stars 0 forks source link

Pin and suffering #308

Closed gekh closed 3 months ago

gekh commented 3 months ago

I found something wrong on this page:

https://fasterthanli.me/articles/pin-and-suffering#position=31.0

Here's what it is:

this code doesn't work

use tokio::time::Sleep;

struct MyFuture {
    sleep: Sleep,
}

impl MyFuture {
    fn new() -> Self {
        Self {
            sleep: tokio::time::sleep(Duration::from_secs(1)),
        }
    }
}

impl Future for MyFuture {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        println!("MyFuture::poll()");
        self.sleep.poll(cx)
    }
}

Here you can find docs how it should be implemented: https://docs.rs/tokio/latest/tokio/time/struct.Sleep.html

use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::time::Sleep;

struct HasSleep {
    sleep: Pin<Box<Sleep>>,
}

impl Future for HasSleep {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
        self.sleep.as_mut().poll(cx)
    }
}
gekh commented 3 months ago

Oh, sorry. I just should've read it further. Close it please.