Book Image

Rust Web Programming - Second Edition

By : Maxwell Flitton
Book Image

Rust Web Programming - Second Edition

By: Maxwell Flitton

Overview of this book

Are safety and high performance a big concern for you while developing web applications? With this practical Rust book, you’ll discover how you can implement Rust on the web to achieve the desired performance and security as you learn techniques and tooling to build fully operational web apps. In this second edition, you’ll get hands-on with implementing emerging Rust web frameworks, including Actix, Rocket, and Hyper. It also features HTTPS configuration on AWS when deploying a web application and introduces you to Terraform for automating the building of web infrastructure on AWS. What’s more, this edition also covers advanced async topics. Built on the Tokio async runtime, this explores TCP and framing, implementing async systems with the actor framework, and queuing tasks on Redis to be consumed by a number of worker nodes. Finally, you’ll go over best practices for packaging Rust servers in distroless Rust Docker images with database drivers, so your servers are a total size of 50Mb each. By the end of this book, you’ll have confidence in your skills to build robust, functional, and scalable web applications from scratch.
Table of Contents (27 chapters)
Free Chapter
1
Part 1:Getting Started with Rust Web Development
4
Part 2:Processing Data and Managing Displays
8
Part 3:Data Persistence
12
Part 4:Testing and Deployment
16
Part 5:Making Our Projects Flexible
19
Part 6:Exploring Protocol Programming and Async Concepts with Low-Level Network Applications

Metaprogramming with macros

Metaprogramming can generally be described as a way in which the program can manipulate itself based on certain instructions. Considering the strong typing Rust has, one of the simplest ways in which we can meta program is by using generics. A classic example of demonstrating generics is through coordinates, as follows:

struct Coordinate <T> {
    x: T,
    y: T
}
fn main() {
    let one = Coordinate{x: 50, y: 50};
    let two = Coordinate{x: 500, y: 500};
    let three = Coordinate{x: 5.6, y: 5.6};
}

In the preceding snippet, we can see that the Coordinate struct managed to take in and handle three different types of numbers. We can add even more variance to the Coordinate struct so we can have two different types of numbers in one struct with the following code:

struct Coordinate <T, X> {
    x: T,
    y: X
}
fn main() {
    let one = Coordinate{x: 50, y: 500};
    let two = Coordinate{x: 5.6, y: 500};
    let three = Coordinate{x: 5.6, y: 50};
}

What is happening in the preceding code with generics is that the compiler is looking for all instances where the struct is used, creating structs with the types used when the compilation is running. Now that we have covered generics, we can move on to the main mechanism of metaprogramming: macros.

Macros enable us to abstract code. We’ve already been using macros in our print functions. The ! notation at the end of the function denotes that this is a macro that’s being called. Defining our own macros is a blend of defining a function and using a lifetime notation within a match statement in the function. To demonstrate this, we will define a macro that capitalizes a string with the following code:

macro_rules! capitalize {
    ($a: expr) => {
        let mut v: Vec<char> = $a.chars().collect();
        v[0] = v[0].to_uppercase().nth(0).unwrap();
        $a = v.into_iter().collect();
    }
}
fn main() {
    let mut x = String::from("test");
    capitalize!(x);
    println!("{}", x);
}

Instead of using the term fn, we use the macro_rules! definition. We then say that $a is the expression passed into the macro. We get the expression, convert it into a vector of chars, then make the first char uppercase, and then convert it back to a string. We must note that we don’t return anything in the capitalize macro, and when we call the macro, we don’t assign a variable to it. However, when we print the x variable at the end, we can see that it is capitalized. This does not behave like an ordinary function. We also must note that we didn’t define a type, instead, we just said it was an expression; the macro still does checks via traits. Passing an integer into the macro creates the following error:

|     capitalize!(32);
|     ---------------- in this macro invocation
|
= help: the trait `std::iter::FromIterator<char>` is not implemented for `{integer}`

Lifetimes, blocks, literals, paths, metaprogramming, and more, can also be passed instead of an expression. While it’s important to have a brief understanding of what’s under the hood of a basic macro for debugging and further reading, diving more into developing complex macros will not help us in developing web apps. We must remember that macros are a last resort and should be used sparingly. Errors thrown in macros can be hard to debug. In web development, a lot of the macros are already defined in third-party packages. Because of this, we do not need to write macros ourselves to get a web app up and running. Instead, we will mainly be using derive macros out of the box.