rustasync-awaitrust-tracing

Where is the trait implementation when instrumenting a future?


I'm having a hard time understanding this simple example from the tracing crate:

use tracing::Instrument;

let my_future = async {
    // ...
};

my_future
    .instrument(tracing::info_span!("my_future"))
    .await

I'm new to async programming and this is probably a noob question.

According to my learning so far, there should be an implementation of tracing::Instrument trait for Future (This statement might be wrong, because implementing a trait for another trait sounds awkward, please correct me). Where is the implementation?

Because I can't find out the implementation, I can't understand how come it's possible to call the instrument() method on my_future.

Please help!


Solution

  • There is an implementation of Instrument for all T where T: Sized, which obviously includes futures. The instrument() trait method returns an Instrumented<T> which only implements Future when T does.

    In other words, you can call instrument() on non-futures, but the result can't be awaited, making it rather useless to do so.