Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Rust Web Programming
Rust Web Programming

Rust Web Programming: A hands-on guide to developing fast and secure web apps with the Rust programming language

eBook
$26.98 $29.99
Paperback
$49.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Rust Web Programming

Before you begin: Join our book community on Discord

Give your feedback straight to the author himself and chat to other early readers on our Discord server (find the "rust-web-programming-3e" channel under EARLY ACCESS SUBSCRIPTION).

https://packt.link/EarlyAccess/

Rust is growing in popularity, but it has a reputation of having a steep learning curve. However, if taught correctly, this learning curve can be reduced. By covering the basic rules around Rust, as well as learning how to manipulate a range of data types and variables, we will be able to write simple programs in the same fashion as dynamically typed languages using a similar number of lines of code.

Understanding the basics is the key to effective web programming in Rust. I have maintained entire Kubernetes clusters where all the servers are written in Rust. Because I utilized traits, error handling, and generics effectively, it made reusing code inRust extremely effective. In my experience, it takes less lines...

Technical requirements

For this chapter, we only need access to the internet as we will be using the online Rust playground to implement the code. The code examples provided can be run in the online Rust playground at https://play.rust-lang.org/.

For detailed instructions, please refer to the file found here: https://github.com/PacktPublishing/Rust-Web-Programming-3E/tree/main/chapter01

What is Rust?

Rust is a cutting-edge systems programming language that has been making waves since Mozilla Research introduced it in 2010. With a focus on safety, concurrency, and performance, Rust is a formidable alternative to traditional languages like C and C++. Its most notable feature, the ownership system, enforces rigorous memory safety rules at compile time. This approach effectively eradicates common pitfalls like null pointer dereferencing and buffer overflows, all without needing a garbage collector.

Designed for high performance, Rust provides granular control over hardware and memory, making it perfect for developing operating systems, game engines, and other performance-critical applications. Its syntax is both modern and expressive, offering features typically seen in higher-level languages, such as pattern matching and algebraic data types, while retaining the efficiency required for system-level programming. Consequently, Rust has rapidly attracted a strong and active...

Reviewing data types and variables in Rust

If you have coded in another language before, you will have used variables and handled different data types. However, Rust does have some quirks that can put off developers. This is especially true if the developer has come from a dynamic language, as these quirks mainly revolve around memory management and reference to variables. These can be intimidating initially, but when you get to understand them, you will learn to appreciate them.

Some people might hear about these quirks and wonder why they should bother with the language at all. This is understandable, but these quirks are why Rust is such a paradigm-shifting language. Working with borrow checking and wrestling with concepts such as lifetimes and references gives us the high-level memory safety of a dynamic language such as Python. However, we can also get memory safe low-level resources such as those delivered by C and C++. This means that we do not have to worry about dangling pointers...

Controlling variable ownership

As we remember from the beginning of the chapter, Rust does not have a garbage collector. However, it has memory safety. It achieves this by having strict rules around variable ownership. These rules are enforced when Rust is being compiled. If you are coming from a dynamic language, then this can initially lead to frustration. This is known as fighting the borrow checker. Sadly, this unjustly gives Rust the steep learning curve reputation, as when you are fighting the borrow checker without knowing what is going on, it can seem like an impossible task to get even the most basic programs written. However, if we take the time to learn the rules before we try and code anything too complex, the knowledge of the rules and the helpfulness of the compiler will make writing code in Rust fun and rewarding. Again, I take the time to remind you that Rust has been the most favorited language 9 years in a row. This is not because it's impossible to get anything...

Building Structs

In modern high-level dynamic languages, objects have been the bedrock for building big applications and solving complex problems, and for good reason. Objects enable us to encapsulate data, functionality, and behavior. In Rust, we do not have objects. However, we do have structs that can hold data in fields. We can then manage the functionality of these structs and group them together with traits. This is a powerful approach, and it gives us the benefits of objects without the high coupling, as highlighted in the following figure:

Figure 1.9 – Difference between Rust structs and objects

We will start with something basic by creating a Human struct with the following code:

#[derive(Debug)]
struct Human<'a> {
    name: &'a str,
    age: i8,
    current_thought: &'a str
}

In the preceding code, we can see that our string literal fields have the same lifetime as the struct itself. We have also applied the Debug trait to the Human struct...

Summary

With Rust, we have seen that there are some traps when coming from a dynamic programming language background. However, with a little bit of knowledge of referencing and basic memory management, we can avoid common pitfalls and write safe, performant code quickly that can handle errors.

In this chapter we also covered the concepts of borrowing and referencing in Rust. While adhering to borrowing rules requires more effort than coding in a garbage collected language, we have a deeper understanding of how variables are placed in memory. This deeper understanding is safer as we know exactly what data we are pointing to. For instance, if we were using a language like Python and we created an instance of an object when we then passed into two dictionaries (python's version of a hash map), then if we updated one instance, the other would also be updated because it is a shared reference to the same memory address, the developer however may never know. In Rust, the borrow checking...

Questions

  1. What is the difference between a str and a String?
  2. Why can't string slices be passed into a function (string slice meaning str as opposed to &str)?
  3. How do we access the data belonging to a key in a HashMap?
  4. When a function results in an error, can we handle other processes, or will the error crash the program instantly?
  5. Why does Rust only allow one mutable borrow at a point in time?
  6. When would we need to define two different lifetimes in a function?
  7. How can structs link to the same struct via one of their fields?
  8. How can we add extra functionality to a struct where the functionality can also be implemented by other structs?
  9. How do we allow a container or function to accept different data structures?
  10. What's the quickest way to add a trait, such as Copy, to a struct?

Answers

  1. A String is a fixed-size reference stored in the stack that points to string-type data on the heap. A str is an immutable sequence of bytes stored somewhere in memory. Because the size of the str is unknown, it can only be handled by a pointer &str.
  2. Since we do not know the size of the string slice at compile time, we cannot allocate the correct amount of memory for it. Strings, on the other hand, have a fixed-size reference stored on the stack that points to the string slice on the heap. Because we know this fixed size of the string reference, we can allocate the correct amount of memory and pass it through to a function.
  3. We use the HashMap's get function. However, we must remember that the get function merely returns an Option struct. If we are confident that there is something there or we want the program to crash if nothing is found, we can directly unwrap it. However, if we don't want that, we can use a match statement and handle the Some and None output as...

Further Reading

  1. Hands on Functional Programming in Rust (2018) Andrew Johnson: chapter one (generics and structs)
  2. Mastering Rust (2019) Rahul Sharma and Vesa Kaihlavirta: chapter one (A tour of the language)
  3. The Problem With Single-threaded Shared Mutability (2015) by Manish Goregaokar: https://manishearth.github.io/blog/2015/05/17/the-problem-with-shared-mutability/

Rust Project Developers, 2024. The Rust Programming Language. [online] Available at: https://doc.rust-lang.org/book/ [Accessed 21 June 2024]

Latimer, N., 2020. Programming Rust. [online] Available at: https://doc.rust-lang.org/stable/rust-by-example/ [Accessed 21 June 2024].

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Build scalable web applications in Rust using popular frameworks such as Actix, Rocket, and Warp
  • Create front-end components that can be injected into multiple views
  • Develop data models in Rust to interact with the database

Description

Are safety and high performance a big concern for you while developing web applications? While most programming languages have a safety or speed trade-off, Rust provides memory safety without using a garbage collector. This means that with its low memory footprint, you can build high-performance and secure web apps with relative ease. This book will take you through each stage of the web development process, showing you how to combine Rust and modern web development principles to build supercharged web apps. You'll start with an introduction to Rust and understand how to avoid common pitfalls when migrating from traditional dynamic programming languages. The book will show you how to structure Rust code for a project that spans multiple pages and modules. Next, you'll explore the Actix Web framework and get a basic web server up and running. As you advance, you'll learn how to process JSON requests and display data from the web app via HTML, CSS, and JavaScript. You'll also be able to persist data and create RESTful services in Rust. Later, you'll build an automated deployment process for the app on an AWS EC2 instance and Docker Hub. Finally, you'll play around with some popular web frameworks in Rust and compare them. By the end of this Rust book, you'll be able to confidently create scalable and fast web applications with Rust.

Who is this book for?

This book on web programming with Rust is for web developers who have programmed in traditional languages such as Python, Ruby, JavaScript, and Java and are looking to develop high-performance web applications with Rust. Although no prior experience with Rust is necessary, a solid understanding of web development principles and basic knowledge of HTML, CSS, and JavaScript are required if you want to get the most out of this book.

What you will learn

  • Structure scalable web apps in Rust in Rocket, Actix Web, and Warp
  • Apply data persistence for your web apps using PostgreSQL
  • Build login, JWT, and config modules for your web apps
  • Serve HTML, CSS, and JavaScript from the Actix Web server
  • Build unit tests and functional API tests in Postman and Newman
  • Deploy the Rust app with NGINX and Docker onto an AWS EC2 instance

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Last updated date : Feb 11, 2025
Publication date : Feb 26, 2021
Length: 394 pages
Edition : 1st
Language : English
ISBN-13 : 9781800566095
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Last updated date : Feb 11, 2025
Publication date : Feb 26, 2021
Length: 394 pages
Edition : 1st
Language : English
ISBN-13 : 9781800566095
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Table of Contents

14 Chapters
Rust Web Programming, Third Edition: A hands-on guide to Rust for modern web development, with microservices and nanoservices Chevron down icon Chevron up icon
1 A Quick Introduction to Rust Chevron down icon Chevron up icon
2 Useful Rust Patterns for Web Programming Chevron down icon Chevron up icon
3 Designing Your Web Application in Rust Chevron down icon Chevron up icon
4 Async Rust Chevron down icon Chevron up icon
5 Handling HTTP Requests Chevron down icon Chevron up icon
6 Processing HTTP Requests Chevron down icon Chevron up icon
7 Displaying Content in the Browser Chevron down icon Chevron up icon
8 Injecting Rust in the Frontend with WASM Chevron down icon Chevron up icon
9 Data Persistence with PostgreSQL Chevron down icon Chevron up icon
10 Managing user sessions Chevron down icon Chevron up icon
11 Communicating Between Servers Chevron down icon Chevron up icon
12 Caching auth sessions Chevron down icon Chevron up icon
13 Observability through logging Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(1 Ratings)
5 star 0%
4 star 100%
3 star 0%
2 star 0%
1 star 0%
Daniel Sep 24, 2024
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
The graph in chapter 1 "what is rust) that display the bench mark of different frameworks has some numbers format that need to be reviewed. There should be an easy way to provide feedback on the book for early access titles (easy to spot erratas for you guys)
Subscriber review Packt
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.

Modal Close icon
Modal Close icon