The Rust Programming Language (Covers Rust 2018)

The Rust Programming Language (Covers Rust 2018)

by Steve Klabnik and Carol Nichols
August 2019, 526 pp.
ISBN-13: 
9781718500440

Look Inside!

The Rust Programming Language (Covers Rust 2018)The Rust Programming Language (Covers Rust 2018)The Rust Programming Language (Covers Rust 2018)The Rust Programming Language (Covers Rust 2018)The Rust Programming Language (Covers Rust 2018)

Download Chapter 2: Programming a Guessing Game

The Rust Programming Language is the official book on Rust: an open source systems programming language that helps you write faster, more reliable software. Rust offers control over low-level details (such as memory usage) in combination with high-level ergonomics, eliminating the hassle traditionally associated with low-level languages.

The authors of The Rust Programming Language, members of the Rust Core Team, share their knowledge and experience to show you how to take full advantage of Rust’s features—from installation to creating robust and scalable programs. You’ll begin with basics like creating functions, choosing data types, and binding variables and then move on to more advanced concepts, such as:

  • Ownership and borrowing, lifetimes, and traits
  • Using Rust’s memory safety guarantees to build fast, safe programs
  • Testing, error handling, and effective refactoring
  • Generics, smart pointers, multithreading, trait objects, and advanced pattern matching
  • Using Cargo, Rust’s built-in package manager, to build, test, and document your code and manage dependencies
  • How best to use Rust’s advanced compiler with compiler-led programming techniques

You’ll find plenty of code examples throughout the book, as well as three chapters dedicated to building complete projects to test your learning: a number guessing game, a Rust implementation of a command line tool, and a multithreaded server.

New to this edition: An extended section on Rust macros, an expanded chapter on modules, and appendixes on Rust development tools and editions.

Author Bio 

Steve Klabnik leads the Rust documentation team and is one of Rust’s core developers. A frequent speaker and prolific open source contributor, he previously worked on projects such as Ruby and Ruby on Rails. Klabnik works at Mozilla.

Carol Nichols is a member of the Rust Core Team and co-founder of Integer 32, LLC, the world’s first Rustfocused software consultancy. Nichols organizes the Rust Belt Rust Conference.

Table of contents 

Foreword
Acknowledgments
Introduction

Chapter 1: Getting Started
Chapter 2: Programming a Guessing Game
Chapter 3: Common Programming Concepts
Chapter 4: Understanding Ownership
Chapter 5: Using Structs to Structure Related Data
Chapter 6: Enums and Pattern Matching
Chapter 7: Managing Growing Projects with Packages, Crates, and Modules
Chapter 8: Common Collections
Chapter 9: Error Handling
Chapter 10: Generic Types, Traits, and Lifetimes
Chapter 11: Writing Automated Tests
Chapter 12: An I/O Project: Building a Command Line Program
Chapter 13: Functional Language Features: Iterators and Closures
Chapter 14: More About Cargo and Crates.io
Chapter 15: Smart Pointers
Chapter 16: Fearless Concurrency
Chapter 17: Object-Oriented Programming Features of Rust
Chapter 18: Patterns and Matching
Chapter 19: Advanced Features
Chapter 20: Final Project: Building a Multithreaded Web Server

View the detailed Table of Contents
View the Index

Reviews 

Check out this interview in Nature with co-author Carol Nichols on why scientists are turning to the Rust programming language.

"Covers everything you could want to know about the language."
Stack Overflow

"The book . . . provides information on how developers can get started with Rust."
—Tiera Oliver, Embedded Computing Design

Updates 

Page xxi: "Rust 1.41.0" should now read "Rust 1.53.0"

Page xxviii: "appendixes" should now read "appendices"

Page 3: The lines:
The easiest way to acquire the build tools is to install Build Tools for Visual Studio 2019 at https://www.visualstudio.com/downloads/#build-tools-for-visual-studio-2019. The tools are in the Other Tools and Frameworks section.

Should now read: https://visualstudio.microsoft.com/visual-cpp-build-tools/

Page 6: The first paragraph, "At the time of this writing…on your computer!" has been replaced with the following:
If you want to stick to a standard style across Rust projects, you can use an automatic formatter tool called rustfmt to format your code in a particular style. The Rust team has included this tool with the standard Rust distribution, like rustc, so it should already be installed on your computer!

Page 18: In the first code block with the cargo run output:
warning: unused 'std::result::Result' which must be used
should now read:
warning: unused 'Result' which must be used

Page 42: The third code block should now read:

fn main() {
let a = [1, 2, 3, 4, 5];
let first = a[0];
}

The line "The variable named second will get the value 2 from index [1] in the array." was deleted.

The first paragraph under "Invalid Array Element Access" was changed to "Consider this example that uses code similar to the guessing game in Chapter 2 to ask the user to enter an array index:"

The last code block on the page should now read:

use std::io;
fn main() {
let a = [1, 2, 3, 4, 5];
println!("Please enter an array index.");
let mut index = String::new();
io::stdin().read_line(&mut index).expect("Failed to read line");
let index: usize = index.trim().parse().expect(""Not a number");
let element = a[index];
println!(
""The value of the element at index {} is: {}"",
index, element
);
}

Page 43: The first line should now read:
This code compiles successfully. If you run this code using cargo run and enter 0, 1, 2, 3, or 4, the program will print out the corresponding value at that index in the array. If you instead enter a number past the end of the array, such as 10, you'll see output like this:

In the first code block, change the content to:

thread 'main' panicked at 'index out of bounds: the len is 5 but the index is 10', src/main.rs:12:19

The second paragraph should now read:
The program resulted in a runtime error at the point of using an invalid value in the indexing operation. The program exited with an error message and didn't execute the final println! statement. When you attempt to access an element using indexing, Rust will check that the index you’ve specified is less than the array length. If the index is greater than or equal to the length, Rust will panic. This check has to happen at runtime, especially in this case, because the compiler can't possibly know what value a user will enter when they run the code later.

Page 78: In Figure 4-6, in the "s" table, the two instances of "5" should now be "11"

Page 156: In the last code block with the error output:
expected u32, found enum 'std::result::Result'
should now read:
expected u32, found enum 'Result'
and:
found type 'std::result::Result<:fs::file std::io::error="">'
should now read:
found type 'Result<:fs::file std::io::error="">'

Page 205: The following sentence in the last paragraph:
Chapter 19 covers more complex scenarios involving lifetime annotations as well as some advanced type system features"

Should now read:
There are also more complex scenarios involving lifetime annotations that you will only need in very advanced scenarios; for those, see the reference at https://doc.rust-lang.org/stable/reference/trait-bounds.html#lifetime-bo....

Page 248: In the first code block with the warning:
warning: unused 'std::result::Result' that must be used
should now read:
warning: unused 'Result' that must be used

Page 341: Figure 15-4 was replaced

Pages: 398-399: The line:
The first call to enumerate produces the
type (0, 'a')
.
Should now read:
The first value produced is the tuple (0, 'a').

Page 411: In the last sentence of the first paragraph: "but when we run this code" should now read: "but when we compile this code"

Page 459: the following line:
We’ve chosen this port for two reasons: HTTP is normally accepted on this port, and 7878 is rust typed on a telephone.

Should now read:
We’ve chosen this port for two reasons: HTTP isn't normally accepted on this port, and 7878 is rust typed on a telephone.

And "1024" should now read "1023"

Page 461: in Listing 20-2, "512" should be changed to "1024"

In the third paragraph, we changed "512" to "1024"

Page 463: in Listing 2-3, we changed "512" to "1024"

Page 464: in Listing 205, we changed "512" to "1024"
Listing 20-5 should now read:

use std::fs;
// --snip--
fn handle_connection(mut stream: TcpStream) {
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
let contents = fs::read_to_string("hello.html").unwrap();
let response = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}",
contents.len(), contents
);
stream.write(response.as_bytes()).unwrap();
// --snip--

The last line on the page should now read:
Next, we use format! to include a Content-Length header and the file's contents in the response .

Page 465: Listing 20-6, should now read:

// --snip--
fn handle_connection(mut stream: TcpStream) {
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
let get = b"GET / HTTP/1.1\r\n";
if buffer.starts_with(get) {
let contents = fs::read_to_string(«hello.html»).unwrap();
// --snip--
stream.flush().unwrap();
} else {
// some other request
}
}

Page 466: Listing 20-7 should now read:
// --snip--
} else {
1 let status_line = "HTTP/1.1 404 NOT FOUND";
2 let contents = fs::read_to_string("404.html").unwrap();
let response = format!(
"{}\r\nContent-Length: {}\r\n\r\n{}",
status_line, contents.len(), contents
);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
}

The Listing 20-7 caption should now read:
Responding to any other request with status code 404 and an error page

The line:
We’re still not returning headers, and the body of the response will be the HTML in the file 404.html .

Should now read:
The body of the response will be the HTML in the file 404.html .

Page 467: in Listing 20-9, we deleted the two instances of: \r\n\r\n

We replaced the tenth code line, "let response…" with:

let response = format!(
"{}\r\nContent-Length: {}\r\n\r\n{}",
status_line, contents.len(), contents
);

The Listing 20-9 caption should now read:
Refactoring the if and else blocks to contain only the code that differs

Page 468: We deleted the three instances of \r\n\r\n in Listing 20-10

Page 522: Between "method syntax" and "M:N threading model" we added an entry for "minigrep project, 233–262"

Page 526: Between "Weak type" and "where clause" we added an entry for "web server project, 457–493"