I'm going through some exercises to learn about working with Pins. In the followinge example, I'm implementing Future for a wrapper around another Future. Calling poll on the wrapper will print the elapsed duration if the Future is Ready. I implemented this without relying on the pin_project crate.

struct MeasurableFuture<Fut> {
    inner_future: Fut,
    started_at: Option<std::time::Instant>,

impl<Fut: Future> Future for MeasurableFuture<Fut> {
    type Output = Fut::Output;

    fn poll(
        mut self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Self::Output> {
        let result;
        unsafe {
            result = self
                .map_unchecked_mut(|this| &mut this.inner_future)
        if result.is_ready() {
            if let Some(start_time) = self.started_at {
                let diff = start_time.elapsed();
                println!("duration was: {:?}", diff);

Questions around this:

  1. I had to bind self as mut locally in the implementation in order to borrow it mutably. Otherwise, this would have consumed self, and I couldn't use started_at later due to the move. Is there a problem with changing the binding mode for self? Is there a more elegant way to get around the move that would happen?
  2. Is there a cleaner way of calling poll on the inner_future?
  3. Is there a better way of executing the effect of printing the duration?



1 Answer 1


Two ways I can think of on how to execute the effect of printing the duration better.

  1. Use the log crate to log instead of println. At least this gives the user the option to control where and how to output the message.
  2. Provide MeasurableFuture with a handler function that can be passed in on instantiation. The handler gets called instead of println. This has the advantage that code which cares gets to use the actual value and can do something useful with it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.