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 Programming Cookbook
Rust Programming Cookbook

Rust Programming Cookbook: Explore the latest features of Rust 2018 for building fast and secure apps

Arrow left icon
Profile Icon Claus Matzinger
Arrow right icon
€18.99 per month
Paperback Oct 2019 444 pages 1st Edition
eBook
€8.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Claus Matzinger
Arrow right icon
€18.99 per month
Paperback Oct 2019 444 pages 1st Edition
eBook
€8.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Rust Programming Cookbook

Going Further with Advanced Rust

There are no doubts as to the difficulties that the Rust language poses to the avid learner. However, if you are reading this, you have gone further than most and invested the time needed to improve. The language and the way it forces you to think about memory is going to introduce new concepts into your programming habits. Rust does not necessarily provide new tools to accomplish things, but the borrowing and ownership rules help us to concern ourselves more with scopes, lifetimes, and freeing memory appropriately, regardless of the language. Hence, let's go deeper into more advanced concepts in Rust in order to complete our understanding of the language – when, why, and how to apply concepts such as the following:

  • Creating meaningful numbers with enums
  • There is no null
  • Complex conditions with pattern matching
  • Implementing custom...

Creating meaningful numbers with enums

Enums, short for enumerations, are well-known programming constructs that many languages feature. These special cases of types allow a number to be mapped to a name. This can be used to tie constants together under a single name and lets us declare values as variants. For example, we could have pi, as well as Euler's number, as variants of an enum, MathConstants. Rust is no different, but it can go a lot further. Instead of simply relying on naming numbers, Rust allows enums the same flexibility as other Rust types have. Let's see what this means in practice.

How to do it...

Follow these steps to explore enums:

  1. Create a new project with cargo new enums --lib and open this folder...

There is no null

Functional languages typically don't have a concept of null for the simple reason that it's always a special case. If you strictly follow functional principles, each input must have a workable output—but what is null? Is it an error? Or within normal operating parameters, but a negative result?

As a legacy feature, null has been around since C/C++, when a pointer could actually point to the (invalid) address, 0. However, many new languages try to move away from that. Rust does not have null, and no return value as a normal case with the Option type. The case of error is covered by the Result type, to which we dedicated an entire chapter, Chapter 5, Handling Errors and Other Results.

How to do it...

...

Complex conditions with pattern matching

As shown in the previous recipe, pattern matching is very useful with enums. However, there is more! Pattern matching is a construct that originates in functional languages and curtails much of the choice between conditional branches and the assignment of properties in struct that commonly follows. These steps are taken at once, reducing the amount of code on the screen and creating something akin to a higher-order switch-case statement.

How to do it...

Just a few steps need to be followed in order to learn more about pattern matching:

  1. Create a new binary project using cargo new pattern-matching. This time, we'll run an actual executable! Again, open the project using Visual...

Implementing custom iterators

The true power of a great language is the way in which it lets the programmer integrate with types in the standard library and around the general ecosystem. One way to do this is the iterator pattern: defined by the Gang of Four in their book Design Patterns (Addison-Wesley Professional, 1994), an iterator is an encapsulation of a pointer moving through a collection. Rust provides a range of implementations on top of the Iterator trait. Let's see how we can leverage that power with only a few lines of code.

Getting ready

We will build an iterator for the linked list we built in an earlier recipe. We recommend either using the Chapter01/testing project or walking with us through construction...

Filtering and transforming sequences efficiently

While in the previous recipe we discussed implementing a custom iterator, it's now time to make use of the functions they provide. Iterators can transform, filter, reduce, or simply convert the underlying elements in a single go, thereby making it a very efficient endeavor.

Getting ready

First, create a new project using cargo new iteration --lib and add the following to the newly created Cargo.toml file in the project's directory:

[dev-dependencies]
rand = "^0.5"

This adds a dependency to the rand (https://github.com/rust-random/rand) crate to the project, which will be installed upon running cargo test the first time. Open the entire project (or the src...

Reading memory the unsafe way

unsafe is a concept in Rust where some compiler safety mechanisms are turned off. These superpowers bring Rust closer to C's abilities to manipulate (almost) arbitrary parts of the memory. unsafe itself qualifies a scope (or function) to be able to use these four superpowers (from https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html ):

  • Dereference a raw pointer.
  • Call an unsafe function or method.
  • Access or modify a mutable static variable.
  • Implement an unsafe trait.

In most projects, unsafe is only required for using the FFI (short for Foreign Function Interface) because it's outside of the borrow checker's reach. Regardless, in this recipe, we are going to explore some unsafe ways to read memory.

How to do it...

...

Shared ownership

Ownership and borrowing are fundamental concepts in Rust; they are the reason no runtime garbage collection is required. As a quick primer: how do they work? In short: scopes. Rust (and many other languages) use (nested) scopes to determine the validity of a variable, so it cannot be used outside of the scope (like a function). In Rust, these scopes own their variables, so they will be gone after the scope finishes. In order for the program to move around values, it can transfer ownership to a nested scope or return it to the parent scope.

For temporary transfers (and multiple viewers), Rust has borrowing, which creates a reference back to the owned value. However, these references are less powerful, and sometimes more complex to maintain (for example, can the reference outlive the original value?), and they are probably the reason why the compiler complains...

Shared mutable ownership

Sharing ownership is great for read-only data. However, mutability is sometimes required, and Rust provides a great way to achieve this. If you recall the rules of ownership and borrowing, if there is a mutable reference, it has to be the only reference to avoid anomalies.

This is typically where the borrow checker comes in: at compile time, it makes sure that the condition holds true. This is where Rust introduces the pattern of interior mutability. By wrapping the data into a RefCell or Cell-type object, immutable and mutable access can be handed out dynamically. Let's see how this works in practice.

Getting ready

Create a new library project using cargo new --lib mut-shared-ownership and open...

Referencing with explicit lifetimes

Lifetimes are common in many languages and typically decide whether a variable is available outside the scope. In Rust, the situation is a bit more complicated thanks to the borrowing and ownership model that extensively uses lifetimes and scopes to automatically manage memory. Instead of reserving memory and cloning stuff into it, we developers want to avoid the inefficiencies and potential slowdowns this causes with references. However, this leads down a tricky path because, as the original value goes out of scope, what happens to the reference?

Since the compiler cannot infer this information from code, you have to help it and annotate the code so it can go and check for proper usage. Let's see what this looks like.

How to do it...

...

Enforcing behavior with trait bounds

When building a complex architecture, prerequisite behavior is very common. In Rust, this means that we cannot build either generic or other types without requiring them to conform to some prior behavior, or, in other words, we need to be able to specify which traits are required. Trait bounds are one way of doing that – and you have seen multiple instances of this already, even if you have skipped many recipes so far.

How to do it...

Follow these steps to learn more about traits:

  1. Create a new project using cargo new trait-bounds and open it in your favorite editor.
  2. Edit src/main.rs to add the following code, where we can easily print a variable's debug format since an implementation...

Working with generic data types

Rust's function overloading is a bit more exotic than in other languages. Instead of redefining the same function with a different type signature, you can achieve the same result by specifying the actual types for a generic implementation. Generics are a great way to provide more general interfaces and are not too complex to implement thanks to helpful compiler messages.

In this recipe, we are going to implement a dynamic array (such as Vec<T>) in a generic way.

How to do it...

Learn how to use generics in just a few steps:

  1. Start off by creating a new library project with cargo new generics --lib and open the project folder in Visual Studio Code.
  2. A dynamic array is a data structure...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Work through recipes featuring advanced concepts such as concurrency, unsafe code, and macros to migrate your codebase to the Rust programming language
  • Learn how to run machine learning models with Rust
  • Explore error handling, macros, and modularization to write maintainable code

Description

Rust 2018, Rust's first major milestone since version 1.0, brings more advancement in the Rust language. The Rust Programming Cookbook is a practical guide to help you overcome challenges when writing Rust code. This Rust book covers recipes for configuring Rust for different environments and architectural designs, and provides solutions to practical problems. It will also take you through Rust's core concepts, enabling you to create efficient, high-performance applications that use features such as zero-cost abstractions and improved memory management. As you progress, you'll delve into more advanced topics, including channels and actors, for building scalable, production-grade applications, and even get to grips with error handling, macros, and modularization to write maintainable code. You will then learn how to overcome common roadblocks when using Rust for systems programming, IoT, web development, and network programming. Finally, you'll discover what Rust 2018 has to offer for embedded programmers. By the end of the book, you'll have learned how to build fast and safe applications and services using Rust.

Who is this book for?

The Rust cookbook is for software developers looking to enhance their knowledge of Rust and leverage its features using modern programming practices. Familiarity with Rust language is expected to get the most out of this book.

What you will learn

  • Understand how Rust provides unique solutions to solve system programming language problems
  • Grasp the core concepts of Rust to develop fast and safe applications
  • Explore the possibility of integrating Rust units into existing applications for improved efficiency
  • Discover how to achieve better parallelism and security with Rust
  • Write Python extensions in Rust
  • Compile external assembly files and use the Foreign Function Interface (FFI)
  • Build web applications and services using Rust for high performance

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 18, 2019
Length: 444 pages
Edition : 1st
Language : English
ISBN-13 : 9781789530667
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Oct 18, 2019
Length: 444 pages
Edition : 1st
Language : English
ISBN-13 : 9781789530667
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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
€264.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

Frequently bought together


Stars icon
Total 107.97
Hands-On Data Structures and Algorithms with Rust
€32.99
Rust Programming Cookbook
€32.99
Mastering Rust
€41.99
Total 107.97 Stars icon
Banner background image

Table of Contents

11 Chapters
Starting Off with Rust Chevron down icon Chevron up icon
Going Further with Advanced Rust Chevron down icon Chevron up icon
Managing Projects with Cargo Chevron down icon Chevron up icon
Fearless Concurrency Chevron down icon Chevron up icon
Handling Errors and Other Results Chevron down icon Chevron up icon
Expressing Yourself with Macros Chevron down icon Chevron up icon
Integrating Rust with Other Languages Chevron down icon Chevron up icon
Safe Programming for the Web Chevron down icon Chevron up icon
Systems Programming Made Easy Chevron down icon Chevron up icon
Getting Practical with Rust Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.