Using the Future trait

Future is a trait that returns a result in the future and represents an operation that can't be completed immediately. Like the Result enumeration, Future has two outcome variants that are represented by the associated types Item and Error. The trait has a poll method, which is what retrieves the result. This method will be called by a reactor until it returns Error or an Async::Ready value. Async is an enumeration that has both Ready and Pending variants, which are used to represent a result of an asynchronous operation. Ready means the value is ready to use, while Pending means the value is not yet available and will be ready later.

As you can see, Future is used for a similar purpose to Result. Unlike Result, however, Future is a trait, which means the implementation is not specified and many types can implement it. A useful feature is the FutureExt trait which can be implemented for all the  Future instances. This has multiple methods to process the result in a delayed manner. For example, if we want to convert an obtained value to another type, the trait has a map method for this purpose. Take a look at the following:

let fut = future::ok(10u64);
let mapped_fut = fut.map(|x| x as f64);

In this example, we created a FutureResult struct from a constant. This type implements the Future trait and represents a value that is immediately ready. Afterward, we called the map method from FutureExt for FutureResult, which expects a closure and returns.

You have to use a reactor to get the result for types that implement the Future trait. We will discuss reactors later in this section. Remember that you can't get the result immediately and use it in the next expression; instead, you have to create chains of futures or streams to get the appropriate result. Keep reading! We will now look into the Stream trait.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.144.229