Rust Essentials - Second Edition - Ivo Balbaert - E-Book

Rust Essentials - Second Edition E-Book

Ivo Balbaert

0,0
41,99 €

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

Leverage the functional programming and concurrency features of Rust and speed up your application development

About This Book

  • Get started with Rust to build scalable and high performance applications
  • Enhance your application development skills using the power of Rust
  • Discover the power of Rust when developing concurrent applications for large and scalable software

Who This Book Is For

The book is for developers looking for a quick entry into using Rust and understanding the core features of the language. Basic programming knowledge is assumed.

What You Will Learn

  • Set up your Rust environment to achieve the highest productivity
  • Bridge the performance gap between safe and unsafe languages
  • Use pattern matching to create flexible code
  • Apply generics and traits to develop widely applicable code
  • Organize your code in modules and crates
  • Build macros to extend Rust's capabilities and reach
  • Apply tasks to tackle problems concurrently in a distributed environment

In Detail

Rust is the new, open source, fast, and safe systems programming language for the 21st century, developed at Mozilla Research, and with a steadily growing community. It was created to solve the dilemma between high-level, slow code with minimal control over the system, and low-level, fast code with maximum system control. It is no longer necessary to learn C/C++ to develop resource intensive and low-level systems applications. This book will give you a head start to solve systems programming and application tasks with Rust.

We start off with an argumentation of Rust's unique place in today's landscape of programming languages. You'll install Rust and learn how to work with its package manager Cargo. The various concepts are introduced step by step: variables, types, functions, and control structures to lay the groundwork. Then we explore more structured data such as strings, arrays, and enums, and you'll see how pattern matching works.

Throughout all this, we stress the unique ways of reasoning that the Rust compiler uses to produce safe code. Next we look at Rust's specific way of error handling, and the overall importance of traits in Rust code. The pillar of memory safety is treated in depth as we explore the various pointer kinds. Next, you'll see how macros can simplify code generation, and how to compose bigger projects with modules and crates. Finally, you'll discover how we can write safe concurrent code in Rust and interface with C programs, get a view of the Rust ecosystem, and explore the use of the standard library.

Style and approach

The book takes a pragmatic approach, showing various methods to solve systems programming tasks with Rust and develop resource intensive and low-level systems applications.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 303

Veröffentlichungsjahr: 2017

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 Essentials

Second Edition

 

 

 

 

 

 

 

 

 

A quick guide to writing fast, safe, and concurrent systems and applications

 

 

 

 

 

 

 

 

 

 

Ivo Balbaert

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Rust Essentials

Second Edition

Copyright © 2017 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.

 

First published: May 2015

Second edition: November 2017

 

Production reference: 1061117

 

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

ISBN 978-1-78839-001-9

 

www.packtpub.com

Credits

Author

Ivo Balbaert

Copy Editor

Safis Editing

Reviewer

Tom Verbesselt

Project Coordinator

 

Vaidehi Sawant

Commissioning Editor

Merint Mathew

Proofreader

Safis Editing

Acquisition Editor

Karan Sadawana

Indexer

Tejal Daruwale Soni

Content Development Editor

Rohit Kumar Singh

Graphics

Abhinash Sahu

Technical Editor

Ruvika Rao

Production Coordinator

Melwyn Dsa

About the Author

Ivo Balbaert is currently a lecturer in (web) programming and databases at CVO Antwerpen, a community college in Belgium. He received a PhD in applied physics from University of Antwerp in 1986. He has worked for 20 years in the software industry as a developer and consultant in several companies, and he has worked for 10 years as a project manager at the University Hospital of Antwerp. From 2000 onward, he switched to teaching, developing software, and writing technical books.

About the Reviewer

Tom Verbesselt started his career as a software engineer in the amazing early world of 3D scanning and printing. However, he couldn't ignore his passion for teaching, and so he became a lecturer at the graduate program at CVO Antwerpen (Antwerp, Belgium). He started his own IT consultancy firm in 2003 and cofounded OWIC, a non-profit organization dedicated to teaching open source software tools, in 2016. Currently, he is the head of the graduate program in IT at CVO Antwerpen, and he is passionate about mobile, web, and new technology.

I have known Ivo for more than 10 years as a colleague at CVO Antwerpen. He is a born teacher and always willing to share his knowledge and insights. He is passionate about programming, and this book will give you all that you need to get started in Rust.  This book is a well guided tour around the Rust programming language. I was amazed by the speed, elegance, and possibilities of this programming language. After reading this book, you will have a solid foundation in the language and the advantages and possibilities that it offers. I've loved every page of it, and I hope you will do too.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

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

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by Packt

Copy and paste, print, and bookmark content

On demand and accessible via a web browser

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1788390016.

 

If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

Conventions

Customer support

Downloading the example code

Errata

Piracy

Questions

Starting with Rust

The advantages of Rust

The trifecta of Rust - safe, fast, and concurrent

Comparison with other languages

The stability of Rust and its evolution

The success of Rust

Where to use Rust

Servo

Installing Rust

rustc--the Rust compiler

Our first program

Working with Cargo

Developer tools

Using Sublime Text

The Standard Library

Summary

Using Variables and Types

Comments

Global constants

Printing with string interpolation

Values and primitive types

Consulting Rust documentation

Binding variables to values

Mutable and immutable variables

Scope of a variable and shadowing

Type checking and conversions

Aliasing

Expressions

The stack and the heap

Summary

Using Functions and Control Structures

Branching on a condition

Looping

Functions

Documenting a function

Attributes

Conditional compilation

Testing

Testing with cargo

The tests module

Summary

Structuring Data and Matching Patterns

Strings

Arrays, vectors, and slices

Vectors

Slices

Strings and arrays

Tuples

Structs

Enums

Result and Option

Getting input from the console

Matching patterns

Program arguments

Summary

Higher Order Functions and Error-Handling

Higher order functions and closures

Iterators

Consumers and adapters

Generic data structures and functions

Error-handling

Panics

Testing for failure

Some more examples of error-handling

The try! macro and the ? operator

Summary

Using Traits and OOP in Rust

Associated functions on structs

Methods on structs

Using a constructor pattern

Using a builder pattern

Methods on tuples and enums

Traits

Using trait constraints

Static and dynamic dispatch

Built-in traits and operator overloading

OOP in Rust

Inheritance with traits

Using the visitor pattern

Summary

Ensuring Memory Safety and Pointers

Pointers and references

Stack and heap

Lifetimes

Copying and moving values - The copy trait

Let's summarize

Pointers

References

Match, struct, and ref

Ownership and borrowing

Ownership

Moving a value

Borrowing a value

Implementing the Drop trait

Moving closure

Boxes

Reference counting

Overview of pointers

Summary

Organizing Code and Macros

Modules and crates

Building crates

Defining a module

Visibility of items

Importing modules and file hierarchy

Importing external crates

Exporting a public interface

Adding external crates to a project

Working with random numbers

Macros

Why macros?

Developing macros

Repetition

Creating a new function

Some other examples

Using macros from crates

Some other built-in macros

Summary

Concurrency - Coding for Multicore Execution

Concurrency and threads

Creating threads

Setting the thread's stack size

Starting a number of threads

Panicking threads

Thread safety

Shared mutable states

The Sync trait

Communication through channels

Sending and receiving data

Making a channel

Sending struct values over a channel

Sending references over a channel

Synchronous and asynchronous

Summary

Programming at the Boundaries

When is code unsafe

Using std::mem

Raw pointers

Interfacing with C

Using a C library

Inlining assembly code

Calling Rust from other languages

Summary

Exploring the Standard Library

Exploring std and the prelude module

Collections - using hashmaps and hashsets

Working with files

Paths

Reading a file

Error-handling with try!

Buffered reading

Writing a file

Error-handling with try!

Filesystem operations

Using Rust without the Standard Library

Summary

The Ecosystem of Crates

The ecosystem of crates

Working with dates and times

File formats and databases

Web development

Graphics and games

OS and embedded system development

Other resources for learning Rust

Summary

Preface

Rust is a stable, open source, and compiled programming language that finally promises software developers the utmost safety--not only type safety, but also memory safety. The compiler carefully checks all uses of variables and pointers so that common problems from C/C++ and other languages, such as pointers to wrong memory locations or null references, are a thing of the past. Possible problems are detected at compilation time, and Rust programs execute at speeds comparable with their C++ counterparts.

Rust runs with a very light runtime, which does not perform garbage collection. Again, the compiler takes care of generating the code that frees all resources at the right time. This means Rust can run in very constrained environments, such as embedded or real-time systems. The built-in safety also guarantees concurrency without data-race problems.

It is clear that Rust is applicable in all use cases where until now C and C++ were the preferred languages and that it will do a better job at it, at least with regard to safety and robustness.

Rust is also a very rich language: it has concepts (such as immutability by default) and constructs (such as traits) that enable developers to write code in a high-level functional and object-oriented style.

The original goal of Rust was to serve as the language for writing a new safe browser engine, devoid of the many security flaws that plague existing browsers such as the Servo project from Mozilla Research.

The goal of this book is to give you a firm foundation for starting to develop in Rust. Throughout the book, we emphasize the three pillars of Rust: safety, performance, and sound concurrency. We will discuss where Rust differs from other programming languages and why this is the case. The code examples are not chosen ad hoc, but they are oriented as part of an ongoing project for building a game so that there is a sense of cohesion and evolution in the examples.

Throughout the book, I will urge you to learn by following along by typing in the code, making the requested modifications, compiling, testing, and working out the exercises.

What this book covers

Chapter 1, Starting with Rust, discusses the main reasons that led to the development of Rust. We compare Rust with other languages and indicate the areas for which it is most appropriate. Then, we guide you through installing all the necessary components for a Rust development environment. In particular, you will learn how to work with Cargo, Rust’s package manager.

Chapter 2, Using Variables and Types, looks at the basic structure of a Rust program. We discuss the primitive types, how to declare variables and whether they have to be typed, and the scope of variables. Immutability, one of the key cornerstones of Rust’s safety strategy is also illustrated. Then, we look at basic operations, how to do formatted printing, and the important difference between expressions and statements.

Chapter 3, Using Functions and Control Structures, shows how to define functions, and the different ways to influence program execution flow in Rust. We also take a look at attributes and how to do testing in Rust.

Chapter 4, Structuring Data and Matching Patterns, discusses the basic data types for programming, such as strings, vectors, slices, tuples, and enums. You will learn how to get input from the console and how to work with program arguments. Then we show you the powerful pattern matching that is possible in Rust and how values are extracted by destructuring patterns.

Chapter 5, Higher Order Functions and Error-Handling, explores the functional features of Rust. We see how data structures and functions can be defined in a generic way. Furthermore, you will learn how to work with Rust’s unique error-handling mechanism.

Chapter 6, Using Traits and OOP in Rust, explores the object-oriented features of Rust. We see how traits can be used to define behavior and to simulate inheritance in data structures. We also explore some common OOP patterns implemented in Rust, such as the visitor and the builder pattern.

Chapter 7, Ensuring Memory Safety and Pointers, exposes the borrow checker, Rust’s mechanism to ensure that only memory safe operations can occur during program execution. Different kinds of pointers are discussed in this chapter.

Chapter 8, Organizing Code and Macros, discusses the bigger code-organizing structures in Rust, such as modules and crates. It also touches upon how to build macros in order to generate code, thus saving time and effort.

Chapter 9, Concurrency – Coding for Multicore Execution, delves into Rust’s concurrency model based on threads and channels. We also discuss a safe strategy for working with shared mutable data. 

Chapter 10, Programming at the Boundaries, looks at how Rust behaves in situations where we have to leave the safety boundaries, such as when interfacing with C or using raw pointers, and how Rust minimizes potential dangers when doing so.

Chapter 11, Exploring the Standard Library, gives us an overview of what is contained in Rust’s Standard Library with an emphasis on collections and the built-in macros. We also discuss how to let Rust work without standard library, for example, in very resource-constrained environments.

Chapter 12, The Ecosystem of Crates, covers how to work with crates built by other developers. We look at crates to work with files and databases, do web development, and develop graphics applications and games.

What you need for this book

To run the code examples in the book, you will need the Rust system for your computer, which can be downloaded from http://www.rust-lang.org/install.html.

This also contains the Cargo project and package manager. To work more comfortably with Rust code, a development environment like Sublime Text can also be of use. Chapter 1, Starting with Rust, contains detailed instructions on how to set up your Rust environment.

Who this book is for

This book is directed at developers with some programming experience, either in C / C++, Java/C# or Python, Ruby, Dart or a similar language, having a basic knowledge of general programming concepts. It will get you up and running quickly, giving you all you need to start building your own Rust projects.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The read_line() method returns a value of type IoResult<String>, which is a specialized Result type."

A block of code is set as follows:

match magician { "Gandalf" => println!("A good magician!"), "Sauron" => println!("A magician turned bad!"), _ => println!("No magician turned up!") }

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

match magician

{ "Gandalf" => println!("A good magician!"), "Sauron" => println!("A magician turned bad!"), _ => println!("No magician turned up!") }

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

# rustc welcome.rs -o start

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "When working with Rust code, select Tools | Build System and RustEnhanced."

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

Click on

Code Download

.

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-Essentials-Second-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Starting with Rust

Rust is a programming language developed at Mozilla Research and backed up by a big open source community. Its development was started in 2006 by language designer Graydon Hoare. Mozilla began sponsoring it in 2009 and it was first presented officially in 2010. Work on this went through a lot of iterations, culminating in early 2015 in the first stable production, version 1.0.0, developed by the Rust Project Developers, consisting of the Rust team at Mozilla and an open source community of over 1800 contributors. Since then, Rust has developed in a steady pace; its current stable version is 1.20.0.

Rust is based on clear and solid principles. It is a systems programming language, equaling C and C++ in its capabilities. It rivals idiomatic C++ in speed, but it lets you work in a much safer way by forbidding code that could cause program crashes due to memory problems. Moreover, it makes concurrent programming and parallel execution on multi-core machines memory safe without garbage collection--it is the only language that does that. By design, Rust eliminates the corruption of shared data through concurrent access, called data races.

This chapter will present you with the main reasons why Rust's popularity and adoption are steadily increasing. Then, we'll set up a working Rust development environment.

We will cover the following:

The advantages of Rust

The trifecta of Rust--safe, fast and concurrent

The stability of Rust and its evolution

The success of Rust

Using Rust

Installing Rust

The Rust compiler

Our first program

Working with Cargo

Developer tools

The Standard Library

The advantages of Rust

Mozilla is a company known for its mission to develop tools for and drive the open standards web, most notably through its flagship browser Firefox. Every browser today, including Firefox, is written in C++, some 1,29,00,992 lines of code for Firefox, and 44,90,488 lines of code for Chrome. This makes them fast, but it is inherently unsafe because the memory manipulations allowed by C and C++ are not checked for validity. If the code is written without the utmost programming discipline on the part of the developers, program crashes, memory leaks, segmentation faults, buffer overflows, and null pointers can occur at program execution. Some of these can result in serious security vulnerabilities, all too familiar in existing browsers. Rust is designed from the ground up to avoid those kind of problems.

Compared to C or C++, on the other side of the programming language spectrum we have Haskell, which is widely known to be a very safe and reliable language, but with very little or no control at the level of memory allocation and other hardware resources. We can plot different languages along this control that is safety axis, and it seems that when a language is safer, like Java compared to C++, it loses low-level control. The inverse is also true; a language that gives more control over resources like C++ provides much less safety.

Rust is made to overcome this dilemma by providing:

High safety through its strong type system and smart compiler

Deep but safe control over low-level resources (as much as C or C++), so it runs close to the hardware

Its main website, http://www.rust-lang.org/en-US/, contains links to installation instructions, docs and the Rust community.

Rust lets you specify exactly how your values are laid out in memory and how that memory is managed; that's why it works well at both ends of the control and safety line. This is the unique selling point of Rust, it breaks the safety-control dichotomy that, before Rust, existed among programming languages. With Rust they can be achieved together without losing performance.

Rust can accomplish both these goals without a garbage collector, in contrast to most modern languages like Java, C#, Python, Ruby, Go, and the like. In fact Rust doesn't even have a garbage collector yet (though an optional garbage collector is being designed).

Rust is a compiled language: the strict safety rules are enforced by the compiler, so they do not cause runtime overhead. As a consequence, Rust can work with a very small runtime, so it can be used for real-time or embedded projects and it can easily integrate with other languages or projects.

Rust is meant for developers and projects where performance and low-level optimizations are important, but also where a safe and stable execution environment is needed. The robustness of the language is specifically suited for projects where that is important, leading to less pressure in the maintenance cycle. Moreover, Rust adds a lot of high-level functional programming techniques to the language, so that it feels at the same time like a low-level and a high-level language.

The trifecta of Rust - safe, fast, and concurrent

Rust is not a revolutionary language with new cutting-edge features, but it incorporates a lot of proven techniques from older languages, while massively improving upon the design of C++ in matters of safe programming.

The Rust developers designed Rust to be a general purpose and multi-paradigm language; like C++, it is an imperative, structured and object-oriented language. Besides that, it inherits a lot from functional languages on the one hand, while also incorporating advanced techniques for concurrent programming on the other hand.

The typing of variables is static (because Rust is compiled) and strong. However, unlike in Java or C++, the developer is not forced to indicate types for everything; the Rust compiler is able to infer types in many cases.

C and C++ applications are known to be haunted by problems that often lead to program crashes or memory leaks, and which are notoriously difficult to debug and solve. Think about dangling pointers, buffer overflows, null pointers, segmentation faults, data races, and so on. The Rust compiler (called rustc) is very intelligent and can detect all these problems while compiling your code, thereby guaranteeing memory safety during execution. This is done by the compiler, retaining complete control over memory layout, but without needing the runtime burden of garbage collection (see Chapter 6, Using Traits and OOP in Rust). Of course, safety also implies much less possibility for security breaches.

Rust compiles to native code like Go and Julia but, in contrast to the other two, Rust needs no runtime with garbage collection. In this respect, it also differs from Java and the languages that run on the JVM, like Scala and Clojure. Most other popular modern languages, like .NET with C# and F#, JavaScript, Python, Ruby, Dart, and so on, all need a virtual machine and garbage collection for their execution.

Rust provides several mechanisms for concurrency and parallelism. The Standard Library gives a model that works with threads to perform work in parallel, where each thread maps to an operating system thread. They do not share heap memory, but communicate data through channels and data races are eliminated by the type system (see Chapter 8, Organizing Code and Macros). If needed in your project, several crates provide an actor-model approach with lightweight threads. These mechanisms make it easy for programmers to leverage the power of the many CPU cores available on current and future computing platforms.

The rustc compiler is completely self-hosted, which means it is written in Rust and can compile itself by using a previous version. It uses the LLVM compiler framework as its backend (for more info, see http://en.wikipedia.org/wiki/LLVM), and produces natively executable code that runs blazingly fast, because it compiles to the same low-level code as C++ ( see some benchmarks at http://benchmarksgame.alioth.debian.org/u64q/rust.php).

Rust is designed to be as portable as C++ and to run on widely-used hardware and software platforms. At present, it runs on Linux, macOS X, Windows, FreeBSD, Android, and iOS. For a more complete overview of where Rust can run, see https://forge.rust-lang.org/platform-support.html.

Rust can call C code as simply and efficiently as calling C code from C itself, and, conversely C code can also call Rust code (see Chapter 9, Concurrency - Coding for Multicore Execution).

Rust developers are called rustaceans.

Other Rust characteristics that will be discussed, in more detail in the later chapters are as follows:

Variables are immutable by default (see

Chapter 2

,

Using Variables and Types

)

Enums (see

Chapter 4

,

Structuring Data and Matching Patterns

)

Pattern matching (see also

Chapter 4

,

Structuring Data and Matching Patterns

)

Generics (see

Chapter 5

,

Higher Order Functions and Error-Handling

)

Higher-order functions and closures (see also

Chapter 5

,

Higher Order Functions and Error-Handling

)

An interface system called

traits

(see

Chapter 6

,

Using Traits and OOP in Rust

)

A hygienic macro system (see

Chapter 8

,

Organizing Code and Macros

)

Zero-cost abstractions, which means that Rust has higher-language constructs, but these do not have an impact on performance

In conclusion, Rust gives you ultimate power over memory allocation, as well as removing many security and stability problems commonly associated with native languages.

Comparison with other languages

Dynamic languages such as Ruby or Python give you the initial speed of coding development, but the price is paid later in:

Writing more tests

Runtime crashes

Production outages

The Rust compiler forces you to get a lot of things right from the beginning at compile time, which is the least expensive place to identify and fix bugs.

Rust's object orientation is not as explicit or evolved as common object-oriented languages such as Java, C# or Python, as it doesn't have classes. Compared with Go, Rust gives you more control over memory and resources and so it lets you code on a lower level. Go also works with a garbage collector; it has no generics and no mechanism to prevent data races between its goroutines used in concurrency. Julia is focused on numerical computing performance, works with a JIT compiler, and also doesn't give you that low-level control as Rust does.

The stability of Rust and its evolution

Rust started out with version 1.0.0, and, at the time of writing, the current version is 1.20.0. Version numbers follow the semantic versioning principle (see http://semver.org/ for further information):

Patch release

: For bug fixes and other minor changes, increment the last number, for example 1.18.1

Minor release

: For new features which don't break existing features, increment the middle number, for example 1.19.0

Major release

: For changes which break backwards compatibility, increment the first number, for example 2.0.0

So, no breaking changes will occur during the current 1.n.m cycle versions, as this cycle is backward compatible; Rust projects which are developed in the older versions of this cycle will still compile in a more recent version. However, to be able to work with new features which are only contained in the more recent version, it is mandatory to compile your code to that specific version.

Rust has a very dynamic cycle of progression. Work is performed on three releases (called channels or builds simultaneously)--nightly, beta, and stable, and they follow a strict six-week release cycle like web browsers:

The

stable channel

is the current stable release, which is advocated for Rust projects that are being used in production.

The

beta channel

is where new features are deemed stable enough to be tested out in bigger, non-deployed projects.

The

nightly channel

build contains the latest experimental features; it is produced from the master branch every 24 hours. You would use it only for experimentation.

The beta and stable channel builds are only updated as new features are backported to their branch. With this arrangement, Rust allows users to access new features and bug fixes quickly.

Here is a concrete example: 1.18 was released on 18th June, 2017, the 1.19-beta was released at the same time, and the master development branch was advanced to 1.20. Six weeks later, on 30th July, Rust 1.19 will come out of beta and become a stable release, 1.20 will be promoted to 1.21-beta, and the master will become the eventual 1.21.

Some features in an experimental stage can only work when the code contains an attribute #[feature]. These may not be used on the stable release channel, only on a beta or nightly release; an example is the box syntax (see chapter 2\code\references.rs).

The success of Rust

Since its production release 1.0, Rust has enjoyed quite a steady uptake. This is manifest if you view a Google Trends survey:

In the well-known TIOBE Index (see https://www.tiobe.com/tiobe-index//), it reached 50th place in September 2015 and is now ranked in 37th position.

In the RedMonk ranking of programming languages (see http://redmonk.com/sogrady/2017/06/08/language-rankings-6-17/), it is ready to join the popularity of Lua, CoffeeScript, and Go.

Also, for two consecutive years, Rust was the most loved programing language on Stack Overflow (see https://insights.stackoverflow.com/survey/2017#most-loved-dreaded-and-wanted).

As a hallmark of its success, today, more than 50 companies are using Rust in production, see https://www.rust-lang.org/en-US/friends.html, amongst which are HoneyPot, Tilde, Chef, npm, Canonical, Coursera, and Dropbox.

Where to use Rust

It is clear from the previous sections that Rust can be used in projects that would normally use C or C++. Indeed, many regard Rust as a successor to, or a replacement for, C/C++. Although Rust is designed to be a systems language, due to its richness of constructs, it has a broad range of possible applications, making it an ideal candidate for applications that fall into one or all of the following categories:

Client applications, like browsers

Low-latency, high-performance systems, like device drivers, games and signal processing

Highly distributed and concurrent systems, like server applications and microservices

Real-time and critical systems, like operating systems or kernels

Embedded systems (requiring a very minimal runtime footprint) or resource-constrained environments, like Raspberry Pi and Arduino, or robotics

Tools or services that can't support the long warmup delays common in

just-in-time

(

JIT

) compiler systems and need instantaneous startup

Web frameworks

Large-scale, high-performance, resource intensive, and complex software systems

Rust is especially suitable when code quality is important, that is, for the following:

Modestly-sized or larger development teams

Code for long-running production use

Code with a longer lifetime that requires regular maintenance and refactoring

Code for which you would normally write a lot of unit tests to safeguard

Servo

Mozilla uses Rust as the language for writing Servo, its new web browser engine designed for parallelism and safety (https://servo.org/).

Due to Rust's compiler design, many kinds of browser security bugs are prevented automatically. In 2013, Samsung got involved, porting Servo to Android and ARM processors. Servo is itself an open source project with more than 750 contributors. It is under heavy development, and amongst other parts it already has its own CSS3 and HTML5 parser implemented in Rust. It passed the web compatibility browser test ACID2 in March 2014 (http://en.wikipedia.org/wiki/Acid2/).

Servo currently supports Linux, OS X, Windows, and Android. Parts of Servo are merged into Gecko (the engine on which Firefox is based), thus lending the Servo project's advancements to Firefox.

Installing Rust

You can install the Rust toolchain on every platform that Rust supports by using the rustup installer tool, which you can find at http://www.rust-lang.org/install.html.

On Windows, double-click on the rustup-init.exe file to install the Rust binaries and dependencies. Rust's installation directory (which by default is C:\Users\username\.cargo\bin) is automatically added to the search path for executables. Additionally you may need the C++ build tools for Visual Studio 2013 or later, which you can download from http://landinghub.visualstudio.com/visual-cpp-build-tools.

On Linux and OS X, run the following command in your shell:

curl https://sh.rustup.rs -sSf | sh

This installs the Rust toolchain in /home/username/.cargo/bin by default.

Verify the correctness of the installation by showing Rust's version by typing rustc -V or rustc - -version in a console, which produces output like the following:

Rust can be uninstalled by running the following command:

rustup self uninstall

The rustup tool enables you to easily switch between stable, beta, and nightly compilers and keep them updated. Moreover, it makes cross-compiling simpler with binary builds of the Standard Library for common platforms.

At https://forge.rust-lang.org/platform-support.html is a list of all the platforms on which Rust can run.

A bare metal stack called zinc for running Rust in embedded environments can be found at http://zinc.rs/; at this moment only the ARM architecture is supported.