19 More crates and async Rust

 

This chapter covers

  • Another external crate: reqwest
  • Using feature flags to compile part of a crate
  • Using async Rust for code that doesn’t block

In this chapter, we will finally get around to using the reqwest crate. As you read through this chapter, you’ll soon see why we didn’t learn it until now: it’s because the reqwest crate is the first one we have encountered that involves async Rust! Well, sort of. Read on to find out.

While we’re at it, we’ll also learn about feature flags, which let you bring in just part of an external crate and thereby help keep compilation time down.

19.1 The reqwest crate

Back in chapter 17, we had a code sample that included a Client (http://mng.bz/mjv4) from the reqwest crate in one of our structs. We didn’t use it at the time because (among other reasons) the Rust Playground doesn’t allow you to make HTTP requests. The code looked like this:

use reqwest::Client;
 
struct Logger {
    logs: Vec<Log>,
    url: String,
    client: Client,
}

Let’s simplify this even more by removing the Logger struct and just creating a Client:

use reqwest::Client;
 
fn main() {
    let client = Client::default();
}

That was easy. So how do we use it? We can use our Client to .post() data, .get() it, .delete(), and so on. The easiest method to use is .get(). With this, we can ask a server to give you the HTML for a website or a response in a form like JSON from a server. The .get() method is pretty simple:

19.2 Feature flags

19.3 Async Rust

19.3.1 Async basics

19.3.2 Checking whether a Future is ready

19.3.3 Using an async run time