46,44 €
Become proficient in designing, developing and deploying effective software systems using the advanced constructs of Rust
Key Features
Book Description
Rust is an empowering language that provides a rare combination of safety, speed, and zero-cost abstractions. Mastering Rust – Second Edition is filled with clear and simple explanations of the language features along with real-world examples, showing you how you can build robust, scalable, and reliable programs.
This second edition of the book improves upon the previous one and touches on all aspects that make Rust a great language. We have included the features from latest Rust 2018 edition such as the new module system, the smarter compiler, helpful error messages, and the stable procedural macros. You'll learn how Rust can be used for systems programming, network programming, and even on the web. You'll also learn techniques such as writing memory-safe code, building idiomatic Rust libraries, writing efficient asynchronous networking code, and advanced macros. The book contains a mix of theory and hands-on tasks so you acquire the skills as well as the knowledge, and it also provides exercises to hammer the concepts in.
After reading this book, you will be able to implement Rust for your enterprise projects, write better tests and documentation, design for performance, and write idiomatic Rust code.
What you will learn
Who this book is for
The book is aimed at beginner and intermediate programmers who already have familiarity with any imperative language and have only heard of Rust as a new language. If you are a developer who wants to write robust, efficient and maintainable software systems and want to become proficient with Rust, this book is for you. It starts by giving a whirlwind tour of the important concepts of Rust and covers advanced features of the language in subsequent chapters using code examples that readers will find useful to advance their knowledge.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 688
Veröffentlichungsjahr: 2019
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: Richa TripathiAcquisition Editor: Denim PintoContent Development Editor: Anugraha ArunagiriTechnical Editor: Aniket IswalkarCopy Editor: Safis EditingProject Coordinator: Ulhas KambaliProofreader: Safis EditingIndexer: Rekha NairGraphics: Tom ScariaProduction Coordinator: Nilesh Mohite
First published: May 2017
Second published: January 2019
Production reference: 1310119
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78934-657-2
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,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.
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
Mapt is fully searchable
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.
Rahul Sharma is passionately curious about teaching programming. He has been writing software for the last two years. He got started with Rust with his work on Servo, a browser engine by Mozilla Research as part of his GSoC project. At present, he works at AtherEnergy, where he is building resilient cloud infrastructure for smart scooters. His interests include systems programming, distributed systems, compilers and type theory. He is also an occasional contributor to the Rust language and does mentoring of interns on the Servo project by Mozilla.
Vesa Kaihlavirta has been programming since he was five, beginning with C64 Basic. His main professional goal in life is to increase awareness of programming languages and software quality in all industries that use software. He's an Arch Linux Developer Fellow, and has been working in the telecom and financial industry for a decade. Vesa lives in Jyvaskyla, central Finland.
Gaurav Aroraa has an M.Phil in computer science. He is a Microsoft MVP; a lifetime member of Computer Society of India; an advisory member of IndiaMentor; and certified as a Scrum trainer/coach, XEN for ITIL-F, and APMG for PRINCE-F and PRINCE-P. He is an open source developer, a contributor to TechNet Wiki, and the founder of Ovatic Systems Private Limited. In over 20 years of his career, he has mentored thousands of students and industry professionals. You can tweet Gaurav on his Twitter handle at @g_arora.
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.
Title Page
Copyright and Credits
Mastering Rust Second Edition
About Packt
Why subscribe?
Packt.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
Getting the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
Getting Started with Rust
What is Rust and why should you care?
Installing the Rust compiler and toolchain
Using rustup.rs
A tour of the language
Primitive types
Declaring variables and immutability
Functions
Closures
Strings
Conditionals and decision making
Match expressions
Loops
User-defined types
Structs
Enums
Functions and methods on types
Impl blocks on structs
Impl blocks for enums
Modules, imports, and use statements
Collections
Arrays
Tuples
Vectors
Hashmaps
Slices
Iterators
Exercise – fixing the word counter
Summary
Managing Projects with Cargo
Package managers
Modules
Nested modules
File as a module
Directory as module
Cargo and crates
Creating a new Cargo project
Cargo and dependencies
Running tests with Cargo
Running examples with Cargo
Cargo workspace
Extending Cargo and tools
Subcommands and Cargo installation
cargo-watch
cargo-edit
cargo-deb
cargo-outdated
Linting code with clippy
Exploring the manifest file – Cargo.toml
Setting up a Rust development environment
Building a project with Cargo – imgtool
Summary
Tests, Documentation, and Benchmarks
Motivation for testing
Organizing tests
Testing primitives
Attributes
Assertion macros
Unit tests
First unit test
Running tests
Isolating test code
Failing tests
Ignoring tests
Integration tests
First integration test
Sharing common code
Documentation
Writing documentation
Generating and viewing documentation
Hosting documentation
Doc attributes
Documentation tests
Benchmarks
Built-in micro-benchmark harness
Benchmarking on stable Rust
Writing and testing a crate – logic gate simulator
Continuous integration with Travis CI
Summary
Types, Generics, and Traits
Type systems and why they matter
Generics
Creating generic types
Generic functions
Generic types
Generic implementations
Using generics
Abstracting behavior with traits
Traits
The many forms of traits
Marker traits
Simple traits
Generic traits
Associated type traits
Inherited traits
Using traits with generics – trait bounds
Trait bounds on types
Trait bounds on generic functions and impl blocks
Using + to compose traits as bounds
Trait bounds with impl trait syntax
Exploring standard library traits
True polymorphism using trait objects
Dispatch
Trait objects
Summary
Memory Management and Safety
Programs and memory
How do programs use memory?
Memory management and its kinds
Approaches to memory allocation
The stack
The heap
Memory management pitfalls
Memory safety
Trifecta of memory safety
Ownership
A brief on scopes
Move and copy semantics
Duplicating types via traits
Copy
Clone
Ownership in action
Borrowing
Borrowing rules
Borrowing in action
Method types based on borrowing
Lifetimes
Lifetime parameters
Lifetime elision and the rules
Lifetimes in user defined types
Lifetime in impl blocks
Multiple lifetimes
Lifetime subtyping
Specifying lifetime bounds on generic types
Pointer types in Rust
References – safe pointers
Raw pointers
Smart pointers
Drop
Deref and DerefMut
Types of smart pointers
Box<T>
Reference counted smart pointers
Rc<T>
Interior mutability
Cell<T>
RefCell<T>
Uses of interior mutability
Summary
Error Handling
Error handling prelude
Recoverable errors
Option
Result
Combinators on Option/Result
Common combinators
Using combinators
Converting between Option and Result
Early returns and the ? operator
Non-recoverable errors
User-friendly panics
Custom errors and the Error trait
Summary
Advanced Concepts
Type system tidbits
Blocks and expressions
Let statements
Loop as an expression
Type clarity and sign distinction in numeric types
Type inference
Type aliases
Strings
Owned strings – String
Borrowed strings – &str
Slicing and dicing strings
Using strings in functions
Joining strings
When to use &str versus String ?
Global values
Constants
Statics
Compile time functions – const fn
Dynamic statics using the lazy_static! macro
Iterators
Implementing a custom iterator
Advanced types
Unsized types
Function types
Never type ! and diverging functions
Unions
Cow
Advanced traits
Sized and ?Sized
Borrow and AsRef
ToOwned
From and Into
Trait objects and object safety
Universal function call syntax
Trait rules
Closures in depth
Fn closures
FnMut closures
FnOnce closures
Consts in structs, enums, and traits
Modules, paths, and imports
Imports
Re-exports
Selective privacy
Advanced match patterns and guards
Match guards
Advanced let destructure
Casting and coercion
Types and memory
Memory alignment
Exploring the std::mem module
Serialization and deserialization using serde
Summary
Concurrency
Program execution models
Concurrency
Approaches to concurrency
Kernel-based
User-level
Pitfalls
Concurrency in Rust
Thread basics
Customizing threads
Accessing data from threads
Concurrency models with threads
Shared state model
Shared ownership with Arc
Mutating shared data from threads
Mutex
Shared mutability with Arc and Mutex
RwLock
Communicating through message passing
Asynchronous channels
Synchronous channels
thread-safety in Rust
What is thread-safety?
Traits for thread-safety
Send
Sync
Concurrency using the actor model
Other crates
Summary
Metaprogramming with Macros
What is metaprogramming?
When to use and not use Rust macros
Macros in Rust and their types
Types of macros
Creating your first macro with macro_rules!
Built-in macros in the standard library
macro_rules! token types
Repetitions in macros
A more involved macro – writing a DSL for HashMap initialization
Macro use case – writing tests
Exercises
Procedural macros
Derive macros
Debugging macros
Useful procedural macro crates
Summary
Unsafe Rust and Foreign Function Interfaces
What is safe and unsafe really?
Unsafe functions and blocks
Unsafe traits and implementations
Calling C code from Rust
Calling Rust code from C
Using external C/C++ libraries from Rust
Creating native Python extensions with PyO3
Creating native extensions in Rust for Node.js
Summary
Logging
What is logging and why do we need it?
The need for logging frameworks
Logging frameworks and their key features
Approaches to logging
Unstructured logging
Structured logging
Logging in Rust
log – Rust's logging facade
The env_logger
log4rs
Structured logging using slog
Summary
Network Programming in Rust
Network programming prelude
Synchronous network I/O
Building a synchronous redis server
Asynchronous network I/O
Async abstractions in Rust
Mio
Futures
Tokio
Building an asynchronous redis server
Summary
Building Web Applications with Rust
Web applications in Rust
Typed HTTP with Hyper
Hyper server APIs – building a URL shortener 
hyper as a client – building a URL shortener client
Web frameworks
Actix-web basics
Building a bookmarks API using Actix-web
Summary
Interacting with Databases in Rust
Why do we need data persistence?
SQLite
PostgreSQL
Connection pooling with r2d2
Postgres and the diesel ORM
Summary
Rust on the Web with WebAssembly
What is WebAssembly?
Design goals of WebAssembly
Getting started with WebAssembly
Trying it out online
Ways to generate WebAssembly
Rust and WebAssembly
Wasm-bindgen
Other WebAssembly projects
Rust
Other languages
Summary
Building Desktop Applications with Rust
Introduction to GUI development
GTK+ framework
Building a hacker news app using gtk-rs
Exercise
Other emerging GUI frameworks
Summary
Debugging
Introduction to debugging
Debuggers in general
Prerequisites for debugging
Setting up gdb
A sample program – buggie
The gdb basics
Debugger integration with Visual Studio Code
RR debugger – a quick overview
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
This book is about Rust, a programming language that empowers you to build all kinds of software systems, ranging from low-level embedded software to dynamic web applications. Rust is fast, reliable, and safe. It offers performance and safety guarantees that reach or even surpass C and C++, while still being a modern language with a relatively low barrier of entry. Rust drive toward incremental improvements, combined with its active and friendly community, promises a great future for the language.
Rust is not a new language by design and doesn't try to reinvent the wheel. Rather, it's a language that has identified unique ideas, hidden away in research-prototype languages that never saw mass adoption. It brings those ideas together into a coherent composition and provides a practical language that lets you build safe software systems, while still being efficient.
This book targets both beginner and intermediate programmers familiar with other imperative languages, but new to Rust. It assumes that you are familiar with at least one imperative programming language, such as C, C++, or Python. Knowing about functional programming is not a requirement, but it's good to have a general idea about it. We make sure to explain any concept or idea that we introduce from these languages, though.
Chapter 1, Getting Started with Rust, gives a brief history on Rust and the motivation behind its design, and covers basic language syntax. The chapter ends with an exercise covering all the language features.
Chapter 2, Managing Projects with Cargo, shows how Rust organizes large projects with its dedicated package manager. This serves as the basis for further chapters. It also covers editor integration with the Visual Studio Code editor.
Chapter 3, Tests, Documentation and Benchmarks, explores the built-in testing harness, writing unit tests, integration tests, and how to write documentation in Rust. We also cover the benchmarking facilities of Rust code. Later, as a final exercise, we build a complete crate with documentation and tests.
Chapter 4, Types, Generics, and Traits, explores Rust's expressive type system and goes on to explain various ways of using the type system by building a complex number library.
Chapter 5, Memory Management and Safety, starts with the motivation for memory management and the various pitfalls in conventional low-level programming languages related to memory. It then moves toward explaining Rust's unique compile-time memory management ideas. We also explain various smart pointer types in Rust.
Chapter 6, Error Handling, starts with the motivation for error handling and explores different models of error handling in other languages. The chapter then examine Rust's error-handling strategy and types, before exploring handling errors in non-recoverable situations. The chapter ends with a library implementing custom error types.
Chapter 7, Advanced Concepts, explores some of the concepts already introduced in previous chapters, in more detail. It provides details on the underlying model of some of the type system abstractions provided by Rust.
Chapter 8, Concurrency, explores Rust's concurrency models and APIs in the standard libraries and teaches you how to build highly concurrent programs with no data races.
Chapter 9, Metaprogramming with Macros, examines how you can write code to generate code using the powerful and advanced macro construct of Rust, and outlines the language's declarative and procedural macros by building both types of macros.
Chapter 10, Unsafe Rust and Foreign Function Interfaces, explores the unsafe mode of Rust and the APIs on offer for interoperating Rust with other languages. The examples includes both calling into Rust from other languages, such as Python, Node.js, and C, as well as covering how Rust can be called from other languages.
Chapter 11, Logging, explains why logging is an important practice in software development, answering why we need logging frameworks, and exploring the crates on offer in the Rust ecosystem that can be used to help integrate logging into the application.
Chapter 12, Network Programming in Rust Sync and Async I/O,gives a brief introduction to network programming. After going through the basics, the chapter covers building a Redis server that can talk to the official Redis client. Lastly, the chapter explains how to use the standard library networking primitives and the Tokio and futures crates.
Chapter 13, Building Web Applications with Rust, starts by exploring the HTTP protocol and builds a simple URL shortener server using the hyper crate, followed by building a URL shortener client using the reqwest crate. In the end, we explore actix-web, a high-performance Async web application framework to build a bookmarks API server.
Chapter 14, Interacting with Databases in Rust, starts with the motivation on the need for database backend applications and moves toward exploring the available crates in the Rust ecosystem to interact with various database backends, such as SQLite and PostgreSQL. The chapter also explores a type-safe ORM crate called diesel. Later, it covers how to integrate our bookmarks API server, built in the previous chapter, to integrate database support using diesel.
Chapter 15, Rust on the Web Using WebAssembly, explains what WebAssembly is and how it can be used by developers. We then move on to exploring the available crates in the Rust ecosystem, and build a live markdown-editor web application using Rust and WebAssembly.
Chapter 16, Building Desktop Applications with Rust, explains how to build desktop applications with Rust using the GTK framework. We'll build a simple hacker-news desktop client.
Chapter 17, Debugging, explores debugging Rust code with GDB and also shows how to integrate GDB with Visual Studio Code editor.
To really grasp the content of this book, it is recommended that you write out the example code and try fiddling with code to get familiar with the Rust's error messages, so they can guide you toward writing correct programs.
There isn't any specific hardware requirements for this book, and any system with a minimum of 1 GB of RAM and a fairly recent Linux operating system would be fine. All code examples and projects in this book were developed on a Linux machine running Ubuntu 16.04. Rust also offers first-class support for other OS platforms, including macOS, BSD, and recent versions of Windows, so all the code examples should compile and run fine on these platforms too.
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.packt.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 & Errata
.
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 athttps://github.com/PacktPublishing/Mastering-RUST-Second-Edition. In case there's an update to the code, it will be updated on the existing GitHub repository. Feel free to raise an issue on GitHub if you find any problems when compiling the code examples.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
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.packt.com/submit-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.
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.
Learning a new language is like building a house – the foundation needs to be strong. With a language that changes the way you think and reason about your code, there's always more effort involved in the beginning, and it's important to be aware of that. The end result, however, is that you get to shift your thinking with these new-found concepts and tools.
This chapter will give you a whirlwind tour on the design philosophy of Rust, an overview of its syntax and the type system. We assume that you have a basic knowledge of mainstream languages such as C, C++, or Python, and the ideas that surround object-oriented programming. Each section will contain example code, along with an explanation of it. There will be ample code examples and output from the compiler, that will help you become familiar with the language. We'll also delve into a brief history of the language and how it continues to evolve.
Getting familiar with a new language requires perseverance, patience, and practice. I highly recommend to all readers that you manually write and don't copy/paste the code examples listed here. The best part of writing and fiddling with Rust code is the precise and helpful error messages you get from the compiler, which the Rust community often likes to call error-driven development. We'll see these errors frequently throughout this book to understand how the compiler thinks of our code.
In this chapter, we will cover the following topics:
What is Rust and why should you care?
Installing the Rust compiler and the toolchain
A brief tour of the language and its syntax
A final exercise, where we'll put what we've learned together
The Rust toolchain has two major components: the compiler, rustc, and the package manager, cargo, which helps manage Rust projects. The toolchain comes in three release channels:
Nightly
: The daily successful build from the master development branch. This contains all the latest features, many of which are unstable.
Beta
: This is released every six weeks. A new beta branch is taken from nightly. It contains only features that are flagged as stable.
Stable
: This is released every six weeks. The previous beta branch becomes the new stable release.
Developers are encouraged to use the stable release channel. However, the nightly version enables bleeding edge features, and some libraries and programs require it. You can change to the nightly toolchain easily with rustup. We'll see how we can do that in a moment.
Rustup is a tool to that installs the Rust compiler on all supported platforms. To make it easier for developers on different platforms to download and use the language, the Rust team developed rustup. It's a command-line tool written in Rust that provides an easy way to install pre-built binaries of the compiler and binary builds of the standard library for cross compiling needs. It can also install other components, such as the Rust source code, documentation, Rust formatting tool (rustfmt), Rust Language Server (RLS for IDEs), and other developer tools, and it runs on all platforms, including Windows.
From their official page at https://rustup.rs, the recommended way to install the toolchain is to run the following command:
curl https://sh.rustup.rs -sSf | sh
By default, the installer installs the stable version of the Rust compiler, its package manager, Cargo, and the language's standard library documentation so that it can be viewed offline. These are installed by default under the ~/.cargo directory. Rustup also updates your PATH environment variable to point to this directory.
The following is a screenshot of running the preceding command on Ubuntu 16.04:
Rust has the following built-in primitive types:
bool
: These are the usual booleans and can be either
true
or
false
.
char
: Characters, such as
e
.
Integer types: These are characterized by the bit width. Rust supports integers that are up to 128 bits wide:
signed
unsigned
i8
u8
i16
u16
i32
u32
i64
u64
i128
u128
isize
: The pointer-sized signed integer type. Equivalent to
i32
on 32-bit CPU and
i64
on 64-bit CPU.
usize
: The pointer-sized unsigned integer type. Equivalent to
i32
on 32-bit CPU and
i64
on 64-bit CPU.
f32
: The 32-bit floating point type. Implements the IEEE 754 standard for floating point representation.
f64
: The 64-bit floating point type.
[T; N]
: A fixed-size array, for the element type,
T
, and the non-negative compile-time constant size N.
[T]
: A dynamically-sized view into a contiguous sequence, for any type
T
.
str
: String slices, mainly used as a reference, that is,
&str
.
(T, U, ..)
: A finite sequence, (T, U, ..) where T and U can be different types.
fn(i32) -> i32
: A function that takes an
i32
and returns an
i32
. Functions also have a type.