>];
edge[tailclip="false"];
table0:ptr0:c -> table1:pte0;
table1:ptr1:c -> table2:pte1;
table2:ptr2:c -> table3:pte2;
table4:ptr4:c -> table5:pte4;
table5:ptr5:c -> table1:pte0;
table6:ptr6:c -> table7:pte6;
table7:ptr7:c -> table1:pte0;
}
================================================
FILE: 2018-edition/ferris.css
================================================
body.light .does_not_compile,
body.light .panics,
body.light .not_desired_behavior,
body.rust .does_not_compile,
body.rust .panics,
body.rust .not_desired_behavior {
background: #fff1f1;
}
body.coal .does_not_compile,
body.coal .panics,
body.coal .not_desired_behavior,
body.navy .does_not_compile,
body.navy .panics,
body.navy .not_desired_behavior,
body.ayu .does_not_compile,
body.ayu .panics,
body.ayu .not_desired_behavior {
background: #501f21;
}
.ferris {
position: absolute;
z-index: 99;
right: 5px;
top: 30px;
width: 10%;
height: auto;
}
.ferris-explain {
width: 100px;
}
================================================
FILE: 2018-edition/ferris.js
================================================
var ferrisTypes = [
{
attr: 'does_not_compile',
title: 'This code does not compile!'
},
{
attr: 'panics',
title: 'This code panics!'
},
{
attr: 'unsafe',
title: 'This code block contains unsafe code.'
},
{
attr: 'not_desired_behavior',
title: 'This code does not produce the desired behavior.'
}
]
document.addEventListener('DOMContentLoaded', () => {
for (var ferrisType of ferrisTypes) {
attachFerrises(ferrisType)
}
})
function attachFerrises (type) {
var elements = document.getElementsByClassName(type.attr)
for (var codeBlock of elements) {
var lines = codeBlock.textContent.split(/\r|\r\n|\n/).length - 1;
if (lines >= 4) {
attachFerris(codeBlock, type)
}
}
}
function attachFerris (element, type) {
var a = document.createElement('a')
a.setAttribute('href', 'ch00-00-introduction.html#ferris')
a.setAttribute('target', '_blank')
var img = document.createElement('img')
img.setAttribute('src', 'img/ferris/' + type.attr + '.svg')
img.setAttribute('title', type.title)
img.className = 'ferris'
a.appendChild(img)
element.parentElement.insertBefore(a, element)
}
================================================
FILE: 2018-edition/src/SUMMARY.md
================================================
# The Rust Programming Language
[Foreword](foreword.md)
[Introduction](ch00-00-introduction.md)
## Getting started
- [Getting Started](ch01-00-getting-started.md)
- [Installation](ch01-01-installation.md)
- [Hello, World!](ch01-02-hello-world.md)
- [Hello, Cargo!](ch01-03-hello-cargo.md)
- [Programming a Guessing Game](ch02-00-guessing-game-tutorial.md)
- [Common Programming Concepts](ch03-00-common-programming-concepts.md)
- [Variables and Mutability](ch03-01-variables-and-mutability.md)
- [Data Types](ch03-02-data-types.md)
- [How Functions Work](ch03-03-how-functions-work.md)
- [Comments](ch03-04-comments.md)
- [Control Flow](ch03-05-control-flow.md)
- [Understanding Ownership](ch04-00-understanding-ownership.md)
- [What is Ownership?](ch04-01-what-is-ownership.md)
- [References & Borrowing](ch04-02-references-and-borrowing.md)
- [Slices](ch04-03-slices.md)
- [Using Structs to Structure Related Data](ch05-00-structs.md)
- [Defining and Instantiating Structs](ch05-01-defining-structs.md)
- [An Example Program Using Structs](ch05-02-example-structs.md)
- [Method Syntax](ch05-03-method-syntax.md)
- [Enums and Pattern Matching](ch06-00-enums.md)
- [Defining an Enum](ch06-01-defining-an-enum.md)
- [The `match` Control Flow Operator](ch06-02-match.md)
- [Concise Control Flow with `if let`](ch06-03-if-let.md)
## Basic Rust Literacy
- [Packages, Crates, and Modules](ch07-00-packages-crates-and-modules.md)
- [Packages and crates for making libraries and executables](ch07-01-packages-and-crates-for-making-libraries-and-executables.md)
- [Modules and `use` to control scope and privacy](ch07-02-modules-and-use-to-control-scope-and-privacy.md)
- [Common Collections](ch08-00-common-collections.md)
- [Vectors](ch08-01-vectors.md)
- [Strings](ch08-02-strings.md)
- [Hash Maps](ch08-03-hash-maps.md)
- [Error Handling](ch09-00-error-handling.md)
- [Unrecoverable Errors with `panic!`](ch09-01-unrecoverable-errors-with-panic.md)
- [Recoverable Errors with `Result`](ch09-02-recoverable-errors-with-result.md)
- [To `panic!` or Not to `panic!`](ch09-03-to-panic-or-not-to-panic.md)
- [Generic Types, Traits, and Lifetimes](ch10-00-generics.md)
- [Generic Data Types](ch10-01-syntax.md)
- [Traits: Defining Shared Behavior](ch10-02-traits.md)
- [Validating References with Lifetimes](ch10-03-lifetime-syntax.md)
- [Testing](ch11-00-testing.md)
- [Writing tests](ch11-01-writing-tests.md)
- [Running tests](ch11-02-running-tests.md)
- [Test Organization](ch11-03-test-organization.md)
- [An I/O Project: Building a Command Line Program](ch12-00-an-io-project.md)
- [Accepting Command Line Arguments](ch12-01-accepting-command-line-arguments.md)
- [Reading a File](ch12-02-reading-a-file.md)
- [Refactoring to Improve Modularity and Error Handling](ch12-03-improving-error-handling-and-modularity.md)
- [Developing the Library’s Functionality with Test Driven Development](ch12-04-testing-the-librarys-functionality.md)
- [Working with Environment Variables](ch12-05-working-with-environment-variables.md)
- [Writing Error Messages to Standard Error Instead of Standard Output](ch12-06-writing-to-stderr-instead-of-stdout.md)
## Thinking in Rust
- [Functional Language Features: Iterators and Closures](ch13-00-functional-features.md)
- [Closures: Anonymous Functions that Can Capture Their Environment](ch13-01-closures.md)
- [Processing a Series of Items with Iterators](ch13-02-iterators.md)
- [Improving Our I/O Project](ch13-03-improving-our-io-project.md)
- [Comparing Performance: Loops vs. Iterators](ch13-04-performance.md)
- [More about Cargo and Crates.io](ch14-00-more-about-cargo.md)
- [Customizing Builds with Release Profiles](ch14-01-release-profiles.md)
- [Publishing a Crate to Crates.io](ch14-02-publishing-to-crates-io.md)
- [Cargo Workspaces](ch14-03-cargo-workspaces.md)
- [Installing Binaries from Crates.io with `cargo install`](ch14-04-installing-binaries.md)
- [Extending Cargo with Custom Commands](ch14-05-extending-cargo.md)
- [Smart Pointers](ch15-00-smart-pointers.md)
- [`Box` Points to Data on the Heap and Has a Known Size](ch15-01-box.md)
- [The `Deref` Trait Allows Access to the Data Through a Reference](ch15-02-deref.md)
- [The `Drop` Trait Runs Code on Cleanup](ch15-03-drop.md)
- [`Rc`, the Reference Counted Smart Pointer](ch15-04-rc.md)
- [`RefCell` and the Interior Mutability Pattern](ch15-05-interior-mutability.md)
- [Creating Reference Cycles and Leaking Memory is Safe](ch15-06-reference-cycles.md)
- [Fearless Concurrency](ch16-00-concurrency.md)
- [Threads](ch16-01-threads.md)
- [Message Passing](ch16-02-message-passing.md)
- [Shared State](ch16-03-shared-state.md)
- [Extensible Concurrency: `Sync` and `Send`](ch16-04-extensible-concurrency-sync-and-send.md)
- [Object Oriented Programming Features of Rust](ch17-00-oop.md)
- [Characteristics of Object-Oriented Languages](ch17-01-what-is-oo.md)
- [Using Trait Objects that Allow for Values of Different Types](ch17-02-trait-objects.md)
- [Implementing an Object-Oriented Design Pattern](ch17-03-oo-design-patterns.md)
## Advanced Topics
- [Patterns Match the Structure of Values](ch18-00-patterns.md)
- [All the Places Patterns May be Used](ch18-01-all-the-places-for-patterns.md)
- [Refutability: Whether a Pattern Might Fail to Match](ch18-02-refutability.md)
- [All the Pattern Syntax](ch18-03-pattern-syntax.md)
- [Advanced Features](ch19-00-advanced-features.md)
- [Unsafe Rust](ch19-01-unsafe-rust.md)
- [Advanced Lifetimes](ch19-02-advanced-lifetimes.md)
- [Advanced Traits](ch19-03-advanced-traits.md)
- [Advanced Types](ch19-04-advanced-types.md)
- [Advanced Functions & Closures](ch19-05-advanced-functions-and-closures.md)
- [Macros](ch19-06-macros.md)
- [Final Project: Building a Multithreaded Web Server](ch20-00-final-project-a-web-server.md)
- [A Single Threaded Web Server](ch20-01-single-threaded.md)
- [Turning our Single Threaded Server into a Multithreaded Server](ch20-02-multithreaded.md)
- [Graceful Shutdown and Cleanup](ch20-03-graceful-shutdown-and-cleanup.md)
- [Appendix](appendix-00.md)
- [A - Keywords](appendix-01-keywords.md)
- [B - Operators and Symbols](appendix-02-operators.md)
- [C - Derivable Traits](appendix-03-derivable-traits.md)
- [D - Useful Development Tools](appendix-04-useful-development-tools.md)
- [E - Editions](appendix-05-editions.md)
- [F - Translations](appendix-06-translation.md)
- [G - How Rust is Made and “Nightly Rust”](appendix-07-nightly-rust.md)
================================================
FILE: 2018-edition/src/appendix-00.md
================================================
# Appendix
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../appendix-00.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/appendix-00.html).
================================================
FILE: 2018-edition/src/appendix-01-keywords.md
================================================
## Appendix A: Keywords
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../appendix-01-keywords.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/appendix-01-keywords.html).
================================================
FILE: 2018-edition/src/appendix-02-operators.md
================================================
## Appendix B: Operators and Symbols
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../appendix-02-operators.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/appendix-02-operators.html).
================================================
FILE: 2018-edition/src/appendix-03-derivable-traits.md
================================================
## Appendix C: Derivable Traits
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../appendix-03-derivable-traits.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/appendix-03-derivable-traits.html).
================================================
FILE: 2018-edition/src/appendix-04-useful-development-tools.md
================================================
# Appendix D - Useful Development Tools
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../appendix-04-useful-development-tools.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/appendix-04-useful-development-tools.html).
================================================
FILE: 2018-edition/src/appendix-05-editions.md
================================================
# Appendix E - Editions
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../appendix-05-editions.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/appendix-05-editions.html).
================================================
FILE: 2018-edition/src/appendix-06-translation.md
================================================
## Appendix F: Translations of the Book
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../appendix-06-translation.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/appendix-06-translation.html).
================================================
FILE: 2018-edition/src/appendix-07-nightly-rust.md
================================================
# Appendix G - How Rust is Made and “Nightly Rust”
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../appendix-07-nightly-rust.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/appendix-07-nightly-rust.html).
================================================
FILE: 2018-edition/src/ch00-00-introduction.md
================================================
# Introduction
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch00-00-introduction.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch00-00-introduction.html).
================================================
FILE: 2018-edition/src/ch01-00-getting-started.md
================================================
# Getting Started
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch01-00-getting-started.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch10-00-getting-started.html).
================================================
FILE: 2018-edition/src/ch01-01-installation.md
================================================
## Installation
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch01-01-installation.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch01-01-installation.html).
================================================
FILE: 2018-edition/src/ch01-02-hello-world.md
================================================
## Hello, World!
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch01-02-hello-world.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch01-02-hello-world.html).
================================================
FILE: 2018-edition/src/ch01-03-hello-cargo.md
================================================
## Hello, Cargo!
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch01-03-hello-cargo.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch01-03-hello-cargo.html).
================================================
FILE: 2018-edition/src/ch02-00-guessing-game-tutorial.md
================================================
# Programming a Guessing Game
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch02-00-guessing-game-tutorial.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch02-00-guessing-game-tutorial.html).
================================================
FILE: 2018-edition/src/ch03-00-common-programming-concepts.md
================================================
# Common Programming Concepts
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch03-00-common-programming-concepts.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch03-00-common-programming-concepts.html).
================================================
FILE: 2018-edition/src/ch03-01-variables-and-mutability.md
================================================
## Variables and Mutability
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch03-01-variables-and-mutability.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch03-01-variables-and-mutability.html).
================================================
FILE: 2018-edition/src/ch03-02-data-types.md
================================================
## Data Types
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch03-02-data-types.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch03-02-data-types.html).
================================================
FILE: 2018-edition/src/ch03-03-how-functions-work.md
================================================
## Functions
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch03-03-how-functions-work.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch03-03-how-functions-work.html).
================================================
FILE: 2018-edition/src/ch03-04-comments.md
================================================
## Comments
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch03-04-comments.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch03-04-comments.html).
================================================
FILE: 2018-edition/src/ch03-05-control-flow.md
================================================
## Control Flow
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch03-05-control-flow.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch03-05-control-flow.html).
================================================
FILE: 2018-edition/src/ch04-00-understanding-ownership.md
================================================
# Understanding Ownership
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch04-00-understanding-ownership.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch04-00-understanding-ownership.html).
================================================
FILE: 2018-edition/src/ch04-01-what-is-ownership.md
================================================
## What Is Ownership?
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch04-01-what-is-ownership.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch04-01-what-is-ownership.html).
================================================
FILE: 2018-edition/src/ch04-02-references-and-borrowing.md
================================================
## References and Borrowing
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch04-02-references-and-borrowing.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch04-02-references-and-borrowing.html).
================================================
FILE: 2018-edition/src/ch04-03-slices.md
================================================
## The Slice Type
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch04-03-slices.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch04-03-slices.html).
================================================
FILE: 2018-edition/src/ch05-00-structs.md
================================================
# Using Structs to Structure Related Data
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch05-00-structs.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch05-00-structs.html).
================================================
FILE: 2018-edition/src/ch05-01-defining-structs.md
================================================
## Defining and Instantiating Structs
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch05-01-defining-structs.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch05-01-defining-structs.html).
================================================
FILE: 2018-edition/src/ch05-02-example-structs.md
================================================
## An Example Program Using Structs
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch05-02-example-structs.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch05-02-example-structs.html).
================================================
FILE: 2018-edition/src/ch05-03-method-syntax.md
================================================
## Method Syntax
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch05-03-method-syntax.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch05-03-method-syntax.html).
================================================
FILE: 2018-edition/src/ch06-00-enums.md
================================================
# Enums and Pattern Matching
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch06-00-enums.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch06-00-enums.html).
================================================
FILE: 2018-edition/src/ch06-01-defining-an-enum.md
================================================
## Defining an Enum
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch06-01-defining-an-enum.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch06-01-defining-an-enum.html).
================================================
FILE: 2018-edition/src/ch06-02-match.md
================================================
## The `match` Control Flow Operator
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch06-02-match.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch06-02-match.html).
================================================
FILE: 2018-edition/src/ch06-03-if-let.md
================================================
## Concise Control Flow with `if let`
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch06-03-if-let.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch06-03-if-let.html).
================================================
FILE: 2018-edition/src/ch07-00-packages-crates-and-modules.md
================================================
# Packages, Crates, and Modules
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../index.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch07-00-packages-crates-and-modules.html).
================================================
FILE: 2018-edition/src/ch07-01-packages-and-crates-for-making-libraries-and-executables.md
================================================
## Packages and Crates for Making Libraries and Executables
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../index.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch07-01-packages-and-crates-for-making-libraries-and-executables.html).
================================================
FILE: 2018-edition/src/ch07-02-modules-and-use-to-control-scope-and-privacy.md
================================================
## The Module System to Control Scope and Privacy
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../index.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch07-02-modules-and-use-to-control-scope-and-privacy.html).
================================================
FILE: 2018-edition/src/ch08-00-common-collections.md
================================================
# Common Collections
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch08-00-common-collections.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch08-00-common-collections.html).
================================================
FILE: 2018-edition/src/ch08-01-vectors.md
================================================
## Storing Lists of Values with Vectors
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch08-01-vectors.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch08-01-vectors.html).
================================================
FILE: 2018-edition/src/ch08-02-strings.md
================================================
## Storing UTF-8 Encoded Text with Strings
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch08-02-strings.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch08-02-strings.html).
================================================
FILE: 2018-edition/src/ch08-03-hash-maps.md
================================================
## Storing Keys with Associated Values in Hash Maps
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch08-03-hash-maps.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch08-03-hash-maps.html).
================================================
FILE: 2018-edition/src/ch09-00-error-handling.md
================================================
# Error Handling
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch09-00-error-handling.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch09-00-error-handling.html).
================================================
FILE: 2018-edition/src/ch09-01-unrecoverable-errors-with-panic.md
================================================
## Unrecoverable Errors with `panic!`
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch09-01-unrecoverable-errors-with-panic.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch09-01-unrecoverable-errors-with-panic.html).
================================================
FILE: 2018-edition/src/ch09-02-recoverable-errors-with-result.md
================================================
## Recoverable Errors with `Result`
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch09-02-recoverable-errors-with-result.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch09-02-recoverable-errors-with-result.html).
================================================
FILE: 2018-edition/src/ch09-03-to-panic-or-not-to-panic.md
================================================
## To `panic!` or Not to `panic!`
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch09-03-to-panic-or-not-to-panic.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch09-03-to-panic-or-not-to-panic.html).
================================================
FILE: 2018-edition/src/ch10-00-generics.md
================================================
# Generic Types, Traits, and Lifetimes
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch10-00-generics.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch10-00-generics.html).
================================================
FILE: 2018-edition/src/ch10-01-syntax.md
================================================
## Generic Data Types
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch10-01-syntax.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch10-01-syntax.html).
================================================
FILE: 2018-edition/src/ch10-02-traits.md
================================================
## Traits: Defining Shared Behavior
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch10-02-traits.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch10-02-traits.html).
================================================
FILE: 2018-edition/src/ch10-03-lifetime-syntax.md
================================================
## Validating References with Lifetimes
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch10-03-lifetime-syntax.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch10-03-lifetime-syntax.html).
================================================
FILE: 2018-edition/src/ch11-00-testing.md
================================================
# Writing Automated Tests
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch11-00-testing.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch11-00-testing.html).
================================================
FILE: 2018-edition/src/ch11-01-writing-tests.md
================================================
## How to Write Tests
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch11-01-writing-tests.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch11-01-writing-tests.html).
================================================
FILE: 2018-edition/src/ch11-02-running-tests.md
================================================
## Controlling How Tests Are Run
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch11-02-running-tests.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch11-02-running-tests.html).
================================================
FILE: 2018-edition/src/ch11-03-test-organization.md
================================================
## Test Organization
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch11-03-test-organization.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch11-03-test-organization.html).
================================================
FILE: 2018-edition/src/ch12-00-an-io-project.md
================================================
# An I/O Project: Building a Command Line Program
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch12-00-an-io-project.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch12-00-an-io-project.html).
================================================
FILE: 2018-edition/src/ch12-01-accepting-command-line-arguments.md
================================================
## Accepting Command Line Arguments
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch12-01-accepting-command-line-arguments.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch12-01-accepting-command-line-arguments.html).
================================================
FILE: 2018-edition/src/ch12-02-reading-a-file.md
================================================
## Reading a File
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch12-02-reading-a-file.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch12-02-reading-a-file.html).
================================================
FILE: 2018-edition/src/ch12-03-improving-error-handling-and-modularity.md
================================================
## Refactoring to Improve Modularity and Error Handling
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch12-03-improving-error-handling-and-modularity.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch12-03-improving-error-handling-and-modularity.html).
================================================
FILE: 2018-edition/src/ch12-04-testing-the-librarys-functionality.md
================================================
## Developing the Library’s Functionality with Test-Driven Development
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch12-04-testing-the-librarys-functionality.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch12-04-testing-the-librarys-functionality.html).
================================================
FILE: 2018-edition/src/ch12-05-working-with-environment-variables.md
================================================
## Working with Environment Variables
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch12-05-working-with-environment-variables.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch12-05-working-with-environment-variables.html).
================================================
FILE: 2018-edition/src/ch12-06-writing-to-stderr-instead-of-stdout.md
================================================
## Writing Error Messages to Standard Error Instead of Standard Output
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch12-06-writing-to-stderr-instead-of-stdout.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch12-06-writing-to-stderr-instead-of-stdout.html).
================================================
FILE: 2018-edition/src/ch13-00-functional-features.md
================================================
# Functional Language Features: Iterators and Closures
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch13-00-functional-features.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch13-00-functional-features.html).
================================================
FILE: 2018-edition/src/ch13-01-closures.md
================================================
## Closures: Anonymous Functions that Can Capture Their Environment
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch13-01-closures.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch13-01-closures.html).
================================================
FILE: 2018-edition/src/ch13-02-iterators.md
================================================
## Processing a Series of Items with Iterators
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch13-02-iterators.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch13-02-iterators.html).
================================================
FILE: 2018-edition/src/ch13-03-improving-our-io-project.md
================================================
## Improving Our I/O Project
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch13-03-improving-our-io-project.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch13-03-improving-our-io-project.html).
================================================
FILE: 2018-edition/src/ch13-04-performance.md
================================================
## Comparing Performance: Loops vs. Iterators
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch13-04-performance.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch13-04-performance.html).
================================================
FILE: 2018-edition/src/ch14-00-more-about-cargo.md
================================================
# More About Cargo and Crates.io
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch14-00-more-about-cargo.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch14-00-more-about-cargo.html).
================================================
FILE: 2018-edition/src/ch14-01-release-profiles.md
================================================
## Customizing Builds with Release Profiles
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch14-01-release-profiles.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch14-01-release-profiles.html).
================================================
FILE: 2018-edition/src/ch14-02-publishing-to-crates-io.md
================================================
## Publishing a Crate to Crates.io
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch14-02-publishing-to-crates-io.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch14-02-publishing-to-crates-io.html).
================================================
FILE: 2018-edition/src/ch14-03-cargo-workspaces.md
================================================
## Cargo Workspaces
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch14-03-cargo-workspaces.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch14-03-cargo-workspaces.html).
================================================
FILE: 2018-edition/src/ch14-04-installing-binaries.md
================================================
## Installing Binaries from Crates.io with `cargo install`
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch14-04-installing-binaries.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch14-04-installing-binaries.html).
================================================
FILE: 2018-edition/src/ch14-05-extending-cargo.md
================================================
## Extending Cargo with Custom Commands
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch14-05-extending-cargo.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch14-05-extending-cargo.html).
================================================
FILE: 2018-edition/src/ch15-00-smart-pointers.md
================================================
# Smart Pointers
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch15-00-smart-pointers.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch15-00-smart-pointers.html).
================================================
FILE: 2018-edition/src/ch15-01-box.md
================================================
## Using `Box` to Point to Data on the Heap
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch15-01-box.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch15-01-box.html).
================================================
FILE: 2018-edition/src/ch15-02-deref.md
================================================
## Treating Smart Pointers Like Regular References with the `Deref` Trait
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch15-02-deref.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch15-02-deref.html).
================================================
FILE: 2018-edition/src/ch15-03-drop.md
================================================
## Running Code on Cleanup with the `Drop` Trait
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch15-03-drop.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch15-03-drop.html).
================================================
FILE: 2018-edition/src/ch15-04-rc.md
================================================
## `Rc`, the Reference Counted Smart Pointer
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch15-04-rc.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch15-04-rc.html).
================================================
FILE: 2018-edition/src/ch15-05-interior-mutability.md
================================================
## `RefCell` and the Interior Mutability Pattern
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch15-05-interior-mutability.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch15-05-interior-mutability.html).
================================================
FILE: 2018-edition/src/ch15-06-reference-cycles.md
================================================
## Reference Cycles Can Leak Memory
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch15-06-reference-cycles.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch15-06-reference-cycles.html).
================================================
FILE: 2018-edition/src/ch16-00-concurrency.md
================================================
# Fearless Concurrency
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch16-00-concurrency.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch16-00-concurrency.html).
================================================
FILE: 2018-edition/src/ch16-01-threads.md
================================================
## Using Threads to Run Code Simultaneously
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch16-01-threads.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch16-01-threads.html).
================================================
FILE: 2018-edition/src/ch16-02-message-passing.md
================================================
## Using Message Passing to Transfer Data Between Threads
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch16-02-message-passing.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch16-02-message-passing.html).
================================================
FILE: 2018-edition/src/ch16-03-shared-state.md
================================================
## Shared-State Concurrency
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch16-03-shared-state.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch16-03-shared-state.html).
================================================
FILE: 2018-edition/src/ch16-04-extensible-concurrency-sync-and-send.md
================================================
## Extensible Concurrency with the `Sync` and `Send` Traits
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch16-04-extensible-concurrency-sync-and-send.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch16-04-extensible-concurrency-sync-and-send.html).
================================================
FILE: 2018-edition/src/ch17-00-oop.md
================================================
# Object Oriented Programming Features of Rust
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch18-00-oop.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch17-00-oop.html).
================================================
FILE: 2018-edition/src/ch17-01-what-is-oo.md
================================================
## Characteristics of Object-Oriented Languages
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch18-01-what-is-oo.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch17-01-what-is-oo.html).
================================================
FILE: 2018-edition/src/ch17-02-trait-objects.md
================================================
## Using Trait Objects that Allow for Values of Different Types
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch18-02-trait-objects.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch17-02-trait-objects.html).
================================================
FILE: 2018-edition/src/ch17-03-oo-design-patterns.md
================================================
## Implementing an Object-Oriented Design Pattern
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch18-03-oo-design-patterns.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch17-03-oo-design-patterns.html).
================================================
FILE: 2018-edition/src/ch18-00-patterns.md
================================================
# Patterns and Matching
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch19-00-patterns.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch18-00-patterns.html).
================================================
FILE: 2018-edition/src/ch18-01-all-the-places-for-patterns.md
================================================
## All the Places Patterns Can Be Used
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch19-01-all-the-places-for-patterns.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch18-01-all-the-places-for-patterns.html).
================================================
FILE: 2018-edition/src/ch18-02-refutability.md
================================================
## Refutability: Whether a Pattern Might Fail to Match
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch19-02-refutability.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch18-02-refutability.html).
================================================
FILE: 2018-edition/src/ch18-03-pattern-syntax.md
================================================
## Pattern Syntax
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch19-03-pattern-syntax.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch18-03-pattern-syntax.html).
================================================
FILE: 2018-edition/src/ch19-00-advanced-features.md
================================================
# Advanced Features
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch20-00-advanced-features.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch19-00-advanced-features.html).
================================================
FILE: 2018-edition/src/ch19-01-unsafe-rust.md
================================================
## Unsafe Rust
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch20-01-unsafe-rust.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch19-01-unsafe-rust.html).
================================================
FILE: 2018-edition/src/ch19-02-advanced-lifetimes.md
================================================
## Advanced Lifetimes
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../index.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch19-02-advanced-lifetimes.html).
================================================
FILE: 2018-edition/src/ch19-03-advanced-traits.md
================================================
## Advanced Traits
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch20-02-advanced-traits.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch19-03-advanced-traits.html).
================================================
FILE: 2018-edition/src/ch19-04-advanced-types.md
================================================
## Advanced Types
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch20-03-advanced-types.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch19-04-advanced-types.html).
================================================
FILE: 2018-edition/src/ch19-05-advanced-functions-and-closures.md
================================================
## Advanced Functions and Closures
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch20-04-advanced-functions-and-closures.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch19-05-advanced-functions-and-closures.html).
================================================
FILE: 2018-edition/src/ch19-06-macros.md
================================================
## Macros
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch20-05-macros.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch19-06-macros.html).
================================================
FILE: 2018-edition/src/ch20-00-final-project-a-web-server.md
================================================
# Final Project: Building a Multithreaded Web Server
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch21-00-final-project-a-web-server.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch20-00-final-project-a-web-server.html).
================================================
FILE: 2018-edition/src/ch20-01-single-threaded.md
================================================
## Building a Single-Threaded Web Server
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch21-01-single-threaded.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch20-01-single-threaded.html).
================================================
FILE: 2018-edition/src/ch20-02-multithreaded.md
================================================
## Turning Our Single-Threaded Server into a Multithreaded Server
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch21-02-multithreaded.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch20-02-multithreaded.html).
================================================
FILE: 2018-edition/src/ch20-03-graceful-shutdown-and-cleanup.md
================================================
## Graceful Shutdown and Cleanup
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch21-03-graceful-shutdown-and-cleanup.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch20-03-graceful-shutdown-and-cleanup.html).
================================================
FILE: 2018-edition/src/foreword.md
================================================
# Foreword
The 2018 edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../foreword.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/foreword.html).
================================================
FILE: ADMIN_TASKS.md
================================================
# Administrative Tasks
This documentation is for anyone managing the repo to remember how to do
occasional maintenance tasks.
## Update the `rustc` version
- Delete your `target` directory, you're about to recompile everything anyway
- Change the version number in `.github/workflows/main.yml`
- Change the version number in `rust-toolchain`, which should change the
version you're using locally with `rustup`
- Change the version number in `src/title-page.md`
- Run `./tools/update-rustc.sh` (see its commented code for details on what it
does)
- Inspect the changes (by looking at the files changed according to git) and
their effects (by looking at the files in `tmp/book-before` and
`tmp/book-after`) and commit them if they look good
- Grep for `manual-regeneration` and follow the instructions in those places to
update output that cannot be generated by a script
## Update the `edition` in all listings
To update the `edition = "[year]"` metadata in all the listings' `Cargo.toml`s,
run the `./tools/update-editions.sh` script. Check the diff to make sure it
looks reasonable, and in particular check whether the updates necessitate any
changes to the text. Then commit the changes.
## Update the `edition` in mdBook config
Open `book.toml` and `nostarch/book.toml` and set the `edition` value in the
`[rust]` table to the new edition.
## Release a new version of the listings
We now make `.tar` files of complete projects containing every listing
available [as GitHub Releases](https://github.com/rust-lang/book/releases). To
create a new release artifact, for example if there have been code changes due
to edits or due to updating Rust and `rustfmt`, do the following:
- Create a git tag for the release and push it to GitHub, or create a new tag
by going to the GitHub UI, [drafting a new release](https://github.com/rust-lang/book/releases/new), and entering a new
tag instead of selecting an existing tag
- Run `cargo run --bin release_listings`, which will generate
`tmp/listings.tar.gz`
- Upload `tmp/listings.tar.gz` in the GitHub UI for the draft release
- Publish the release
## Add a new listing
To facilitate the scripts that run `rustfmt` on all the listings, update the
output when the compiler is updated, and produce release artifacts containing
full projects for the listings, any listing beyond the most trivial should be
extracted into a file. To do that:
- Find where the new listing should go in the `listings` directory.
- There is one subdirectory for each chapter
- Numbered listings should use `listing-[chapter num]-[listing num]` for
their directory names.
- Listings without a number should start with `no-listing-` followed by a
number that indicates its position in the chapter relative to the other
listings without numbers in the chapter, then a short description that
someone could read to find the code they're looking for.
- Listings used only for displaying the output of the code (for example, when
we say "if we had written x instead of y, we would get this compiler
error:" but we don't actually show code x) should be named with
`output-only-` followed by a number that indicates its position in the
chapter relative to the other listings used only for output, then a short
description that authors or contributors could read to find the code
they're looking for.
- **Remember to adjust surrounding listing numbers as appropriate!**
- Create a full Cargo project in that directory, either by using `cargo new` or
copying another listing as a starting point.
- Add the code and any surrounding code needed to create a full working example.
- If you only want to show part of the code in the file, use anchor comments
(`// ANCHOR: some_tag` and `// ANCHOR_END: some_tag`) to mark the parts of
the file you want to show.
- For Rust code, use the `{{#rustdoc_include [filename:some_tag]}}` directive
within the code blocks in the text. The `rustdoc_include` directive gives the
code that doesn't get displayed to `rustdoc` for `mdbook test` purposes.
- For anything else, use the `{{#include [filename:some_tag]}}` directive.
- If you want to display the output of a command in the text as well, create an
`output.txt` file in the listing's directory as follows:
- Run the command, like `cargo run` or `cargo test`, and copy all of the
output.
- Create a new `output.txt` file with the first line `$ [the command you
ran]`.
- Paste the output you just copied.
- Run `./tools/update-rustc.sh`, which should perform some normalization on
the compiler output.
- Include the output in the text with the `{{#include [filename]}}` directive.
- Add and commit output.txt.
- If you want to display output but for some reason it can't be generated by a
script (say, because of user input or external events like making a web
request), keep the output inline but make a comment that contains
`manual-regeneration` and instructions for manually updating the inline
output.
- If you don't want this example to even be attempted to be formatted by
`rustfmt` (for example because the example doesn't parse on purpose), add a
`rustfmt-ignore` file in the listing's directory and the reason it's not
being formatted as the contents of that file (in case it's a rustfmt bug that
might get fixed someday).
## See the effect of some change on the rendered book
To check, say, updating `mdbook` or changing the way files get included:
- Generate a built book before the change you want to test by running `mdbook
build -d tmp/book-before`
- Apply the changes you want to test and run `mdbook build -d tmp/book-after`
- Run `./tools/megadiff.sh`
- Files remaining in `tmp/book-before` and `tmp/book-after` have differences
you can manually inspect with your favorite diff viewing mechanism
## Produce new markdown files for No Starch
- Run `./tools/nostarch.sh`
- Spot check the files that script created in the `nostarch` directory
- Check them into git if you're starting a round of edits
## Produce markdown from docx for diffing
- Save the docx file to `tmp/chapterXX.docx`.
- In Word, go to the review tab, choose "Accept all changes and stop tracking"
- Save the docx again and close Word
- Run `./tools/doc-to-md.sh`
- This should write `nostarch/chapterXX.md`. Adjust the XSL in
`tools/doc-to-md.xsl` and run `./tools/doc-to-md.sh` again if needed.
## Generate Graphviz dot
We're using [Graphviz](http://graphviz.org/) for some of the diagrams in the
book. The source for those files live in the `dot` directory. To turn a `dot`
file, for example, `dot/trpl04-01.dot` into an `svg`, run:
```bash
$ dot dot/trpl04-01.dot -Tsvg > src/img/trpl04-01.svg
```
In the generated SVG, remove the width and the height attributes from the `svg`
element and set the `viewBox` attribute to `0.00 0.00 1000.00 1000.00` or other
values that don't cut off the image.
## Publish a preview to GitHub Pages
We sometimes publish to GitHub Pages for in-progress previews. The recommended
flow for publishing is:
- Install the `ghp-import` tool by running `pip install ghp-import` (or `pipx install ghp-import`, using [pipx][pipx]).
- In the root, run `tools/generate-preview.sh`
[pipx]: https://pipx.pypa.io/stable/#install-pipx
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing
We'd love your help! Thanks for caring about the book.
## Where to Edit
All edits should be made in the `src` directory.
The `nostarch` directory contains snapshots for sending edits to the publishers
of the print version. The snapshot files reflect what has been sent or not, so
they only get updated when edits are sent to No Starch. **Do not submit pull
requests changing files in the `nostarch` directory, they will be closed.**
We use [`rustfmt`][rustfmt] to apply standard formatting to Rust code in the
repo and [`dprint`][dprint] to apply standard formatting to the Markdown source
and the non-Rust code in the project.
[rustfmt]: https://github.com/rust-lang/rustfmt
[dprint]: https://dprint.dev
You will normally have `rustfmt` installed if you have a Rust toolchain
installed; if for some reason you do not have a copy of `rustfmt`, you can add
it by running the following command:
```sh
rustup component add rustfmt
```
To install `dprint`, you can run the following command:
```sh
cargo install dprint
```
Or follow the [instructions][install-dprint] on the `dprint` website.
[install-dprint]: https://dprint.dev/install/
To format Rust code, you can run `rustfmt `, and to format other
files, you can pass `dprint fmt `. Many text editors also have native
support or extensions for both `rustfmt` and `dprint`.
## Checking for Fixes
The book rides the Rust release trains. Therefore, if you see a problem on
https://doc.rust-lang.org/stable/book, it may already be fixed on the `main`
branch in this repo, but the fix hasn't gone through nightly -> beta -> stable
yet. Please check the `main` branch in this repo before reporting an issue.
Looking at the history for a particular file can also give more information on
how or whether an issue has been fixed or not if you're trying to figure that
out.
Please also search open and closed issues and open and closed PRs before
reporting a new issue or opening a new PR.
## Licensing
This repository is under the same license as Rust itself, MIT/Apache2. You
can find the full text of each license in the `LICENSE-*` files in this
repository.
## Code of Conduct
The Rust project has [a code of conduct](http://rust-lang.org/policies/code-of-conduct)
that governs all sub-projects, including this one. Please respect it!
## Expectations
Because the book is [printed][nostarch], and because we want
to keep the online version of the book close to the print version when
possible, it may take longer than you're used to for us to address your issue
or pull request.
[nostarch]: https://nostarch.com/rust-programming-language-2nd-edition
So far, we've been doing a larger revision to coincide with [Rust Editions](https://doc.rust-lang.org/edition-guide/). Between those larger
revisions, we will only be correcting errors. If your issue or pull request
isn't strictly fixing an error, it might sit until the next time that we're
working on a large revision: expect on the order of months or years. Thank you
for your patience!
## Help wanted
If you're looking for ways to help that don't involve large amounts of
reading or writing, check out the [open issues with the E-help-wanted
label][help-wanted]. These might be small fixes to the text, Rust code,
frontend code, or shell scripts that would help us be more efficient or
enhance the book in some way!
[help-wanted]: https://github.com/rust-lang/book/issues?q=is%3Aopen+is%3Aissue+label%3AE-help-wanted
## Translations
We'd love help translating the book! See the [Translations] label to join in
efforts that are currently in progress. Open a new issue to start working on
a new language! We're waiting on [mdbook support] for multiple languages
before we merge any in, but feel free to start!
[Translations]: https://github.com/rust-lang/book/issues?q=is%3Aopen+is%3Aissue+label%3ATranslations
[mdbook support]: https://github.com/rust-lang/mdBook/issues/5
================================================
FILE: COPYRIGHT
================================================
This repository is licensed under the Apache License, Version 2.0
or the MIT
license , at your option.
================================================
FILE: Cargo.toml
================================================
[workspace]
members = ["packages/tools"]
default-members = ["packages/tools"]
resolver = "2"
exclude = [
"linkchecker", # linkchecker is part of the CI workflow
"listings", # these are intentionally distinct from the workspace
"tmp", # listings are built here when updating output via tools/update-rustc.sh
]
[workspace.dependencies]
walkdir = "2.3.1"
docopt = "1.1.0"
serde = "1.0"
regex = "1.3.3"
lazy_static = "1.4.0"
flate2 = "1.0.13"
tar = "0.4.26"
================================================
FILE: LICENSE-APACHE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: LICENSE-MIT
================================================
Copyright (c) 2010 The Rust Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
================================================
FILE: README.md
================================================
# The Rust Programming Language

This repository contains the source of "The Rust Programming Language" book.
[The book is available in dead-tree form from No Starch Press][nostarch].
[nostarch]: https://nostarch.com/rust-programming-language-2nd-edition
You can also read the book for free online. Please see the book as shipped with
the latest [stable], [beta], or [nightly] Rust releases. Be aware that issues
in those versions may have been fixed in this repository already, as those
releases are updated less frequently.
[stable]: https://doc.rust-lang.org/stable/book/
[beta]: https://doc.rust-lang.org/beta/book/
[nightly]: https://doc.rust-lang.org/nightly/book/
See the [releases] to download just the code of all the code listings that appear in the book.
[releases]: https://github.com/rust-lang/book/releases
## Requirements
Building the book requires [mdBook], ideally the same version that
rust-lang/rust uses in [this file][rust-mdbook]. To get it:
[mdBook]: https://github.com/rust-lang/mdBook
[rust-mdbook]: https://github.com/rust-lang/rust/blob/HEAD/src/tools/rustbook/Cargo.toml
```bash
$ cargo install mdbook --locked --version
```
## Building
To build the book, type:
```bash
$ mdbook build
```
The output will be in the `book` subdirectory. To check it out, open it in
your web browser.
_Firefox:_
```bash
$ firefox book/index.html # Linux
$ open -a "Firefox" book/index.html # OS X
$ Start-Process "firefox.exe" .\book\index.html # Windows (PowerShell)
$ start firefox.exe .\book\index.html # Windows (Cmd)
```
_Chrome:_
```bash
$ google-chrome book/index.html # Linux
$ open -a "Google Chrome" book/index.html # OS X
$ Start-Process "chrome.exe" .\book\index.html # Windows (PowerShell)
$ start chrome.exe .\book\index.html # Windows (Cmd)
```
To run the tests:
```bash
$ cd packages/trpl
$ mdbook test --library-path packages/trpl/target/debug/deps
```
## Contributing
We'd love your help! Please see [CONTRIBUTING.md][contrib] to learn about the
kinds of contributions we're looking for.
[contrib]: https://github.com/rust-lang/book/blob/main/CONTRIBUTING.md
Because the book is [printed][nostarch], and because we want
to keep the online version of the book close to the print version when
possible, it may take longer than you're used to for us to address your issue
or pull request.
So far, we've been doing a larger revision to coincide with [Rust Editions](https://doc.rust-lang.org/edition-guide/). Between those larger
revisions, we will only be correcting errors. If your issue or pull request
isn't strictly fixing an error, it might sit until the next time that we're
working on a large revision: expect on the order of months or years. Thank you
for your patience!
### Translations
We'd love help translating the book! See the [Translations] label to join in
efforts that are currently in progress. Open a new issue to start working on
a new language! We're waiting on [mdbook support] for multiple languages
before we merge any in, but feel free to start!
[Translations]: https://github.com/rust-lang/book/issues?q=is%3Aopen+is%3Aissue+label%3ATranslations
[mdbook support]: https://github.com/rust-lang/mdBook/issues/5
## Spellchecking
To scan source files for spelling errors, you can use the `spellcheck.sh`
script available in the `ci` directory. It needs a dictionary of valid words,
which is provided in `ci/dictionary.txt`. If the script produces a false
positive (say, you used the word `BTreeMap` which the script considers invalid),
you need to add this word to `ci/dictionary.txt` (keep the sorted order for
consistency).
================================================
FILE: TODO.md
================================================
# In each chapter
- [ ] Manual regeneration
- [ ] Check for upstream changes from last snapshot
- [ ] Propagate updated output to docx
- [ ] Extract docx and check diff
- [ ] Answer all comments
- [ ] Check cross references
- [ ] Check indentation of --snip--
- [ ] Numbered lines, Gray out unchanged lines
- [ ] Check line wrapping
- [ ] Check for unneeded command/compiling/running output
- [ ] Check println style and error messages
- [ ] Add alt text to images
- [ ] Index tags
- [ ] search for "convention" conventions:naming:of blah
- [ ] check for double spaces, spaces at the end of paragraphs
================================================
FILE: book.toml
================================================
# Sync any changes to this *other than where explicitly specified* with the copy
# in `nostarch/book.toml`!
[book]
title = "The Rust Programming Language"
authors = ["Steve Klabnik", "Carol Nichols", "Chris Krycho", "Contributions from the Rust Community"]
[output.html]
additional-css = ["ferris.css", "theme/2018-edition.css", "theme/semantic-notes.css", "theme/listing.css"]
additional-js = ["ferris.js"]
git-repository-url = "https://github.com/rust-lang/book"
[output.html.search]
use-boolean-and = true
[output.html.redirect]
"ch17-00-oop.html" = "ch18-00-oop.html"
"ch17-01-what-is-oo.html" = "ch18-01-what-is-oo.html"
"ch17-02-trait-objects.html" = "ch18-02-trait-objects.html"
"ch17-03-oo-design-patterns.html" = "ch18-03-oo-design-patterns.html"
"ch18-00-patterns.html" = "ch19-00-patterns.html"
"ch18-01-all-the-places-for-patterns.html" = "ch19-01-all-the-places-for-patterns.html"
"ch18-02-refutability.html" = "ch19-02-refutability.html"
"ch18-03-pattern-syntax.html" = "ch19-03-pattern-syntax.html"
"ch19-00-advanced-features.html" = "ch20-00-advanced-features.html"
"ch19-01-unsafe-rust.html" = "ch20-01-unsafe-rust.html"
"ch19-03-advanced-traits.html" = "ch20-02-advanced-traits.html"
"ch20-03-advanced-traits.html" = "ch20-02-advanced-traits.html"
"ch19-04-advanced-types.html" = "ch20-03-advanced-types.html"
"ch20-04-advanced-types.html" = "ch20-03-advanced-types.html"
"ch19-05-advanced-functions-and-closures.html" = "ch20-04-advanced-functions-and-closures.html"
"ch20-05-advanced-functions-and-closures.html" = "ch20-04-advanced-functions-and-closures.html"
"ch19-06-macros.html" = "ch20-05-macros.html"
"ch20-06-macros.html" = "ch20-05-macros.html"
"ch20-00-final-project-a-web-server.html" = "ch21-00-final-project-a-web-server.html"
"ch20-01-single-threaded.html" = "ch21-01-single-threaded.html"
"ch20-02-multithreaded.html" = "ch21-02-multithreaded.html"
"ch20-03-graceful-shutdown-and-cleanup.html" = "ch21-03-graceful-shutdown-and-cleanup.html"
# Do not sync this preprocessor; it is for the HTML renderer only.
[preprocessor.trpl-note]
command = "cargo run --manifest-path packages/mdbook-trpl/Cargo.toml --bin mdbook-trpl-note"
[preprocessor.trpl-listing]
command = "cargo run --manifest-path packages/mdbook-trpl/Cargo.toml --bin mdbook-trpl-listing"
output-mode = "default"
[rust]
edition = "2024"
[build]
extra-watch-dirs = ["packages/mdbook-trpl"]
================================================
FILE: ci/dictionary.txt
================================================
personal_ws-1.1 en 0 utf-8
abcabcabc
abcd
abcdefghijklmnopqrstuvwxyz
ABIs
AddAssign
Addr
adfb
afdc
aggregator
AGraph
aliasability
alignof
alloc
allocator
AlwaysEqual
Amir
anotherusername
APIs
app's
aren
args
ArgumentV
associativity
async
atomics
attr
autocompletion
AveragedCollection
backend
backported
backtrace
backtraces
BACKTRACE
Backtraces
Baz's
beefeb
benchmarking
bioinformatics
bitand
BitAnd
BitAndAssign
bitor
BitOr
BitOrAssign
bitwise
Bitwise
bitxor
BitXor
BitXorAssign
Bjarne
Boehm
bool
boolean
Boolean
Booleans
booleans
Bors
BorrowMutError
BoxMeUp
boxt
BTreeSet
BufRead
BufReader
BuildHasher
byteorder
Cacher
cacher
Cagain
callsite
CamelCase
cargodoc
centric
chacha
ChangeColor
ChangeColorMessage
charset
choo
chXX
chYY
clippy
clippy's
cmdlet
coercions
combinator
ConcreteType
config
Config
confignew
const
consts
constant's
copyeditor
couldn
CPUs
cratesio
CRLF
cryptocurrencies
cryptographic
cryptographically
CStr
CString
ctrl
Ctrl
customizable
CustomSmartPointer
CustomSmartPointers
data's
DataStruct
dbea
deallocate
deallocated
deallocating
deallocation
debounce
debuginfo
decl
decrementing
deduplicate
deduplicating
deps
deref
Deref
dereference
Dereference
dereferenced
dereferences
dereferencing
DerefMut
DeriveInput
Dest
destructor
destructure
destructured
destructures
destructuring
Destructuring
deterministically
DevOps
devtools
didn
Dobrý
doccargo
doccratesio
DOCTYPE
doesn
disambiguating
DisplayBacktrace
DivAssign
DraftPost
DSTs
durations
ebook
ebooks
Edsger
efdcd
egular
ElementRef
else's
emoji
encodings
enum
Enum
enums
enum's
Enums
eprintln
Erlang
ErrorKind
Español
ETAPS
eval
executables
ExitCode
expr
extern
favicon
ferris
FFFD
FFFF
figcaption
fieldname
filename
Filename
filesystem
Filesystem
filesystem's
filesystems
filmmaking
Firefox
FirstAwaitPoint
FnMut
FnOnce
formatter
formatters
FrenchToast
FromIterator
FromResidual
frontend
FuturesUnordered
GetAwaitPoint
getrandom
getter
getters
GGraph
GitHub
gitignore
grapheme
Grapheme
growable
gzip
handcoded
handoff
hardcode
hardcoded
hardcoding
hasher
hashers
HashMap
HashSet
Haskell
hasn
HeadB
HeadC
HelloMacro
helloworld
HelloWorld
HelloWorldName
Hmmm
Hoare
Hola
homogenous
html
http
https
hyperoptimize
hypotheticals
Iceburgh
ident
IDE
IDEs
IDE's
IEEE
impl
implementor
implementors
ImportantExcerpt
incrementing
IndexMut
indices
init
initializer
initializers
inline
instantiation
internet
interoperate
IntoFuture
IntoIterator
intra
intratask
InvalidDigit
invariants
ioerror
iokind
ioresult
IoResult
iostdin
IpAddr
IpAddrKind
irst
isize
iter
iterator's
JavaScript
JoinAll
JoinHandle
Kay's
kinded
Klabnik
Krycho
lang
LastWriteTime
latin
liballoc
libc
libcollections
libcore
libpanic
librarys
libreoffice
libstd
libunwind
lifecycle
LimitTracker
linter
LLVM
lobally
locators
LockResult
login
lookup
loopback
lossy
Lukas
lval
macOS
Matsakis
mathematic
mdbook
memoization
metadata
Metadata
metaprogramming
metavariable
mibbit
Mibbit
microcontroller
microcontrollers
millis
minigrep
Miri
miri
mixup
mkdir
MockMessenger
modifiability
modularity
monomorphization
Monomorphization
monomorphized
MoveMessage
Mozilla
mpsc
MSRV
msvc
MulAssign
multibyte
multithreaded
multithreading
mutex
mutex's
Mutex
mutexes
Mutexes
MutexGuard
mutext
mutextarct
MyAsyncStateMachine
MyBox
myprogram
namespace
namespaced
namespaces
namespacing
natively
newfound
NewJob
NewsArticle
NewThread
newtype
newtypes
nitty
nocapture
nomicon
nonadministrators
nondeterministic
nonequality
nongeneric
noplayground
NoStarch
NotFound
nsprust
null's
OCaml
offsetof
online
OpenGL
optimizations
OptionalFloatingPointNumber
OptionalNumber
optiont
OsStr
OsString
other's
otherinstall
OtherError
OurError
OutlinePrint
overloadable
overread
PageTitleFuture
PanicPayload
parallelizable
param
parameterize
ParseIntError
PartialEq
PartialOrd
pbcopy
PendingReview
PendingReviewPost
PlaceholderType
polymorphism
PoolCreationError
por
portia
postfix
powershell
PowerShell
powi
preallocate
preallocates
preprocessing
Preprocessing
preprocessor
PrimaryColor
println
priv
proc
proto
pseudocode
pthreads
pushups
QuitMessage
quux
RAII
randcrate
RangeFrom
RangeTo
RangeFull
README
READMEs
ReadFinished
ReceiverStream
rect
recurse
recv
redeclaring
Refactoring
refactor
refactoring
refcell
RefCell
refcellt
refcelltrct
RefMut
reformats
refutability
reimplement
RemAssign
repost
repr
representable
request's
resizes
resizing
ReturnedError
retweet
rewordings
rint
ripgrep
Rumbul
runnable
runtime
runtimes
Rustacean
Rustaceans
rUsT
rustc
rustdoc
RUSTFLAGS
Rustonomicon
rustfix
rustfmt
RustLangES
rustup
sampleproject
screenshot
searchstring
SecondaryColor
SecondAwaitPoint
SelectBox
semver
SemVer
serde
ShirtColor
ShlAssign
ShrAssign
shouldn
Simula
siphash
SipHash
situps
sizeof
SliceIndex
Smalltalk
snuck
SocialPost
someproject
SomeType
someusername
SPDX
spdx
SpreadsheetCell
sqrt
stackoverflow
startup
StaticRef
stderr
stdin
Stdin
stdlib
stdout
steveklabnik's
stringify
StreamExt
Stroustrup
Stroustrup's
struct
Struct
structs
struct's
Structs
StrWrap
SubAssign
subclasses
subcommand
subcommands
subdirectories
subdirectory
submodule
submodules
Submodules
submodule’s
suboptimal
subpath
subslices
substring
subtasks
subteams
subtree
subtyping
summarizable
supertrait
supertraits
TcpListener
TcpStream
templating
test's
TextAwaitPoint
TextField
That'd
there'd
ThreadPool
threadpool
timestamp
Tiếng
timeline
tlborm
tlsv
TODO
TokenStream
Tokio
tokio
toml
TOML
toolchain
toolchains
ToString
tradeoff
tradeoffs
TrafficLight
transcoding
trpl
tuesday
tuple
tuples
turbofish
Turon
typeof
TypeName
UFCS
unary
Unary
uncomment
Uncomment
uncommenting
unevaluated
unhandled
unicode
Uninstalling
uninstall
unittests
unix
unpopulated
unoptimized
UnsafeCell
unsafety
unsized
unsynchronized
Unyank
UpperCamelCase
URIs
urls
UsefulType
username
USERPROFILE
usize
UsState
util
utils
vals
variable's
variant's
vers
versa
vert
Versioning
visualstudio
Vlissides
vscode
vtable
waitlist
wasi
wasn
weakt
WeatherForecast
webpage
WebSocket
whitespace
wildcard
wildcards
Wirth
workflow
workspace
workspaces
Workspaces
wouldn
writeln
WriteMessage
xcode
xpression
yyyy
zerocopy
ZipImpl
================================================
FILE: ci/spellcheck.sh
================================================
#!/bin/bash
set -eu
aspell --version
# Checks project Markdown files for spelling mistakes.
# Notes:
# This script needs dictionary file ($dict_filename) with project-specific
# valid words. If this file is missing, first invocation of a script generates
# a file of words considered typos at the moment. User should remove real typos
# from this file and leave only valid words. When script generates false
# positive after source modification, new valid word should be added
# to dictionary file.
# Default mode of this script is interactive. Each source file is scanned for
# typos. aspell opens window, suggesting fixes for each found typo. Original
# files with errors will be backed up to files with format "filename.md.bak".
# When running in CI, this script should be run in "list" mode (pass "list"
# as first argument). In this mode script scans all files and reports found
# errors. Exit code in this case depends on scan result:
# 1 if any errors found,
# 0 if all is clear.
# Script skips words with length less than or equal to 3. This helps to avoid
# some false positives.
# We can consider skipping source code in markdown files (```code```) to reduce
# rate of false positives, but then we lose ability to detect typos in code
# comments/strings etc.
shopt -s nullglob
dict_filename=./ci/dictionary.txt
markdown_sources=(./src/*.md)
mode="check"
# aspell repeatedly modifies the personal dictionary for some reason,
# so we should use a copy of our dictionary.
dict_path="/tmp/dictionary.txt"
if [[ "$1" == "list" ]]; then
mode="list"
fi
# Error if running in list (CI) mode and there isn't a dictionary file;
# creating one in CI won't do any good :(
if [[ "$mode" == "list" && ! -f "$dict_filename" ]]; then
echo "No dictionary file found! A dictionary file is required in CI!"
exit 1
fi
if [[ ! -f "$dict_filename" ]]; then
# Pre-check mode: generates dictionary of words aspell consider typos.
# After user validates that this file contains only valid words, we can
# look for typos using this dictionary and some default aspell dictionary.
echo "Scanning files to generate dictionary file '$dict_filename'."
echo "Please check that it doesn't contain any misspellings."
echo "personal_ws-1.1 en 0 utf-8" > "$dict_filename"
cat "${markdown_sources[@]}" | aspell --ignore 3 list | sort -u >> "$dict_filename"
elif [[ "$mode" == "list" ]]; then
# List (default) mode: scan all files, report errors.
declare -i retval=0
cp "$dict_filename" "$dict_path"
if [ ! -f $dict_path ]; then
retval=1
exit "$retval"
fi
for fname in "${markdown_sources[@]}"; do
command=$(aspell --ignore 3 --personal="$dict_path" "$mode" < "$fname")
if [[ -n "$command" ]]; then
for error in $command; do
# FIXME: find more correct way to get line number
# (ideally from aspell). Now it can make some false positives,
# because it is just a grep.
grep --with-filename --line-number --color=always "$error" "$fname"
done
retval=1
fi
done
exit "$retval"
elif [[ "$mode" == "check" ]]; then
# Interactive mode: fix typos.
cp "$dict_filename" "$dict_path"
if [ ! -f $dict_path ]; then
retval=1
exit "$retval"
fi
for fname in "${markdown_sources[@]}"; do
aspell --ignore 3 --dont-backup --personal="$dict_path" "$mode" "$fname"
done
fi
================================================
FILE: ci/validate.sh
================================================
#!/bin/bash
set -eu
for file in src/*.md ; do
echo Checking references in "$file"
cargo run --quiet --bin link2print < "$file" > /dev/null
done
================================================
FILE: dot/trpl04-01.dot
================================================
digraph {
rankdir=LR;
overlap=false;
dpi=300.0;
node [shape="plaintext"];
table0[label=<
>;];
}
}
edge [tailclip = false;];
pinned_box -> pin [tailport = "source:c"; arrowhead = "none";];
pin -> string2 [headport = "target";];
}
================================================
FILE: dprint.jsonc
================================================
{
"typescript": {
},
"json": {
},
"markdown": {
},
"malva": {
},
"excludes": [
"**/node_modules",
"**/*-lock.json",
"**/target",
// We don’t to apply auto-formatting to this *yet*, at a minimum. It may be
// helpful as a way of replacing some of the manual formatting we do in both
// the nostarch script and the script for pulling data back over from docx,
// though, so we may *start* doing so in the future.
"nostarch",
// These should never change at this point
"2018-edition",
"first-edition",
"second-edition",
"redirects",
// has empty list items which look like headings to a formatter
".github/ISSUE_TEMPLATE/bug_report.md",
],
"plugins": [
"https://plugins.dprint.dev/typescript-0.93.3.wasm",
"https://plugins.dprint.dev/json-0.19.4.wasm",
"https://plugins.dprint.dev/markdown-0.17.8.wasm",
"https://plugins.dprint.dev/g-plane/malva-v0.11.0.wasm",
],
}
================================================
FILE: ferris.css
================================================
body.light .does_not_compile,
body.light .panics,
body.light .not_desired_behavior,
body.rust .does_not_compile,
body.rust .panics,
body.rust .not_desired_behavior {
background: #fff1f1;
}
body.coal .does_not_compile,
body.coal .panics,
body.coal .not_desired_behavior,
body.navy .does_not_compile,
body.navy .panics,
body.navy .not_desired_behavior,
body.ayu .does_not_compile,
body.ayu .panics,
body.ayu .not_desired_behavior {
background: #501f21;
}
.ferris-container {
position: absolute;
z-index: 99;
right: 5px;
top: 30px;
}
.ferris {
vertical-align: top;
margin-left: 0.2em;
height: auto;
}
.ferris-large {
width: 4.5em;
}
.ferris-small {
width: 2.3em;
}
.ferris-explain {
width: 100px;
}
/*
A bit of a hack to make small Ferris use the existing buttons container but
only show/hide the buttons on hover over the `pre`. Targeting `.listing`
increases the specificity of this rule.
*/
pre > .buttons {
visibility: visible;
opacity: 1;
transition: none;
}
pre > .buttons button {
visibility: hidden;
opacity: 0;
transition: visibility 0.1s linear, opacity 0.1s linear;
}
pre:hover > .buttons button {
visibility: visible;
opacity: 1;
}
================================================
FILE: ferris.js
================================================
// @ts-check
/**
* @typedef {{ attr: string, title: string }} FerrisType
*/
/** @type {Array} */
const FERRIS_TYPES = [
{
attr: "does_not_compile",
title: "This code does not compile!",
},
{
attr: "panics",
title: "This code panics!",
},
{
attr: "not_desired_behavior",
title: "This code does not produce the desired behavior.",
},
];
document.addEventListener("DOMContentLoaded", () => {
for (let ferrisType of FERRIS_TYPES) {
attachFerrises(ferrisType);
}
});
/**
* @param {FerrisType} type
*/
function attachFerrises(type) {
let elements = document.getElementsByClassName(type.attr);
for (let codeBlock of elements) {
// Skip SVG etc.: in principle, these should never be attached to those, but
// this means if someone happens to have a browser extension which *is*
// attaching them, it will not break the code.
if (!(codeBlock instanceof HTMLElement)) {
continue;
}
let codeLines = codeBlock.innerText;
let extra = codeLines.endsWith("\n") ? 1 : 0;
let numLines = codeLines.split("\n").length - extra;
/** @type {'small' | 'large'} */
let size = numLines < 4 ? "small" : "large";
let container = prepareFerrisContainer(codeBlock, size == "small");
if (!container) {
continue;
}
container.appendChild(createFerris(type, size));
}
}
/**
* @param {HTMLElement} element - Code block element to attach a Ferris to.
* @param {boolean} useButtons - Whether to attach to existing buttons.
* @returns {Element | null} - The container element to use.
*/
function prepareFerrisContainer(element, useButtons) {
let foundButtons = element.parentElement?.querySelector(".buttons");
if (useButtons && foundButtons) {
return foundButtons;
}
let div = document.createElement("div");
div.classList.add("ferris-container");
if (!element.parentElement) {
console.error(`Could not install Ferris on ${element}, which is missing a parent`);
return null;
}
element.parentElement.insertBefore(div, element);
return div;
}
/**
* @param {FerrisType} type
* @param {'small' | 'large'} size
* @returns {HTMLAnchorElement} - The generated anchor element.
*/
function createFerris(type, size) {
let a = document.createElement("a");
a.setAttribute("href", "ch00-00-introduction.html#ferris");
a.setAttribute("target", "_blank");
let img = document.createElement("img");
img.setAttribute("src", "img/ferris/" + type.attr + ".svg");
img.setAttribute("title", type.title);
img.classList.add("ferris");
img.classList.add("ferris-" + size);
a.appendChild(img);
return a;
}
================================================
FILE: first-edition/book.toml
================================================
[book]
title = "The Rust Programming Language"
authors = ["The Rust Project Developers"]
================================================
FILE: first-edition/src/README.md
================================================
# The Rust Programming Language
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../index.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/README.html).
================================================
FILE: first-edition/src/SUMMARY.md
================================================
# Summary
[Introduction](README.md)
* [Getting Started](getting-started.md)
* [Tutorial: Guessing Game](guessing-game.md)
* [Syntax and Semantics](syntax-and-semantics.md)
* [Variable Bindings](variable-bindings.md)
* [Functions](functions.md)
* [Primitive Types](primitive-types.md)
* [Comments](comments.md)
* [if](if.md)
* [Loops](loops.md)
* [Vectors](vectors.md)
* [Ownership](ownership.md)
* [References and Borrowing](references-and-borrowing.md)
* [Lifetimes](lifetimes.md)
* [Mutability](mutability.md)
* [Structs](structs.md)
* [Enums](enums.md)
* [Match](match.md)
* [Patterns](patterns.md)
* [Method Syntax](method-syntax.md)
* [Strings](strings.md)
* [Generics](generics.md)
* [Traits](traits.md)
* [Drop](drop.md)
* [if let](if-let.md)
* [Trait Objects](trait-objects.md)
* [Closures](closures.md)
* [Universal Function Call Syntax](ufcs.md)
* [Crates and Modules](crates-and-modules.md)
* [`const` and `static`](const-and-static.md)
* [Attributes](attributes.md)
* [`type` aliases](type-aliases.md)
* [Casting between types](casting-between-types.md)
* [Associated Types](associated-types.md)
* [Unsized Types](unsized-types.md)
* [Operators and Overloading](operators-and-overloading.md)
* [Deref coercions](deref-coercions.md)
* [Macros](macros.md)
* [Raw Pointers](raw-pointers.md)
* [`unsafe`](unsafe.md)
* [Effective Rust](effective-rust.md)
* [The Stack and the Heap](the-stack-and-the-heap.md)
* [Testing](testing.md)
* [Conditional Compilation](conditional-compilation.md)
* [Documentation](documentation.md)
* [Iterators](iterators.md)
* [Concurrency](concurrency.md)
* [Error Handling](error-handling.md)
* [Choosing your Guarantees](choosing-your-guarantees.md)
* [FFI](ffi.md)
* [Borrow and AsRef](borrow-and-asref.md)
* [Release Channels](release-channels.md)
* [Using Rust without the standard library](using-rust-without-the-standard-library.md)
* [Procedural Macros (and custom derive)](procedural-macros.md)
* [Glossary](glossary.md)
* [Syntax Index](syntax-index.md)
* [Bibliography](bibliography.md)
================================================
FILE: first-edition/src/associated-types.md
================================================
# Associated Types
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch20-02-advanced-traits.html#specifying-placeholder-types-in-trait-definitions-with-associated-types) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/associated-types.html).
================================================
FILE: first-edition/src/attributes.md
================================================
# Attributes
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../index.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/attributes.html).
================================================
FILE: first-edition/src/bibliography.md
================================================
# Bibliography
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../index.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/bibliography.html).
================================================
FILE: first-edition/src/borrow-and-asref.md
================================================
# Borrow and AsRef
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch15-00-smart-pointers.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/borrow-and-asref.html).
================================================
FILE: first-edition/src/casting-between-types.md
================================================
# Casting Between Types
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../index.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/casting-between-types.html).
================================================
FILE: first-edition/src/choosing-your-guarantees.md
================================================
# Choosing your Guarantees
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch15-00-smart-pointers.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/choosing-your-guarantees.html).
================================================
FILE: first-edition/src/closures.md
================================================
# Closures
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch13-01-closures.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/closures.html).
================================================
FILE: first-edition/src/comments.md
================================================
# Comments
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch03-04-comments.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/comments.html).
================================================
FILE: first-edition/src/concurrency.md
================================================
# Concurrency
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch16-00-concurrency.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/concurrency.html).
================================================
FILE: first-edition/src/conditional-compilation.md
================================================
# Conditional Compilation
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../index.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/conditional-compilation.html).
================================================
FILE: first-edition/src/const-and-static.md
================================================
# const and static
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch20-01-unsafe-rust.html#accessing-or-modifying-a-mutable-static-variable) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/const-and-static.html).
================================================
FILE: first-edition/src/crates-and-modules.md
================================================
# Crates and Modules
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch07-00-managing-growing-projects-with-packages-crates-and-modules.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/crates-and-modules.html).
================================================
FILE: first-edition/src/deref-coercions.md
================================================
# `Deref` coercions
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch15-02-deref.html#implicit-deref-coercions-with-functions-and-methods) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/deref-coercions.html).
================================================
FILE: first-edition/src/documentation.md
================================================
# Documentation
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch14-02-publishing-to-crates-io.html#making-useful-documentation-comments) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/documentation.html).
================================================
FILE: first-edition/src/drop.md
================================================
# Drop
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch15-03-drop.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/drop.html).
================================================
FILE: first-edition/src/effective-rust.md
================================================
# Effective Rust
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../index.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/effective-rust.html).
================================================
FILE: first-edition/src/enums.md
================================================
# Enums
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch06-01-defining-an-enum.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/enums.html).
================================================
FILE: first-edition/src/error-handling.md
================================================
# Error Handling
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch09-00-error-handling.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/error-handling.html).
================================================
FILE: first-edition/src/ffi.md
================================================
# Foreign Function Interface
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch20-01-unsafe-rust.html#calling-rust-functions-from-other-languages) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/ffi.html).
================================================
FILE: first-edition/src/functions.md
================================================
# Functions
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch03-03-how-functions-work.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/functions.html).
================================================
FILE: first-edition/src/generics.md
================================================
# Generics
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch10-00-generics.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/generics.html).
================================================
FILE: first-edition/src/getting-started.md
================================================
# Getting Started
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch00-00-introduction.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/getting-started.html).
================================================
FILE: first-edition/src/glossary.md
================================================
# Glossary
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../index.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/glossary.html).
================================================
FILE: first-edition/src/guessing-game.md
================================================
# Guessing Game
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch02-00-guessing-game-tutorial.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/guessing-game.html).
================================================
FILE: first-edition/src/if-let.md
================================================
# if let
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch06-03-if-let.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/if-let.html).
================================================
FILE: first-edition/src/if.md
================================================
# if
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch03-05-control-flow.html#if-expressions) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/if.html).
================================================
FILE: first-edition/src/iterators.md
================================================
# Iterators
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch13-02-iterators.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/iterators.html).
================================================
FILE: first-edition/src/lifetimes.md
================================================
# Lifetimes
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch10-03-lifetime-syntax.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/lifetimes.html).
================================================
FILE: first-edition/src/loops.md
================================================
# Loops
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch03-05-control-flow.html#repetition-with-loops) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/loops.html).
================================================
FILE: first-edition/src/macros.md
================================================
# Macros
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch20-05-macros.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/macros.html).
================================================
FILE: first-edition/src/match.md
================================================
# Match
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch06-02-match.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/match.html).
================================================
FILE: first-edition/src/method-syntax.md
================================================
# Method Syntax
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch05-03-method-syntax.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/method-syntax.html).
================================================
FILE: first-edition/src/mutability.md
================================================
# Mutability
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch03-01-variables-and-mutability.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/mutability.html).
================================================
FILE: first-edition/src/operators-and-overloading.md
================================================
# Operators and Overloading
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch20-02-advanced-traits.html#default-generic-type-parameters-and-operator-overloading) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/operators-and-overloading.html).
================================================
FILE: first-edition/src/ownership.md
================================================
# Ownership
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch04-00-understanding-ownership.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/ownership.html).
================================================
FILE: first-edition/src/patterns.md
================================================
# Patterns
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch19-03-pattern-syntax.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/patterns.html).
================================================
FILE: first-edition/src/primitive-types.md
================================================
# Primitive Types
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch03-02-data-types.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/primitive-types.html).
================================================
FILE: first-edition/src/procedural-macros.md
================================================
# Procedural Macros (and custom Derive)
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch20-05-macros.html?highlight=procedural#procedural-macros-for-generating-code-from-attributes) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/procedural-macros.html).
================================================
FILE: first-edition/src/raw-pointers.md
================================================
# Raw Pointers
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch20-01-unsafe-rust.html#dereferencing-a-raw-pointer) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/raw-pointers.html).
================================================
FILE: first-edition/src/references-and-borrowing.md
================================================
# References and Borrowing
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch04-02-references-and-borrowing.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/references-and-borrowing.html).
================================================
FILE: first-edition/src/release-channels.md
================================================
# Release Channels
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../index.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/release-channels.html).
================================================
FILE: first-edition/src/strings.md
================================================
# Strings
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch08-02-strings.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/strings.html).
================================================
FILE: first-edition/src/structs.md
================================================
# Structs
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch05-00-structs.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/structs.html).
================================================
FILE: first-edition/src/syntax-and-semantics.md
================================================
# Syntax and Semantics
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch03-00-common-programming-concepts.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/syntax-and-semantics.html).
================================================
FILE: first-edition/src/syntax-index.md
================================================
# Syntax Index
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../index.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/syntax-index.html).
================================================
FILE: first-edition/src/testing.md
================================================
# Testing
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch11-00-testing.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/testing.html).
================================================
FILE: first-edition/src/the-stack-and-the-heap.md
================================================
# The Stack and the Heap
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch04-01-what-is-ownership.html#the-stack-and-the-heap) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/the-stack-and-the-heap.html).
================================================
FILE: first-edition/src/trait-objects.md
================================================
# Trait Objects
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch18-02-trait-objects.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/trait-objects.html).
================================================
FILE: first-edition/src/traits.md
================================================
# Traits
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch10-02-traits.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/traits.html).
================================================
FILE: first-edition/src/type-aliases.md
================================================
# Type Aliases
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch20-03-advanced-types.html#creating-type-synonyms-with-type-aliases) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/type-aliases.html).
================================================
FILE: first-edition/src/ufcs.md
================================================
# Universal Function Call Syntax
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../index.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/ufcs.html).
================================================
FILE: first-edition/src/unsafe.md
================================================
# Unsafe
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch20-01-unsafe-rust.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/unsafe.html).
================================================
FILE: first-edition/src/unsized-types.md
================================================
# Unsized Types
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch20-03-advanced-types.html#dynamically-sized-types-and-the-sized-trait) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/unsized-types.html).
================================================
FILE: first-edition/src/using-rust-without-the-standard-library.md
================================================
# Using Rust Without the Standard Library
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../index.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/using-rust-without-the-standard-library.html).
================================================
FILE: first-edition/src/variable-bindings.md
================================================
# Variable Bindings
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../index.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/variable-bindings.html).
================================================
FILE: first-edition/src/vectors.md
================================================
# Vectors
The first edition of the book is no longer distributed with Rust's documentation.
If you came here via a link or web search, you may want to check out [the current
version of the book](../ch08-01-vectors.html) instead.
If you have an internet connection, you can [find a copy distributed with
Rust
1.30](https://doc.rust-lang.org/1.30.0/book/first-edition/vectors.html).
================================================
FILE: listings/ch02-guessing-game-tutorial/listing-02-01/Cargo.toml
================================================
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
================================================
FILE: listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs
================================================
// ANCHOR: all
// ANCHOR: io
use std::io;
// ANCHOR_END: io
// ANCHOR: main
fn main() {
// ANCHOR_END: main
// ANCHOR: print
println!("Guess the number!");
println!("Please input your guess.");
// ANCHOR_END: print
// ANCHOR: string
let mut guess = String::new();
// ANCHOR_END: string
// ANCHOR: read
io::stdin()
.read_line(&mut guess)
// ANCHOR_END: read
// ANCHOR: expect
.expect("Failed to read line");
// ANCHOR_END: expect
// ANCHOR: print_guess
println!("You guessed: {guess}");
// ANCHOR_END: print_guess
}
// ANCHOR: all
================================================
FILE: listings/ch02-guessing-game-tutorial/listing-02-02/Cargo.toml
================================================
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.8.5"
================================================
FILE: listings/ch02-guessing-game-tutorial/listing-02-02/src/main.rs
================================================
use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {guess}");
}
================================================
FILE: listings/ch02-guessing-game-tutorial/listing-02-03/Cargo.toml
================================================
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.8.5"
================================================
FILE: listings/ch02-guessing-game-tutorial/listing-02-03/src/main.rs
================================================
// ANCHOR: all
use std::io;
// ANCHOR: ch07-04
use rand::Rng;
fn main() {
// ANCHOR_END: ch07-04
println!("Guess the number!");
// ANCHOR: ch07-04
let secret_number = rand::thread_rng().gen_range(1..=100);
// ANCHOR_END: ch07-04
println!("The secret number is: {secret_number}");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {guess}");
// ANCHOR: ch07-04
}
// ANCHOR_END: ch07-04
// ANCHOR_END: all
================================================
FILE: listings/ch02-guessing-game-tutorial/listing-02-04/Cargo.toml
================================================
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.8.5"
================================================
FILE: listings/ch02-guessing-game-tutorial/listing-02-04/output.txt
================================================
$ cargo build
Compiling libc v0.2.86
Compiling getrandom v0.2.2
Compiling cfg-if v1.0.0
Compiling ppv-lite86 v0.2.10
Compiling rand_core v0.6.2
Compiling rand_chacha v0.3.0
Compiling rand v0.8.5
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
error[E0308]: mismatched types
--> src/main.rs:23:21
|
23 | match guess.cmp(&secret_number) {
| --- ^^^^^^^^^^^^^^ expected `&String`, found `&{integer}`
| |
| arguments to this method are incorrect
|
= note: expected reference `&String`
found reference `&{integer}`
note: method defined here
--> /rustc/1159e78c4747b02ef996e55082b704c09b970588/library/core/src/cmp.rs:979:8
For more information about this error, try `rustc --explain E0308`.
error: could not compile `guessing_game` (bin "guessing_game") due to 1 previous error
================================================
FILE: listings/ch02-guessing-game-tutorial/listing-02-04/src/main.rs
================================================
// ANCHOR: here
use std::cmp::Ordering;
use std::io;
use rand::Rng;
fn main() {
// --snip--
// ANCHOR_END: here
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
println!("The secret number is: {secret_number}");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
// ANCHOR: here
println!("You guessed: {guess}");
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => println!("You win!"),
}
}
// ANCHOR_END: here
================================================
FILE: listings/ch02-guessing-game-tutorial/listing-02-05/Cargo.toml
================================================
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.8.5"
================================================
FILE: listings/ch02-guessing-game-tutorial/listing-02-05/src/main.rs
================================================
use std::cmp::Ordering;
use std::io;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
println!("The secret number is: {secret_number}");
loop {
println!("Please input your guess.");
let mut guess = String::new();
// ANCHOR: here
// --snip--
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
// ANCHOR: ch19
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
// ANCHOR_END: ch19
println!("You guessed: {guess}");
// --snip--
// ANCHOR_END: here
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
================================================
FILE: listings/ch02-guessing-game-tutorial/listing-02-06/Cargo.toml
================================================
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.8.5"
================================================
FILE: listings/ch02-guessing-game-tutorial/listing-02-06/src/main.rs
================================================
use std::cmp::Ordering;
use std::io;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
println!("You guessed: {guess}");
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
================================================
FILE: listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/Cargo.toml
================================================
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/output.txt
================================================
$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.08s
Running `target/debug/guessing_game`
Hello, world!
================================================
FILE: listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/src/main.rs
================================================
fn main() {
println!("Hello, world!");
}
================================================
FILE: listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/Cargo.toml
================================================
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
================================================
FILE: listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/output.txt
================================================
$ cargo build
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
warning: unused `Result` that must be used
--> src/main.rs:10:5
|
10 | io::stdin().read_line(&mut guess);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: this `Result` may be an `Err` variant, which should be handled
= note: `#[warn(unused_must_use)]` on by default
help: use `let _ = ...` to ignore the resulting value
|
10 | let _ = io::stdin().read_line(&mut guess);
| +++++++
warning: `guessing_game` (bin "guessing_game") generated 1 warning
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.59s
================================================
FILE: listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/src/main.rs
================================================
use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess);
println!("You guessed: {guess}");
}
================================================
FILE: listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/Cargo.toml
================================================
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.8.5"
================================================
FILE: listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/src/main.rs
================================================
use std::cmp::Ordering;
use std::io;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
println!("The secret number is: {secret_number}");
println!("Please input your guess.");
// ANCHOR: here
// --snip--
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = guess.trim().parse().expect("Please type a number!");
println!("You guessed: {guess}");
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => println!("You win!"),
}
// ANCHOR_END: here
}
================================================
FILE: listings/ch02-guessing-game-tutorial/no-listing-04-looping/Cargo.toml
================================================
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.8.5"
================================================
FILE: listings/ch02-guessing-game-tutorial/no-listing-04-looping/src/main.rs
================================================
use std::cmp::Ordering;
use std::io;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
// ANCHOR: here
// --snip--
println!("The secret number is: {secret_number}");
loop {
println!("Please input your guess.");
// --snip--
// ANCHOR_END: here
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = guess.trim().parse().expect("Please type a number!");
println!("You guessed: {guess}");
// ANCHOR: here
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => println!("You win!"),
}
}
}
// ANCHOR_END: here
================================================
FILE: listings/ch02-guessing-game-tutorial/no-listing-05-quitting/Cargo.toml
================================================
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.8.5"
================================================
FILE: listings/ch02-guessing-game-tutorial/no-listing-05-quitting/src/main.rs
================================================
use std::cmp::Ordering;
use std::io;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
println!("The secret number is: {secret_number}");
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = guess.trim().parse().expect("Please type a number!");
println!("You guessed: {guess}");
// ANCHOR: here
// --snip--
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
// ANCHOR_END: here
================================================
FILE: listings/ch03-common-programming-concepts/listing-03-01/Cargo.toml
================================================
[package]
name = "functions"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/listing-03-01/src/main.rs
================================================
fn main() {
let y = 6;
}
================================================
FILE: listings/ch03-common-programming-concepts/listing-03-02/Cargo.toml
================================================
[package]
name = "branches"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/listing-03-02/output.txt
================================================
$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.30s
Running `target/debug/branches`
The value of number is: 5
================================================
FILE: listings/ch03-common-programming-concepts/listing-03-02/src/main.rs
================================================
fn main() {
let condition = true;
let number = if condition { 5 } else { 6 };
println!("The value of number is: {number}");
}
================================================
FILE: listings/ch03-common-programming-concepts/listing-03-03/Cargo.toml
================================================
[package]
name = "loops"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/listing-03-03/src/main.rs
================================================
fn main() {
let mut number = 3;
while number != 0 {
println!("{number}!");
number -= 1;
}
println!("LIFTOFF!!!");
}
================================================
FILE: listings/ch03-common-programming-concepts/listing-03-04/Cargo.toml
================================================
[package]
name = "loops"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/listing-03-04/output.txt
================================================
$ cargo run
Compiling loops v0.1.0 (file:///projects/loops)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.32s
Running `target/debug/loops`
the value is: 10
the value is: 20
the value is: 30
the value is: 40
the value is: 50
================================================
FILE: listings/ch03-common-programming-concepts/listing-03-04/src/main.rs
================================================
fn main() {
let a = [10, 20, 30, 40, 50];
let mut index = 0;
while index < 5 {
println!("the value is: {}", a[index]);
index += 1;
}
}
================================================
FILE: listings/ch03-common-programming-concepts/listing-03-05/Cargo.toml
================================================
[package]
name = "loops"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/listing-03-05/src/main.rs
================================================
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a {
println!("the value is: {element}");
}
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/Cargo.toml
================================================
[package]
name = "variables"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/output.txt
================================================
$ cargo run
Compiling variables v0.1.0 (file:///projects/variables)
error[E0384]: cannot assign twice to immutable variable `x`
--> src/main.rs:4:5
|
2 | let x = 5;
| - first assignment to `x`
3 | println!("The value of x is: {x}");
4 | x = 6;
| ^^^^^ cannot assign twice to immutable variable
|
help: consider making this binding mutable
|
2 | let mut x = 5;
| +++
For more information about this error, try `rustc --explain E0384`.
error: could not compile `variables` (bin "variables") due to 1 previous error
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/src/main.rs
================================================
fn main() {
let x = 5;
println!("The value of x is: {x}");
x = 6;
println!("The value of x is: {x}");
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-02-adding-mut/Cargo.toml
================================================
[package]
name = "variables"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-02-adding-mut/output.txt
================================================
$ cargo run
Compiling variables v0.1.0 (file:///projects/variables)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.30s
Running `target/debug/variables`
The value of x is: 5
The value of x is: 6
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-02-adding-mut/src/main.rs
================================================
fn main() {
let mut x = 5;
println!("The value of x is: {x}");
x = 6;
println!("The value of x is: {x}");
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-03-shadowing/Cargo.toml
================================================
[package]
name = "variables"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-03-shadowing/output.txt
================================================
$ cargo run
Compiling variables v0.1.0 (file:///projects/variables)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/variables`
The value of x in the inner scope is: 12
The value of x is: 6
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-03-shadowing/src/main.rs
================================================
fn main() {
let x = 5;
let x = x + 1;
{
let x = x * 2;
println!("The value of x in the inner scope is: {x}");
}
println!("The value of x is: {x}");
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/Cargo.toml
================================================
[package]
name = "variables"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/src/main.rs
================================================
fn main() {
// ANCHOR: here
let spaces = " ";
let spaces = spaces.len();
// ANCHOR_END: here
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/Cargo.toml
================================================
[package]
name = "variables"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/output.txt
================================================
$ cargo run
Compiling variables v0.1.0 (file:///projects/variables)
error[E0308]: mismatched types
--> src/main.rs:3:14
|
2 | let mut spaces = " ";
| ----- expected due to this value
3 | spaces = spaces.len();
| ^^^^^^^^^^^^ expected `&str`, found `usize`
For more information about this error, try `rustc --explain E0308`.
error: could not compile `variables` (bin "variables") due to 1 previous error
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/src/main.rs
================================================
fn main() {
// ANCHOR: here
let mut spaces = " ";
spaces = spaces.len();
// ANCHOR_END: here
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-06-floating-point/Cargo.toml
================================================
[package]
name = "floating-point"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-06-floating-point/src/main.rs
================================================
fn main() {
let x = 2.0; // f64
let y: f32 = 3.0; // f32
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/Cargo.toml
================================================
[package]
name = "numeric-operations"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/src/main.rs
================================================
fn main() {
// addition
let sum = 5 + 10;
// subtraction
let difference = 95.5 - 4.3;
// multiplication
let product = 4 * 30;
// division
let quotient = 56.7 / 32.2;
let truncated = -5 / 3; // Results in -1
// remainder
let remainder = 43 % 5;
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-08-boolean/Cargo.toml
================================================
[package]
name = "boolean"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-08-boolean/src/main.rs
================================================
fn main() {
let t = true;
let f: bool = false; // with explicit type annotation
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-09-char/Cargo.toml
================================================
[package]
name = "char"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-09-char/src/main.rs
================================================
fn main() {
let c = 'z';
let z: char = 'ℤ'; // with explicit type annotation
let heart_eyed_cat = '😻';
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-10-tuples/Cargo.toml
================================================
[package]
name = "tuples"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-10-tuples/src/main.rs
================================================
fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/Cargo.toml
================================================
[package]
name = "tuples"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/src/main.rs
================================================
fn main() {
let tup = (500, 6.4, 1);
let (x, y, z) = tup;
println!("The value of y is: {y}");
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/Cargo.toml
================================================
[package]
name = "tuples"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/src/main.rs
================================================
fn main() {
let x: (i32, f64, u8) = (500, 6.4, 1);
let five_hundred = x.0;
let six_point_four = x.1;
let one = x.2;
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-13-arrays/Cargo.toml
================================================
[package]
name = "arrays"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-13-arrays/src/main.rs
================================================
fn main() {
let a = [1, 2, 3, 4, 5];
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-14-array-indexing/Cargo.toml
================================================
[package]
name = "arrays"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-14-array-indexing/src/main.rs
================================================
fn main() {
let a = [1, 2, 3, 4, 5];
let first = a[0];
let second = a[1];
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/Cargo.toml
================================================
[package]
name = "arrays"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/src/main.rs
================================================
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("Index entered was not a number");
let element = a[index];
println!("The value of the element at index {index} is: {element}");
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-16-functions/Cargo.toml
================================================
[package]
name = "functions"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-16-functions/output.txt
================================================
$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.28s
Running `target/debug/functions`
Hello, world!
Another function.
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-16-functions/src/main.rs
================================================
fn main() {
println!("Hello, world!");
another_function();
}
fn another_function() {
println!("Another function.");
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/Cargo.toml
================================================
[package]
name = "functions"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/output.txt
================================================
$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.21s
Running `target/debug/functions`
The value of x is: 5
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/src/main.rs
================================================
fn main() {
another_function(5);
}
fn another_function(x: i32) {
println!("The value of x is: {x}");
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/Cargo.toml
================================================
[package]
name = "functions"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/output.txt
================================================
$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/functions`
The measurement is: 5h
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/src/main.rs
================================================
fn main() {
print_labeled_measurement(5, 'h');
}
fn print_labeled_measurement(value: i32, unit_label: char) {
println!("The measurement is: {value}{unit_label}");
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/Cargo.toml
================================================
[package]
name = "functions"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/output.txt
================================================
$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
error: expected expression, found `let` statement
--> src/main.rs:2:14
|
2 | let x = (let y = 6);
| ^^^
|
= note: only supported directly in conditions of `if` and `while` expressions
warning: unnecessary parentheses around assigned value
--> src/main.rs:2:13
|
2 | let x = (let y = 6);
| ^ ^
|
= note: `#[warn(unused_parens)]` on by default
help: remove these parentheses
|
2 - let x = (let y = 6);
2 + let x = let y = 6;
|
warning: `functions` (bin "functions") generated 1 warning
error: could not compile `functions` (bin "functions") due to 1 previous error; 1 warning emitted
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/rustfmt-ignore
================================================
This listing deliberately doesn't parse so rustfmt fails.
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/src/main.rs
================================================
fn main() {
let x = (let y = 6);
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/Cargo.toml
================================================
[package]
name = "functions"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/src/main.rs
================================================
fn main() {
let y = {
let x = 3;
x + 1
};
println!("The value of y is: {y}");
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-21-function-return-values/Cargo.toml
================================================
[package]
name = "functions"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-21-function-return-values/output.txt
================================================
$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.30s
Running `target/debug/functions`
The value of x is: 5
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-21-function-return-values/src/main.rs
================================================
fn five() -> i32 {
5
}
fn main() {
let x = five();
println!("The value of x is: {x}");
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/Cargo.toml
================================================
[package]
name = "functions"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/src/main.rs
================================================
fn main() {
let x = plus_one(5);
println!("The value of x is: {x}");
}
fn plus_one(x: i32) -> i32 {
x + 1
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/Cargo.toml
================================================
[package]
name = "functions"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/output.txt
================================================
$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
error[E0308]: mismatched types
--> src/main.rs:7:24
|
7 | fn plus_one(x: i32) -> i32 {
| -------- ^^^ expected `i32`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression
8 | x + 1;
| - help: remove this semicolon to return this value
For more information about this error, try `rustc --explain E0308`.
error: could not compile `functions` (bin "functions") due to 1 previous error
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/src/main.rs
================================================
fn main() {
let x = plus_one(5);
println!("The value of x is: {x}");
}
fn plus_one(x: i32) -> i32 {
x + 1;
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/Cargo.toml
================================================
[package]
name = "comments"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/src/main.rs
================================================
fn main() {
let lucky_number = 7; // I'm feeling lucky today
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/Cargo.toml
================================================
[package]
name = "comments"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/src/main.rs
================================================
fn main() {
// I'm feeling lucky today
let lucky_number = 7;
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-26-if-true/Cargo.toml
================================================
[package]
name = "branches"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-26-if-true/output.txt
================================================
$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/branches`
condition was true
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-26-if-true/src/main.rs
================================================
fn main() {
let number = 3;
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-27-if-false/Cargo.toml
================================================
[package]
name = "branches"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-27-if-false/output.txt
================================================
$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/branches`
condition was false
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-27-if-false/src/main.rs
================================================
fn main() {
// ANCHOR: here
let number = 7;
// ANCHOR_END: here
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/Cargo.toml
================================================
[package]
name = "branches"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/output.txt
================================================
$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
error[E0308]: mismatched types
--> src/main.rs:4:8
|
4 | if number {
| ^^^^^^ expected `bool`, found integer
For more information about this error, try `rustc --explain E0308`.
error: could not compile `branches` (bin "branches") due to 1 previous error
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/src/main.rs
================================================
fn main() {
let number = 3;
if number {
println!("number was three");
}
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/Cargo.toml
================================================
[package]
name = "branches"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/src/main.rs
================================================
fn main() {
let number = 3;
if number != 0 {
println!("number was something other than zero");
}
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-30-else-if/Cargo.toml
================================================
[package]
name = "branches"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-30-else-if/output.txt
================================================
$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/branches`
number is divisible by 3
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-30-else-if/src/main.rs
================================================
fn main() {
let number = 6;
if number % 4 == 0 {
println!("number is divisible by 4");
} else if number % 3 == 0 {
println!("number is divisible by 3");
} else if number % 2 == 0 {
println!("number is divisible by 2");
} else {
println!("number is not divisible by 4, 3, or 2");
}
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/Cargo.toml
================================================
[package]
name = "branches"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/output.txt
================================================
$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
error[E0308]: `if` and `else` have incompatible types
--> src/main.rs:4:44
|
4 | let number = if condition { 5 } else { "six" };
| - ^^^^^ expected integer, found `&str`
| |
| expected because of this
For more information about this error, try `rustc --explain E0308`.
error: could not compile `branches` (bin "branches") due to 1 previous error
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/src/main.rs
================================================
fn main() {
let condition = true;
let number = if condition { 5 } else { "six" };
println!("The value of number is: {number}");
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-32-5-loop-labels/Cargo.toml
================================================
[package]
name = "loops"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-32-5-loop-labels/output.txt
================================================
$ cargo run
Compiling loops v0.1.0 (file:///projects/loops)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.58s
Running `target/debug/loops`
count = 0
remaining = 10
remaining = 9
count = 1
remaining = 10
remaining = 9
count = 2
remaining = 10
End count = 2
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-32-5-loop-labels/src/main.rs
================================================
fn main() {
let mut count = 0;
'counting_up: loop {
println!("count = {count}");
let mut remaining = 10;
loop {
println!("remaining = {remaining}");
if remaining == 9 {
break;
}
if count == 2 {
break 'counting_up;
}
remaining -= 1;
}
count += 1;
}
println!("End count = {count}");
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-32-loop/Cargo.toml
================================================
[package]
name = "loops"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-32-loop/src/main.rs
================================================
fn main() {
loop {
println!("again!");
}
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/Cargo.toml
================================================
[package]
name = "loops"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/src/main.rs
================================================
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("The result is {result}");
}
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-34-for-range/Cargo.toml
================================================
[package]
name = "loops"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/no-listing-34-for-range/src/main.rs
================================================
fn main() {
for number in (1..4).rev() {
println!("{number}!");
}
println!("LIFTOFF!!!");
}
================================================
FILE: listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/Cargo.toml
================================================
[package]
name = "no_type_annotations"
version = "0.1.0"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
================================================
FILE: listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/output.txt
================================================
$ cargo build
Compiling no_type_annotations v0.1.0 (file:///projects/no_type_annotations)
error[E0284]: type annotations needed
--> src/main.rs:2:9
|
2 | let guess = "42".parse().expect("Not a number!");
| ^^^^^ ----- type must be known at this point
|
= note: cannot satisfy `<_ as FromStr>::Err == _`
help: consider giving `guess` an explicit type
|
2 | let guess: /* Type */ = "42".parse().expect("Not a number!");
| ++++++++++++
For more information about this error, try `rustc --explain E0284`.
error: could not compile `no_type_annotations` (bin "no_type_annotations") due to 1 previous error
================================================
FILE: listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/src/main.rs
================================================
fn main() {
let guess = "42".parse().expect("Not a number!");
}
================================================
FILE: listings/ch04-understanding-ownership/listing-04-01/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/listing-04-01/rustfmt-ignore
================================================
We have some weird comments pointing out borrowing scopes that we don't want to change;
unfortunately I haven't found a way to skip them with rustfmt that works so for now we're going to
manually skip those listings. See: https://github.com/rust-lang/rustfmt/issues/4028
================================================
FILE: listings/ch04-understanding-ownership/listing-04-01/src/main.rs
================================================
fn main() {
// ANCHOR: here
{ // s is not valid here, since it's not yet declared
let s = "hello"; // s is valid from this point forward
// do stuff with s
} // this scope is now over, and s is no longer valid
// ANCHOR_END: here
}
================================================
FILE: listings/ch04-understanding-ownership/listing-04-02/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/listing-04-02/src/main.rs
================================================
fn main() {
// ANCHOR: here
let x = 5;
let y = x;
// ANCHOR_END: here
}
================================================
FILE: listings/ch04-understanding-ownership/listing-04-03/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/listing-04-03/rustfmt-ignore
================================================
We have some weird comments pointing out borrowing scopes that we don't want to change;
unfortunately I haven't found a way to skip them with rustfmt that works so for now we're going to
manually skip those listings. See: https://github.com/rust-lang/rustfmt/issues/4028
================================================
FILE: listings/ch04-understanding-ownership/listing-04-03/src/main.rs
================================================
fn main() {
let s = String::from("hello"); // s comes into scope
takes_ownership(s); // s's value moves into the function...
// ... and so is no longer valid here
let x = 5; // x comes into scope
makes_copy(x); // Because i32 implements the Copy trait,
// x does NOT move into the function,
// so it's okay to use x afterward.
} // Here, x goes out of scope, then s. However, because s's value was moved,
// nothing special happens.
fn takes_ownership(some_string: String) { // some_string comes into scope
println!("{some_string}");
} // Here, some_string goes out of scope and `drop` is called. The backing
// memory is freed.
fn makes_copy(some_integer: i32) { // some_integer comes into scope
println!("{some_integer}");
} // Here, some_integer goes out of scope. Nothing special happens.
================================================
FILE: listings/ch04-understanding-ownership/listing-04-04/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/listing-04-04/rustfmt-ignore
================================================
We have some weird comments pointing out borrowing scopes that we don't want to change;
unfortunately I haven't found a way to skip them with rustfmt that works so for now we're going to
manually skip those listings. See: https://github.com/rust-lang/rustfmt/issues/4028
================================================
FILE: listings/ch04-understanding-ownership/listing-04-04/src/main.rs
================================================
fn main() {
let s1 = gives_ownership(); // gives_ownership moves its return
// value into s1
let s2 = String::from("hello"); // s2 comes into scope
let s3 = takes_and_gives_back(s2); // s2 is moved into
// takes_and_gives_back, which also
// moves its return value into s3
} // Here, s3 goes out of scope and is dropped. s2 was moved, so nothing
// happens. s1 goes out of scope and is dropped.
fn gives_ownership() -> String { // gives_ownership will move its
// return value into the function
// that calls it
let some_string = String::from("yours"); // some_string comes into scope
some_string // some_string is returned and
// moves out to the calling
// function
}
// This function takes a String and returns a String.
fn takes_and_gives_back(a_string: String) -> String {
// a_string comes into
// scope
a_string // a_string is returned and moves out to the calling function
}
================================================
FILE: listings/ch04-understanding-ownership/listing-04-05/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/listing-04-05/src/main.rs
================================================
fn main() {
let s1 = String::from("hello");
let (s2, len) = calculate_length(s1);
println!("The length of '{s2}' is {len}.");
}
fn calculate_length(s: String) -> (String, usize) {
let length = s.len(); // len() returns the length of a String
(s, length)
}
================================================
FILE: listings/ch04-understanding-ownership/listing-04-06/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/listing-04-06/output.txt
================================================
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0596]: cannot borrow `*some_string` as mutable, as it is behind a `&` reference
--> src/main.rs:8:5
|
8 | some_string.push_str(", world");
| ^^^^^^^^^^^ `some_string` is a `&` reference, so the data it refers to cannot be borrowed as mutable
|
help: consider changing this to be a mutable reference
|
7 | fn change(some_string: &mut String) {
| +++
For more information about this error, try `rustc --explain E0596`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
================================================
FILE: listings/ch04-understanding-ownership/listing-04-06/src/main.rs
================================================
fn main() {
let s = String::from("hello");
change(&s);
}
fn change(some_string: &String) {
some_string.push_str(", world");
}
================================================
FILE: listings/ch04-understanding-ownership/listing-04-07/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/listing-04-07/src/main.rs
================================================
// ANCHOR: here
fn first_word(s: &String) -> usize {
// ANCHOR: as_bytes
let bytes = s.as_bytes();
// ANCHOR_END: as_bytes
// ANCHOR: iter
for (i, &item) in bytes.iter().enumerate() {
// ANCHOR_END: iter
// ANCHOR: inside_for
if item == b' ' {
return i;
}
}
s.len()
// ANCHOR_END: inside_for
}
// ANCHOR_END: here
fn main() {}
================================================
FILE: listings/ch04-understanding-ownership/listing-04-08/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/listing-04-08/src/main.rs
================================================
fn first_word(s: &String) -> usize {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
// ANCHOR: here
fn main() {
let mut s = String::from("hello world");
let word = first_word(&s); // word will get the value 5
s.clear(); // this empties the String, making it equal to ""
// word still has the value 5 here, but s no longer has any content that we
// could meaningfully use with the value 5, so word is now totally invalid!
}
// ANCHOR_END: here
================================================
FILE: listings/ch04-understanding-ownership/listing-04-09/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/listing-04-09/src/main.rs
================================================
// ANCHOR: here
fn first_word(s: &str) -> &str {
// ANCHOR_END: here
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
// ANCHOR: usage
fn main() {
let my_string = String::from("hello world");
// `first_word` works on slices of `String`s, whether partial or whole.
let word = first_word(&my_string[0..6]);
let word = first_word(&my_string[..]);
// `first_word` also works on references to `String`s, which are equivalent
// to whole slices of `String`s.
let word = first_word(&my_string);
let my_string_literal = "hello world";
// `first_word` works on slices of string literals, whether partial or
// whole.
let word = first_word(&my_string_literal[0..6]);
let word = first_word(&my_string_literal[..]);
// Because string literals *are* string slices already,
// this works too, without the slice syntax!
let word = first_word(my_string_literal);
}
// ANCHOR_END: usage
================================================
FILE: listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/src/main.rs
================================================
fn main() {
// ANCHOR: here
let mut s = String::from("hello");
s.push_str(", world!"); // push_str() appends a literal to a String
println!("{s}"); // this will print `hello, world!`
// ANCHOR_END: here
}
================================================
FILE: listings/ch04-understanding-ownership/no-listing-02-string-scope/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/no-listing-02-string-scope/rustfmt-ignore
================================================
We have some weird comments pointing out borrowing scopes that we don't want to change;
unfortunately I haven't found a way to skip them with rustfmt that works so for now we're going to
manually skip those listings. See: https://github.com/rust-lang/rustfmt/issues/4028
================================================
FILE: listings/ch04-understanding-ownership/no-listing-02-string-scope/src/main.rs
================================================
fn main() {
// ANCHOR: here
{
let s = String::from("hello"); // s is valid from this point forward
// do stuff with s
} // this scope is now over, and s is no
// longer valid
// ANCHOR_END: here
}
================================================
FILE: listings/ch04-understanding-ownership/no-listing-03-string-move/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/no-listing-03-string-move/src/main.rs
================================================
fn main() {
// ANCHOR: here
let s1 = String::from("hello");
let s2 = s1;
// ANCHOR_END: here
}
================================================
FILE: listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/output.txt
================================================
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0382]: borrow of moved value: `s1`
--> src/main.rs:5:16
|
2 | let s1 = String::from("hello");
| -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait
3 | let s2 = s1;
| -- value moved here
4 |
5 | println!("{s1}, world!");
| ^^ value borrowed here after move
|
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider cloning the value if the performance cost is acceptable
|
3 | let s2 = s1.clone();
| ++++++++
For more information about this error, try `rustc --explain E0382`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
================================================
FILE: listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/src/main.rs
================================================
fn main() {
// ANCHOR: here
let s1 = String::from("hello");
let s2 = s1;
println!("{s1}, world!");
// ANCHOR_END: here
}
================================================
FILE: listings/ch04-understanding-ownership/no-listing-04b-replacement-drop/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/no-listing-04b-replacement-drop/src/main.rs
================================================
fn main() {
// ANCHOR: here
let mut s = String::from("hello");
s = String::from("ahoy");
println!("{s}, world!");
// ANCHOR_END: here
}
================================================
FILE: listings/ch04-understanding-ownership/no-listing-05-clone/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/no-listing-05-clone/src/main.rs
================================================
fn main() {
// ANCHOR: here
let s1 = String::from("hello");
let s2 = s1.clone();
println!("s1 = {s1}, s2 = {s2}");
// ANCHOR_END: here
}
================================================
FILE: listings/ch04-understanding-ownership/no-listing-06-copy/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/no-listing-06-copy/src/main.rs
================================================
fn main() {
// ANCHOR: here
let x = 5;
let y = x;
println!("x = {x}, y = {y}");
// ANCHOR_END: here
}
================================================
FILE: listings/ch04-understanding-ownership/no-listing-07-reference/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/no-listing-07-reference/src/main.rs
================================================
// ANCHOR: all
fn main() {
// ANCHOR: here
let s1 = String::from("hello");
let len = calculate_length(&s1);
// ANCHOR_END: here
println!("The length of '{s1}' is {len}.");
}
fn calculate_length(s: &String) -> usize {
s.len()
}
// ANCHOR_END: all
================================================
FILE: listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/rustfmt-ignore
================================================
We have some weird comments pointing out borrowing scopes that we don't want to change;
unfortunately I haven't found a way to skip them with rustfmt that works so for now we're going to
manually skip those listings. See: https://github.com/rust-lang/rustfmt/issues/4028
================================================
FILE: listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/src/main.rs
================================================
fn main() {
let s1 = String::from("hello");
let len = calculate_length(&s1);
println!("The length of '{s1}' is {len}.");
}
// ANCHOR: here
fn calculate_length(s: &String) -> usize { // s is a reference to a String
s.len()
} // Here, s goes out of scope. But because s does not have ownership of what
// it refers to, the String is not dropped.
// ANCHOR_END: here
================================================
FILE: listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/src/main.rs
================================================
fn main() {
let mut s = String::from("hello");
change(&mut s);
}
fn change(some_string: &mut String) {
some_string.push_str(", world");
}
================================================
FILE: listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/output.txt
================================================
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0499]: cannot borrow `s` as mutable more than once at a time
--> src/main.rs:5:14
|
4 | let r1 = &mut s;
| ------ first mutable borrow occurs here
5 | let r2 = &mut s;
| ^^^^^^ second mutable borrow occurs here
6 |
7 | println!("{r1}, {r2}");
| -- first borrow later used here
For more information about this error, try `rustc --explain E0499`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
================================================
FILE: listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/src/main.rs
================================================
fn main() {
// ANCHOR: here
let mut s = String::from("hello");
let r1 = &mut s;
let r2 = &mut s;
println!("{r1}, {r2}");
// ANCHOR_END: here
}
================================================
FILE: listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/src/main.rs
================================================
fn main() {
// ANCHOR: here
let mut s = String::from("hello");
{
let r1 = &mut s;
} // r1 goes out of scope here, so we can make a new reference with no problems.
let r2 = &mut s;
// ANCHOR_END: here
}
================================================
FILE: listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/output.txt
================================================
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
--> src/main.rs:6:14
|
4 | let r1 = &s; // no problem
| -- immutable borrow occurs here
5 | let r2 = &s; // no problem
6 | let r3 = &mut s; // BIG PROBLEM
| ^^^^^^ mutable borrow occurs here
7 |
8 | println!("{r1}, {r2}, and {r3}");
| -- immutable borrow later used here
For more information about this error, try `rustc --explain E0502`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
================================================
FILE: listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/src/main.rs
================================================
fn main() {
// ANCHOR: here
let mut s = String::from("hello");
let r1 = &s; // no problem
let r2 = &s; // no problem
let r3 = &mut s; // BIG PROBLEM
println!("{r1}, {r2}, and {r3}");
// ANCHOR_END: here
}
================================================
FILE: listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/src/main.rs
================================================
fn main() {
// ANCHOR: here
let mut s = String::from("hello");
let r1 = &s; // no problem
let r2 = &s; // no problem
println!("{r1} and {r2}");
// Variables r1 and r2 will not be used after this point.
let r3 = &mut s; // no problem
println!("{r3}");
// ANCHOR_END: here
}
================================================
FILE: listings/ch04-understanding-ownership/no-listing-14-dangling-reference/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/no-listing-14-dangling-reference/output.txt
================================================
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0106]: missing lifetime specifier
--> src/main.rs:5:16
|
5 | fn dangle() -> &String {
| ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static`
|
5 | fn dangle() -> &'static String {
| +++++++
help: instead, you are more likely to want to return an owned value
|
5 - fn dangle() -> &String {
5 + fn dangle() -> String {
|
For more information about this error, try `rustc --explain E0106`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
================================================
FILE: listings/ch04-understanding-ownership/no-listing-14-dangling-reference/src/main.rs
================================================
fn main() {
let reference_to_nothing = dangle();
}
fn dangle() -> &String {
let s = String::from("hello");
&s
}
================================================
FILE: listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/rustfmt-ignore
================================================
We have some weird comments pointing out borrowing scopes that we don't want to change;
unfortunately I haven't found a way to skip them with rustfmt that works so for now we're going to
manually skip those listings. See: https://github.com/rust-lang/rustfmt/issues/4028
================================================
FILE: listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/src/main.rs
================================================
fn main() {
let reference_to_nothing = dangle();
}
// ANCHOR: here
fn dangle() -> &String { // dangle returns a reference to a String
let s = String::from("hello"); // s is a new String
&s // we return a reference to the String, s
} // Here, s goes out of scope and is dropped, so its memory goes away.
// Danger!
// ANCHOR_END: here
================================================
FILE: listings/ch04-understanding-ownership/no-listing-16-no-dangle/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/no-listing-16-no-dangle/src/main.rs
================================================
fn main() {
let string = no_dangle();
}
// ANCHOR: here
fn no_dangle() -> String {
let s = String::from("hello");
s
}
// ANCHOR_END: here
================================================
FILE: listings/ch04-understanding-ownership/no-listing-17-slice/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/no-listing-17-slice/src/main.rs
================================================
fn main() {
// ANCHOR: here
let s = String::from("hello world");
let hello = &s[0..5];
let world = &s[6..11];
// ANCHOR_END: here
}
================================================
FILE: listings/ch04-understanding-ownership/no-listing-18-first-word-slice/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/no-listing-18-first-word-slice/src/main.rs
================================================
// ANCHOR: here
fn first_word(s: &String) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
// ANCHOR_END: here
fn main() {}
================================================
FILE: listings/ch04-understanding-ownership/no-listing-19-slice-error/Cargo.toml
================================================
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch04-understanding-ownership/no-listing-19-slice-error/output.txt
================================================
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
--> src/main.rs:18:5
|
16 | let word = first_word(&s);
| -- immutable borrow occurs here
17 |
18 | s.clear(); // error!
| ^^^^^^^^^ mutable borrow occurs here
19 |
20 | println!("the first word is: {word}");
| ---- immutable borrow later used here
For more information about this error, try `rustc --explain E0502`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
================================================
FILE: listings/ch04-understanding-ownership/no-listing-19-slice-error/src/main.rs
================================================
fn first_word(s: &String) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
// ANCHOR: here
fn main() {
let mut s = String::from("hello world");
let word = first_word(&s);
s.clear(); // error!
println!("the first word is: {word}");
}
// ANCHOR_END: here
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-01/Cargo.toml
================================================
[package]
name = "structs"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-01/src/main.rs
================================================
// ANCHOR: here
struct User {
active: bool,
username: String,
email: String,
sign_in_count: u64,
}
// ANCHOR_END: here
fn main() {}
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-02/Cargo.toml
================================================
[package]
name = "structs"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-02/src/main.rs
================================================
struct User {
active: bool,
username: String,
email: String,
sign_in_count: u64,
}
// ANCHOR: here
fn main() {
let user1 = User {
active: true,
username: String::from("someusername123"),
email: String::from("someone@example.com"),
sign_in_count: 1,
};
}
// ANCHOR_END: here
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-03/Cargo.toml
================================================
[package]
name = "structs"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-03/src/main.rs
================================================
struct User {
active: bool,
username: String,
email: String,
sign_in_count: u64,
}
// ANCHOR: here
fn main() {
let mut user1 = User {
active: true,
username: String::from("someusername123"),
email: String::from("someone@example.com"),
sign_in_count: 1,
};
user1.email = String::from("anotheremail@example.com");
}
// ANCHOR_END: here
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-04/Cargo.toml
================================================
[package]
name = "structs"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-04/src/main.rs
================================================
struct User {
active: bool,
username: String,
email: String,
sign_in_count: u64,
}
// ANCHOR: here
fn build_user(email: String, username: String) -> User {
User {
active: true,
username: username,
email: email,
sign_in_count: 1,
}
}
// ANCHOR_END: here
fn main() {
let user1 = build_user(
String::from("someone@example.com"),
String::from("someusername123"),
);
}
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-05/Cargo.toml
================================================
[package]
name = "structs"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-05/src/main.rs
================================================
struct User {
active: bool,
username: String,
email: String,
sign_in_count: u64,
}
// ANCHOR: here
fn build_user(email: String, username: String) -> User {
User {
active: true,
username,
email,
sign_in_count: 1,
}
}
// ANCHOR_END: here
fn main() {
let user1 = build_user(
String::from("someone@example.com"),
String::from("someusername123"),
);
}
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-06/Cargo.toml
================================================
[package]
name = "structs"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-06/src/main.rs
================================================
struct User {
active: bool,
username: String,
email: String,
sign_in_count: u64,
}
// ANCHOR: here
fn main() {
// --snip--
// ANCHOR_END: here
let user1 = User {
email: String::from("someone@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
// ANCHOR: here
let user2 = User {
active: user1.active,
username: user1.username,
email: String::from("another@example.com"),
sign_in_count: user1.sign_in_count,
};
}
// ANCHOR_END: here
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-07/Cargo.toml
================================================
[package]
name = "structs"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-07/src/main.rs
================================================
struct User {
active: bool,
username: String,
email: String,
sign_in_count: u64,
}
// ANCHOR: here
fn main() {
// --snip--
// ANCHOR_END: here
let user1 = User {
email: String::from("someone@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
// ANCHOR: here
let user2 = User {
email: String::from("another@example.com"),
..user1
};
}
// ANCHOR_END: here
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-08/Cargo.toml
================================================
[package]
name = "rectangles"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-08/output.txt
================================================
$ cargo run
Compiling rectangles v0.1.0 (file:///projects/rectangles)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.42s
Running `target/debug/rectangles`
The area of the rectangle is 1500 square pixels.
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-08/src/main.rs
================================================
// ANCHOR: all
fn main() {
let width1 = 30;
let height1 = 50;
println!(
"The area of the rectangle is {} square pixels.",
area(width1, height1)
);
}
// ANCHOR: here
fn area(width: u32, height: u32) -> u32 {
// ANCHOR_END: here
width * height
}
// ANCHOR_END: all
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-09/Cargo.toml
================================================
[package]
name = "rectangles"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-09/src/main.rs
================================================
fn main() {
let rect1 = (30, 50);
println!(
"The area of the rectangle is {} square pixels.",
area(rect1)
);
}
fn area(dimensions: (u32, u32)) -> u32 {
dimensions.0 * dimensions.1
}
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-10/Cargo.toml
================================================
[package]
name = "rectangles"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-10/src/main.rs
================================================
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!(
"The area of the rectangle is {} square pixels.",
area(&rect1)
);
}
fn area(rectangle: &Rectangle) -> u32 {
rectangle.width * rectangle.height
}
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-11/Cargo.toml
================================================
[package]
name = "rectangles"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-11/output.txt
================================================
$ cargo run
Compiling rectangles v0.1.0 (file:///projects/rectangles)
error[E0277]: `Rectangle` doesn't implement `std::fmt::Display`
--> src/main.rs:12:25
|
12 | println!("rect1 is {rect1}");
| -^^^^^-
| ||
| |`Rectangle` cannot be formatted with the default formatter
| required by this formatting parameter
|
= help: the trait `std::fmt::Display` is not implemented for `Rectangle`
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
For more information about this error, try `rustc --explain E0277`.
error: could not compile `rectangles` (bin "rectangles") due to 1 previous error
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-11/src/main.rs
================================================
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!("rect1 is {rect1}");
}
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-12/Cargo.toml
================================================
[package]
name = "rectangles"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-12/output.txt
================================================
$ cargo run
Compiling rectangles v0.1.0 (file:///projects/rectangles)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.48s
Running `target/debug/rectangles`
rect1 is Rectangle { width: 30, height: 50 }
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-12/src/main.rs
================================================
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!("rect1 is {rect1:?}");
}
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-13/Cargo.toml
================================================
[package]
name = "rectangles"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-13/src/main.rs
================================================
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!(
"The area of the rectangle is {} square pixels.",
rect1.area()
);
}
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-14/Cargo.toml
================================================
[package]
name = "rectangles"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-14/src/main.rs
================================================
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
}
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-15/Cargo.toml
================================================
[package]
name = "rectangles"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-15/src/main.rs
================================================
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
// ANCHOR: here
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
// ANCHOR_END: here
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
}
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-16/Cargo.toml
================================================
[package]
name = "rectangles"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/listing-05-16/src/main.rs
================================================
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
// ANCHOR: here
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
impl Rectangle {
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
// ANCHOR_END: here
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
}
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/Cargo.toml
================================================
[package]
name = "structs"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/src/main.rs
================================================
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
fn main() {
let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);
}
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/Cargo.toml
================================================
[package]
name = "structs"
version = "0.1.0"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/output.txt
================================================
$ cargo run
Compiling structs v0.1.0 (file:///projects/structs)
error[E0106]: missing lifetime specifier
--> src/main.rs:3:15
|
3 | username: &str,
| ^ expected named lifetime parameter
|
help: consider introducing a named lifetime parameter
|
1 ~ struct User<'a> {
2 | active: bool,
3 ~ username: &'a str,
|
error[E0106]: missing lifetime specifier
--> src/main.rs:4:12
|
4 | email: &str,
| ^ expected named lifetime parameter
|
help: consider introducing a named lifetime parameter
|
1 ~ struct User<'a> {
2 | active: bool,
3 | username: &str,
4 ~ email: &'a str,
|
For more information about this error, try `rustc --explain E0106`.
error: could not compile `structs` (bin "structs") due to 2 previous errors
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/src/main.rs
================================================
struct User {
active: bool,
username: &str,
email: &str,
sign_in_count: u64,
}
fn main() {
let user1 = User {
email: "someone@example.com",
username: "someusername123",
active: true,
sign_in_count: 1,
};
}
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/Cargo.toml
================================================
[package]
name = "rectangles"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/src/main.rs
================================================
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
// ANCHOR: here
impl Rectangle {
fn square(size: u32) -> Self {
Self {
width: size,
height: size,
}
}
}
// ANCHOR_END: here
fn main() {
let sq = Rectangle::square(3);
}
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/no-listing-04-unit-like-structs/Cargo.toml
================================================
[package]
name = "structs"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/no-listing-04-unit-like-structs/src/main.rs
================================================
struct AlwaysEqual;
fn main() {
let subject = AlwaysEqual;
}
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/no-listing-05-dbg-macro/Cargo.toml
================================================
[package]
name = "rectangles"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/no-listing-05-dbg-macro/output.txt
================================================
$ cargo run
Compiling rectangles v0.1.0 (file:///projects/rectangles)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.61s
Running `target/debug/rectangles`
[src/main.rs:10:16] 30 * scale = 60
[src/main.rs:14:5] &rect1 = Rectangle {
width: 60,
height: 50,
}
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/no-listing-05-dbg-macro/src/main.rs
================================================
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let scale = 2;
let rect1 = Rectangle {
width: dbg!(30 * scale),
height: 50,
};
dbg!(&rect1);
}
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/no-listing-06-method-field-interaction/Cargo.toml
================================================
[package]
name = "rectangles"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/no-listing-06-method-field-interaction/src/main.rs
================================================
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
// ANCHOR: here
impl Rectangle {
fn width(&self) -> bool {
self.width > 0
}
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
if rect1.width() {
println!("The rectangle has a nonzero width; it is {}", rect1.width);
}
}
// ANCHOR_END: here
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/Cargo.toml
================================================
[package]
name = "rectangles"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/output.txt
================================================
$ cargo run
Compiling rectangles v0.1.0 (file:///projects/rectangles)
error[E0277]: `Rectangle` doesn't implement `Debug`
--> src/main.rs:12:31
|
12 | println!("rect1 is {:?}", rect1);
| ---- ^^^^^ `Rectangle` cannot be formatted using `{:?}` because it doesn't implement `Debug`
| |
| required by this formatting parameter
|
= help: the trait `Debug` is not implemented for `Rectangle`
= note: add `#[derive(Debug)]` to `Rectangle` or manually `impl Debug for Rectangle`
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider annotating `Rectangle` with `#[derive(Debug)]`
|
1 + #[derive(Debug)]
2 | struct Rectangle {
|
For more information about this error, try `rustc --explain E0277`.
error: could not compile `rectangles` (bin "rectangles") due to 1 previous error
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/src/main.rs
================================================
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!("rect1 is {:?}", rect1);
}
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/Cargo.toml
================================================
[package]
name = "rectangles"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/output.txt
================================================
$ cargo run
Compiling rectangles v0.1.0 (file:///projects/rectangles)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.48s
Running `target/debug/rectangles`
rect1 is Rectangle {
width: 30,
height: 50,
}
================================================
FILE: listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/src/main.rs
================================================
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!("rect1 is {rect1:#?}");
}
================================================
FILE: listings/ch06-enums-and-pattern-matching/listing-06-01/Cargo.toml
================================================
[package]
name = "enums"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch06-enums-and-pattern-matching/listing-06-01/src/main.rs
================================================
fn main() {
// ANCHOR: here
enum IpAddrKind {
V4,
V6,
}
struct IpAddr {
kind: IpAddrKind,
address: String,
}
let home = IpAddr {
kind: IpAddrKind::V4,
address: String::from("127.0.0.1"),
};
let loopback = IpAddr {
kind: IpAddrKind::V6,
address: String::from("::1"),
};
// ANCHOR_END: here
}
================================================
FILE: listings/ch06-enums-and-pattern-matching/listing-06-02/Cargo.toml
================================================
[package]
name = "enums"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch06-enums-and-pattern-matching/listing-06-02/src/main.rs
================================================
// ANCHOR: here
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
// ANCHOR_END: here
fn main() {}
================================================
FILE: listings/ch06-enums-and-pattern-matching/listing-06-03/Cargo.toml
================================================
[package]
name = "enums"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch06-enums-and-pattern-matching/listing-06-03/src/main.rs
================================================
// ANCHOR: here
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
}
// ANCHOR_END: here
fn main() {}
================================================
FILE: listings/ch06-enums-and-pattern-matching/listing-06-04/Cargo.toml
================================================
[package]
name = "enums"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch06-enums-and-pattern-matching/listing-06-04/src/main.rs
================================================
// ANCHOR: here
#[derive(Debug)] // so we can inspect the state in a minute
enum UsState {
Alabama,
Alaska,
// --snip--
}
enum Coin {
Penny,
Nickel,
Dime,
Quarter(UsState),
}
// ANCHOR_END: here
fn main() {}
================================================
FILE: listings/ch06-enums-and-pattern-matching/listing-06-05/Cargo.toml
================================================
[package]
name = "enums"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch06-enums-and-pattern-matching/listing-06-05/src/main.rs
================================================
fn main() {
// ANCHOR: here
fn plus_one(x: Option) -> Option {
match x {
// ANCHOR: first_arm
None => None,
// ANCHOR_END: first_arm
// ANCHOR: second_arm
Some(i) => Some(i + 1),
// ANCHOR_END: second_arm
}
}
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
// ANCHOR_END: here
}
================================================
FILE: listings/ch06-enums-and-pattern-matching/listing-06-06/Cargo.toml
================================================
[package]
name = "enums"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch06-enums-and-pattern-matching/listing-06-06/src/main.rs
================================================
fn main() {
// ANCHOR: here
let config_max = Some(3u8);
match config_max {
Some(max) => println!("The maximum is configured to be {max}"),
_ => (),
}
// ANCHOR_END: here
}
================================================
FILE: listings/ch06-enums-and-pattern-matching/listing-06-07/Cargo.toml
================================================
[package]
name = "enums"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch06-enums-and-pattern-matching/listing-06-07/src/main.rs
================================================
#[derive(Debug)] // so we can inspect the state in a minute
enum UsState {
Alabama,
Alaska,
// --snip--
}
// ANCHOR: state
impl UsState {
fn existed_in(&self, year: u16) -> bool {
match self {
UsState::Alabama => year >= 1819,
UsState::Alaska => year >= 1959,
// -- snip --
}
}
}
// ANCHOR_END: state
enum Coin {
Penny,
Nickel,
Dime,
Quarter(UsState),
}
// ANCHOR: describe
fn describe_state_quarter(coin: Coin) -> Option {
if let Coin::Quarter(state) = coin {
if state.existed_in(1900) {
Some(format!("{state:?} is pretty old, for America!"))
} else {
Some(format!("{state:?} is relatively new."))
}
} else {
None
}
}
// ANCHOR_END: describe
fn main() {
if let Some(desc) = describe_state_quarter(Coin::Quarter(UsState::Alaska)) {
println!("{desc}");
}
}
================================================
FILE: listings/ch06-enums-and-pattern-matching/listing-06-08/Cargo.toml
================================================
[package]
name = "enums"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch06-enums-and-pattern-matching/listing-06-08/src/main.rs
================================================
#[derive(Debug)] // so we can inspect the state in a minute
enum UsState {
Alabama,
Alaska,
// --snip--
}
impl UsState {
fn existed_in(&self, year: u16) -> bool {
match self {
UsState::Alabama => year >= 1819,
UsState::Alaska => year >= 1959,
// -- snip --
}
}
}
enum Coin {
Penny,
Nickel,
Dime,
Quarter(UsState),
}
// ANCHOR: describe
fn describe_state_quarter(coin: Coin) -> Option {
let state = if let Coin::Quarter(state) = coin {
state
} else {
return None;
};
if state.existed_in(1900) {
Some(format!("{state:?} is pretty old, for America!"))
} else {
Some(format!("{state:?} is relatively new."))
}
}
// ANCHOR_END: describe
fn main() {
if let Some(desc) = describe_state_quarter(Coin::Quarter(UsState::Alaska)) {
println!("{desc}");
}
}
================================================
FILE: listings/ch06-enums-and-pattern-matching/listing-06-09/Cargo.toml
================================================
[package]
name = "enums"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch06-enums-and-pattern-matching/listing-06-09/src/main.rs
================================================
#[derive(Debug)] // so we can inspect the state in a minute
enum UsState {
Alabama,
Alaska,
// --snip--
}
impl UsState {
fn existed_in(&self, year: u16) -> bool {
match self {
UsState::Alabama => year >= 1819,
UsState::Alaska => year >= 1959,
// -- snip --
}
}
}
enum Coin {
Penny,
Nickel,
Dime,
Quarter(UsState),
}
// ANCHOR: describe
fn describe_state_quarter(coin: Coin) -> Option {
let Coin::Quarter(state) = coin else {
return None;
};
if state.existed_in(1900) {
Some(format!("{state:?} is pretty old, for America!"))
} else {
Some(format!("{state:?} is relatively new."))
}
}
// ANCHOR_END: describe
fn main() {
if let Some(desc) = describe_state_quarter(Coin::Quarter(UsState::Alaska)) {
println!("{desc}");
}
}
================================================
FILE: listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/Cargo.toml
================================================
[package]
name = "enums"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/src/main.rs
================================================
// ANCHOR: def
enum IpAddrKind {
V4,
V6,
}
// ANCHOR_END: def
fn main() {
// ANCHOR: instance
let four = IpAddrKind::V4;
let six = IpAddrKind::V6;
// ANCHOR_END: instance
// ANCHOR: fn_call
route(IpAddrKind::V4);
route(IpAddrKind::V6);
// ANCHOR_END: fn_call
}
// ANCHOR: fn
fn route(ip_kind: IpAddrKind) {}
// ANCHOR_END: fn
================================================
FILE: listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/Cargo.toml
================================================
[package]
name = "enums"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/src/main.rs
================================================
fn main() {
// ANCHOR: here
enum IpAddr {
V4(String),
V6(String),
}
let home = IpAddr::V4(String::from("127.0.0.1"));
let loopback = IpAddr::V6(String::from("::1"));
// ANCHOR_END: here
}
================================================
FILE: listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/Cargo.toml
================================================
[package]
name = "enums"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/src/main.rs
================================================
fn main() {
// ANCHOR: here
enum IpAddr {
V4(u8, u8, u8, u8),
V6(String),
}
let home = IpAddr::V4(127, 0, 0, 1);
let loopback = IpAddr::V6(String::from("::1"));
// ANCHOR_END: here
}
================================================
FILE: listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/Cargo.toml
================================================
[package]
name = "enums"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/src/main.rs
================================================
// ANCHOR: here
struct QuitMessage; // unit struct
struct MoveMessage {
x: i32,
y: i32,
}
struct WriteMessage(String); // tuple struct
struct ChangeColorMessage(i32, i32, i32); // tuple struct
// ANCHOR_END: here
fn main() {}
================================================
FILE: listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/Cargo.toml
================================================
[package]
name = "enums"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/src/main.rs
================================================
fn main() {
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
// ANCHOR: here
impl Message {
fn call(&self) {
// method body would be defined here
}
}
let m = Message::Write(String::from("hello"));
m.call();
// ANCHOR_END: here
}
================================================
FILE: listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/Cargo.toml
================================================
[package]
name = "enums"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/src/main.rs
================================================
fn main() {
// ANCHOR: here
let some_number = Some(5);
let some_char = Some('e');
let absent_number: Option = None;
// ANCHOR_END: here
}
================================================
FILE: listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/Cargo.toml
================================================
[package]
name = "enums"
version = "0.1.0"
edition = "2024"
[dependencies]
================================================
FILE: listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/output.txt
================================================
$ cargo run
Compiling enums v0.1.0 (file:///projects/enums)
error[E0277]: cannot add `Option` to `i8`
--> src/main.rs:5:17
|
5 | let sum = x + y;
| ^ no implementation for `i8 + Option`
|
= help: the trait `Add