How to print future value for debugging?
Asked Answered
X

1

7

I have started to recently use futures in Rust, but I couldn't find any way to print the future value for debugging purpose. I get this error even with the formatting helper:

^^^^^^^^ `futures::Future<Item=hyper::Response, Error=hyper::Error>` cannot be formatted using `{:?}` because it doesn't implement `std::fmt::Debug`

for the below code

#[cfg(test)]
println!(">>>>>>>> Future value returned {:?}", future);

Is there any existing solution (macros) to debug this?

Xylina answered 27/5, 2018 at 20:16 Comment(4)
It's kinda tricky since a Future represents some future value which has yet to materialize, so what would there be to print about it? What information do you want? Maybe you can wrap it in some type which adds contextual information you can print out when you need to. Otherwise you can only do this once you've waited on the result.Germanic
println!(">>>>>>>> Future value returned {:?}", future.poll()); ?Quinquagesima
It's very straightforward to print a future value. It's possible that you are having a problem printing a specific future, except you didn't include a minimal reproducible example and your question is aimed at the general case.Remmer
@shepmaster I think the issue is, as you mentioned, with my specific future. I have a Future<Item = hyper::Response, Error = hyper::Error> which doesn't get resolved for the client request. I will try to look into the issue based on this clarification nowXylina
I
1

You have to either specify the concrete type (not trait) that implements Debug or you have to rely on the impl Trait declaration but ensure that you also implement Debug.

extern crate futures;

use futures::{Future, future::FutureResult};
use std::fmt::Debug;

fn get_default_future<'s>() -> FutureResult<&'s str, ()> {
    futures::future::ok::<_, ()>("foo")
}

fn get_printable_future() -> impl Future + Debug {
    futures::future::ok::<_, ()>("bar")
}

fn main() {
    println!("{:?}", get_default_future());
    println!("{:?}", get_printable_future());
}

The trait itself does not require the underlying struct to implement Debug. Even if the struct implements Debug, you have to make sure when returning the trait instead of the struct that you declare it to implement Debug. It should compile then.

Isley answered 29/5, 2018 at 7:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.