Rust Programming Cookbook - Claus Matzinger - E-Book

Rust Programming Cookbook E-Book

Claus Matzinger

0,0
36,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Practical solutions to overcome challenges in creating console and web applications and working with systems-level and embedded code, network programming, deep neural networks, and much more.




Key Features



  • 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



Book 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.




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



Who this book is 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.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 465

Veröffentlichungsjahr: 2019

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Rust Programming Cookbook

 

 

 

 

 

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

 

 

 

 

 

 

 

 

 

 

 

Claus Matzinger

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Rust Programming Cookbook

Copyright © 2019 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

 

Commissioning Editor:Pavan RamchandaniAcquisition Editor:Denim PintoContent Development Editor:Pathikrit RoySenior Editor: Storm MannTechnical Editor:Gaurav GalaCopy Editor: Safis EditingProject Coordinator:Prajakta NaikProofreader: Safis EditingIndexer:Pratik ShirodkarProduction Designer:Jyoti Chauhan

First published: October 2019

Production reference: 1181019

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78953-066-7

www.packt.com

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
A book like this can only stand on the shoulders of giants – those in the Rust community and those in my life. To the community, thank you for maintaining Rust, the packages, and a great spirit; to my wife, Christine, thank you for your support, all the feedback, and for being so much more than my friend. 
– Claus Matzinger
 

Packt.com

Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Fully searchable for easy access to vital information

Copy and paste, print, and bookmark content

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks. 

Claus and I share a common history in the Rust project. We are both members of the Rust community, and we are both Rust teachers – Claus as a book writer, and I as a trainer. We spent hours and hours thinking about where Rust can be useful and how to motivate people to apply the language to their problem domain.

Rust is a surprisingly flexible language with huge potential in all domains. From server-side distributed systems down to tiny embedded devices, Rust can be your language of choice. This can be great, but also daunting. To a beginner or even to those switching domains, this can make the language harder to approach. Cookbooks are one way to deal with this problem. They give you a small glimpse into a number of different domains and somewhere to start. These examples are not meant to be used as-is. They are a starting point to iterate away from.

Rust is, in all its perceived complexity, a language based on a strong core principle: keeping reasoning local. You don’t need much context to read a Rust function. This makes small examples, like the ones in this book, the perfect starting point: whether you are using them as a reference for learning or as a basis to steadily iterate towards the solution to your problem.

To write cookbooks, you need a tinkerer that wants to play across multiple domains. Claus is such a tinkerer while also being excellent at explaining! Finding the “motivating example” is his core skill. Every time we speak, there is something new he has tinkered with. Not only that, he’ll tell you the why, the how, and the what of the bit he played with along with what the bit embodies. The examples in this book are well-researched and reasoned. This gives them longevity, even if minutiae might change.

Cookbooks differ from the usual introduction book in that they don’t pick a path or a story through their subject. They invite the reader to look around, find something of interest, and play with it. They are perfect for cross-reading and browsing. The metaphor of the cookbook is a strong one.

Programming language cookbooks are not for the restaurant kitchen. Restaurant kitchens need to ensure that every meal is of the same high quality, which is why they cook exactly by numbers. This book is for the home kitchen: you use an example once, to figure out how it works. Then you modify it or combine it with others. Sometimes, the result is pleasing, sometimes not. But you will have learned in the process. This exploration style of learning is strong and pleasing. A good cookbook sparks this process and the one in your hands is no exception.

Florian Gilcher Managing Director at Ferrous Systems

Contributors

About the author

Claus Matzinger is a software engineer with a very diverse background. After working in a small company maintaining code for embedded devices, he joined a large corporation to work on legacy Smalltalk applications. This led to a great interest in programming languages early on, and Claus became the CTO for a health games start-up based on Scala technology. Since then, Claus' roles have shifted toward customer-facing roles in the IoT database technology start-up, Crate IO (creators of CrateDB), and, most recently, Microsoft. There, he hosts a podcast, writes code together with customers, and blogs about the solutions arising from these engagements. For more than 5 years, Claus has been implementing software to help customers innovate, achieve, and maintain success.

About the reviewer

Pradeep R is a software professional and technology enthusiast from Gigamon who is passionate about network programming and security. He has extensive experience in working on leading enterprise network switching, routing, and security solutions, as well as working on next-generation network pervasive visibility solutions to improve network analysis and security.

His areas of interest span over different programming languages and he extensively works with C, C++, Python, and Rust. In his spare time, he works on building competence in emerging technologies and reviews books related to software programming, the most recent being Rust Cookbook and Rust Networking Basics.

I would like to thank Vigneshwer Dhinakaran, my brother, who has shown me that boundaries exist only in our minds and that they are meant to be breached. I would also like to acknowledge, with gratitude, members of my family: my mother, Vasanthi; my grandma, Sulochana; and my sister, Deepika, for their constant encouragement and support.

 

 

 

 

 

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

Rust Programming Cookbook

Dedication

About Packt

Why subscribe?

Foreword

Contributors

About the author

About the reviewer

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Download the color images

Code in Action

Conventions used

Sections

Getting ready

How to do it…

How it works…

There's more…

See also

Get in touch

Reviews

Starting Off with Rust

Setting up your environment

Getting ready

How to do it...

Managing the Rust installation with rustup.rs

Installing Visual Studio Code and extensions

Troubleshooting

How it works...

Working with the command line I/O

How to do it...

How it works...

Creating and using data types

How to do it...

How it works...

Controlling execution flow

How to do it...

How it works...

Splitting your code with crates and modules

Getting ready

How to do it...

How it works...

Writing tests and benchmarks

Getting ready

How to do it...

How it works...

Documenting your code

Getting ready

How to do it...

How it works...

Testing your documentation

Getting ready

How to do it...

How it works...

Sharing code among types

How to do it...

How it works...

Sequence types in Rust

How to do it...

How it works...

Debugging Rust

Getting ready

How to do it...

How it works...

Going Further with Advanced Rust

Creating meaningful numbers with enums

How to do it...

How it works...

There is no null

How to do it...

How it works...

Complex conditions with pattern matching

How to do it...

How it works...

Implementing custom iterators

Getting ready

How to do it...

How it works...

Filtering and transforming sequences efficiently

Getting ready

How to do it...

How it works...

Reading memory the unsafe way

How to do it...

How it works...

Shared ownership

Getting ready

How to do it...

How it works...

Shared mutable ownership

Getting ready

How to do it...

How it works...

Referencing with explicit lifetimes

How to do it...

How it works...

Enforcing behavior with trait bounds

How to do it...

How it works...

Working with generic data types

How to do it...

How it works...

Managing Projects with Cargo

Organizing large projects with workspaces

How to do it...

How it works...

Uploading to crates.io

Getting ready

How to do it...

How it works...

Using dependencies and external crates

How to do it...

How it works...

See also...

Extending cargo with sub-commands

Getting ready

How to do it...

How it works...

Testing your project with cargo

How to do it...

How it works...

Continuous integration with cargo

Getting ready

How to do it...

How it works...

Customizing the build

How to do it...

How it works...

Fearless Concurrency

Moving data into new threads

How to do it...

How it works...

Managing multiple threads

How to do it...

How it works...

Using channels to communicate between threads

How to do it...

How it works...

Sharing mutable states

How to do it...

How it works...

Multiprocessing in Rust

How to do it...

How it works...

Making sequential code parallel

How to do it...

How it works...

Concurrent data processing in vectors

How to do it...

How it works...

Shared immutable states

How to do it...

How it works...

Handling asynchronous messages with actors

How to do it...

How it works...

Asynchronous programming with futures

How to do it...

How it works...

Handling Errors and Other Results

Panicking responsibly

How to do it...

How it works...

Handling multiple errors

How to do it...

How it works...

Working with exceptional results

How to do it...

How it works...

Seamless error handling

How to do it...

How it works...

Customizing errors

How to do it...

How it works...

Resilient programming

How to do it...

How it works...

Working with external crates for error handling

How to do it...

How it works...

Moving between Option and Result

How to do it...

How it works...

Expressing Yourself with Macros

Building custom macros in Rust

How to do it...

How it works...

Implementing matching with macros

How to do it...

How it works...

Using predefined macros

How to do it...

How it works...

Code generation using macros

How to do it...

How it works...

Macro overloading

How to do it...

How it works...

Using repeat for parameter ranges

How to do it...

How it works...

Don't Repeat Yourself 

How to do it...

How it works...

Integrating Rust with Other Languages

Including legacy C code

Getting ready

How to do it...

How it works...

Calling into Rust from Node.js using FFI

Getting ready

How to do it ...

How it works...

Running Rust in the browser

Getting ready

How to do it...

How it works...

Using Rust and Python 

Getting ready

How to do it...

How it works...

Generating bindings for legacy applications

Getting ready

How to do it...

How it works...

Safe Programming for the Web

Setting up a web server

Getting ready

How to do it...

How it works...

Designing a RESTful API

Getting ready

How to do it...

How it works...

Handling JSON payloads

Getting ready

How to do it...

How it works...

Web error handling

Getting ready

How to do it...

How it works...

Rendering HTML templates

Getting ready

How to do it...

How it works...

Using an ORM to save data to a database

Getting ready

How to do it...

How it works...

Running advanced queries using an ORM

Getting ready

How to do it...

How it works...

Authentication on the web

Getting ready

How to do it...

How it works...

Systems Programming Made Easy

Cross-compiling Rust

Getting ready

How to do it...

How it works...

There's more...

Creating I2C device drivers

How to do it...

How it works...

Efficiently reading hardware sensors

How to do it...

How it works...

Getting Practical with Rust

Generating random numbers

How to do it...

How it works...

Writing to and reading from files

Getting ready

How to do it...

How it works...

Parsing unstructured formats like JSON

Getting ready

How to do it...

How it works...

Extract text using regular expressions

How to do it... 

How it works...

Recursively searching the filesystem

How to do it...

How it works...

Custom command-line arguments

How to do it...

How it works...

Working with piped input data

Getting ready

How to do it...

How it works...

Sending web requests

How to do it...

How it works...

Running machine learning models

Getting ready

How to do it...

How it works...

Configuring and using logging

How to do it...

How it works...

Starting subprocesses

How to do it...

How it works...

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Several years ago, I set out learning a new programming language every year – as many programmers do. There are many paradigms, rules, and insights to be gained from knowing another programming language, and then I found Rust. Rust turned out to be too much fun to write to simply move on, and after the steep learning curve, it became even more fun. So, there I had it: having learned a total of two additional (TypeScript and Rust) languages, I stuck to Rust. Why? Let's find out.

Rust is a systems programming language that provides memory safety by default without a garbage collector, which impacts its runtime behavior. Regardless of this fact, Rust is a very versatile language that can be used across various domains, be it web programming, game engines, or web clients. Moreover, it challenges conventional thinking about scopes and memory allocation, making you a better programmer in any language, be it C#, Java, or Python. The latest push on the part of companies such as Amazon, Microsoft, and Google shows that the ecosystem has now evolved to a point where things are stabilizing enough for enterprise usage – a great sign for a future Rust professional. 

In this book, we have compiled the most useful experiments with sensible use cases to make you productive fast. We have tried to cover a wide range of applications and hope you find useful concepts as well as solutions that are directly applicable to your daily development work. 

Who this book is for

This book is not your typical book to learn a programming language. Instead of diving deep into concepts, we want to show a range of possible projects, solutions, and applications that provide further links to concepts and other resources. Thus, we think this book is for anyone looking to get into practical applications quickly – regardless of their Rust experience. However, programming fundamentals (in any language) are required – they are the fundamental base your Rust skills will rest on. 

What this book covers

Chapter 1, Starting off with Rust, covers how to set up Rust toolchains on your computer and the fundamental constructs of the language. These range from writing tests and benchmarks to language constructs such as loops, if expressions, traits, and structs.

Chapter 2, Going Further with Advanced Rust, answers questions about more in-depth features of the language as well as patterns for creating meaningful programs. Topics include borrowing and ownership in complex scenarios, the Option type, pattern matching, generics, explicit lifetimes, and enums.

Chapter 3, Managing Projects with Cargo, uses the cargo tool to manage additional crates, extensions, projects, and tests. You will find recipes that empower you to work on larger projects and solve challenges faced in managing them.

Chapter 4, Fearless Concurrency, goes into some best practices and recipes to build safe, fast programs. In addition to this, popular libraries such as Rayon are presented as we demonstrate that Rust is a great language for doing all kinds of concurrent tasks. 

Chapter 5, Handling Errors and Other Results, explains how Rust uses the Result type and panics to perform error handling, integrating most failure cases into a regular workflow that needs to be treated. This chapter shows applicable patterns and best practices around avoiding unexpected crashes and unnecessary complexity.

Chapter 6, Expressing Yourself with Macros, explains how Rust's unique macro system extends the functionality of programs before compilation—in a type safe way. These macros can be implemented for many possible custom scenarios, and many crates use this ability. This chapter is all about creating useful macros to make your life easier and your programs safer.

Chapter 7, Integrating Rust with Other Languages, uses and works with different binary units and languages from within Rust in order to port legacy software or benefit from better SDKs. This is realized mostly through the Foreign Function Interface (FFI), which enables quick and easy integration with other native binaries. On top of that, it is possible to publish to npm (the Node.js package repository) from Rust using WebAssembly. These and other things are discussed in this chapter.

Chapter 8, Safe Programming for the Web, uses a state-of-the-art web framework to show the fundamentals of web programming – actix-web, which showcases an actor-based approach to handling requests, in productive use at Microsoft.

Chapter 9, Systems Programming Made Easy, explains how Rust is a great choice for running workloads on small devices with limited resources. In particular, the lack of a garbage collector and the resulting predictable runtime makes it a great fit for running sensor data collectors. Creating such a loop together with the required driver to read data is what we cover in this chapter.

Chapter 10, Getting Practical with Rust, covers practical considerations in Rust programming, such as parsing command-line arguments, working with neural networks (machine learning with PyTorch's C++ API), searching, regular expressions, web requests, and much more.

To get the most out of this book

We consider a few things in terms of programming fundamentals and we assume that you are familiar with these concepts already. Here is a list of terms you should be able to explain in a programming context:

Types and enums

Control statements and execution flow

Program architectures and patterns

Streams and iterators

Linking

Generics

Equipped with this knowledge, you can dive in with an editor of your choice (we recommend Visual Studio Code (https://code.visualstudio.com), together with the official Rust extension (https://marketplace.visualstudio.com/items?itemName=rust-lang.rust)). While Rust is a cross-platform programming language, some recipes are significantly easier on Linux or macOS. Windows users are encouraged to use the Windows Subsystem for Linux (https://docs.microsoft.com/en-us/windows/wsl/install-win10) for a better experience. 

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packt.com

.

Select the

Support

tab.

Click on

Code Downloads

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Rust-Programming-Cookbook. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781789530667_ColorImages.pdf.

Code in Action

Visit the following link to check out videos of the code being run: http://bit.ly/2oMSy1J

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."

A block of code is set as follows:

macro_rules! strange_patterns { (The pattern must match precisely) => { "Text" }; (42) => { "Numeric" }; (;<=,<=;) => { "Alpha" };}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

#[test]#[should_panic]

fn test_failing_make_fn() {

make_fn!(fail, {assert!(false)}); fail(); }

Any command-line input or output is written as follows:

$ cargo run

Bold: Indicates a new term, an important word, or words that you see on screen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).

To give clear instructions on how to complete a recipe, use these sections as follows:

Getting ready

This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

Starting Off with Rust

The Rust ecosystem has grown considerably over the last year, and the 2018 edition, in particular, brought a significant push toward stabilization. The tooling is developing and important libraries are maturing to a point where many bigger companies use Rust in production.

One of the features of Rust is a steep learning curve—which is mostly due to a fundamental change in how to think about memory allocation. It is not uncommon for experienced programmers in other languages (such as C#) to feel overwhelmed with the way things are done in Rust. In this chapter, we will try to overcome this and lower the bar to get started!

In this chapter, we will cover the following recipes:

Getting everything ready

Working with the command line I/O

Creating and using data types

Controlling execution flow

Splitting your code with crates and modules

Writing tests and benchmarks

Documenting your code

Testing your documentation

Sharing code among types

Sequence types in Rust

Debugging Rust

Setting up your environment

Since the programming language comes with a variety of toolchains, tools, linkers, and compiler versions, choosing the best-fitting variation is not easy. Additionally, Rust works on all major operating systems—which adds another variable. 

However, installing Rust has become a trivial task when using rustup (https://rustup.rs/). On the website, a helpful script (or installer on Windows) that takes care of retrieving and installing the required components can be downloaded. The same tool lets you switch between and update (and uninstall) these components as well. This is the recommended way.

Choosing to use the Microsoft Visual Studio Compiler (MSVC) together with Rust requires that you install additional software such as the Visual C++ runtime and compiler tools. 

To write code, an editor is also required. Since Visual Studio Code sports some Rust parts, it is a great choice together with the Rust extension. It's an open source editor developed by Microsoft and is well received across the world and the Rust community. In this recipe, we will install the following components:

Visual Studio Code (

https://code.visualstudio.com/

)

rustup

 (

https://rustup.rs

)

rustc

(and the rest of the compiler toolchains)

cargo

RLS

(short for

Rust Language Server

—this is for autocompletion)

Rust language support for Visual Studio Code

Getting ready

On a computer running either macOS, Linux, or Windows, only a web browser and internet connection are required. Bear in mind that the Windows installation works a little bit different from the *nix systems (Linux and macOS), which use scripts. 

How to do it...

Each of the parts requires us to navigate to their respective websites, download the installer, and follow their instructions:

Open the browser and navigate to

 

https://rustup.rs

 and 

https://code.visualstudio.com/

.

Choose the installers fit for your operating system.

After downloading, run the installers and follow their instructions, choosing the

stable

branches.

Once successfully installed, we'll go deeper into each installation.

Now, let's go behind the scenes to understand the installation better

Managing the Rust installation with rustup.rs

To test whether the installation of the Rust toolchain with rustup was successful, the rustc command is available to run in Terminal (or PowerShell on Windows):

$ rustc --version

rustc 1.33.0 (2aa4c46cf 2019-02-28)

Note that you will have a later version when you are running this. It doesn't matter if you stick to the 2018 edition for your code.

Rust requires a native linker to be available on your system. On Linux or Unix systems (such as macOS), Rust calls cc for linking, whereas on Windows, the linker of choice is Microsoft Visual Studio's linker, which depends on having Microsoft Visual C++ Build Tools installed. While it's possible to use an open source toolchain on Windows as well, this exercise is left for more advanced users.

Even with the 2018 edition, some useful features are still only available on nightly. To install the nightly edition of rustc, perform these steps:

Run

rustup install nightly

 (use

nightly-msvc

on Windows if you are not using the GNU toolchain) in a Terminal or PowerShell window.

After the command finishes, the default toolchain (used in

cargo

) can be switched using

rustup default nightly

.

Installing Visual Studio Code and extensions

In its vanilla version, Visual Studio Code comes with syntax highlighting for many languages. However, for autocompletion or/and checking syntax, an extension is required. The Rust project supplies this extension:

Open Visual Studio Code.

Use

Ctrl

+

P

(

cmd

+

P

on macOS) to open the command-line interface, then type

ext install rust-lang.rust

to install the extension. The process should look like this:

The extension uses RLS to do static code analysis and provide completion and syntax checking. The extension should install the RLS component automatically, but sometimes it will fail to do this. One solution is to add the following configuration to Visual Studio Code's settings.json file (useCtrl+P/cmd+Pto find it):

{ "rust-client.channel":"stable"}

Alternatively, rustup will also install RLS with the rustup component add rls command.

Troubleshooting

Occasionally, updating the tools will lead to errors that files are missing or cannot be overwritten. This can be for a wide range of reasons, but a full reset of the installations can help. On Linux or macOS systems, the following command takes care of deleting anything rustup installed:

$ rm -Rf ~/.rustup

Windows's PowerShell now supports many Linux-like commands:

PS> rm ~/.rustup

This leads to the same result. After deleting the current installation, install rustup from scratch—this should install the latest version.

Now, let's go behind the scenes to understand the code better.

How it works...

The shell script, rustup.sh, is a great way to install Rust and it is the primary way to install Rust and other components today. In fact, it is common to use the script also in CI systems to install the compiler and other tools. 

rustup is an open source project maintained by the Rust project and can be found on GitHub: https://github.com/rust-lang/rustup.rs. 

We've successfully learned how to set up our environment. Now let's move on to the next recipe.

Working with the command line I/O

The traditional way of communicating with the user on the command line is using standard streams. Rust includes helpful macros to deal with these simple cases. In this recipe, we will explore the basic workings of the classic Hello World program.

How it works...

Let's go through the code to understand the execution flow.

cargo is described in depth in Chapter 2, Managing Projects with Cargo, in this book.

The initial snippet is generated when cargo new hello-world is executed in step 1. As a project of type binary, a main function is required and rustc will be looking for it. Upon calling cargo run, cargo orchestrates compilation (with rustc) and linking (msvc on Windows, cc on *nix) and runs the resultant binary via its entry point: the main function (step 5). 

In the function we create in step 3, we write a series of print!/println!/eprintln! statements, which are Rust macros. These macros facilitate the writing to the standard output or standard error channels of a command-line application and include additional arguments. In fact, if arguments are missing, the compiler won't compile the program.

Rust's macros work directly on the syntax tree of the language, providing type safety and the ability to check the parameters and arguments. Therefore, they can be seen as a function call with a few special abilities—but more on that in Chapter 6, Expressing Yourself with Macros.   

The various arguments and the template string are combined using formatters, a powerful way to add real variables to the output without the need of concatenations or similar workarounds. This will reduce the number of allocations, considerably improving performance and memory efficiency. There is a wide range of how to format data types; to understand it more deeply, check out Rust's excellent documentation (https://doc.rust-lang.org/std/fmt/). 

The last step then shows the output that the various combinations produced.

We've successfully learned to work with the command line I/O. Now, let's move on to the next recipe.

Creating and using data types

Rust features all of the basic types: signed and unsigned integers up to 64 bits in width; floating-point types up to 64 bits; character types; and Booleans. Of course, any program will need more complex data structures to remain readable.

If you are unfamiliar with unit tests in Rust (or in general), we suggest going through the Writing tests and benchmarksrecipe here in this chapter first.

In this recipe, we'll look at good basic practices to create and use data types. 

How it works...

This recipe played with several concepts, so let's unpack them here. After setting up a library to work with unit tests as our playground in step 1 to step 3, we create a first test to work on some built-in data types to go through the basics in step 4 and step 5. Since Rust is particularly picky about type conversions, the test applies some math functions on the outcomes and inputs of different types.

For experienced programmers, there is nothing new here, except for the fact that there is an overflow_sub() type operation that allows for overflowing operations. Other than that, Rust might be a bit more verbose thanks to the (intentional) lack of implicit casting. In step 5, we intentionally provoke an overflow, which leads to a runtime panic (and is the test result we are looking for). 

As shown in step 5, Rust offers struct as the foundation for complex types, which can have attached implementation blocks as well as derived (#[derive(Clone, Copy, Debug)]) implementations (such as the Debug and Copy traits). In step 6, we go through using the type and its implications:

No overhead on custom types: 

struct

has exactly the size that the sum of its properties has

Some operations implicitly invoke a trait implementation

such as the assignment operator 

or 

the 

Copy

 

trait

 (which is essentially a shallow copy)

Changing property values requires the mutability of the entire

struct

 function

There are a few aspects that work like that because the default allocation strategy is to prefer the stack whenever possible (or if nothing else is mentioned). Therefore, a shallow copy of the data performs a copy of the actual data as opposed to a reference to it, which is what happens with heap allocations. In this case, Rust forces an explicit call to clone() so the data behind the reference is copied as well. 

We've successfully learned how to create and use data types. Now, let's move on to the next recipe.

Controlling execution flow

In Rust, controlling the execution flow of a program goes beyond simple if and while statements. We will see how to do that in this recipe.

How it works...

Although not vastly different from many languages' control statements, the basic constructs in Rust can change the way you think about variable assignments. It certainly transformed our mental models to be more data-focused. This means that instead of thinking if this condition is reached, assign this other value to a variable, a reversed assign this other value to a variable if this condition is reached—or shorter transform this variable if this condition applies—may take over. 

This is the functional stream in the Rust programming language and it lends itself well to shortening and focusing the important parts of a piece of code. Similar implications can be made from the loop constructs since everything is a scope and has a return value. Using these capabilities will make every program a lot more readable and shorter, especially if it's just simple operations. 

We've successfully learned how to control execution flow. Now, let's move on to the next recipe.

Splitting your code with crates and modules

Rust knows two types of code units: crates and modules. A crate is an external library, complete with its own Cargo.toml configuration file, dependencies, tests, and code. Modules, on the other hand, split the crate into logical parts that are only visible to the user if they import specific functions. Since the 2018 edition of Rust, the difference in using these structural encapsulations has been minimized. 

Getting ready

This time, we are going to create two projects: one that offers some type of function and another one to use it. Therefore, use cargo to create both projects: cargo new rust-pilib --lib and cargo new pi-estimator. The second command creates a binary executable so we can run the compilation result, while the former is a library (crate). 

This recipe is going to create a small program that prints out estimations of pi () and rounds them to two decimal places. It's nothing fancy and easy for anyone to understand.

Naming crates is hard. The main repository (https://crates.io/) is very permissive and has already seen name squatting (where people reserve names with the intent to sell them—think of names such as YouTube or Facebook, which would make nice API client names for these companies), and many crates are re-implementations of C libraries or wrap them. A good practice is to call the repository or directory rust-mycoolCwrapper and use mycoolCwrapper to name the crate itself. This way, only issues specific to your crate come in while the name is easy to guess in people's dependencies!