diff --git a/.cargo/config b/.cargo/config new file mode 100644 index 0000000000..2de1871303 --- /dev/null +++ b/.cargo/config @@ -0,0 +1,3 @@ +[cargo-new] +name = "Your Name" +email = "you@example.com" diff --git a/2018-edition/book.toml b/2018-edition/book.toml new file mode 100644 index 0000000000..9c71e2a918 --- /dev/null +++ b/2018-edition/book.toml @@ -0,0 +1,7 @@ +[book] +title = "The Rust Programming Language" +author = "Steve Klabnik and Carol Nichols, with Contributions from the Rust Community" + +[output.html] +additional-css = ["ferris.css", "src/theme/2018-edition.css"] +additional-js = ["ferris.js"] diff --git a/src/dot/trpl04-01.dot b/2018-edition/dot/trpl04-01.dot similarity index 62% rename from src/dot/trpl04-01.dot rename to 2018-edition/dot/trpl04-01.dot index f8aa8fb451..331d591338 100644 --- a/src/dot/trpl04-01.dot +++ b/2018-edition/dot/trpl04-01.dot @@ -6,17 +6,17 @@ digraph { table0[label=< - + - - + +
s1
nomevalor
namevalue
ptr
tamanho5
capacidade5
len5
capacity5
>]; table1[label=< - - + + - - + +
índicevalor
0t
indexvalue
0h
1e
2x
3t
2l
3l
4o
>]; diff --git a/src/dot/trpl04-02.dot b/2018-edition/dot/trpl04-02.dot similarity index 62% rename from src/dot/trpl04-02.dot rename to 2018-edition/dot/trpl04-02.dot index 15df0fbf0f..e46d2ed4aa 100644 --- a/src/dot/trpl04-02.dot +++ b/2018-edition/dot/trpl04-02.dot @@ -6,25 +6,25 @@ digraph { table0[label=< - + - - + +
s1
nomevalor
namevalue
ptr
tamanho5
capacidade5
len5
capacity5
>]; table3[label=< - + - - + +
s2
nomevalor
namevalue
ptr
tamanho5
capacidade5
len5
capacity5
>]; table1[label=< - - + + - - + +
índicevalor
0t
indexvalue
0h
1e
2x
3t
2l
3l
4o
>]; diff --git a/src/dot/trpl04-03.dot b/2018-edition/dot/trpl04-03.dot similarity index 59% rename from src/dot/trpl04-03.dot rename to 2018-edition/dot/trpl04-03.dot index eb2cb6089e..16c0b28607 100644 --- a/src/dot/trpl04-03.dot +++ b/2018-edition/dot/trpl04-03.dot @@ -6,33 +6,33 @@ digraph { table0[label=< - + - - + +
s2
nomevalor
namevalue
ptr
tamanho5
capacidade5
len5
capacity5
>]; table1[label=< - - + + - - + +
índicevalor
0t
indexvalue
0h
1e
2x
3t
2l
3l
4o
>]; table3[label=< - + - - + +
s1
nomevalor
namevalue
ptr
tamanho5
capacidade5
len5
capacity5
>]; table4[label=< - - + + - - + +
índicevalor
0t
indexvalue
0h
1e
2x
3t
2l
3l
4o
>]; diff --git a/src/dot/trpl04-04.dot b/2018-edition/dot/trpl04-04.dot similarity index 62% rename from src/dot/trpl04-04.dot rename to 2018-edition/dot/trpl04-04.dot index efb1205890..1c95c231c3 100644 --- a/src/dot/trpl04-04.dot +++ b/2018-edition/dot/trpl04-04.dot @@ -6,25 +6,25 @@ digraph { table0[label=< - + - - + +
s1
nomevalor
namevalue
ptr
tamanho5
capacidade5
len5
capacity5
>]; table3[label=< - + - - + +
s2
nomevalor
namevalue
ptr
tamanho5
capacidade5
len5
capacity5
>]; table1[label=< - - + + - - + +
índicevalor
0t
indexvalue
0h
1e
2x
3t
2l
3l
4o
>]; diff --git a/src/dot/trpl04-05.dot b/2018-edition/dot/trpl04-05.dot similarity index 67% rename from src/dot/trpl04-05.dot rename to 2018-edition/dot/trpl04-05.dot index 22091316a5..ca1f7e06e9 100644 --- a/src/dot/trpl04-05.dot +++ b/2018-edition/dot/trpl04-05.dot @@ -6,22 +6,22 @@ digraph { table0[label=< - +
s
nomevalor
namevalue
ptr
>]; table1[label=< - + - - + +
s1
nomevalor
namevalue
ptr
tamanho5
capacidade5
len5
capacity5
>]; table2[label=< - - + + - - + +
índicevalor
0t
indexvalue
0h
1e
2x
3t
2l
3l
4o
>]; diff --git a/src/dot/trpl04-06.dot b/2018-edition/dot/trpl04-06.dot similarity index 55% rename from src/dot/trpl04-06.dot rename to 2018-edition/dot/trpl04-06.dot index 90077e245b..a23f179a77 100644 --- a/src/dot/trpl04-06.dot +++ b/2018-edition/dot/trpl04-06.dot @@ -5,32 +5,32 @@ digraph { node [shape="plaintext"]; table0[label=< - - + + - +
longo
nomevalor
world
namevalue
ptr
tamanho5
len5
>]; table3[label=< - + - - + +
s
nomevalor
namevalue
ptr
tamanho11
capacidade11
len11
capacity11
>]; table4[label=< - - + + - - + + - + - - - + + +
índicevalor
0t
indexvalue
0h
1e
2x
3t
2l
3l
4o
5
6l
6w
7o
8n
9g
10o
8r
9l
10d
>]; diff --git a/2018-edition/dot/trpl15-01.dot b/2018-edition/dot/trpl15-01.dot new file mode 100644 index 0000000000..e8b95f9a3f --- /dev/null +++ b/2018-edition/dot/trpl15-01.dot @@ -0,0 +1,24 @@ +digraph { + rankdir=LR; + overlap=false; + dpi=300.0; + node [shape="plaintext"]; + + table0[label=< + + +
Cons
i32 + + +
Cons
i32 + + +
Cons
i32 + + +
Cons
i32 + + +
Cons
i32
>]; +} + diff --git a/2018-edition/dot/trpl15-02.dot b/2018-edition/dot/trpl15-02.dot new file mode 100644 index 0000000000..f7dfd22c97 --- /dev/null +++ b/2018-edition/dot/trpl15-02.dot @@ -0,0 +1,18 @@ +digraph { + rankdir=LR; + overlap=false; + dpi=300.0; + node [shape="plaintext"]; + + table0[label=< + + + +
Cons
i32 + + + +
Box
usize
+
>]; +} + diff --git a/2018-edition/dot/trpl15-03.dot b/2018-edition/dot/trpl15-03.dot new file mode 100644 index 0000000000..16f026814b --- /dev/null +++ b/2018-edition/dot/trpl15-03.dot @@ -0,0 +1,51 @@ +digraph { + rankdir=LR; + overlap=false; + dpi=300.0; + node [shape="plaintext"]; + + table4[label=< + +
b
>]; + + table5[label=< + +
3
>]; + + + table0[label=< + +
a
>]; + + table1[label=< + +
5
>]; + + table2[label=< + +
10
>]; + + table3[label=< + +
Nil
>]; + + + table6[label=< + +
c
>]; + + table7[label=< + +
4
>]; + + + 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; +} + diff --git a/2018-edition/ferris.css b/2018-edition/ferris.css new file mode 100644 index 0000000000..371207924c --- /dev/null +++ b/2018-edition/ferris.css @@ -0,0 +1,33 @@ +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; +} diff --git a/2018-edition/ferris.js b/2018-edition/ferris.js new file mode 100644 index 0000000000..5e79b3c711 --- /dev/null +++ b/2018-edition/ferris.js @@ -0,0 +1,51 @@ +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) +} diff --git a/2018-edition/src/SUMMARY.md b/2018-edition/src/SUMMARY.md new file mode 100644 index 0000000000..57a1916da4 --- /dev/null +++ b/2018-edition/src/SUMMARY.md @@ -0,0 +1,132 @@ +# 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) diff --git a/2018-edition/src/appendix-00.md b/2018-edition/src/appendix-00.md new file mode 100644 index 0000000000..c4145d6d8c --- /dev/null +++ b/2018-edition/src/appendix-00.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/appendix-01-keywords.md b/2018-edition/src/appendix-01-keywords.md new file mode 100644 index 0000000000..dde1ac6ce9 --- /dev/null +++ b/2018-edition/src/appendix-01-keywords.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/appendix-02-operators.md b/2018-edition/src/appendix-02-operators.md new file mode 100644 index 0000000000..4bca5b78f0 --- /dev/null +++ b/2018-edition/src/appendix-02-operators.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/appendix-03-derivable-traits.md b/2018-edition/src/appendix-03-derivable-traits.md new file mode 100644 index 0000000000..effe9c22af --- /dev/null +++ b/2018-edition/src/appendix-03-derivable-traits.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/appendix-04-useful-development-tools.md b/2018-edition/src/appendix-04-useful-development-tools.md new file mode 100644 index 0000000000..9757c17ab8 --- /dev/null +++ b/2018-edition/src/appendix-04-useful-development-tools.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/appendix-05-editions.md b/2018-edition/src/appendix-05-editions.md new file mode 100644 index 0000000000..fe22543627 --- /dev/null +++ b/2018-edition/src/appendix-05-editions.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/appendix-06-translation.md b/2018-edition/src/appendix-06-translation.md new file mode 100644 index 0000000000..ef6345533e --- /dev/null +++ b/2018-edition/src/appendix-06-translation.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/appendix-07-nightly-rust.md b/2018-edition/src/appendix-07-nightly-rust.md new file mode 100644 index 0000000000..d5ee3806de --- /dev/null +++ b/2018-edition/src/appendix-07-nightly-rust.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/ch00-00-introduction.md b/2018-edition/src/ch00-00-introduction.md new file mode 100644 index 0000000000..2645d6f549 --- /dev/null +++ b/2018-edition/src/ch00-00-introduction.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/ch01-00-getting-started.md b/2018-edition/src/ch01-00-getting-started.md new file mode 100644 index 0000000000..18db714093 --- /dev/null +++ b/2018-edition/src/ch01-00-getting-started.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/ch01-01-installation.md b/2018-edition/src/ch01-01-installation.md new file mode 100644 index 0000000000..29ec038dee --- /dev/null +++ b/2018-edition/src/ch01-01-installation.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch01-02-hello-world.md b/2018-edition/src/ch01-02-hello-world.md new file mode 100644 index 0000000000..f56f59291c --- /dev/null +++ b/2018-edition/src/ch01-02-hello-world.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch01-03-hello-cargo.md b/2018-edition/src/ch01-03-hello-cargo.md new file mode 100644 index 0000000000..464955150a --- /dev/null +++ b/2018-edition/src/ch01-03-hello-cargo.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch02-00-guessing-game-tutorial.md b/2018-edition/src/ch02-00-guessing-game-tutorial.md new file mode 100644 index 0000000000..40a5936914 --- /dev/null +++ b/2018-edition/src/ch02-00-guessing-game-tutorial.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/ch03-00-common-programming-concepts.md b/2018-edition/src/ch03-00-common-programming-concepts.md new file mode 100644 index 0000000000..52e38dedf3 --- /dev/null +++ b/2018-edition/src/ch03-00-common-programming-concepts.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/ch03-01-variables-and-mutability.md b/2018-edition/src/ch03-01-variables-and-mutability.md new file mode 100644 index 0000000000..990602058a --- /dev/null +++ b/2018-edition/src/ch03-01-variables-and-mutability.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch03-02-data-types.md b/2018-edition/src/ch03-02-data-types.md new file mode 100644 index 0000000000..7109be297d --- /dev/null +++ b/2018-edition/src/ch03-02-data-types.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch03-03-how-functions-work.md b/2018-edition/src/ch03-03-how-functions-work.md new file mode 100644 index 0000000000..60213ba9ae --- /dev/null +++ b/2018-edition/src/ch03-03-how-functions-work.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch03-04-comments.md b/2018-edition/src/ch03-04-comments.md new file mode 100644 index 0000000000..679c7ee212 --- /dev/null +++ b/2018-edition/src/ch03-04-comments.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch03-05-control-flow.md b/2018-edition/src/ch03-05-control-flow.md new file mode 100644 index 0000000000..de3f331be2 --- /dev/null +++ b/2018-edition/src/ch03-05-control-flow.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch04-00-understanding-ownership.md b/2018-edition/src/ch04-00-understanding-ownership.md new file mode 100644 index 0000000000..d48cc711b7 --- /dev/null +++ b/2018-edition/src/ch04-00-understanding-ownership.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/ch04-01-what-is-ownership.md b/2018-edition/src/ch04-01-what-is-ownership.md new file mode 100644 index 0000000000..f6a2e485e9 --- /dev/null +++ b/2018-edition/src/ch04-01-what-is-ownership.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch04-02-references-and-borrowing.md b/2018-edition/src/ch04-02-references-and-borrowing.md new file mode 100644 index 0000000000..a6b9d5cba3 --- /dev/null +++ b/2018-edition/src/ch04-02-references-and-borrowing.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch04-03-slices.md b/2018-edition/src/ch04-03-slices.md new file mode 100644 index 0000000000..8e1f8bcf92 --- /dev/null +++ b/2018-edition/src/ch04-03-slices.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch05-00-structs.md b/2018-edition/src/ch05-00-structs.md new file mode 100644 index 0000000000..8957ae29d4 --- /dev/null +++ b/2018-edition/src/ch05-00-structs.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/ch05-01-defining-structs.md b/2018-edition/src/ch05-01-defining-structs.md new file mode 100644 index 0000000000..abd150f93b --- /dev/null +++ b/2018-edition/src/ch05-01-defining-structs.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch05-02-example-structs.md b/2018-edition/src/ch05-02-example-structs.md new file mode 100644 index 0000000000..ac6b43e19d --- /dev/null +++ b/2018-edition/src/ch05-02-example-structs.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch05-03-method-syntax.md b/2018-edition/src/ch05-03-method-syntax.md new file mode 100644 index 0000000000..a45b9f3346 --- /dev/null +++ b/2018-edition/src/ch05-03-method-syntax.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch06-00-enums.md b/2018-edition/src/ch06-00-enums.md new file mode 100644 index 0000000000..55d2cd1624 --- /dev/null +++ b/2018-edition/src/ch06-00-enums.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/ch06-01-defining-an-enum.md b/2018-edition/src/ch06-01-defining-an-enum.md new file mode 100644 index 0000000000..81c2603dcc --- /dev/null +++ b/2018-edition/src/ch06-01-defining-an-enum.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch06-02-match.md b/2018-edition/src/ch06-02-match.md new file mode 100644 index 0000000000..5663fb82a8 --- /dev/null +++ b/2018-edition/src/ch06-02-match.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch06-03-if-let.md b/2018-edition/src/ch06-03-if-let.md new file mode 100644 index 0000000000..24b14c1d02 --- /dev/null +++ b/2018-edition/src/ch06-03-if-let.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch07-00-packages-crates-and-modules.md b/2018-edition/src/ch07-00-packages-crates-and-modules.md new file mode 100644 index 0000000000..b4ea933777 --- /dev/null +++ b/2018-edition/src/ch07-00-packages-crates-and-modules.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/ch07-01-packages-and-crates-for-making-libraries-and-executables.md b/2018-edition/src/ch07-01-packages-and-crates-for-making-libraries-and-executables.md new file mode 100644 index 0000000000..605267733d --- /dev/null +++ b/2018-edition/src/ch07-01-packages-and-crates-for-making-libraries-and-executables.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch07-02-modules-and-use-to-control-scope-and-privacy.md b/2018-edition/src/ch07-02-modules-and-use-to-control-scope-and-privacy.md new file mode 100644 index 0000000000..c137290e20 --- /dev/null +++ b/2018-edition/src/ch07-02-modules-and-use-to-control-scope-and-privacy.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch08-00-common-collections.md b/2018-edition/src/ch08-00-common-collections.md new file mode 100644 index 0000000000..079daccf3d --- /dev/null +++ b/2018-edition/src/ch08-00-common-collections.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/ch08-01-vectors.md b/2018-edition/src/ch08-01-vectors.md new file mode 100644 index 0000000000..e13e45d522 --- /dev/null +++ b/2018-edition/src/ch08-01-vectors.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch08-02-strings.md b/2018-edition/src/ch08-02-strings.md new file mode 100644 index 0000000000..2ca314b872 --- /dev/null +++ b/2018-edition/src/ch08-02-strings.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch08-03-hash-maps.md b/2018-edition/src/ch08-03-hash-maps.md new file mode 100644 index 0000000000..365ede452a --- /dev/null +++ b/2018-edition/src/ch08-03-hash-maps.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch09-00-error-handling.md b/2018-edition/src/ch09-00-error-handling.md new file mode 100644 index 0000000000..d499077757 --- /dev/null +++ b/2018-edition/src/ch09-00-error-handling.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/ch09-01-unrecoverable-errors-with-panic.md b/2018-edition/src/ch09-01-unrecoverable-errors-with-panic.md new file mode 100644 index 0000000000..4850a3d00e --- /dev/null +++ b/2018-edition/src/ch09-01-unrecoverable-errors-with-panic.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch09-02-recoverable-errors-with-result.md b/2018-edition/src/ch09-02-recoverable-errors-with-result.md new file mode 100644 index 0000000000..12c2158f97 --- /dev/null +++ b/2018-edition/src/ch09-02-recoverable-errors-with-result.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch09-03-to-panic-or-not-to-panic.md b/2018-edition/src/ch09-03-to-panic-or-not-to-panic.md new file mode 100644 index 0000000000..1d1d06e482 --- /dev/null +++ b/2018-edition/src/ch09-03-to-panic-or-not-to-panic.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch10-00-generics.md b/2018-edition/src/ch10-00-generics.md new file mode 100644 index 0000000000..e295912479 --- /dev/null +++ b/2018-edition/src/ch10-00-generics.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/ch10-01-syntax.md b/2018-edition/src/ch10-01-syntax.md new file mode 100644 index 0000000000..0237c76945 --- /dev/null +++ b/2018-edition/src/ch10-01-syntax.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch10-02-traits.md b/2018-edition/src/ch10-02-traits.md new file mode 100644 index 0000000000..667383339b --- /dev/null +++ b/2018-edition/src/ch10-02-traits.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch10-03-lifetime-syntax.md b/2018-edition/src/ch10-03-lifetime-syntax.md new file mode 100644 index 0000000000..a3ccf0033b --- /dev/null +++ b/2018-edition/src/ch10-03-lifetime-syntax.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch11-00-testing.md b/2018-edition/src/ch11-00-testing.md new file mode 100644 index 0000000000..33f5d7eeb1 --- /dev/null +++ b/2018-edition/src/ch11-00-testing.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/ch11-01-writing-tests.md b/2018-edition/src/ch11-01-writing-tests.md new file mode 100644 index 0000000000..17c608e61f --- /dev/null +++ b/2018-edition/src/ch11-01-writing-tests.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch11-02-running-tests.md b/2018-edition/src/ch11-02-running-tests.md new file mode 100644 index 0000000000..3774076846 --- /dev/null +++ b/2018-edition/src/ch11-02-running-tests.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch11-03-test-organization.md b/2018-edition/src/ch11-03-test-organization.md new file mode 100644 index 0000000000..92cca4c74d --- /dev/null +++ b/2018-edition/src/ch11-03-test-organization.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch12-00-an-io-project.md b/2018-edition/src/ch12-00-an-io-project.md new file mode 100644 index 0000000000..3e1fbac98e --- /dev/null +++ b/2018-edition/src/ch12-00-an-io-project.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/ch12-01-accepting-command-line-arguments.md b/2018-edition/src/ch12-01-accepting-command-line-arguments.md new file mode 100644 index 0000000000..a91b0cad1c --- /dev/null +++ b/2018-edition/src/ch12-01-accepting-command-line-arguments.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch12-02-reading-a-file.md b/2018-edition/src/ch12-02-reading-a-file.md new file mode 100644 index 0000000000..6ef3349398 --- /dev/null +++ b/2018-edition/src/ch12-02-reading-a-file.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch12-03-improving-error-handling-and-modularity.md b/2018-edition/src/ch12-03-improving-error-handling-and-modularity.md new file mode 100644 index 0000000000..5d52ab8933 --- /dev/null +++ b/2018-edition/src/ch12-03-improving-error-handling-and-modularity.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch12-04-testing-the-librarys-functionality.md b/2018-edition/src/ch12-04-testing-the-librarys-functionality.md new file mode 100644 index 0000000000..12b0204d82 --- /dev/null +++ b/2018-edition/src/ch12-04-testing-the-librarys-functionality.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch12-05-working-with-environment-variables.md b/2018-edition/src/ch12-05-working-with-environment-variables.md new file mode 100644 index 0000000000..d6316cb2d3 --- /dev/null +++ b/2018-edition/src/ch12-05-working-with-environment-variables.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch12-06-writing-to-stderr-instead-of-stdout.md b/2018-edition/src/ch12-06-writing-to-stderr-instead-of-stdout.md new file mode 100644 index 0000000000..6114b4bb8c --- /dev/null +++ b/2018-edition/src/ch12-06-writing-to-stderr-instead-of-stdout.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch13-00-functional-features.md b/2018-edition/src/ch13-00-functional-features.md new file mode 100644 index 0000000000..466b49c6f5 --- /dev/null +++ b/2018-edition/src/ch13-00-functional-features.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/ch13-01-closures.md b/2018-edition/src/ch13-01-closures.md new file mode 100644 index 0000000000..bc580304e8 --- /dev/null +++ b/2018-edition/src/ch13-01-closures.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch13-02-iterators.md b/2018-edition/src/ch13-02-iterators.md new file mode 100644 index 0000000000..7f5e9cf867 --- /dev/null +++ b/2018-edition/src/ch13-02-iterators.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch13-03-improving-our-io-project.md b/2018-edition/src/ch13-03-improving-our-io-project.md new file mode 100644 index 0000000000..5148fcf1bb --- /dev/null +++ b/2018-edition/src/ch13-03-improving-our-io-project.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch13-04-performance.md b/2018-edition/src/ch13-04-performance.md new file mode 100644 index 0000000000..817a13844f --- /dev/null +++ b/2018-edition/src/ch13-04-performance.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch14-00-more-about-cargo.md b/2018-edition/src/ch14-00-more-about-cargo.md new file mode 100644 index 0000000000..dea00b8aa5 --- /dev/null +++ b/2018-edition/src/ch14-00-more-about-cargo.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/ch14-01-release-profiles.md b/2018-edition/src/ch14-01-release-profiles.md new file mode 100644 index 0000000000..eb9946ac73 --- /dev/null +++ b/2018-edition/src/ch14-01-release-profiles.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch14-02-publishing-to-crates-io.md b/2018-edition/src/ch14-02-publishing-to-crates-io.md new file mode 100644 index 0000000000..a5707e5ace --- /dev/null +++ b/2018-edition/src/ch14-02-publishing-to-crates-io.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch14-03-cargo-workspaces.md b/2018-edition/src/ch14-03-cargo-workspaces.md new file mode 100644 index 0000000000..50691e6541 --- /dev/null +++ b/2018-edition/src/ch14-03-cargo-workspaces.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch14-04-installing-binaries.md b/2018-edition/src/ch14-04-installing-binaries.md new file mode 100644 index 0000000000..b6e196bb93 --- /dev/null +++ b/2018-edition/src/ch14-04-installing-binaries.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch14-05-extending-cargo.md b/2018-edition/src/ch14-05-extending-cargo.md new file mode 100644 index 0000000000..ed1235de65 --- /dev/null +++ b/2018-edition/src/ch14-05-extending-cargo.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch15-00-smart-pointers.md b/2018-edition/src/ch15-00-smart-pointers.md new file mode 100644 index 0000000000..de4c648df0 --- /dev/null +++ b/2018-edition/src/ch15-00-smart-pointers.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/ch15-01-box.md b/2018-edition/src/ch15-01-box.md new file mode 100644 index 0000000000..cbbc07bbf8 --- /dev/null +++ b/2018-edition/src/ch15-01-box.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch15-02-deref.md b/2018-edition/src/ch15-02-deref.md new file mode 100644 index 0000000000..b5f1f8612a --- /dev/null +++ b/2018-edition/src/ch15-02-deref.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch15-03-drop.md b/2018-edition/src/ch15-03-drop.md new file mode 100644 index 0000000000..2ae0b436d9 --- /dev/null +++ b/2018-edition/src/ch15-03-drop.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch15-04-rc.md b/2018-edition/src/ch15-04-rc.md new file mode 100644 index 0000000000..2b4015e7e4 --- /dev/null +++ b/2018-edition/src/ch15-04-rc.md @@ -0,0 +1,10 @@ +## `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). \ No newline at end of file diff --git a/2018-edition/src/ch15-05-interior-mutability.md b/2018-edition/src/ch15-05-interior-mutability.md new file mode 100644 index 0000000000..fb1f96df7a --- /dev/null +++ b/2018-edition/src/ch15-05-interior-mutability.md @@ -0,0 +1,10 @@ +## `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). \ No newline at end of file diff --git a/2018-edition/src/ch15-06-reference-cycles.md b/2018-edition/src/ch15-06-reference-cycles.md new file mode 100644 index 0000000000..ac93fe3bbc --- /dev/null +++ b/2018-edition/src/ch15-06-reference-cycles.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch16-00-concurrency.md b/2018-edition/src/ch16-00-concurrency.md new file mode 100644 index 0000000000..1cf6b2f580 --- /dev/null +++ b/2018-edition/src/ch16-00-concurrency.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/ch16-01-threads.md b/2018-edition/src/ch16-01-threads.md new file mode 100644 index 0000000000..708e30be79 --- /dev/null +++ b/2018-edition/src/ch16-01-threads.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch16-02-message-passing.md b/2018-edition/src/ch16-02-message-passing.md new file mode 100644 index 0000000000..4540efaac3 --- /dev/null +++ b/2018-edition/src/ch16-02-message-passing.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch16-03-shared-state.md b/2018-edition/src/ch16-03-shared-state.md new file mode 100644 index 0000000000..043aa25cdb --- /dev/null +++ b/2018-edition/src/ch16-03-shared-state.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch16-04-extensible-concurrency-sync-and-send.md b/2018-edition/src/ch16-04-extensible-concurrency-sync-and-send.md new file mode 100644 index 0000000000..44a4a0b197 --- /dev/null +++ b/2018-edition/src/ch16-04-extensible-concurrency-sync-and-send.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch17-00-oop.md b/2018-edition/src/ch17-00-oop.md new file mode 100644 index 0000000000..c731bbc95b --- /dev/null +++ b/2018-edition/src/ch17-00-oop.md @@ -0,0 +1,10 @@ +# 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](../ch17-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). \ No newline at end of file diff --git a/2018-edition/src/ch17-01-what-is-oo.md b/2018-edition/src/ch17-01-what-is-oo.md new file mode 100644 index 0000000000..ed1ec4013d --- /dev/null +++ b/2018-edition/src/ch17-01-what-is-oo.md @@ -0,0 +1,10 @@ +## 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](../ch17-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). \ No newline at end of file diff --git a/2018-edition/src/ch17-02-trait-objects.md b/2018-edition/src/ch17-02-trait-objects.md new file mode 100644 index 0000000000..1999647aae --- /dev/null +++ b/2018-edition/src/ch17-02-trait-objects.md @@ -0,0 +1,10 @@ +## 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](../ch17-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). \ No newline at end of file diff --git a/2018-edition/src/ch17-03-oo-design-patterns.md b/2018-edition/src/ch17-03-oo-design-patterns.md new file mode 100644 index 0000000000..1b74425fe2 --- /dev/null +++ b/2018-edition/src/ch17-03-oo-design-patterns.md @@ -0,0 +1,10 @@ +## 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](../ch17-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). \ No newline at end of file diff --git a/2018-edition/src/ch18-00-patterns.md b/2018-edition/src/ch18-00-patterns.md new file mode 100644 index 0000000000..f3da1f40d2 --- /dev/null +++ b/2018-edition/src/ch18-00-patterns.md @@ -0,0 +1,10 @@ +# 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](../ch18-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). \ No newline at end of file diff --git a/2018-edition/src/ch18-01-all-the-places-for-patterns.md b/2018-edition/src/ch18-01-all-the-places-for-patterns.md new file mode 100644 index 0000000000..ccf3884069 --- /dev/null +++ b/2018-edition/src/ch18-01-all-the-places-for-patterns.md @@ -0,0 +1,10 @@ +## 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](../ch18-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). \ No newline at end of file diff --git a/2018-edition/src/ch18-02-refutability.md b/2018-edition/src/ch18-02-refutability.md new file mode 100644 index 0000000000..074f950e65 --- /dev/null +++ b/2018-edition/src/ch18-02-refutability.md @@ -0,0 +1,10 @@ +## 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](../ch18-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-refuatbility.html). \ No newline at end of file diff --git a/2018-edition/src/ch18-03-pattern-syntax.md b/2018-edition/src/ch18-03-pattern-syntax.md new file mode 100644 index 0000000000..0e0929e7b8 --- /dev/null +++ b/2018-edition/src/ch18-03-pattern-syntax.md @@ -0,0 +1,10 @@ +## 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](../ch18-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). \ No newline at end of file diff --git a/2018-edition/src/ch19-00-advanced-features.md b/2018-edition/src/ch19-00-advanced-features.md new file mode 100644 index 0000000000..b34d6b9b67 --- /dev/null +++ b/2018-edition/src/ch19-00-advanced-features.md @@ -0,0 +1,10 @@ +# 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](../ch19-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). \ No newline at end of file diff --git a/2018-edition/src/ch19-01-unsafe-rust.md b/2018-edition/src/ch19-01-unsafe-rust.md new file mode 100644 index 0000000000..34b569fee6 --- /dev/null +++ b/2018-edition/src/ch19-01-unsafe-rust.md @@ -0,0 +1,10 @@ +## 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](../ch19-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). \ No newline at end of file diff --git a/2018-edition/src/ch19-02-advanced-lifetimes.md b/2018-edition/src/ch19-02-advanced-lifetimes.md new file mode 100644 index 0000000000..dd84b46278 --- /dev/null +++ b/2018-edition/src/ch19-02-advanced-lifetimes.md @@ -0,0 +1,10 @@ +## 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). \ No newline at end of file diff --git a/2018-edition/src/ch19-03-advanced-traits.md b/2018-edition/src/ch19-03-advanced-traits.md new file mode 100644 index 0000000000..4219b208b9 --- /dev/null +++ b/2018-edition/src/ch19-03-advanced-traits.md @@ -0,0 +1,10 @@ +## 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](../ch19-03-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). \ No newline at end of file diff --git a/2018-edition/src/ch19-04-advanced-types.md b/2018-edition/src/ch19-04-advanced-types.md new file mode 100644 index 0000000000..fecbd52dc8 --- /dev/null +++ b/2018-edition/src/ch19-04-advanced-types.md @@ -0,0 +1,10 @@ +## 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](../ch19-04-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). \ No newline at end of file diff --git a/2018-edition/src/ch19-05-advanced-functions-and-closures.md b/2018-edition/src/ch19-05-advanced-functions-and-closures.md new file mode 100644 index 0000000000..1bf0450904 --- /dev/null +++ b/2018-edition/src/ch19-05-advanced-functions-and-closures.md @@ -0,0 +1,10 @@ +## 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](../ch19-05-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). \ No newline at end of file diff --git a/2018-edition/src/ch19-06-macros.md b/2018-edition/src/ch19-06-macros.md new file mode 100644 index 0000000000..bf019c5d68 --- /dev/null +++ b/2018-edition/src/ch19-06-macros.md @@ -0,0 +1,10 @@ +## 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](../ch19-06-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). \ No newline at end of file diff --git a/2018-edition/src/ch20-00-final-project-a-web-server.md b/2018-edition/src/ch20-00-final-project-a-web-server.md new file mode 100644 index 0000000000..f9b9e5c2d2 --- /dev/null +++ b/2018-edition/src/ch20-00-final-project-a-web-server.md @@ -0,0 +1,10 @@ +# 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](../ch20-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). \ No newline at end of file diff --git a/2018-edition/src/ch20-01-single-threaded.md b/2018-edition/src/ch20-01-single-threaded.md new file mode 100644 index 0000000000..30d0884adb --- /dev/null +++ b/2018-edition/src/ch20-01-single-threaded.md @@ -0,0 +1,10 @@ +## 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](../ch20-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). \ No newline at end of file diff --git a/2018-edition/src/ch20-02-multithreaded.md b/2018-edition/src/ch20-02-multithreaded.md new file mode 100644 index 0000000000..e8b592ad22 --- /dev/null +++ b/2018-edition/src/ch20-02-multithreaded.md @@ -0,0 +1,10 @@ +## 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](../ch20-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). \ No newline at end of file diff --git a/2018-edition/src/ch20-03-graceful-shutdown-and-cleanup.md b/2018-edition/src/ch20-03-graceful-shutdown-and-cleanup.md new file mode 100644 index 0000000000..928d199bee --- /dev/null +++ b/2018-edition/src/ch20-03-graceful-shutdown-and-cleanup.md @@ -0,0 +1,10 @@ +## 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](../ch20-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). \ No newline at end of file diff --git a/2018-edition/src/foreword.md b/2018-edition/src/foreword.md new file mode 100644 index 0000000000..3af707e354 --- /dev/null +++ b/2018-edition/src/foreword.md @@ -0,0 +1,10 @@ +# 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). \ No newline at end of file diff --git a/2018-edition/src/img/ferris/does_not_compile.svg b/2018-edition/src/img/ferris/does_not_compile.svg new file mode 100644 index 0000000000..5d345f14e0 --- /dev/null +++ b/2018-edition/src/img/ferris/does_not_compile.svg @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/2018-edition/src/img/ferris/not_desired_behavior.svg b/2018-edition/src/img/ferris/not_desired_behavior.svg new file mode 100644 index 0000000000..47f402455f --- /dev/null +++ b/2018-edition/src/img/ferris/not_desired_behavior.svg @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/2018-edition/src/img/ferris/panics.svg b/2018-edition/src/img/ferris/panics.svg new file mode 100644 index 0000000000..be55f5e09b --- /dev/null +++ b/2018-edition/src/img/ferris/panics.svg @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/2018-edition/src/img/ferris/unsafe.svg b/2018-edition/src/img/ferris/unsafe.svg new file mode 100644 index 0000000000..d4fdc08dd6 --- /dev/null +++ b/2018-edition/src/img/ferris/unsafe.svg @@ -0,0 +1,291 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/2018-edition/src/img/trpl04-01.svg b/2018-edition/src/img/trpl04-01.svg new file mode 100644 index 0000000000..314f53ba12 --- /dev/null +++ b/2018-edition/src/img/trpl04-01.svg @@ -0,0 +1,68 @@ + + + + + + +%3 + + + +table0 + +s1 + +name + +value + +ptr + + +len + +5 + +capacity + +5 + + + +table1 + +index + +value + +0 + +h + +1 + +e + +2 + +l + +3 + +l + +4 + +o + + + +table0:c->table1:pointee + + + + + diff --git a/2018-edition/src/img/trpl04-02.svg b/2018-edition/src/img/trpl04-02.svg new file mode 100644 index 0000000000..70d490f0bc --- /dev/null +++ b/2018-edition/src/img/trpl04-02.svg @@ -0,0 +1,95 @@ + + + + + + +%3 + + + +table0 + +s1 + +name + +value + +ptr + + +len + +5 + +capacity + +5 + + + +table1 + +index + +value + +0 + +h + +1 + +e + +2 + +l + +3 + +l + +4 + +o + + + +table0:c->table1:pointee + + + + + +table3 + +s2 + +name + +value + +ptr + + +len + +5 + +capacity + +5 + + + +table3:c->table1:pointee + + + + + diff --git a/2018-edition/src/img/trpl04-03.svg b/2018-edition/src/img/trpl04-03.svg new file mode 100644 index 0000000000..7c153e23a3 --- /dev/null +++ b/2018-edition/src/img/trpl04-03.svg @@ -0,0 +1,123 @@ + + + + + + +%3 + + + +table0 + +s2 + +name + +value + +ptr + + +len + +5 + +capacity + +5 + + + +table1 + +index + +value + +0 + +h + +1 + +e + +2 + +l + +3 + +l + +4 + +o + + + +table0:c->table1:pointee + + + + + +table3 + +s1 + +name + +value + +ptr + + +len + +5 + +capacity + +5 + + + +table4 + +index + +value + +0 + +h + +1 + +e + +2 + +l + +3 + +l + +4 + +o + + + +table3:c->table4:pointee + + + + + diff --git a/2018-edition/src/img/trpl04-04.svg b/2018-edition/src/img/trpl04-04.svg new file mode 100644 index 0000000000..a0513abd90 --- /dev/null +++ b/2018-edition/src/img/trpl04-04.svg @@ -0,0 +1,96 @@ + + + + + + +%3 + + + +table0 + + +s1 + +name + +value + +ptr + + +len + +5 + +capacity + +5 + + + +table1 + +index + +value + +0 + +h + +1 + +e + +2 + +l + +3 + +l + +4 + +o + + + +table0:c->table1:pointee + + + + + +table3 + +s2 + +name + +value + +ptr + + +len + +5 + +capacity + +5 + + + +table3:c->table1:pointee + + + + + diff --git a/2018-edition/src/img/trpl04-05.svg b/2018-edition/src/img/trpl04-05.svg new file mode 100644 index 0000000000..b4bf2ebee8 --- /dev/null +++ b/2018-edition/src/img/trpl04-05.svg @@ -0,0 +1,87 @@ + + + + + + +%3 + + + +table0 + +s + +name + +value + +ptr + + + + +table1 + +s1 + +name + +value + +ptr + + +len + +5 + +capacity + +5 + + + +table0:c->table1:borrowee + + + + + +table2 + +index + +value + +0 + +h + +1 + +e + +2 + +l + +3 + +l + +4 + +o + + + +table1:c->table2:pointee + + + + + diff --git a/2018-edition/src/img/trpl04-06.svg b/2018-edition/src/img/trpl04-06.svg new file mode 100644 index 0000000000..e64415fe43 --- /dev/null +++ b/2018-edition/src/img/trpl04-06.svg @@ -0,0 +1,115 @@ + + + + + + +%3 + + + +table0 + +world + +name + +value + +ptr + + +len + +5 + + + +table4 + +index + +value + +0 + +h + +1 + +e + +2 + +l + +3 + +l + +4 + +o + +5 + + + +6 + +w + +7 + +o + +8 + +r + +9 + +l + +10 + +d + + + +table0:c->table4:pointee2 + + + + + +table3 + +s + +name + +value + +ptr + + +len + +11 + +capacity + +11 + + + +table3:c->table4:pointee + + + + + diff --git a/2018-edition/src/img/trpl14-01.png b/2018-edition/src/img/trpl14-01.png new file mode 100644 index 0000000000..5fc59898ce Binary files /dev/null and b/2018-edition/src/img/trpl14-01.png differ diff --git a/2018-edition/src/img/trpl14-02.png b/2018-edition/src/img/trpl14-02.png new file mode 100644 index 0000000000..78e7e7ba74 Binary files /dev/null and b/2018-edition/src/img/trpl14-02.png differ diff --git a/second-edition/src/img/trpl14-07.png b/2018-edition/src/img/trpl14-03.png similarity index 100% rename from second-edition/src/img/trpl14-07.png rename to 2018-edition/src/img/trpl14-03.png diff --git a/second-edition/src/img/trpl14-10.png b/2018-edition/src/img/trpl14-04.png similarity index 100% rename from second-edition/src/img/trpl14-10.png rename to 2018-edition/src/img/trpl14-04.png diff --git a/2018-edition/src/img/trpl15-01.svg b/2018-edition/src/img/trpl15-01.svg new file mode 100644 index 0000000000..bbeef968a2 --- /dev/null +++ b/2018-edition/src/img/trpl15-01.svg @@ -0,0 +1,43 @@ + + + + + + +%3 + + + +table0 + +Cons + +i32 + + +Cons + +i32 + + +Cons + +i32 + + +Cons + +i32 + + +Cons + +i32 + + + + + diff --git a/2018-edition/src/img/trpl15-02.svg b/2018-edition/src/img/trpl15-02.svg new file mode 100644 index 0000000000..4454df8c38 --- /dev/null +++ b/2018-edition/src/img/trpl15-02.svg @@ -0,0 +1,26 @@ + + + + + + +%3 + + + +table0 + +Cons + +i32 + + +Box + +usize + + + diff --git a/2018-edition/src/img/trpl15-03.svg b/2018-edition/src/img/trpl15-03.svg new file mode 100644 index 0000000000..dbc3b5cdb0 --- /dev/null +++ b/2018-edition/src/img/trpl15-03.svg @@ -0,0 +1,109 @@ + + + + + + +%3 + + + +table4 +b + + + +table5 + +3 + +   + + + +table4:c->table5:pte4 + + + + + +table1 + +5 + +   + + + +table5:c->table1:pte0 + + + + + +table0 +a + + + +table0:c->table1:pte0 + + + + + +table2 + +10 + +   + + + +table1:c->table2:pte1 + + + + + +table3 + +Nil + + + +table2:c->table3:pte2 + + + + + +table6 +c + + + +table7 + +4 + +   + + + +table6:c->table7:pte6 + + + + + +table7:c->table1:pte0 + + + + + diff --git a/2018-edition/src/img/trpl15-04.svg b/2018-edition/src/img/trpl15-04.svg new file mode 100644 index 0000000000..96ad98ca13 --- /dev/null +++ b/2018-edition/src/img/trpl15-04.svg @@ -0,0 +1,55 @@ + + + + + + +%3 + + +table0 + +a + + +table1 + +5 + + + + +table2 + +b + + +table3 + +10 + + + + +table0:ref->table1:data + + + + +table1:ref->table2:data + + + + +table2:ref->table3:data + + + + +table3:ref->table0:data + + + + + diff --git a/2018-edition/src/img/trpl20-01.png b/2018-edition/src/img/trpl20-01.png new file mode 100644 index 0000000000..19e2cbc0ac Binary files /dev/null and b/2018-edition/src/img/trpl20-01.png differ diff --git a/2018-edition/src/theme/2018-edition.css b/2018-edition/src/theme/2018-edition.css new file mode 100644 index 0000000000..b1dcf93641 --- /dev/null +++ b/2018-edition/src/theme/2018-edition.css @@ -0,0 +1,9 @@ +span.caption { + font-size: .8em; + font-weight: 600; +} + +span.caption code { + font-size: 0.875em; + font-weight: 400; +} diff --git a/2018-edition/src/theme/index.hbs b/2018-edition/src/theme/index.hbs new file mode 100644 index 0000000000..f3f1b52fa8 --- /dev/null +++ b/2018-edition/src/theme/index.hbs @@ -0,0 +1,37 @@ + + + + + + Outdated link: {{ title }} + + + + + + + + + + + + + + + {{#each additional_css}} + + {{/each}} + + +
+
+ {{> header}} +
+
+ {{{ content }}} +
+
+
+
+ + diff --git a/ADMIN_TASKS.md b/ADMIN_TASKS.md new file mode 100644 index 0000000000..ad02693a33 --- /dev/null +++ b/ADMIN_TASKS.md @@ -0,0 +1,109 @@ +# Administrative Tasks + +This documentation is for Carol and Steve and anyone else managing the repo to remember how to do +occasional maintenance tasks. + +## Update the `rustc` version + +- Change the version number in `.travis.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 + +## 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 [fileame: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 + +- TODO Carol to document this next time she does it + +## 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. diff --git a/CONTRIBUTING-en-us.md b/CONTRIBUTING-en-us.md deleted file mode 100644 index 9407266eb7..0000000000 --- a/CONTRIBUTING-en-us.md +++ /dev/null @@ -1,99 +0,0 @@ -# Contributing - -## First edition - -The first edition of the book is no longer actively being worked on, since -we're concentrating our efforts on bringing the second edition to print. We -will accept pull requests for small tweaks to the first edition; any larger -work should be spent improving the second edition. Issues will likely be closed -unless they are also issues in the second edition. - -## Second edition - -We're currently working with No Starch Press to bring the second edition of the -book to print. Each chapter goes through [a number of stages][project]: - -[project]: https://github.com/rust-lang/book/projects/1 - -* We write and edit a chapter's initial content -* No Starch provides a round of edits and questions -* We revise, clarify, and check those edits -* A Technical Reviewer checks for the accuracy of technical details -* No Starch copyedits the chapter for spelling, grammar, wording, consistency -* We revise, clarify, and check the copyedits -* The chapter goes to layout, at which point only minor changes should be made - -### Documenting newly stabilized features - -New features added to Rust will be documented in the ["Newest Features" -Appendix][new] per [RFC 1636][rfc]. We'd love pull requests adding new -sections! These sections may be incorporated into the book at some point, but -we have no timeline for doing so; see the Post-publication section below for -more details. - -[new]: https://github.com/rust-lang/book/blob/master/second-edition/src/appendix-06-newest-features.md -[rfc]: https://github.com/rust-lang/rfcs/pull/1636#issuecomment-247325313 - -### Corrections and Modifications - -We would love issues and pull requests to the Markdown files in the src -directory, up until the chapter goes to layout with No Starch. At that point, -we will likely only be accepting changes that correct factual errors or major -problems and not, for example, minor wording changes. - -You can check which chapters have gone to layout and are frozen on the [project -page][project] by scrolling all the way to the right to find the column titled -**Frozen**. - -### Review - -Our [open pull requests][pulls] are new chapters or edits that we're currently -working on. We would love if you would read through those and make comments for -any suggestions or corrections! - -[pulls]: https://github.com/rust-lang/book/pulls - -### Translations - -We'd especially love help translating the second edition of 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! The chapters in [the frozen column] of the project won't see major -changes, so if you start with those, you won't have to redo work :) - -[Translations]: https://github.com/rust-lang/book/issues?q=is%3Aopen+is%3Aissue+label%3ATranslations -[mdbook support]: https://github.com/azerupi/mdBook/issues/5 -[the frozen column]: https://github.com/rust-lang/book/projects/1 - -### 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 - -### Post-publication - -After the second edition of the book goes to print, here are our intentions for -changes: - -* The online version should stay fairly close to the printed version. For - example, you should be able to look at listing 10-3 in the book and find - listing 10-3 in the online version and copy-paste the code if you want to - play with it. Major changes to correct errors should get documented in - errata. -* There are multiple efforts starting to translate the online book into - other languages. It would help the translations stay in sync if we're not - constantly changing the text. -* Someday there might be a third edition, once there are enough large, new - features in Rust to warrant such a thing. We don't have any schedule in mind - for that though, nor have we decided if it would be modifications to the - second edition or a ground-up rewrite. Until we have plans for that, we won't - be accepting pull requests that aren't fixing errors, for example, changing - the way something is worded. - -This repository is under the same license as Rust itself, MIT/Apache2. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 154a80bc8d..34096cfec4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,3 +1,50 @@ + + # Contribuições ## Tabela de Conteúdos - [Por onde começar?](#por-onde-come%C3%A7ar) diff --git a/second-edition/Cargo.lock b/Cargo.lock similarity index 52% rename from second-edition/Cargo.lock rename to Cargo.lock index 928f6b1244..14188d080e 100644 --- a/second-edition/Cargo.lock +++ b/Cargo.lock @@ -1,3 +1,10 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adler32" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "aho-corasick" version = "0.5.3" @@ -6,6 +13,24 @@ dependencies = [ "memchr 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "cc" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cfg-if" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "crc32fast" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "docopt" version = "0.6.86" @@ -17,6 +42,28 @@ dependencies = [ "strsim 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "filetime" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)", + "redox_syscall 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "flate2" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "crc32fast 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)", + "miniz-sys 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", + "miniz_oxide 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "kernel32-sys" version = "0.2.2" @@ -44,6 +91,28 @@ dependencies = [ "libc 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "miniz-sys" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cc 1.0.45 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "miniz_oxide" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "adler32 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "redox_syscall" +version = "0.1.56" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "regex" version = "0.1.80" @@ -66,9 +135,11 @@ name = "rust-book" version = "0.0.1" dependencies = [ "docopt 0.6.86 (registry+https://github.com/rust-lang/crates.io-index)", + "flate2 1.0.11 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)", "regex 0.1.80 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)", + "tar 0.4.26 (registry+https://github.com/rust-lang/crates.io-index)", "walkdir 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -82,6 +153,17 @@ name = "strsim" version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "tar" +version = "0.4.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "filetime 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)", + "redox_syscall 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)", + "xattr 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "thread-id" version = "2.0.0" @@ -118,25 +200,66 @@ name = "winapi" version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "winapi" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "winapi-build" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "xattr" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)", +] + [metadata] +"checksum adler32 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "5d2e7343e7fc9de883d1b0341e0b13970f764c14101234857d2ddafa1cb1cac2" "checksum aho-corasick 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ca972c2ea5f742bfce5687b9aef75506a764f61d37f8f649047846a9686ddb66" +"checksum cc 1.0.45 (registry+https://github.com/rust-lang/crates.io-index)" = "4fc9a35e1f4290eb9e5fc54ba6cf40671ed2a2514c3eeb2b2a908dda2ea5a1be" +"checksum cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" +"checksum crc32fast 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ba125de2af0df55319f41944744ad91c71113bf74a4646efff39afe1f6842db1" "checksum docopt 0.6.86 (registry+https://github.com/rust-lang/crates.io-index)" = "4a7ef30445607f6fc8720f0a0a2c7442284b629cf0d049286860fae23e71c4d9" +"checksum filetime 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)" = "6bd7380b54ced79dda72ecc35cc4fbbd1da6bba54afaa37e96fd1c2a308cd469" +"checksum flate2 1.0.11 (registry+https://github.com/rust-lang/crates.io-index)" = "2adaffba6388640136149e18ed080b77a78611c1e1d6de75aedcdf78df5d4682" "checksum kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" "checksum lazy_static 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)" = "236eb37a62591d4a41a89b7763d7de3e06ca02d5ab2815446a8bae5d2f8c2d57" "checksum libc 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)" = "5ba3df4dcb460b9dfbd070d41c94c19209620c191b0340b929ce748a2bcd42d2" "checksum memchr 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)" = "d8b629fb514376c675b98c1421e80b151d3817ac42d7c667717d282761418d20" +"checksum miniz-sys 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)" = "1e9e3ae51cea1576ceba0dde3d484d30e6e5b86dee0b2d412fe3a16a15c98202" +"checksum miniz_oxide 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7108aff85b876d06f22503dcce091e29f76733b2bfdd91eebce81f5e68203a10" +"checksum redox_syscall 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)" = "2439c63f3f6139d1b57529d16bc3b8bb855230c8efcc5d3a896c8bea7c3b1e84" "checksum regex 0.1.80 (registry+https://github.com/rust-lang/crates.io-index)" = "4fd4ace6a8cf7860714a2c2280d6c1f7e6a413486c13298bbc86fd3da019402f" "checksum regex-syntax 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)" = "f9ec002c35e86791825ed294b50008eea9ddfc8def4420124fbc6b08db834957" "checksum rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)" = "dcf128d1287d2ea9d80910b5f1120d0b8eede3fbf1abe91c40d39ea7d51e6fda" "checksum strsim 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "67f84c44fbb2f91db7fef94554e6b2ac05909c9c0b0bc23bb98d3a1aebfe7f7c" +"checksum tar 0.4.26 (registry+https://github.com/rust-lang/crates.io-index)" = "b3196bfbffbba3e57481b6ea32249fbaf590396a52505a2615adbb79d9d826d3" "checksum thread-id 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a9539db560102d1cef46b8b78ce737ff0bb64e7e18d35b2a5688f7d097d0ff03" "checksum thread_local 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)" = "8576dbbfcaef9641452d5cf0df9b0e7eeab7694956dd33bb61515fb8f18cfdd5" "checksum utf8-ranges 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "a1ca13c08c41c9c3e04224ed9ff80461d97e121589ff27c753a16cb10830ae0f" "checksum walkdir 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "c66c0b9792f0a765345452775f3adbd28dde9d33f30d13e5dcc5ae17cf6f3780" "checksum winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" +"checksum winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" "checksum winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +"checksum xattr 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "244c3741f4240ef46274860397c7c74e50eb23624996930e484c16679633a54c" diff --git a/second-edition/Cargo.toml b/Cargo.toml similarity index 75% rename from second-edition/Cargo.toml rename to Cargo.toml index bb6763509f..1de23b46b6 100644 --- a/second-edition/Cargo.toml +++ b/Cargo.toml @@ -3,11 +3,16 @@ name = "rust-book" version = "0.0.1" authors = ["Steve Klabnik "] description = "The Rust Book" +edition = "2018" [[bin]] name = "concat_chapters" path = "tools/src/bin/concat_chapters.rs" +[[bin]] +name = "convert_quotes" +path = "tools/src/bin/convert_quotes.rs" + [[bin]] name = "lfp" path = "tools/src/bin/lfp.rs" @@ -16,6 +21,14 @@ path = "tools/src/bin/lfp.rs" name = "link2print" path = "tools/src/bin/link2print.rs" +[[bin]] +name = "release_listings" +path = "tools/src/bin/release_listings.rs" + +[[bin]] +name = "remove_hidden_lines" +path = "tools/src/bin/remove_hidden_lines.rs" + [[bin]] name = "remove_links" path = "tools/src/bin/remove_links.rs" @@ -24,13 +37,11 @@ path = "tools/src/bin/remove_links.rs" name = "remove_markup" path = "tools/src/bin/remove_markup.rs" -[[bin]] -name = "convert_quotes" -path = "tools/src/bin/convert_quotes.rs" - [dependencies] walkdir = "0.1.5" docopt = "0.6.82" rustc-serialize = "0.3.19" regex = "0.1.73" lazy_static = "0.2.1" +flate2 = "1.0" +tar = "0.4.16" diff --git a/README.md b/README.md index 006d6ea765..507ad4332e 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,20 @@ + + # A Linguagem de Programação Rust - + -[![Build Status](https://travis-ci.com/rust-lang/book.svg?branch=master)](https://travis-ci.com/rust-lang/book) Este repositório contém o código-fonte do livro "A Linguagem de Programação Rust". - +--> [Este livro está disponível na forma de árvore morta pela No Starch Press][nostarch]. [nostarch]: https://nostarch.com/rust -Você também pode ler o livro gratuitamente online. Por favor veja o livro assim como incluído com as versões [estável][stable], [beta] e [nightly] de Rust. Esteja ciente de que problemas nessas versões podem já ter sido corrigidas neste repositório, dado que essas versões são atualizadas menos frequentemente. +Você também pode ler o livro gratuitamente online. Por favor veja o livro assim +como incluído com as versões [estável][stable], [beta] e [nightly] de Rust. +Esteja ciente de que problemas nessas versões podem já ter sido corrigidas +neste repositório, dado que essas versões são atualizadas menos frequentemente. [stable]: https://doc.rust-lang.org/stable/book/ [beta]: https://doc.rust-lang.org/beta/book/ [nightly]: https://doc.rust-lang.org/nightly/book/ - + +Veja [releases] para baixar somente o código de todos códigos fontes que +aparecem no livro. + +[releases]: https://github.com/rust-lang/book/releases + + + +--> ## Requisitos -Construir o livro requer o [mdBook]. Idealmente a mesma versão 0.3.x que rust-lang/rust usa [nesse arquivo][rust-mdbook]. Para obtê-lo: +Construir o livro requer o [mdBook]. Idealmente a mesma versão 0.3.x que rust-lang/rust +usa [nesse arquivo][rust-mdbook]. Para obtê-lo: -[mdbook]: https://github.com/rust-lang-nursery/mdBook +[mdBook]: https://github.com/rust-lang-nursery/mdBook [rust-mdbook]: https://github.com/rust-lang/rust/blob/master/src/tools/rustbook/Cargo.toml ```bash $ cargo install mdbook --vers [version-num] ``` - + +## Construindo + +Para construir o livro, entre: ```bash $ mdbook build ``` + -_Firefox:_ +O resultado estará na subpasta `book`. Para checá-lo, o abra no seu browser. +_Firefox:_ ```bash $ firefox book/index.html # Linux $ open -a "Firefox" book/index.html # OS X @@ -75,7 +99,6 @@ $ 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 @@ -83,108 +106,77 @@ $ Start-Process "chrome.exe" .\book\index.html # Windows (PowerShell) $ start chrome.exe .\book\index.html # Windows (Cmd) ``` + + +Para rodar os testes: ```bash $ mdbook test ``` --> -## Construindo - -Para construir o livro, entre: - -```bash -$ mdbook build -``` - -O resultado estará na subpasta `book`. Para checá-lo, o abra no seu 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) -``` - Para rodar os testes: ```bash $ mdbook test ``` - +--> ## Contribuindo -Nós adoraríamos sua ajuda! Por favor veja o [CONTRIBUTING.md][contrib] para saber mais sobre o tipo de contribuições que nós procuramos. +Nós adoraríamos sua ajuda! Por favor veja o [CONTRIBUTING.md][contrib] para +saber mais sobre o tipo de contribuições que nós procuramos. [contrib]: https://github.com/rust-lang/book/blob/master/CONTRIBUTING.md - +--> ### Traduções -Nós adoraríamos ajuda na tradução deste livro! Veja os labels [Translating][translations] para se ajuntar aos esforços que estão atualmente em progresso. Abra novas issues para começar a trabalhar numa nova linguagem! Nós estamos esperando pelo [suporte do mdbook][mdbook support] a múltiplas linguagens antes de juntá-las a esse repositório, mas sinta-se livre para começar! +Nós adoraríamos ajuda na tradução deste livro! Veja os labels +[Translating][Translations] para se ajuntar aos esforços que estão atualmente +em progresso. Abra novas issues para começar a trabalhar numa nova linguagem! +Nós estamos esperando pelo [suporte do mdbook][mdbook support] a múltiplas +linguagens antes de juntá-las a esse repositório, mas sinta-se livre para +começar! -[translations]: https://github.com/rust-lang/book/issues?q=is%3Aopen+is%3Aissue+label%3ATranslations +[Translations]: https://github.com/rust-lang/book/issues?q=is%3Aopen+is%3Aissue+label%3ATranslations [mdbook support]: https://github.com/rust-lang-nursery/mdBook/issues/5 - - -## Graphviz dot - -Nós estamos usando o [Graphviz](http://graphviz.org/) para alguns dos diagramas no livro. Os arquivos-fonte estão no diretório `dot`. Para transformar um arquivo `dot`, por exemplo o `dot/trpl04-01.dot`, em `svg`, rode: - -```bash -$ dot dot/trpl04-01.dot -Tsvg > src/img/trpl04-01.svg -``` -No arquivo SVG gerado, remova os atributos _width_ e _height_ do elemento `svg` e dê `0.00 0.00 1000.00 1000.00`, ou outros valores que não cortem a imagem, ao atributo `viewBox`. - - +`dictionary.txt` (keep the sorted order for consistency). +--> ## Checagem de grafia -Para procurar erros de grafia nos arquivos, você pode usar o _script_ `spellcheck.sh`. Ele precisa de um dicionário de palavras válidas, o qual é provido em `dictionary.txt`. Se o script produzir um falso positivo (por exemplo, se você usou a palavra `BTreeMap`, a qual o script considera inválida), você precisará adicionar essa palavra a `dicitonary.txt` (mantenha-o ordenado por consistência). +Para procurar erros de grafia nos arquivos, você pode usar o _script_ +`spellcheck.sh`. Ele precisa de um dicionário de palavras válidas, o qual é +provido em `dictionary.txt`. Se o script produzir um falso positivo (por +exemplo, se você usou a palavra `BTreeMap`, a qual o script considera +inválida), você precisará adicionar essa palavra a `dicitonary.txt` ( +mantenha-o ordenado por consistência). + diff --git a/book.json b/book.json deleted file mode 100644 index d8bf0499f5..0000000000 --- a/book.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "title": "A Linguagem de Programação Rust", - "author": "Os Desenvolvedores do Projeto Rust" -} diff --git a/book.toml b/book.toml new file mode 100644 index 0000000000..6797f2df86 --- /dev/null +++ b/book.toml @@ -0,0 +1,7 @@ +[book] +title = "The Rust Programming Language" +author = "Steve Klabnik and Carol Nichols, with Contributions from the Rust Community" + +[output.html] +additional-css = ["ferris.css", "theme/2018-edition.css"] +additional-js = ["ferris.js"] diff --git a/ci/build.sh b/ci/build.sh new file mode 100755 index 0000000000..13f4509a5b --- /dev/null +++ b/ci/build.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +set -e + +export PATH=$PATH:/home/travis/.cargo/bin; + +echo 'Spellchecking...' +bash ci/spellcheck.sh list +echo 'Testing...' +mdbook test +echo 'Building...' +mdbook build +echo 'Linting for local file paths...' +cargo run --bin lfp src +echo 'Validating references' +for file in src/*.md ; do + echo Checking references in $file + cargo run --quiet --bin link2print < $file > /dev/null +done diff --git a/second-edition/dictionary.txt b/ci/dictionary.txt similarity index 89% rename from second-edition/dictionary.txt rename to ci/dictionary.txt index 1abbb31604..2ac71a6742 100644 --- a/second-edition/dictionary.txt +++ b/ci/dictionary.txt @@ -6,6 +6,7 @@ adaptor adaptors AddAssign Addr +afdc aggregator AGraph aliasability @@ -21,6 +22,8 @@ args associativity async atomics +attr +autocompletion AveragedCollection backend backported @@ -28,7 +31,7 @@ backtrace backtraces BACKTRACE Backtraces -Baz’s +Baz's benchmarking bioinformatics bitand @@ -49,6 +52,7 @@ Boolean Booleans Bors BorrowMutError +BoxMeUp BTreeSet BuildHasher Cacher @@ -62,12 +66,15 @@ charset choo chXX chYY +clippy +clippy's coercions combinator ConcreteType config Config const +consts constant's copyeditor couldn @@ -84,13 +91,17 @@ Ctrl customizable CustomSmartPointer CustomSmartPointers -data’s +data's +DataStruct deallocate deallocated deallocating deallocation debuginfo +decl decrementing +deduplicate +deduplicating deps deref Deref @@ -119,6 +130,7 @@ disambiguating DivAssign DraftPost DSTs +ebook ebooks Edsger egular @@ -133,10 +145,11 @@ Enums eprintln Erlang ErrorKind -Executables +executables expr extern favicon +ferris FFFD FFFF figcaption @@ -145,9 +158,9 @@ filename Filename filesystem Filesystem +filesystem's filesystems Firefox -FnBox FnMut FnOnce formatter @@ -172,6 +185,9 @@ HashMap HashSet Haskell hasn +HeadB +HeadC +HelloMacro helloworld HelloWorld HelloWorldName @@ -181,6 +197,7 @@ Hola homogenous html hyperoptimize +hypotheticals Iceburgh ident IDE @@ -196,15 +213,18 @@ IndexMut indices init initializer +initializers inline instantiation internet +interoperate IntoIterator InvalidDigit invariants ioerror iokind ioresult +IoResult iostdin IpAddr IpAddrKind @@ -216,7 +236,9 @@ JavaScript JoinHandle Kay's kinded +Klabnik lang +LastWriteTime latin liballoc libc @@ -226,8 +248,10 @@ libpanic librarys libreoffice libstd +libunwind lifecycle LimitTracker +linter LLVM lobally locators @@ -269,7 +293,9 @@ Mutex mutexes Mutexes MutexGuard +mutext MyBox +myprogram namespace namespaced namespaces @@ -284,8 +310,12 @@ newtypes nitty nocapture nomicon +nonadministrators +nondeterministic nonequality +nongeneric NotFound +nsprust null's OCaml offsetof @@ -300,11 +330,13 @@ other's OutlinePrint overloadable overread +PanicPayload param parameterize ParseIntError PartialEq PartialOrd +pbcopy PendingReview PendingReviewPost PlaceholderType @@ -314,6 +346,8 @@ portia powershell PowerShell powi +preallocate +preallocates preprocessing Preprocessing preprocessor @@ -341,7 +375,9 @@ refactor refactoring refcell RefCell +refcellt RefMut +reformats refutability reimplement RemAssign @@ -363,8 +399,10 @@ rUsT rustc rustdoc Rustonomicon +rustfix rustfmt rustup +sampleproject screenshot searchstring SecondaryColor @@ -376,8 +414,10 @@ ShlAssign ShrAssign shouldn Simula +siphash situps sizeof +SliceIndex Smalltalk snuck someproject @@ -403,6 +443,7 @@ Struct structs struct's Structs +StrWrap SubAssign subclasses subcommand @@ -413,10 +454,12 @@ submodule submodules Submodules suboptimal +subpath substring subteams subtree subtyping +summarizable supertrait supertraits TcpListener @@ -455,6 +498,7 @@ unary Unary uncomment Uncomment +uncommenting unevaluated Uninstalling uninstall @@ -477,10 +521,15 @@ variable's variant's vers versa +vert Versioning visualstudio +Vlissides +vscode vtable +waitlist wasn +weakt WeatherForecast WebSocket whitespace diff --git a/second-edition/spellcheck.sh b/ci/spellcheck.sh similarity index 76% rename from second-edition/spellcheck.sh rename to ci/spellcheck.sh index fd3aa04e1d..f1c84a5f08 100755 --- a/second-edition/spellcheck.sh +++ b/ci/spellcheck.sh @@ -1,17 +1,8 @@ #!/bin/bash -# Copyright 2016 The Rust Project Developers. See the COPYRIGHT -# file at the top-level directory of this distribution and at -# http://rust-lang.org/COPYRIGHT. -# -# Licensed under the Apache License, Version 2.0 or the MIT license -# , at your -# option. This file may not be copied, modified, or distributed -# except according to those terms. aspell --version -# Checks project markdown files for spell errors +# Checks project Markdown files for spelling mistakes. # Notes: @@ -41,18 +32,25 @@ aspell --version shopt -s nullglob -dict_filename=./dictionary.txt +dict_filename=./ci/dictionary.txt markdown_sources=(./src/*.md) mode="check" -# aspell repeatedly modifies personal dictionary for some purpose, -# so we should use a copy of our dictionary -dict_path="/tmp/$dict_filename" +# 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 @@ -63,7 +61,7 @@ if [[ ! -f "$dict_filename" ]]; then 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 + # List (default) mode: scan all files, report errors. declare -i retval=0 cp "$dict_filename" "$dict_path" @@ -77,9 +75,9 @@ elif [[ "$mode" == "list" ]]; then 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 + # 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 + # because it is just a grep. grep --with-filename --line-number --color=always "$error" "$fname" done retval=1 @@ -87,7 +85,7 @@ elif [[ "$mode" == "list" ]]; then done exit "$retval" elif [[ "$mode" == "check" ]]; then - # Interactive mode: fix typos + # Interactive mode: fix typos. cp "$dict_filename" "$dict_path" if [ ! -f $dict_path ]; then diff --git a/dot/trpl04-01.dot b/dot/trpl04-01.dot new file mode 100644 index 0000000000..331d591338 --- /dev/null +++ b/dot/trpl04-01.dot @@ -0,0 +1,26 @@ +digraph { + rankdir=LR; + overlap=false; + dpi=300.0; + node [shape="plaintext"]; + + table0[label=< + + + + + +
s1
namevalue
ptr
len5
capacity5
>]; + table1[label=< + + + + + + +
indexvalue
0h
1e
2l
3l
4o
>]; + + edge[tailclip="false"]; + table0:pointer:c -> table1:pointee; +} + diff --git a/dot/trpl04-02.dot b/dot/trpl04-02.dot new file mode 100644 index 0000000000..e46d2ed4aa --- /dev/null +++ b/dot/trpl04-02.dot @@ -0,0 +1,35 @@ +digraph { + rankdir=LR; + overlap=false; + dpi=300.0; + node [shape="plaintext"]; + + table0[label=< + + + + + +
s1
namevalue
ptr
len5
capacity5
>]; + table3[label=< + + + + + +
s2
namevalue
ptr
len5
capacity5
>]; + + table1[label=< + + + + + + +
indexvalue
0h
1e
2l
3l
4o
>]; + + edge[tailclip="false"]; + table0:pointer:c -> table1:pointee; + table3:pointer:c -> table1:pointee; +} + diff --git a/dot/trpl04-03.dot b/dot/trpl04-03.dot new file mode 100644 index 0000000000..16c0b28607 --- /dev/null +++ b/dot/trpl04-03.dot @@ -0,0 +1,44 @@ +digraph { + rankdir=LR; + overlap=false; + dpi=300.0; + node [shape="plaintext"]; + + table0[label=< + + + + + +
s2
namevalue
ptr
len5
capacity5
>]; + table1[label=< + + + + + + +
indexvalue
0h
1e
2l
3l
4o
>]; + + table3[label=< + + + + + +
s1
namevalue
ptr
len5
capacity5
>]; + table4[label=< + + + + + + +
indexvalue
0h
1e
2l
3l
4o
>]; + + + edge[tailclip="false"]; + table0:pointer:c -> table1:pointee; + table3:pointer:c -> table4:pointee; +} + diff --git a/dot/trpl04-04.dot b/dot/trpl04-04.dot new file mode 100644 index 0000000000..1c95c231c3 --- /dev/null +++ b/dot/trpl04-04.dot @@ -0,0 +1,35 @@ +digraph { + rankdir=LR; + overlap=false; + dpi=300.0; + node [shape="plaintext"]; + + table0[label=< + + + + + +
s1
namevalue
ptr
len5
capacity5
>]; + table3[label=< + + + + + +
s2
namevalue
ptr
len5
capacity5
>]; + + table1[label=< + + + + + + +
indexvalue
0h
1e
2l
3l
4o
>]; + + edge[tailclip="false"]; + table0:pointer:c -> table1:pointee; + table3:pointer:c -> table1:pointee; +} + diff --git a/dot/trpl04-05.dot b/dot/trpl04-05.dot new file mode 100644 index 0000000000..ca1f7e06e9 --- /dev/null +++ b/dot/trpl04-05.dot @@ -0,0 +1,32 @@ +digraph { + rankdir=LR; + overlap=false; + dpi=300.0; + node [shape="plaintext"]; + + table0[label=< + + + +
s
namevalue
ptr
>]; + table1[label=< + + + + + +
s1
namevalue
ptr
len5
capacity5
>]; + table2[label=< + + + + + + +
indexvalue
0h
1e
2l
3l
4o
>]; + + edge[tailclip="false"]; + table1:pointer:c -> table2:pointee; + table0:borrower:c -> table1:borrowee; +} + diff --git a/dot/trpl04-06.dot b/dot/trpl04-06.dot new file mode 100644 index 0000000000..a23f179a77 --- /dev/null +++ b/dot/trpl04-06.dot @@ -0,0 +1,41 @@ +digraph { + rankdir=LR; + overlap=false; + dpi=300.0; + node [shape="plaintext"]; + + table0[label=< + + + + +
world
namevalue
ptr
len5
>]; + + table3[label=< + + + + + +
s
namevalue
ptr
len11
capacity11
>]; + table4[label=< + + + + + + + + + + + + +
indexvalue
0h
1e
2l
3l
4o
5
6w
7o
8r
9l
10d
>]; + + + edge[tailclip="false"]; + table0:pointer2:c -> table4:pointee2; + table3:pointer:c -> table4:pointee; +} + diff --git a/dot/trpl15-01.dot b/dot/trpl15-01.dot new file mode 100644 index 0000000000..e8b95f9a3f --- /dev/null +++ b/dot/trpl15-01.dot @@ -0,0 +1,24 @@ +digraph { + rankdir=LR; + overlap=false; + dpi=300.0; + node [shape="plaintext"]; + + table0[label=< + + +
Cons
i32 + + +
Cons
i32 + + +
Cons
i32 + + +
Cons
i32 + + +
Cons
i32
>]; +} + diff --git a/dot/trpl15-02.dot b/dot/trpl15-02.dot new file mode 100644 index 0000000000..f7dfd22c97 --- /dev/null +++ b/dot/trpl15-02.dot @@ -0,0 +1,18 @@ +digraph { + rankdir=LR; + overlap=false; + dpi=300.0; + node [shape="plaintext"]; + + table0[label=< + + + +
Cons
i32 + + + +
Box
usize
+
>]; +} + diff --git a/dot/trpl15-03.dot b/dot/trpl15-03.dot new file mode 100644 index 0000000000..16f026814b --- /dev/null +++ b/dot/trpl15-03.dot @@ -0,0 +1,51 @@ +digraph { + rankdir=LR; + overlap=false; + dpi=300.0; + node [shape="plaintext"]; + + table4[label=< + +
b
>]; + + table5[label=< + +
3
>]; + + + table0[label=< + +
a
>]; + + table1[label=< + +
5
>]; + + table2[label=< + +
10
>]; + + table3[label=< + +
Nil
>]; + + + table6[label=< + +
c
>]; + + table7[label=< + +
4
>]; + + + 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; +} + diff --git a/ferris.css b/ferris.css new file mode 100644 index 0000000000..371207924c --- /dev/null +++ b/ferris.css @@ -0,0 +1,33 @@ +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; +} diff --git a/ferris.js b/ferris.js new file mode 100644 index 0000000000..5e79b3c711 --- /dev/null +++ b/ferris.js @@ -0,0 +1,51 @@ +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) +} diff --git a/first-edition/src/README.md b/first-edition/src/README.md index 995b32318f..31babb298c 100644 --- a/first-edition/src/README.md +++ b/first-edition/src/README.md @@ -1,50 +1,10 @@ # The Rust Programming Language -Welcome! This book will teach you about the [Rust Programming Language][rust]. -Rust is a systems programming language focused on three goals: safety, speed, -and concurrency. It maintains these goals without having a garbage collector, -making it a useful language for a number of use cases other languages aren’t -good at: embedding in other languages, programs with specific space and time -requirements, and writing low-level code, like device drivers and operating -systems. It improves on current languages targeting this space by having a -number of compile-time safety checks that produce no runtime overhead, while -eliminating all data races. Rust also aims to achieve ‘zero-cost abstractions’ -even though some of these abstractions feel like those of a high-level language. -Even then, Rust still allows precise control like a low-level language would. +The first edition of the book is no longer distributed with Rust's documentation. -[rust]: https://www.rust-lang.org +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. -“The Rust Programming Language” is split into chapters. This introduction -is the first. After this: - -* [Getting started][gs] - Set up your computer for Rust development. -* [Tutorial: Guessing Game][gg] - Learn some Rust with a small project. -* [Syntax and Semantics][ss] - Each bit of Rust, broken down into small chunks. -* [Effective Rust][er] - Higher-level concepts for writing excellent Rust code. -* [Glossary][gl] - A reference of terms used in the book. -* [Bibliography][bi] - Background on Rust's influences, papers about Rust. - -[gs]: getting-started.html -[gg]: guessing-game.html -[er]: effective-rust.html -[ss]: syntax-and-semantics.html -[gl]: glossary.html -[bi]: bibliography.html - -### Contributing - -The source files from which this book is generated can be found on -[GitHub][book]. - -### Second edition of this book - -There are two editions of "The Rust Programming Language", this being the -first edition. - -The [second edition][second-edition] is a complete re-write. It is still under -construction, though it is far enough along to learn most of Rust. We suggest -reading the second edition and then checking out the first edition later to pick -up some of the more esoteric parts of the language. - -[book]: https://github.com/rust-lang/book/tree/master/first-edition/src -[second-edition]: ../second-edition/index.html +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). \ No newline at end of file diff --git a/first-edition/src/associated-types.md b/first-edition/src/associated-types.md index 4db2b9e5ee..626048e9e6 100644 --- a/first-edition/src/associated-types.md +++ b/first-edition/src/associated-types.md @@ -1,202 +1,10 @@ # Associated Types -Associated types are a powerful part of Rust’s type system. They’re related to -the idea of a ‘type family’, in other words, grouping multiple types together. That -description is a bit abstract, so let’s dive right into an example. If you want -to write a `Graph` trait, you have two types to be generic over: the node type -and the edge type. So you might write a trait, `Graph`, that looks like -this: +The first edition of the book is no longer distributed with Rust's documentation. -```rust -trait Graph { - fn has_edge(&self, &N, &N) -> bool; - fn edges(&self, &N) -> Vec; - // Etc. -} -``` +If you came here via a link or web search, you may want to check out [the current +version of the book](../ch19-03-advanced-traits.html#specifying-placeholder-types-in-trait-definitions-with-associated-types) instead. -While this sort of works, it ends up being awkward. For example, any function -that wants to take a `Graph` as a parameter now _also_ needs to be generic over -the `N`ode and `E`dge types too: - -```rust,ignore -fn distance>(graph: &G, start: &N, end: &N) -> u32 { ... } -``` - -Our distance calculation works regardless of our `Edge` type, so the `E` stuff in -this signature is a distraction. - -What we really want to say is that a certain `E`dge and `N`ode type come together -to form each kind of `Graph`. We can do that with associated types: - -```rust -trait Graph { - type N; - type E; - - fn has_edge(&self, &Self::N, &Self::N) -> bool; - fn edges(&self, &Self::N) -> Vec; - // Etc. -} -``` - -Now, our clients can be abstract over a given `Graph`: - -```rust,ignore -fn distance(graph: &G, start: &G::N, end: &G::N) -> u32 { ... } -``` - -No need to deal with the `E`dge type here! - -Let’s go over all this in more detail. - -## Defining associated types - -Let’s build that `Graph` trait. Here’s the definition: - -```rust -trait Graph { - type N; - type E; - - fn has_edge(&self, &Self::N, &Self::N) -> bool; - fn edges(&self, &Self::N) -> Vec; -} -``` - -Simple enough. Associated types use the `type` keyword, and go inside the body -of the trait, with the functions. - -These type declarations work the same way as those for functions. For example, -if we wanted our `N` type to implement `Display`, so we can print the nodes out, -we could do this: - -```rust -use std::fmt; - -trait Graph { - type N: fmt::Display; - type E; - - fn has_edge(&self, &Self::N, &Self::N) -> bool; - fn edges(&self, &Self::N) -> Vec; -} -``` - -## Implementing associated types - -Just like any trait, traits that use associated types use the `impl` keyword to -provide implementations. Here’s a simple implementation of Graph: - -```rust -# trait Graph { -# type N; -# type E; -# fn has_edge(&self, &Self::N, &Self::N) -> bool; -# fn edges(&self, &Self::N) -> Vec; -# } -struct Node; - -struct Edge; - -struct MyGraph; - -impl Graph for MyGraph { - type N = Node; - type E = Edge; - - fn has_edge(&self, n1: &Node, n2: &Node) -> bool { - true - } - - fn edges(&self, n: &Node) -> Vec { - Vec::new() - } -} -``` - -This silly implementation always returns `true` and an empty `Vec`, but it -gives you an idea of how to implement this kind of thing. We first need three -`struct`s, one for the graph, one for the node, and one for the edge. If it made -more sense to use a different type, that would work as well, we’re going to -use `struct`s for all three here. - -Next is the `impl` line, which is an implementation like any other trait. - -From here, we use `=` to define our associated types. The name the trait uses -goes on the left of the `=`, and the concrete type we’re `impl`ementing this -for goes on the right. Finally, we use the concrete types in our function -declarations. - -## Trait objects with associated types - -There’s one more bit of syntax we should talk about: trait objects. If you -try to create a trait object from a trait with an associated type, like this: - -```rust,ignore -# trait Graph { -# type N; -# type E; -# fn has_edge(&self, &Self::N, &Self::N) -> bool; -# fn edges(&self, &Self::N) -> Vec; -# } -# struct Node; -# struct Edge; -# struct MyGraph; -# impl Graph for MyGraph { -# type N = Node; -# type E = Edge; -# fn has_edge(&self, n1: &Node, n2: &Node) -> bool { -# true -# } -# fn edges(&self, n: &Node) -> Vec { -# Vec::new() -# } -# } -let graph = MyGraph; -let obj = Box::new(graph) as Box; -``` - -You’ll get two errors: - -```text -error: the value of the associated type `E` (from the trait `main::Graph`) must -be specified [E0191] -let obj = Box::new(graph) as Box; - ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -24:44 error: the value of the associated type `N` (from the trait -`main::Graph`) must be specified [E0191] -let obj = Box::new(graph) as Box; - ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -``` - -We can’t create a trait object like this, because we don’t know the associated -types. Instead, we can write this: - -```rust -# trait Graph { -# type N; -# type E; -# fn has_edge(&self, &Self::N, &Self::N) -> bool; -# fn edges(&self, &Self::N) -> Vec; -# } -# struct Node; -# struct Edge; -# struct MyGraph; -# impl Graph for MyGraph { -# type N = Node; -# type E = Edge; -# fn has_edge(&self, n1: &Node, n2: &Node) -> bool { -# true -# } -# fn edges(&self, n: &Node) -> Vec { -# Vec::new() -# } -# } -let graph = MyGraph; -let obj = Box::new(graph) as Box>; -``` - -The `N=Node` syntax allows us to provide a concrete type, `Node`, for the `N` -type parameter. Same with `E=Edge`. If we didn’t provide this constraint, we -couldn’t be sure which `impl` to match this trait object to. +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). diff --git a/first-edition/src/attributes.md b/first-edition/src/attributes.md index 49ac9b2c4f..b39fcdd679 100644 --- a/first-edition/src/attributes.md +++ b/first-edition/src/attributes.md @@ -1,70 +1,10 @@ # Attributes -Declarations can be annotated with ‘attributes’ in Rust. They look like this: +The first edition of the book is no longer distributed with Rust's documentation. -```rust -#[test] -# fn foo() {} -``` +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. -or like this: - -```rust -# mod foo { -#![test] -# } -``` - -The difference between the two is the `!`, which changes what the attribute -applies to: - -```rust,ignore -#[foo] -struct Foo; - -mod bar { - #![bar] -} -``` - -The `#[foo]` attribute applies to the next item, which is the `struct` -declaration. The `#![bar]` attribute applies to the item enclosing it, which is -the `mod` declaration. Otherwise, they’re the same. Both change the meaning of -the item they’re attached to somehow. - -For example, consider a function like this: - -```rust -#[test] -fn check() { - assert_eq!(2, 1 + 1); -} -``` - -It is marked with `#[test]`. This means it’s special: when you run -[tests][tests], this function will execute. When you compile as usual, it won’t -even be included. This function is now a test function. - -[tests]: testing.html - -Attributes may also have additional data: - -```rust -#[inline(always)] -fn super_fast_fn() { -# } -``` - -Or even keys and values: - -```rust -#[cfg(target_os = "macos")] -mod macos_only { -# } -``` - -Rust attributes are used for a number of different things. There is a full list -of attributes [in the reference][reference]. Currently, you are not allowed to -create your own attributes, the Rust compiler defines them. - -[reference]: ../../reference/attributes.html +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). \ No newline at end of file diff --git a/first-edition/src/bibliography.md b/first-edition/src/bibliography.md index 3a624b5daf..9609068fd0 100644 --- a/first-edition/src/bibliography.md +++ b/first-edition/src/bibliography.md @@ -1,83 +1,10 @@ # Bibliography -This is a reading list of material relevant to Rust. It includes prior -research that has - at one time or another - influenced the design of -Rust, as well as publications about Rust. +The first edition of the book is no longer distributed with Rust's documentation. -### Type system +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. -* [Region based memory management in Cyclone](http://209.68.42.137/ucsd-pages/Courses/cse227.w03/handouts/cyclone-regions.pdf) -* [Safe manual memory management in Cyclone](http://www.cs.umd.edu/projects/PL/cyclone/scp.pdf) -* [Typeclasses: making ad-hoc polymorphism less ad hoc](http://www.ps.uni-sb.de/courses/typen-ws99/class.ps.gz) -* [Macros that work together](https://www.cs.utah.edu/plt/publications/jfp12-draft-fcdf.pdf) -* [Traits: composable units of behavior](http://scg.unibe.ch/archive/papers/Scha03aTraits.pdf) -* [Alias burying](http://www.cs.uwm.edu/faculty/boyland/papers/unique-preprint.ps) - We tried something similar and abandoned it. -* [External uniqueness is unique enough](http://www.cs.uu.nl/research/techreps/UU-CS-2002-048.html) -* [Uniqueness and Reference Immutability for Safe Parallelism](https://research.microsoft.com/pubs/170528/msr-tr-2012-79.pdf) -* [Region Based Memory Management](http://www.cs.ucla.edu/~palsberg/tba/papers/tofte-talpin-iandc97.pdf) - -### Concurrency - -* [Singularity: rethinking the software stack](https://research.microsoft.com/pubs/69431/osr2007_rethinkingsoftwarestack.pdf) -* [Language support for fast and reliable message passing in singularity OS](https://research.microsoft.com/pubs/67482/singsharp.pdf) -* [Scheduling multithreaded computations by work stealing](http://supertech.csail.mit.edu/papers/steal.pdf) -* [Thread scheduling for multiprogramming multiprocessors](http://www.eecis.udel.edu/%7Ecavazos/cisc879-spring2008/papers/arora98thread.pdf) -* [The data locality of work stealing](http://www.aladdin.cs.cmu.edu/papers/pdfs/y2000/locality_spaa00.pdf) -* [Dynamic circular work stealing deque](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.170.1097&rep=rep1&type=pdf) - The Chase/Lev deque -* [Work-first and help-first scheduling policies for async-finish task parallelism](http://www.cs.rice.edu/%7Eyguo/pubs/PID824943.pdf) - More general than fully-strict work stealing -* [A Java fork/join calamity](http://www.coopsoft.com/ar/CalamityArticle.html) - critique of Java's fork/join library, particularly its application of work stealing to non-strict computation -* [Scheduling techniques for concurrent systems](http://www.stanford.edu/~ouster/cgi-bin/papers/coscheduling.pdf) -* [Contention aware scheduling](http://www.blagodurov.net/files/a8-blagodurov.pdf) -* [Balanced work stealing for time-sharing multicores](http://www.cse.ohio-state.edu/hpcs/WWW/HTML/publications/papers/TR-12-1.pdf) -* [Three layer cake for shared-memory programming](http://dl.acm.org/citation.cfm?id=1953616&dl=ACM&coll=DL&CFID=524387192&CFTOKEN=44362705) -* [Non-blocking steal-half work queues](http://www.cs.bgu.ac.il/%7Ehendlerd/papers/p280-hendler.pdf) -* [Reagents: expressing and composing fine-grained concurrency](http://www.mpi-sws.org/~turon/reagents.pdf) -* [Algorithms for scalable synchronization of shared-memory multiprocessors](https://www.cs.rochester.edu/u/scott/papers/1991_TOCS_synch.pdf) -* [Epoch-based reclamation](https://www.cl.cam.ac.uk/techreports/UCAM-CL-TR-579.pdf). - -### Others - -* [Crash-only software](https://www.usenix.org/legacy/events/hotos03/tech/full_papers/candea/candea.pdf) -* [Composing High-Performance Memory Allocators](http://people.cs.umass.edu/~emery/pubs/berger-pldi2001.pdf) -* [Reconsidering Custom Memory Allocation](http://people.cs.umass.edu/~emery/pubs/berger-oopsla2002.pdf) - -### Papers *about* Rust - -* [GPU Programming in Rust: Implementing High Level Abstractions in a -Systems Level -Language](http://www.cs.indiana.edu/~eholk/papers/hips2013.pdf). Early GPU work by Eric Holk. -* [Parallel closures: a new twist on an old - idea](https://www.usenix.org/conference/hotpar12/parallel-closures-new-twist-old-idea) - - not exactly about Rust, but by nmatsakis -* [Patina: A Formalization of the Rust Programming - Language](ftp://ftp.cs.washington.edu/tr/2015/03/UW-CSE-15-03-02.pdf). Early - formalization of a subset of the type system, by Eric Reed. -* [Experience Report: Developing the Servo Web Browser Engine using - Rust](http://arxiv.org/abs/1505.07383). By Lars Bergstrom. -* [Implementing a Generic Radix Trie in - Rust](https://michaelsproul.github.io/rust_radix_paper/rust-radix-sproul.pdf). Undergrad - paper by Michael Sproul. -* [Reenix: Implementing a Unix-Like Operating System in - Rust](http://scialex.github.io/reenix.pdf). Undergrad paper by Alex - Light. -* [Evaluation of performance and productivity metrics of potential - programming languages in the HPC environment](http://octarineparrot.com/assets/mrfloya-thesis-ba.pdf). - Bachelor's thesis by Florian Wilkens. Compares C, Go and Rust. -* [Nom, a byte oriented, streaming, zero copy, parser combinators library - in Rust](http://spw15.langsec.org/papers/couprie-nom.pdf). By - Geoffroy Couprie, research for VLC. -* [Graph-Based Higher-Order Intermediate - Representation](http://compilers.cs.uni-saarland.de/papers/lkh15_cgo.pdf). An - experimental IR implemented in Impala, a Rust-like language. -* [Code Refinement of Stencil - Codes](http://compilers.cs.uni-saarland.de/papers/ppl14_web.pdf). Another - paper using Impala. -* [Parallelization in Rust with fork-join and - friends](http://publications.lib.chalmers.se/records/fulltext/219016/219016.pdf). Linus - Farnstrand's master's thesis. -* [Session Types for - Rust](http://munksgaard.me/papers/laumann-munksgaard-larsen.pdf). Philip - Munksgaard's master's thesis. Research for Servo. -* [Ownership is Theft: Experiences Building an Embedded OS in Rust - Amit Levy, et. al.](http://amitlevy.com/papers/tock-plos2015.pdf) -* [You can't spell trust without Rust](https://raw.githubusercontent.com/Gankro/thesis/master/thesis.pdf). Alexis Beingessner's master's thesis. -* [Rust as a Language for High Performance GC Implementation](http://users.cecs.anu.edu.au/~steveb/downloads/pdf/rust-ismm-2016.pdf) +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). \ No newline at end of file diff --git a/first-edition/src/borrow-and-asref.md b/first-edition/src/borrow-and-asref.md index 3b1ef1a2ae..a088bc8d75 100644 --- a/first-edition/src/borrow-and-asref.md +++ b/first-edition/src/borrow-and-asref.md @@ -1,93 +1,10 @@ # Borrow and AsRef -The [`Borrow`][borrow] and [`AsRef`][asref] traits are very similar, but -different. Here’s a quick refresher on what these two traits mean. +The first edition of the book is no longer distributed with Rust's documentation. -[borrow]: ../../std/borrow/trait.Borrow.html -[asref]: ../../std/convert/trait.AsRef.html +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. -# Borrow - -The `Borrow` trait is used when you’re writing a data structure, and you want to -use either an owned or borrowed type as synonymous for some purpose. - -For example, [`HashMap`][hashmap] has a [`get` method][get] which uses `Borrow`: - -```rust,ignore -fn get(&self, k: &Q) -> Option<&V> - where K: Borrow, - Q: Hash + Eq -``` - -[hashmap]: ../../std/collections/struct.HashMap.html -[get]: ../../std/collections/struct.HashMap.html#method.get - -This signature is pretty complicated. The `K` parameter is what we’re interested -in here. It refers to a parameter of the `HashMap` itself: - -```rust,ignore -struct HashMap { -``` - -The `K` parameter is the type of _key_ the `HashMap` uses. So, looking at -the signature of `get()` again, we can use `get()` when the key implements -`Borrow`. That way, we can make a `HashMap` which uses `String` keys, -but use `&str`s when we’re searching: - -```rust -use std::collections::HashMap; - -let mut map = HashMap::new(); -map.insert("Foo".to_string(), 42); - -assert_eq!(map.get("Foo"), Some(&42)); -``` - -This is because the standard library has `impl Borrow for String`. - -For most types, when you want to take an owned or borrowed type, a `&T` is -enough. But one area where `Borrow` is effective is when there’s more than one -kind of borrowed value. This is especially true of references and slices: you -can have both an `&T` or a `&mut T`. If we wanted to accept both of these types, -`Borrow` is up for it: - -```rust -use std::borrow::Borrow; -use std::fmt::Display; - -fn foo + Display>(a: T) { - println!("a is borrowed: {}", a); -} - -let mut i = 5; - -foo(&i); -foo(&mut i); -``` - -This will print out `a is borrowed: 5` twice. - -# AsRef - -The `AsRef` trait is a conversion trait. It’s used for converting some value to -a reference in generic code. Like this: - -```rust -let s = "Hello".to_string(); - -fn foo>(s: T) { - let slice = s.as_ref(); -} -``` - -# Which should I use? - -We can see how they’re kind of the same: they both deal with owned and borrowed -versions of some type. However, they’re a bit different. - -Choose `Borrow` when you want to abstract over different kinds of borrowing, or -when you’re building a data structure that treats owned and borrowed values in -equivalent ways, such as hashing and comparison. - -Choose `AsRef` when you want to convert something to a reference directly, and -you’re writing generic code. +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). diff --git a/first-edition/src/casting-between-types.md b/first-edition/src/casting-between-types.md index d565aa9dcb..34d4e84e57 100644 --- a/first-edition/src/casting-between-types.md +++ b/first-edition/src/casting-between-types.md @@ -1,204 +1,10 @@ # Casting Between Types -Rust, with its focus on safety, provides two different ways of casting -different types between each other. The first, `as`, is for safe casts. -In contrast, `transmute` allows for arbitrary casting, and is one of the -most dangerous features of Rust! +The first edition of the book is no longer distributed with Rust's documentation. -# Coercion +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. -Coercion between types is implicit and has no syntax of its own, but can -be spelled out with [`as`](#explicit-coercions). - -Coercion occurs in `let`, `const`, and `static` statements; in -function call arguments; in field values in struct initialization; and in a -function result. - -The most common case of coercion is removing mutability from a reference: - -* `&mut T` to `&T` - -An analogous conversion is to remove mutability from a -[raw pointer](raw-pointers.html): - -* `*mut T` to `*const T` - -References can also be coerced to raw pointers: - -* `&T` to `*const T` - -* `&mut T` to `*mut T` - -Custom coercions may be defined using [`Deref`](deref-coercions.html). - -Coercion is transitive. - -# `as` - -The `as` keyword does safe casting: - -```rust -let x: i32 = 5; - -let y = x as i64; -``` - -There are three major categories of safe cast: explicit coercions, casts -between numeric types, and pointer casts. - -Casting is not transitive: even if `e as U1 as U2` is a valid -expression, `e as U2` is not necessarily so (in fact it will only be valid if -`U1` coerces to `U2`). - - -## Explicit coercions - -A cast `e as U` is valid if `e` has type `T` and `T` *coerces* to `U`. - -## Numeric casts - -A cast `e as U` is also valid in any of the following cases: - -* `e` has type `T` and `T` and `U` are any numeric types; *numeric-cast* -* `e` is an enum with no data attached to the variants (a "field-less enumeration"), - and `U` is an integer type; *enum-cast* -* `e` has type `bool` or `char` and `U` is an integer type; *prim-int-cast* -* `e` has type `u8` and `U` is `char`; *u8-char-cast* - -For example - -```rust -let one = true as u8; -let at_sign = 64 as char; -let two_hundred = -56i8 as u8; -``` - -The semantics of numeric casts are: - -* Casting between two integers of the same size (e.g. i32 -> u32) is a no-op -* Casting from a larger integer to a smaller integer (e.g. u32 -> u8) will - truncate -* Casting from a smaller integer to a larger integer (e.g. u8 -> u32) will - * zero-extend if the source is unsigned - * sign-extend if the source is signed -* Casting from a float to an integer will round the float towards zero - * **[NOTE: currently this will cause Undefined Behavior if the rounded - value cannot be represented by the target integer type][float-int]**. - This includes Inf and NaN. This is a bug and will be fixed. -* Casting from an integer to float will produce the floating point - representation of the integer, rounded if necessary (rounding strategy - unspecified) -* Casting from an f32 to an f64 is perfect and lossless -* Casting from an f64 to an f32 will produce the closest possible value - (rounding strategy unspecified) - * **[NOTE: currently this will cause Undefined Behavior if the value - is finite but larger or smaller than the largest or smallest finite - value representable by f32][float-float]**. This is a bug and will - be fixed. - -[float-int]: https://github.com/rust-lang/rust/issues/10184 -[float-float]: https://github.com/rust-lang/rust/issues/15536 - -## Pointer casts - -Perhaps surprisingly, it is safe to cast [raw pointers](raw-pointers.html) to and -from integers, and to cast between pointers to different types subject to -some constraints. It is only unsafe to dereference the pointer: - -```rust -let a = 300 as *const char; // `a` is a pointer to location 300. -let b = a as u32; -``` - -`e as U` is a valid pointer cast in any of the following cases: - -* `e` has type `*T`, `U` has type `*U_0`, and either `U_0: Sized` or - `unsize_kind(T) == unsize_kind(U_0)`; a *ptr-ptr-cast* - -* `e` has type `*T` and `U` is a numeric type, while `T: Sized`; *ptr-addr-cast* - -* `e` is an integer and `U` is `*U_0`, while `U_0: Sized`; *addr-ptr-cast* - -* `e` has type `&[T; n]` and `U` is `*const T`; *array-ptr-cast* - -* `e` is a function pointer type and `U` has type `*T`, - while `T: Sized`; *fptr-ptr-cast* - -* `e` is a function pointer type and `U` is an integer; *fptr-addr-cast* - - -# `transmute` - -`as` only allows safe casting, and will for example reject an attempt to -cast four bytes into a `u32`: - -```rust,ignore -let a = [0u8, 0u8, 0u8, 0u8]; - -let b = a as u32; // Four u8s makes a u32. -``` - -This errors with: - -```text -error: non-scalar cast: `[u8; 4]` as `u32` -let b = a as u32; // Four u8s makes a u32. - ^~~~~~~~ -``` - -This is a ‘non-scalar cast’ because we have multiple values here: the four -elements of the array. These kinds of casts are very dangerous, because they -make assumptions about the way that multiple underlying structures are -implemented. For this, we need something more dangerous. - -The `transmute` function is very simple, but very scary. It tells Rust to treat -a value of one type as though it were another type. It does this regardless of -the typechecking system, and completely trusts you. - -In our previous example, we know that an array of four `u8`s represents a `u32` -properly, and so we want to do the cast. Using `transmute` instead of `as`, -Rust lets us: - -```rust -use std::mem; - -fn main() { - unsafe { - let a = [0u8, 1u8, 0u8, 0u8]; - let b = mem::transmute::<[u8; 4], u32>(a); - println!("{}", b); // 256 - // Or, more concisely: - let c: u32 = mem::transmute(a); - println!("{}", c); // 256 - } -} -``` - -We have to wrap the operation in an `unsafe` block for this to compile -successfully. Technically, only the `mem::transmute` call itself needs to be in -the block, but it's nice in this case to enclose everything related, so you -know where to look. In this case, the details about `a` are also important, and -so they're in the block. You'll see code in either style, sometimes the context -is too far away, and wrapping all of the code in `unsafe` isn't a great idea. - -While `transmute` does very little checking, it will at least make sure that -the types are the same size. This errors: - -```rust,ignore -use std::mem; - -unsafe { - let a = [0u8, 0u8, 0u8, 0u8]; - - let b = mem::transmute::<[u8; 4], u64>(a); -} -``` - -with: - -```text -error: transmute called with differently sized types: [u8; 4] (32 bits) to u64 -(64 bits) -``` - -Other than that, you're on your own! +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). \ No newline at end of file diff --git a/first-edition/src/chapter_1.md b/first-edition/src/chapter_1.md deleted file mode 100644 index b743fda354..0000000000 --- a/first-edition/src/chapter_1.md +++ /dev/null @@ -1 +0,0 @@ -# Chapter 1 diff --git a/first-edition/src/choosing-your-guarantees.md b/first-edition/src/choosing-your-guarantees.md index 4e69c8bdba..9e56d9da23 100644 --- a/first-edition/src/choosing-your-guarantees.md +++ b/first-edition/src/choosing-your-guarantees.md @@ -1,360 +1,10 @@ # Choosing your Guarantees -One important feature of Rust is that it lets us control the costs and guarantees -of a program. +The first edition of the book is no longer distributed with Rust's documentation. -There are various “wrapper type” abstractions in the Rust standard library which embody -a multitude of trade-offs between cost, ergonomics, and guarantees. Many let one choose between -run-time and compile-time enforcement. This section will explain a few selected abstractions in -detail. +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. -Before proceeding, it is highly recommended that one reads about [ownership][ownership] and -[borrowing][borrowing] in Rust. - -[ownership]: ownership.html -[borrowing]: references-and-borrowing.html - -# Basic pointer types - -## `Box` - -[`Box`][box] is an “owned” pointer, or a “box”. While it can hand -out references to the contained data, it is the only owner of the data. In particular, consider -the following: - -```rust -let x = Box::new(1); -let y = x; -// `x` is no longer accessible here. -``` - -Here, the box was _moved_ into `y`. As `x` no longer owns it, the compiler will no longer allow the -programmer to use `x` after this. A box can similarly be moved _out_ of a function by returning it. - -When a box (that hasn't been moved) goes out of scope, destructors are run. These destructors take -care of deallocating the inner data. - -This is a zero-cost abstraction for dynamic allocation. If you want to allocate some memory on the -heap and safely pass around a pointer to that memory, this is ideal. Note that you will only be -allowed to share references to this by the regular borrowing rules, checked at compile time. - -[box]: ../../std/boxed/struct.Box.html - -## `&T` and `&mut T` - -These are immutable and mutable references respectively. They follow the “read-write lock” -pattern, such that one may either have only one mutable reference to some data, or any number of -immutable ones, but not both. This guarantee is enforced at compile time, and has no visible cost at -runtime. In most cases these two pointer types suffice for sharing cheap references between sections -of code. - -These pointers cannot be copied in such a way that they outlive the lifetime associated with them. - -## `*const T` and `*mut T` - -These are C-like raw pointers with no lifetime or ownership attached to them. They point to -some location in memory with no other restrictions. The only guarantee that these provide is that -they cannot be dereferenced except in code marked `unsafe`. - -These are useful when building safe, low cost abstractions like `Vec`, but should be avoided in -safe code. - -## `Rc` - -This is the first wrapper we will cover that has a runtime cost. - -[`Rc`][rc] is a reference counted pointer. In other words, this lets us have multiple "owning" -pointers to the same data, and the data will be dropped (destructors will be run) when all pointers -are out of scope. - -Internally, it contains a shared “reference count” (also called “refcount”), -which is incremented each time the `Rc` is cloned, and decremented each time one of the `Rc`s goes -out of scope. The main responsibility of `Rc` is to ensure that destructors are called for shared -data. - -The internal data here is immutable, and if a cycle of references is created, the data will be -leaked. If we want data that doesn't leak when there are cycles, we need a garbage collector. - -#### Guarantees - -The main guarantee provided here is that the data will not be destroyed until all references to it -are out of scope. - -This should be used when we wish to dynamically allocate and share some data (read-only) between -various portions of your program, where it is not certain which portion will finish using the pointer -last. It's a viable alternative to `&T` when `&T` is either impossible to statically check for -correctness, or creates extremely unergonomic code where the programmer does not wish to spend the -development cost of working with. - -This pointer is _not_ thread-safe, and Rust will not let it be sent or shared with other threads. -This lets one avoid the cost of atomics in situations where they are unnecessary. - -There is a sister smart pointer to this one, `Weak`. This is a non-owning, but also non-borrowed, -smart pointer. It is also similar to `&T`, but it is not restricted in lifetime—a `Weak` -can be held on to forever. However, it is possible that an attempt to access the inner data may fail -and return `None`, since this can outlive the owned `Rc`s. This is useful for cyclic -data structures and other things. - -#### Cost - -As far as memory goes, `Rc` is a single allocation, though it will allocate two extra words (i.e. -two `usize` values) as compared to a regular `Box` (for "strong" and "weak" refcounts). - -`Rc` has the computational cost of incrementing/decrementing the refcount whenever it is cloned -or goes out of scope respectively. Note that a clone will not do a deep copy, rather it will simply -increment the inner reference count and return a copy of the `Rc`. - -[rc]: ../../std/rc/struct.Rc.html - -# Cell types - -`Cell`s provide interior mutability. In other words, they contain data which can be manipulated even -if the type cannot be obtained in a mutable form (for example, when it is behind an `&`-ptr or -`Rc`). - -[The documentation for the `cell` module has a pretty good explanation for these][cell-mod]. - -These types are _generally_ found in struct fields, but they may be found elsewhere too. - -## `Cell` - -[`Cell`][cell] is a type that provides zero-cost interior mutability by moving data in and -out of the cell. -Since the compiler knows that all the data owned by the contained value is on the stack, there's -no worry of leaking any data behind references (or worse!) by simply replacing the data. - -It is still possible to violate your own invariants using this wrapper, so be careful when using it. -If a field is wrapped in `Cell`, it's a nice indicator that the chunk of data is mutable and may not -stay the same between the time you first read it and when you intend to use it. - -```rust -use std::cell::Cell; - -let x = Cell::new(1); -let y = &x; -let z = &x; -x.set(2); -y.set(3); -z.set(4); -println!("{}", x.get()); -``` - -Note that here we were able to mutate the same value from various immutable references. - -This has the same runtime cost as the following: - -```rust,ignore -let mut x = 1; -let y = &mut x; -let z = &mut x; -x = 2; -*y = 3; -*z = 4; -println!("{}", x); -``` - -but it has the added benefit of actually compiling successfully. - -#### Guarantees - -This relaxes the “no aliasing with mutability” restriction in places where it's -unnecessary. However, this also relaxes the guarantees that the restriction provides; so if your -invariants depend on data stored within `Cell`, you should be careful. - -This is useful for mutating primitives and other types when there is no easy way of -doing it in line with the static rules of `&` and `&mut`. - -`Cell` does not let you obtain interior references to the data, which makes it safe to freely -mutate. - -#### Cost - -There is no runtime cost to using `Cell`, however if you are using it to wrap larger -structs, it might be worthwhile to instead wrap individual fields in `Cell` since each write is -otherwise a full copy of the struct. - - -## `RefCell` - -[`RefCell`][refcell] also provides interior mutability, but doesn't move data in and out of the -cell. - -However, it has a runtime cost. `RefCell` enforces the read-write lock pattern at runtime (it's -like a single-threaded mutex), unlike `&T`/`&mut T` which do so at compile time. This is done by the -`borrow()` and `borrow_mut()` functions, which modify an internal reference count and return smart -pointers which can be dereferenced immutably and mutably respectively. The refcount is restored when -the smart pointers go out of scope. With this system, we can dynamically ensure that there are never -any other borrows active when a mutable borrow is active. If the programmer attempts to make such a -borrow, the thread will panic. - -```rust -use std::cell::RefCell; - -let x = RefCell::new(vec![1,2,3,4]); -{ - println!("{:?}", *x.borrow()) -} - -{ - let mut my_ref = x.borrow_mut(); - my_ref.push(1); -} -``` - -Similar to `Cell`, this is mainly useful for situations where it's hard or impossible to satisfy the -borrow checker. Generally we know that such mutations won't happen in a nested form, but it's good -to check. - -For large, complicated programs, it becomes useful to put some things in `RefCell`s to make things -simpler. For example, a lot of the maps in the `ctxt` struct in the Rust compiler internals -are inside this wrapper. These are only modified once (during creation, which is not right after -initialization) or a couple of times in well-separated places. However, since this struct is -pervasively used everywhere, juggling mutable and immutable pointers would be hard (perhaps -impossible) and probably form a soup of `&`-ptrs which would be hard to extend. On the other hand, -the `RefCell` provides a cheap (not zero-cost) way of safely accessing these. In the future, if -someone adds some code that attempts to modify the cell when it's already borrowed, it will cause a -(usually deterministic) panic which can be traced back to the offending borrow. - -Similarly, in Servo's DOM there is a lot of mutation, most of which is local to a DOM type, but some -of which crisscrosses the DOM and modifies various things. Using `RefCell` and `Cell` to guard all -mutation lets us avoid worrying about mutability everywhere, and it simultaneously highlights the -places where mutation is _actually_ happening. - -Note that `RefCell` should be avoided if a mostly simple solution is possible with `&` pointers. - -#### Guarantees - -`RefCell` relaxes the _static_ restrictions preventing aliased mutation, and replaces them with -_dynamic_ ones. As such the guarantees have not changed. - -#### Cost - -`RefCell` does not allocate, but it contains an additional "borrow state" -indicator (one word in size) along with the data. - -At runtime each borrow causes a modification/check of the refcount. - -[cell-mod]: ../../std/cell/index.html -[cell]: ../../std/cell/struct.Cell.html -[refcell]: ../../std/cell/struct.RefCell.html - -# Synchronous types - -Many of the types above cannot be used in a threadsafe manner. Particularly, `Rc` and -`RefCell`, which both use non-atomic reference counts (_atomic_ reference counts are those which -can be incremented from multiple threads without causing a data race), cannot be used this way. This -makes them cheaper to use, but we need thread-safe versions of these too. They exist, in the form of -`Arc` and `Mutex`/`RwLock` - -Note that the non-threadsafe types _cannot_ be sent between threads, and this is checked at compile -time. - -There are many useful wrappers for concurrent programming in the [sync][sync] module, but only the -major ones will be covered below. - -[sync]: ../../std/sync/index.html - -## `Arc` - -[`Arc`][arc] is a version of `Rc` that uses an atomic reference count (hence, "Arc"). -This can be sent freely between threads. - -C++'s `shared_ptr` is similar to `Arc`, however in the case of C++ the inner data is always mutable. -For semantics similar to that from C++, we should use `Arc>`, `Arc>`, or -`Arc>`[^4] (`UnsafeCell` is a cell type that can be used to hold any data and has -no runtime cost, but accessing it requires `unsafe` blocks). The last one should only be used if we -are certain that the usage won't cause any memory unsafety. Remember that writing to a struct is not -an atomic operation, and many functions like `vec.push()` can reallocate internally and cause unsafe -behavior, so even monotonicity may not be enough to justify `UnsafeCell`. - -[^4]: `Arc>` actually won't compile since `UnsafeCell` isn't `Send` or `Sync`, but we can wrap it in a type and implement `Send`/`Sync` for it manually to get `Arc>` where `Wrapper` is `struct Wrapper(UnsafeCell)`. - -#### Guarantees - -Like `Rc`, this provides the (thread-safe) guarantee that the destructor for the internal data will -be run when the last `Arc` goes out of scope (barring any cycles). - -#### Cost - -This has the added cost of using atomics for changing the refcount (which will happen whenever it is -cloned or goes out of scope). When sharing data from an `Arc` in a single thread, it is preferable -to share `&` pointers whenever possible. - -[arc]: ../../std/sync/struct.Arc.html - -## `Mutex` and `RwLock` - -[`Mutex`][mutex] and [`RwLock`][rwlock] provide mutual-exclusion via RAII guards (guards are -objects which maintain some state, like a lock, until their destructor is called). For both of -these, the mutex is opaque until we call `lock()` on it, at which point the thread will block -until a lock can be acquired, and then a guard will be returned. This guard can be used to access -the inner data (mutably), and the lock will be released when the guard goes out of scope. - -```rust,ignore -{ - let guard = mutex.lock(); - // `guard` dereferences mutably to the inner type. - *guard += 1; -} // Lock is released when destructor runs. -``` - - -`RwLock` has the added benefit of being efficient for multiple reads. It is always safe to have -multiple readers to shared data as long as there are no writers; and `RwLock` lets readers acquire a -"read lock". Such locks can be acquired concurrently and are kept track of via a reference count. -Writers must obtain a "write lock" which can only be obtained when all readers have gone out of -scope. - -#### Guarantees - -Both of these provide safe shared mutability across threads, however they are prone to deadlocks. -Some level of additional protocol safety can be obtained via the type system. - -#### Costs - -These use internal atomic-like types to maintain the locks, which are pretty costly (they can block -all memory reads across processors till they're done). Waiting on these locks can also be slow when -there's a lot of concurrent access happening. - -[rwlock]: ../../std/sync/struct.RwLock.html -[mutex]: ../../std/sync/struct.Mutex.html -[sessions]: https://github.com/Munksgaard/rust-sessions - -# Composition - -A common gripe when reading Rust code is with types like `Rc>>` (or even more -complicated compositions of such types). It's not always clear what the composition does, or why the -author chose one like this (and when one should be using such a composition in one's own code) - -Usually, it's a case of composing together the guarantees that you need, without paying for stuff -that is unnecessary. - -For example, `Rc>` is one such composition. `Rc` itself can't be dereferenced mutably; -because `Rc` provides sharing and shared mutability can lead to unsafe behavior, so we put -`RefCell` inside to get dynamically verified shared mutability. Now we have shared mutable data, -but it's shared in a way that there can only be one mutator (and no readers) or multiple readers. - -Now, we can take this a step further, and have `Rc>>` or `Rc>>`. These -are both shareable, mutable vectors, but they're not the same. - -With the former, the `RefCell` is wrapping the `Vec`, so the `Vec` in its entirety is -mutable. At the same time, there can only be one mutable borrow of the whole `Vec` at a given time. -This means that your code cannot simultaneously work on different elements of the vector from -different `Rc` handles. However, we are able to push and pop from the `Vec` at will. This is -similar to a `&mut Vec` with the borrow checking done at runtime. - -With the latter, the borrowing is of individual elements, but the overall vector is immutable. Thus, -we can independently borrow separate elements, but we cannot push or pop from the vector. This is -similar to a `&mut [T]`[^3], but, again, the borrow checking is at runtime. - -In concurrent programs, we have a similar situation with `Arc>`, which provides shared -mutability and ownership. - -When reading code that uses these, go in step by step and look at the guarantees/costs provided. - -When choosing a composed type, we must do the reverse; figure out which guarantees we want, and at -which point of the composition we need them. For example, if there is a choice between -`Vec>` and `RefCell>`, we should figure out the trade-offs as done above and pick -one. - -[^3]: `&[T]` and `&mut [T]` are _slices_; they consist of a pointer and a length and can refer to a portion of a vector or array. `&mut [T]` can have its elements mutated, however its length cannot be touched. +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). diff --git a/first-edition/src/closures.md b/first-edition/src/closures.md index 0fe08bfb68..3852e28f59 100644 --- a/first-edition/src/closures.md +++ b/first-edition/src/closures.md @@ -1,537 +1,10 @@ # Closures -Sometimes it is useful to wrap up a function and _free variables_ for better -clarity and reuse. The free variables that can be used come from the -enclosing scope and are ‘closed over’ when used in the function. From this, we -get the name ‘closures’ and Rust provides a really great implementation of -them, as we’ll see. +The first edition of the book is no longer distributed with Rust's documentation. -# Syntax +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. -Closures look like this: - -```rust -let plus_one = |x: i32| x + 1; - -assert_eq!(2, plus_one(1)); -``` - -We create a binding, `plus_one`, and assign it to a closure. The closure’s -arguments go between the pipes (`|`), and the body is an expression, in this -case, `x + 1`. Remember that `{ }` is an expression, so we can have multi-line -closures too: - -```rust -let plus_two = |x| { - let mut result: i32 = x; - - result += 1; - result += 1; - - result -}; - -assert_eq!(4, plus_two(2)); -``` - -You’ll notice a few things about closures that are a bit different from regular -named functions defined with `fn`. The first is that we did not need to -annotate the types of arguments the closure takes or the values it returns. We -can: - -```rust -let plus_one = |x: i32| -> i32 { x + 1 }; - -assert_eq!(2, plus_one(1)); -``` - -But we don’t have to. Why is this? Basically, it was chosen for ergonomic -reasons. While specifying the full type for named functions is helpful with -things like documentation and type inference, the full type signatures of -closures are rarely documented since they’re anonymous, and they don’t cause -the kinds of error-at-a-distance problems that inferring named function types -can. - -The second is that the syntax is similar, but a bit different. I’ve added -spaces here for easier comparison: - -```rust -fn plus_one_v1 (x: i32) -> i32 { x + 1 } -let plus_one_v2 = |x: i32| -> i32 { x + 1 }; -let plus_one_v3 = |x: i32| x + 1 ; -``` - -Small differences, but they’re similar. - -# Closures and their environment - -The environment for a closure can include bindings from its enclosing scope in -addition to parameters and local bindings. It looks like this: - -```rust -let num = 5; -let plus_num = |x: i32| x + num; - -assert_eq!(10, plus_num(5)); -``` - -This closure, `plus_num`, refers to a `let` binding in its scope: `num`. More -specifically, it borrows the binding. If we do something that would conflict -with that binding, we get an error. Like this one: - -```rust,ignore -let mut num = 5; -let plus_num = |x: i32| x + num; - -let y = &mut num; -``` - -Which errors with: - -```text -error: cannot borrow `num` as mutable because it is also borrowed as immutable - let y = &mut num; - ^~~ -note: previous borrow of `num` occurs here due to use in closure; the immutable - borrow prevents subsequent moves or mutable borrows of `num` until the borrow - ends - let plus_num = |x| x + num; - ^~~~~~~~~~~ -note: previous borrow ends here -fn main() { - let mut num = 5; - let plus_num = |x| x + num; - - let y = &mut num; -} -^ -``` - -A verbose yet helpful error message! As it says, we can’t take a mutable borrow -on `num` because the closure is already borrowing it. If we let the closure go -out of scope, we can: - -```rust -let mut num = 5; -{ - let plus_num = |x: i32| x + num; - -} // `plus_num` goes out of scope; borrow of `num` ends. - -let y = &mut num; -``` - -If your closure requires it, however, Rust will take ownership and move -the environment instead. This doesn’t work: - -```rust,ignore -let nums = vec![1, 2, 3]; - -let takes_nums = || nums; - -println!("{:?}", nums); -``` - -We get this error: - -```text -note: `nums` moved into closure environment here because it has type - `[closure(()) -> collections::vec::Vec]`, which is non-copyable -let takes_nums = || nums; - ^~~~~~~ -``` - -`Vec` has ownership over its contents, and therefore, when we refer to it -in our closure, we have to take ownership of `nums`. It’s the same as if we’d -passed `nums` to a function that took ownership of it. - -## `move` closures - -We can force our closure to take ownership of its environment with the `move` -keyword: - -```rust -let num = 5; - -let owns_num = move |x: i32| x + num; -``` - -Now, even though the keyword is `move`, the variables follow normal move semantics. -In this case, `5` implements `Copy`, and so `owns_num` takes ownership of a copy -of `num`. So what’s the difference? - -```rust -let mut num = 5; - -{ - let mut add_num = |x: i32| num += x; - - add_num(5); -} - -assert_eq!(10, num); -``` - -So in this case, our closure took a mutable reference to `num`, and then when -we called `add_num`, it mutated the underlying value, as we’d expect. We also -needed to declare `add_num` as `mut` too, because we’re mutating its -environment. - -If we change to a `move` closure, it’s different: - -```rust -let mut num = 5; - -{ - let mut add_num = move |x: i32| num += x; - - add_num(5); -} - -assert_eq!(5, num); -``` - -We only get `5`. Rather than taking a mutable borrow out on our `num`, we took -ownership of a copy. - -Another way to think about `move` closures: they give a closure its own stack -frame. Without `move`, a closure may be tied to the stack frame that created -it, while a `move` closure is self-contained. This means that you cannot -generally return a non-`move` closure from a function, for example. - -But before we talk about taking and returning closures, we should talk some -more about the way that closures are implemented. As a systems language, Rust -gives you tons of control over what your code does, and closures are no -different. - -# Closure implementation - -Rust’s implementation of closures is a bit different than other languages. They -are effectively syntax sugar for traits. You’ll want to make sure to have read -the [traits][traits] section before this one, as well as the section on [trait -objects][trait-objects]. - -[traits]: traits.html -[trait-objects]: trait-objects.html - -Got all that? Good. - -The key to understanding how closures work under the hood is something a bit -strange: Using `()` to call a function, like `foo()`, is an overloadable -operator. From this, everything else clicks into place. In Rust, we use the -trait system to overload operators. Calling functions is no different. We have -three separate traits to overload with: - -* `Fn` -* `FnMut` -* `FnOnce` - -There are a few differences between these traits, but a big one is `self`: -`Fn` takes `&self`, `FnMut` takes `&mut self`, and `FnOnce` takes `self`. This -covers all three kinds of `self` via the usual method call syntax. But we’ve -split them up into three traits, rather than having a single one. This gives us -a large amount of control over what kind of closures we can take. - -The `|| {}` syntax for closures is sugar for these three traits. Rust will -generate a struct for the environment, `impl` the appropriate trait, and then -use it. - -# Taking closures as arguments - -Now that we know that closures are traits, we already know how to accept and -return closures: the same as any other trait! - -This also means that we can choose static vs dynamic dispatch as well. First, -let’s write a function which takes something callable, calls it, and returns -the result: - -```rust -fn call_with_one(some_closure: F) -> i32 - where F: Fn(i32) -> i32 { - - some_closure(1) -} - -let answer = call_with_one(|x| x + 2); - -assert_eq!(3, answer); -``` - -We pass our closure, `|x| x + 2`, to `call_with_one`. It does what it -suggests: it calls the closure, giving it `1` as an argument. - -Let’s examine the signature of `call_with_one` in more depth: - -```rust -fn call_with_one(some_closure: F) -> i32 -# where F: Fn(i32) -> i32 { -# some_closure(1) } -``` - -We take one parameter, and it has the type `F`. We also return an `i32`. This part -isn’t interesting. The next part is: - -```rust -# fn call_with_one(some_closure: F) -> i32 - where F: Fn(i32) -> i32 { -# some_closure(1) } -``` - -Because `Fn` is a trait, we can use it as a bound for our generic type. In -this case, our closure takes an `i32` as an argument and returns an `i32`, and -so the generic bound we use is `Fn(i32) -> i32`. - -There’s one other key point here: because we’re bounding a generic with a -trait, this will get monomorphized, and therefore, we’ll be doing static -dispatch into the closure. That’s pretty neat. In many languages, closures are -inherently heap allocated, and will always involve dynamic dispatch. In Rust, -we can stack allocate our closure environment, and statically dispatch the -call. This happens quite often with iterators and their adapters, which often -take closures as arguments. - -Of course, if we want dynamic dispatch, we can get that too. A trait object -handles this case, as usual: - -```rust -fn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 { - some_closure(1) -} - -let answer = call_with_one(&|x| x + 2); - -assert_eq!(3, answer); -``` - -Now we take a trait object, a `&Fn`. And we have to make a reference -to our closure when we pass it to `call_with_one`, so we use `&||`. - -A quick note about closures that use explicit lifetimes. Sometimes you might have a closure -that takes a reference like so: - -```rust -fn call_with_ref(some_closure:F) -> i32 - where F: Fn(&i32) -> i32 { - - let value = 0; - some_closure(&value) -} -``` - -Normally you can specify the lifetime of the parameter to our closure. We -could annotate it on the function declaration: - -```rust,ignore -fn call_with_ref<'a, F>(some_closure:F) -> i32 - where F: Fn(&'a i32) -> i32 { -``` - -However, this presents a problem in our case. When a function has an explicit -lifetime parameter, that lifetime must be at least as long as the *entire* -call to that function. The borrow checker will complain that `value` doesn't -live long enough, because it is only in scope after its declaration inside the -function body. - -What we need is a closure that can borrow its argument only for its own -invocation scope, not for the outer function's scope. In order to say that, -we can use Higher-Ranked Trait Bounds with the `for<...>` syntax: - -```ignore -fn call_with_ref(some_closure:F) -> i32 - where F: for<'a> Fn(&'a i32) -> i32 { -``` - -This lets the Rust compiler find the minimum lifetime to invoke our closure and -satisfy the borrow checker's rules. Our function then compiles and executes as we -expect. - -```rust -fn call_with_ref(some_closure:F) -> i32 - where F: for<'a> Fn(&'a i32) -> i32 { - - let value = 0; - some_closure(&value) -} -``` - -# Function pointers and closures - -A function pointer is kind of like a closure that has no environment. As such, -you can pass a function pointer to any function expecting a closure argument, -and it will work: - -```rust -fn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 { - some_closure(1) -} - -fn add_one(i: i32) -> i32 { - i + 1 -} - -let f = add_one; - -let answer = call_with_one(&f); - -assert_eq!(2, answer); -``` - -In this example, we don’t strictly need the intermediate variable `f`, -the name of the function works just fine too: - -```rust,ignore -let answer = call_with_one(&add_one); -``` - -# Returning closures - -It’s very common for functional-style code to return closures in various -situations. If you try to return a closure, you may run into an error. At -first, it may seem strange, but we’ll figure it out. Here’s how you’d probably -try to return a closure from a function: - -```rust,ignore -fn factory() -> (Fn(i32) -> i32) { - let num = 5; - - |x| x + num -} - -let f = factory(); - -let answer = f(1); -assert_eq!(6, answer); -``` - -This gives us these long, related errors: - -```text -error: the trait bound `core::ops::Fn(i32) -> i32 : core::marker::Sized` is not satisfied [E0277] -fn factory() -> (Fn(i32) -> i32) { - ^~~~~~~~~~~~~~~~ -note: `core::ops::Fn(i32) -> i32` does not have a constant size known at compile-time -fn factory() -> (Fn(i32) -> i32) { - ^~~~~~~~~~~~~~~~ -error: the trait bound `core::ops::Fn(i32) -> i32 : core::marker::Sized` is not satisfied [E0277] -let f = factory(); - ^ -note: `core::ops::Fn(i32) -> i32` does not have a constant size known at compile-time -let f = factory(); - ^ -``` - -In order to return something from a function, Rust needs to know what -size the return type is. But since `Fn` is a trait, it could be various -things of various sizes: many different types can implement `Fn`. An easy -way to give something a size is to take a reference to it, as references -have a known size. So we’d write this: - -```rust,ignore -fn factory() -> &(Fn(i32) -> i32) { - let num = 5; - - |x| x + num -} - -let f = factory(); - -let answer = f(1); -assert_eq!(6, answer); -``` - -But we get another error: - -```text -error: missing lifetime specifier [E0106] -fn factory() -> &(Fn(i32) -> i32) { - ^~~~~~~~~~~~~~~~~ -``` - -Right. Because we have a reference, we need to give it a lifetime. But -our `factory()` function takes no arguments, so -[elision](lifetimes.html#lifetime-elision) doesn’t kick in here. Then what -choices do we have? Try `'static`: - -```rust,ignore -fn factory() -> &'static (Fn(i32) -> i32) { - let num = 5; - - |x| x + num -} - -let f = factory(); - -let answer = f(1); -assert_eq!(6, answer); -``` - -But we get another error: - -```text -error: mismatched types: - expected `&'static core::ops::Fn(i32) -> i32`, - found `[closure@:7:9: 7:20]` -(expected &-ptr, - found closure) [E0308] - |x| x + num - ^~~~~~~~~~~ - -``` - -This error is letting us know that we don’t have a `&'static Fn(i32) -> i32`, -we have a `[closure@:7:9: 7:20]`. Wait, what? - -Because each closure generates its own environment `struct` and implementation -of `Fn` and friends, these types are anonymous. They exist solely for -this closure. So Rust shows them as `closure@`, rather than some -autogenerated name. - -The error also points out that the return type is expected to be a reference, -but what we are trying to return is not. Further, we cannot directly assign a -`'static` lifetime to an object. So we'll take a different approach and return -a ‘trait object’ by `Box`ing up the `Fn`. This _almost_ works: - -```rust,ignore -fn factory() -> Box i32> { - let num = 5; - - Box::new(|x| x + num) -} - -let f = factory(); - -let answer = f(1); -assert_eq!(6, answer); -``` - -There’s just one last problem: - -```text -error: closure may outlive the current function, but it borrows `num`, -which is owned by the current function [E0373] -Box::new(|x| x + num) - ^~~~~~~~~~~ -``` - -Well, as we discussed before, closures borrow their environment. And in this -case, our environment is based on a stack-allocated `5`, the `num` variable -binding. So the borrow has a lifetime of the stack frame. So if we returned -this closure, the function call would be over, the stack frame would go away, -and our closure is capturing an environment of garbage memory! With one last -fix, we can make this work: - -```rust -fn factory() -> Box i32> { - let num = 5; - - Box::new(move |x| x + num) -} - -let f = factory(); - -let answer = f(1); -assert_eq!(6, answer); -``` - -By making the inner closure a `move Fn`, we create a new stack frame for our -closure. By `Box`ing it up, we’ve given it a known size, allowing it to -escape our stack frame. +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). diff --git a/first-edition/src/comments.md b/first-edition/src/comments.md index 0e68ab218e..cf56cd67b1 100644 --- a/first-edition/src/comments.md +++ b/first-edition/src/comments.md @@ -1,59 +1,10 @@ # Comments -Now that we have some functions, it’s a good idea to learn about comments. -Comments are notes that you leave to other programmers to help explain things -about your code. The compiler mostly ignores them. +The first edition of the book is no longer distributed with Rust's documentation. -Rust has two kinds of comments that you should care about: *line comments* -and *doc comments*. +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. -```rust -// Line comments are anything after ‘//’ and extend to the end of the line. - -let x = 5; // This is also a line comment. - -// If you have a long explanation for something, you can put line comments next -// to each other. Put a space between the // and your comment so that it’s -// more readable. -``` - -The other kind of comment is a doc comment. Doc comments use `///` instead of -`//`, and support Markdown notation inside: - -```rust -/// Adds one to the number given. -/// -/// # Examples -/// -/// ``` -/// let five = 5; -/// -/// assert_eq!(6, add_one(5)); -/// # fn add_one(x: i32) -> i32 { -/// # x + 1 -/// # } -/// ``` -fn add_one(x: i32) -> i32 { - x + 1 -} -``` - -There is another style of doc comment, `//!`, to comment containing items (e.g. -crates, modules or functions), instead of the items following it. Commonly used -inside crates root (lib.rs) or modules root (mod.rs): - -``` -//! # The Rust Standard Library -//! -//! The Rust Standard Library provides the essential runtime -//! functionality for building portable Rust software. -``` - -When writing doc comments, providing some examples of usage is very, very -helpful. You’ll notice we’ve used a new macro here: `assert_eq!`. This compares -two values, and `panic!`s if they’re not equal to each other. It’s very helpful -in documentation. There’s another macro, `assert!`, which `panic!`s if the -value passed to it is `false`. - -You can use the [`rustdoc`](documentation.html) tool to generate HTML documentation -from these doc comments, and also to run the code examples as tests! +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). diff --git a/first-edition/src/concurrency.md b/first-edition/src/concurrency.md index a8af9cad77..adb6e85b8a 100644 --- a/first-edition/src/concurrency.md +++ b/first-edition/src/concurrency.md @@ -1,465 +1,10 @@ # Concurrency -Concurrency and parallelism are incredibly important topics in computer -science, and are also a hot topic in industry today. Computers are gaining more -and more cores, yet many programmers aren't prepared to fully utilize them. +The first edition of the book is no longer distributed with Rust's documentation. -Rust's memory safety features also apply to its concurrency story. Even -concurrent Rust programs must be memory safe, having no data races. Rust's type -system is up to the task, and gives you powerful ways to reason about -concurrent code at compile time. +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. -Before we talk about the concurrency features that come with Rust, it's important -to understand something: Rust is low-level enough that the vast majority of -this is provided by the standard library, not by the language. This means that -if you don't like some aspect of the way Rust handles concurrency, you can -implement an alternative way of doing things. -[mio](https://github.com/carllerche/mio) is a real-world example of this -principle in action. - -## Background: `Send` and `Sync` - -Concurrency is difficult to reason about. In Rust, we have a strong, static -type system to help us reason about our code. As such, Rust gives us two traits -to help us make sense of code that can possibly be concurrent. - -### `Send` - -The first trait we're going to talk about is -[`Send`](../../std/marker/trait.Send.html). When a type `T` implements `Send`, it -indicates that something of this type is able to have ownership transferred -safely between threads. - -This is important to enforce certain restrictions. For example, if we have a -channel connecting two threads, we would want to be able to send some data -down the channel and to the other thread. Therefore, we'd ensure that `Send` was -implemented for that type. - -In the opposite way, if we were wrapping a library with [FFI][ffi] that isn't -thread-safe, we wouldn't want to implement `Send`, and so the compiler will help -us enforce that it can't leave the current thread. - -[ffi]: ffi.html - -### `Sync` - -The second of these traits is called [`Sync`](../../std/marker/trait.Sync.html). -When a type `T` implements `Sync`, it indicates that something -of this type has no possibility of introducing memory unsafety when used from -multiple threads concurrently through shared references. This implies that -types which don't have [interior mutability](mutability.html) are inherently -`Sync`, which includes simple primitive types (like `u8`) and aggregate types -containing them. - -For sharing references across threads, Rust provides a wrapper type called -`Arc`. `Arc` implements `Send` and `Sync` if and only if `T` implements -both `Send` and `Sync`. For example, an object of type `Arc>` cannot -be transferred across threads because -[`RefCell`](choosing-your-guarantees.html#refcellt) does not implement -`Sync`, consequently `Arc>` would not implement `Send`. - -These two traits allow you to use the type system to make strong guarantees -about the properties of your code under concurrency. Before we demonstrate -why, we need to learn how to create a concurrent Rust program in the first -place! - -## Threads - -Rust's standard library provides a library for threads, which allow you to -run Rust code in parallel. Here's a basic example of using `std::thread`: - -```rust -use std::thread; - -fn main() { - thread::spawn(|| { - println!("Hello from a thread!"); - }); -} -``` - -The `thread::spawn()` method accepts a [closure](closures.html), which is executed in a -new thread. It returns a handle to the thread, that can be used to -wait for the child thread to finish and extract its result: - -```rust -use std::thread; - -fn main() { - let handle = thread::spawn(|| { - "Hello from a thread!" - }); - - println!("{}", handle.join().unwrap()); -} -``` - -As closures can capture variables from their environment, we can also try to -bring some data into the other thread: - -```rust,ignore -use std::thread; - -fn main() { - let x = 1; - thread::spawn(|| { - println!("x is {}", x); - }); -} -``` - -However, this gives us an error: - -```text -5:19: 7:6 error: closure may outlive the current function, but it - borrows `x`, which is owned by the current function -... -5:19: 7:6 help: to force the closure to take ownership of `x` (and any other referenced variables), - use the `move` keyword, as shown: - thread::spawn(move || { - println!("x is {}", x); - }); -``` - -This is because by default closures capture variables by reference, and thus the -closure only captures a _reference to `x`_. This is a problem, because the -thread may outlive the scope of `x`, leading to a dangling pointer. - -To fix this, we use a `move` closure as mentioned in the error message. `move` -closures are explained in depth [here](closures.html#move-closures); basically -they move variables from their environment into themselves. - -```rust -use std::thread; - -fn main() { - let x = 1; - thread::spawn(move || { - println!("x is {}", x); - }); -} -``` - -Many languages have the ability to execute threads, but it's wildly unsafe. -There are entire books about how to prevent errors that occur from shared -mutable state. Rust helps out with its type system here as well, by preventing -data races at compile time. Let's talk about how you actually share things -between threads. - -## Safe Shared Mutable State - -Due to Rust's type system, we have a concept that sounds like a lie: "safe -shared mutable state." Many programmers agree that shared mutable state is -very, very bad. - -Someone once said this: - -> Shared mutable state is the root of all evil. Most languages attempt to deal -> with this problem through the 'mutable' part, but Rust deals with it by -> solving the 'shared' part. - -The same [ownership system](ownership.html) that helps prevent using pointers -incorrectly also helps rule out data races, one of the worst kinds of -concurrency bugs. - -As an example, here is a Rust program that would have a data race in many -languages. It will not compile: - -```rust,ignore -use std::thread; -use std::time::Duration; - -fn main() { - let mut data = vec![1, 2, 3]; - - for i in 0..3 { - thread::spawn(move || { - data[0] += i; - }); - } - - thread::sleep(Duration::from_millis(50)); -} -``` - -This gives us an error: - -```text -8:17 error: capture of moved value: `data` - data[0] += i; - ^~~~ -``` - -Rust knows this wouldn't be safe! If we had a reference to `data` in each -thread, and the thread takes ownership of the reference, we'd have three owners! -`data` gets moved out of `main` in the first call to `spawn()`, so subsequent -calls in the loop cannot use this variable. - -So, we need some type that lets us have more than one owning reference to a -value. Usually, we'd use `Rc` for this, which is a reference counted type -that provides shared ownership. It has some runtime bookkeeping that keeps track -of the number of references to it, hence the "reference count" part of its name. - -Calling `clone()` on an `Rc` will return a new owned reference and bump the -internal reference count. We create one of these for each thread: - - -```rust,ignore -use std::thread; -use std::time::Duration; -use std::rc::Rc; - -fn main() { - let mut data = Rc::new(vec![1, 2, 3]); - - for i in 0..3 { - // Create a new owned reference: - let data_ref = data.clone(); - - // Use it in a thread: - thread::spawn(move || { - data_ref[0] += i; - }); - } - - thread::sleep(Duration::from_millis(50)); -} -``` - -This won't work, however, and will give us the error: - -```text -13:9: 13:22 error: the trait bound `alloc::rc::Rc> : core::marker::Send` - is not satisfied -... -13:9: 13:22 note: `alloc::rc::Rc>` - cannot be sent between threads safely -``` - -As the error message mentions, `Rc` cannot be sent between threads safely. This -is because the internal reference count is not maintained in a thread-safe -manner and can have a data race. - -To solve this, we'll use `Arc`, Rust's standard atomic reference count type. - -The Atomic part means `Arc` can safely be accessed from multiple threads. -To do this the compiler guarantees that mutations of the internal count use -indivisible operations which can't have data races. - -In essence, `Arc` is a type that lets us share ownership of data _across -threads_. - - -```rust,ignore -use std::thread; -use std::sync::Arc; -use std::time::Duration; - -fn main() { - let mut data = Arc::new(vec![1, 2, 3]); - - for i in 0..3 { - let data = data.clone(); - thread::spawn(move || { - data[0] += i; - }); - } - - thread::sleep(Duration::from_millis(50)); -} -``` - -Similarly to last time, we use `clone()` to create a new owned handle. -This handle is then moved into the new thread. - -And... still gives us an error. - -```text -:11:24 error: cannot borrow immutable borrowed content as mutable -:11 data[0] += i; - ^~~~ -``` - -`Arc` by default has immutable contents. It allows the _sharing_ of data -between threads, but shared mutable data is unsafe—and when threads are -involved—can cause data races! - - -Usually when we wish to make something in an immutable position mutable, we use -`Cell` or `RefCell` which allow safe mutation via runtime checks or -otherwise (see also: [Choosing Your Guarantees](choosing-your-guarantees.html)). -However, similar to `Rc`, these are not thread-safe. If we try using these, we -will get an error about these types not being `Sync`, and the code will fail to -compile. - -It looks like we need some type that allows us to safely mutate a shared value -across threads, for example a type that can ensure only one thread at a time is -able to mutate the value inside it at any one time. - -For that, we can use the `Mutex` type! - -Here's the working version: - -```rust -use std::sync::{Arc, Mutex}; -use std::thread; -use std::time::Duration; - -fn main() { - let data = Arc::new(Mutex::new(vec![1, 2, 3])); - - for i in 0..3 { - let data = data.clone(); - thread::spawn(move || { - let mut data = data.lock().unwrap(); - data[0] += i; - }); - } - - thread::sleep(Duration::from_millis(50)); -} -``` - -Note that the value of `i` is bound (copied) to the closure and not shared -among the threads. - -We're "locking" the mutex here. A mutex (short for "mutual exclusion"), as -mentioned, only allows one thread at a time to access a value. When we wish to -access the value, we use `lock()` on it. This will "lock" the mutex, and no -other thread will be able to lock it (and hence, do anything with the value) -until we're done with it. If a thread attempts to lock a mutex which is already -locked, it will wait until the other thread releases the lock. - -The lock "release" here is implicit; when the result of the lock (in this case, -`data`) goes out of scope, the lock is automatically released. - -Note that [`lock`](../../std/sync/struct.Mutex.html#method.lock) method of -[`Mutex`](../../std/sync/struct.Mutex.html) has this signature: - -```rust,ignore -fn lock(&self) -> LockResult> -``` - -and because `Send` is not implemented for `MutexGuard`, the guard cannot -cross thread boundaries, ensuring thread-locality of lock acquire and release. - -Let's examine the body of the thread more closely: - -```rust -# use std::sync::{Arc, Mutex}; -# use std::thread; -# use std::time::Duration; -# fn main() { -# let data = Arc::new(Mutex::new(vec![1, 2, 3])); -# for i in 0..3 { -# let data = data.clone(); -thread::spawn(move || { - let mut data = data.lock().unwrap(); - data[0] += i; -}); -# } -# thread::sleep(Duration::from_millis(50)); -# } -``` - -First, we call `lock()`, which acquires the mutex's lock. Because this may fail, -it returns a `Result`, and because this is just an example, we `unwrap()` -it to get a reference to the data. Real code would have more robust error handling -here. We're then free to mutate it, since we have the lock. - -Lastly, while the threads are running, we wait on a short timer. But -this is not ideal: we may have picked a reasonable amount of time to -wait but it's more likely we'll either be waiting longer than -necessary or not long enough, depending on just how much time the -threads actually take to finish computing when the program runs. - -A more precise alternative to the timer would be to use one of the -mechanisms provided by the Rust standard library for synchronizing -threads with each other. Let's talk about one of them: channels. - -## Channels - -Here's a version of our code that uses channels for synchronization, rather -than waiting for a specific time: - -```rust -use std::sync::{Arc, Mutex}; -use std::thread; -use std::sync::mpsc; - -fn main() { - let data = Arc::new(Mutex::new(0)); - - // `tx` is the "transmitter" or "sender". - // `rx` is the "receiver". - let (tx, rx) = mpsc::channel(); - - for _ in 0..10 { - let (data, tx) = (data.clone(), tx.clone()); - - thread::spawn(move || { - let mut data = data.lock().unwrap(); - *data += 1; - - tx.send(()).unwrap(); - }); - } - - for _ in 0..10 { - rx.recv().unwrap(); - } -} -``` - -We use the `mpsc::channel()` method to construct a new channel. We `send` -a simple `()` down the channel, and then wait for ten of them to come back. - -While this channel is sending a generic signal, we can send any data that -is `Send` over the channel! - -```rust -use std::thread; -use std::sync::mpsc; - -fn main() { - let (tx, rx) = mpsc::channel(); - - for i in 0..10 { - let tx = tx.clone(); - - thread::spawn(move || { - let answer = i * i; - - tx.send(answer).unwrap(); - }); - } - - for _ in 0..10 { - println!("{}", rx.recv().unwrap()); - } -} -``` - -Here we create 10 threads, asking each to calculate the square of a number (`i` -at the time of `spawn()`), and then `send()` back the answer over the channel. - - -## Panics - -A `panic!` will crash the currently executing thread. You can use Rust's -threads as a simple isolation mechanism: - -```rust -use std::thread; - -let handle = thread::spawn(move || { - panic!("oops!"); -}); - -let result = handle.join(); - -assert!(result.is_err()); -``` - -`Thread.join()` gives us a `Result` back, which allows us to check if the thread -has panicked or not. +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). diff --git a/first-edition/src/conditional-compilation.md b/first-edition/src/conditional-compilation.md index 0562e9fc43..80184ba3ef 100644 --- a/first-edition/src/conditional-compilation.md +++ b/first-edition/src/conditional-compilation.md @@ -1,91 +1,10 @@ # Conditional Compilation -Rust has a special attribute, `#[cfg]`, which allows you to compile code -based on a flag passed to the compiler. It has two forms: +The first edition of the book is no longer distributed with Rust's documentation. -```rust -#[cfg(foo)] -# fn foo() {} +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. -#[cfg(bar = "baz")] -# fn bar() {} -``` - -They also have some helpers: - -```rust -#[cfg(any(unix, windows))] -# fn foo() {} - -#[cfg(all(unix, target_pointer_width = "32"))] -# fn bar() {} - -#[cfg(not(foo))] -# fn not_foo() {} -``` - -These can nest arbitrarily: - -```rust -#[cfg(any(not(unix), all(target_os="macos", target_arch = "powerpc")))] -# fn foo() {} -``` - -As for how to enable or disable these switches, if you’re using Cargo, -they get set in the [`[features]` section][features] of your `Cargo.toml`: - -[features]: http://doc.crates.io/manifest.html#the-features-section - -```toml -[features] -# no features by default -default = [] - -# Add feature "foo" here, then you can use it. -# Our "foo" feature depends on nothing else. -foo = [] -``` - -When you do this, Cargo passes along a flag to `rustc`: - -```text ---cfg feature="${feature_name}" -``` - -The sum of these `cfg` flags will determine which ones get activated, and -therefore, which code gets compiled. Let’s take this code: - -```rust -#[cfg(feature = "foo")] -mod foo { -} -``` - -If we compile it with `cargo build --features "foo"`, it will send the `--cfg -feature="foo"` flag to `rustc`, and the output will have the `mod foo` in it. -If we compile it with a regular `cargo build`, no extra flags get passed on, -and so, no `foo` module will exist. - -# cfg_attr - -You can also set another attribute based on a `cfg` variable with `cfg_attr`: - -```rust -#[cfg_attr(a, b)] -# fn foo() {} -``` - -Will be the same as `#[b]` if `a` is set by `cfg` attribute, and nothing otherwise. - -# cfg! - -The `cfg!` macro lets you use these kinds of flags elsewhere in your code, too: - -```rust -if cfg!(target_os = "macos") || cfg!(target_os = "ios") { - println!("Think Different!"); -} -``` - -These will be replaced by a `true` or `false` at compile-time, depending on the -configuration settings. +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). diff --git a/first-edition/src/const-and-static.md b/first-edition/src/const-and-static.md index e50a21367b..aa634112b2 100644 --- a/first-edition/src/const-and-static.md +++ b/first-edition/src/const-and-static.md @@ -1,89 +1,10 @@ # const and static -Rust has a way of defining constants with the `const` keyword: +The first edition of the book is no longer distributed with Rust's documentation. -```rust -const N: i32 = 5; -``` +If you came here via a link or web search, you may want to check out [the current +version of the book](../ch19-01-unsafe-rust.html#accessing-or-modifying-a-mutable-static-variable) instead. -Unlike [`let`][let] bindings, you must annotate the type of a `const`. - -[let]: variable-bindings.html - -Constants live for the entire lifetime of a program. More specifically, -constants in Rust have no fixed address in memory. This is because they’re -effectively inlined to each place that they’re used. References to the same -constant are not necessarily guaranteed to refer to the same memory address for -this reason. - -# `static` - -Rust provides a ‘global variable’ sort of facility in static items. They’re -similar to constants, but static items aren’t inlined upon use. This means that -there is only one instance for each value, and it’s at a fixed location in -memory. - -Here’s an example: - -```rust -static N: i32 = 5; -``` - -Unlike [`let`][let] bindings, you must annotate the type of a `static`. - -Statics live for the entire lifetime of a program, and therefore any -reference stored in a static has a [`'static` lifetime][lifetimes]: - -```rust -static NAME: &'static str = "Steve"; -``` - -The type of a `static` value must be `Sync` unless the `static` value is -mutable. - -[lifetimes]: lifetimes.html - -## Mutability - -You can introduce mutability with the `mut` keyword: - -```rust -static mut N: i32 = 5; -``` - -Because this is mutable, one thread could be updating `N` while another is -reading it, causing memory unsafety. As such both accessing and mutating a -`static mut` is [`unsafe`][unsafe], and so must be done in an `unsafe` block: - -```rust -# static mut N: i32 = 5; - -unsafe { - N += 1; - - println!("N: {}", N); -} -``` - -[unsafe]: unsafe.html - -# Initializing - -Both `const` and `static` have requirements for giving them a value. They must -be given a value that’s a constant expression. In other words, you cannot use -the result of a function call or anything similarly complex or at runtime. - -# Dropping - -Types implementing [`Drop`][drop] are allowed in `const` and `static` -definitions. Constants are inlined where they are used and are dropped -accordingly. `static` values are not dropped. - -[drop]: drop.html - -# Which construct should I use? - -Almost always, if you can choose between the two, choose `const`. It’s pretty -rare that you actually want a memory location associated with your constant, -and using a `const` allows for optimizations like constant propagation not only -in your crate but downstream crates. +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). diff --git a/first-edition/src/crates-and-modules.md b/first-edition/src/crates-and-modules.md index 10e66d42c6..66262b3401 100644 --- a/first-edition/src/crates-and-modules.md +++ b/first-edition/src/crates-and-modules.md @@ -1,598 +1,10 @@ # Crates and Modules -When a project starts getting large, it’s considered good software -engineering practice to split it up into a bunch of smaller pieces, and then -fit them together. It is also important to have a well-defined interface, so -that some of your functionality is private, and some is public. To facilitate -these kinds of things, Rust has a module system. +The first edition of the book is no longer distributed with Rust's documentation. -# Basic terminology: Crates and Modules +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. -Rust has two distinct terms that relate to the module system: ‘crate’ and -‘module’. A crate is synonymous with a ‘library’ or ‘package’ in other -languages. Hence “Cargo” as the name of Rust’s package management tool: you -ship your crates to others with Cargo. Crates can produce an executable or a -library, depending on the project. - -Each crate has an implicit *root module* that contains the code for that crate. -You can then define a tree of sub-modules under that root module. Modules allow -you to partition your code within the crate itself. - -As an example, let’s make a *phrases* crate, which will give us various phrases -in different languages. To keep things simple, we’ll stick to ‘greetings’ and -‘farewells’ as two kinds of phrases, and use English and Japanese (日本語) as -two languages for those phrases to be in. We’ll use this module layout: - -```text - +-----------+ - +---| greetings | - +---------+ | +-----------+ - +---| english |---+ - | +---------+ | +-----------+ - | +---| farewells | -+---------+ | +-----------+ -| phrases |---+ -+---------+ | +-----------+ - | +---| greetings | - | +----------+ | +-----------+ - +---| japanese |--+ - +----------+ | +-----------+ - +---| farewells | - +-----------+ -``` - -In this example, `phrases` is the name of our crate. All of the rest are -modules. You can see that they form a tree, branching out from the crate -*root*, which is the root of the tree: `phrases` itself. - -Now that we have a plan, let’s define these modules in code. To start, -generate a new crate with Cargo: - -```bash -$ cargo new phrases -$ cd phrases -``` - -If you remember, this generates a simple project for us: - -```bash -$ tree . -. -├── Cargo.toml -└── src - └── lib.rs - -1 directory, 2 files -``` - -`src/lib.rs` is our crate root, corresponding to the `phrases` in our diagram -above. - -# Defining Modules - -To define each of our modules, we use the `mod` keyword. Let’s make our -`src/lib.rs` look like this: - -```rust -mod english { - mod greetings { - } - - mod farewells { - } -} - -mod japanese { - mod greetings { - } - - mod farewells { - } -} -``` - -After the `mod` keyword, you give the name of the module. Module names follow -the conventions for other Rust identifiers: `lower_snake_case`. The contents of -each module are within curly braces (`{}`). - -Within a given `mod`, you can declare sub-`mod`s. We can refer to sub-modules -with double-colon (`::`) notation: our four nested modules are -`english::greetings`, `english::farewells`, `japanese::greetings`, and -`japanese::farewells`. Because these sub-modules are namespaced under their -parent module, the names don’t conflict: `english::greetings` and -`japanese::greetings` are distinct, even though their names are both -`greetings`. - -Because this crate does not have a `main()` function, and is called `lib.rs`, -Cargo will build this crate as a library: - -```bash -$ cargo build - Compiling phrases v0.0.1 (file:///home/you/projects/phrases) -$ ls target/debug -build deps examples libphrases-a7448e02a0468eaa.rlib native -``` - -`libphrases-.rlib` is the compiled crate. Before we see how to use this -crate from another crate, let’s break it up into multiple files. - -# Multiple File Crates - -If each crate were just one file, these files would get very large. It’s often -easier to split up crates into multiple files, and Rust supports this in two -ways. - -Instead of declaring a module like this: - -```rust,ignore -mod english { - // Contents of our module go here. -} -``` - -We can instead declare our module like this: - -```rust,ignore -mod english; -``` - -If we do that, Rust will expect to find either a `english.rs` file, or a -`english/mod.rs` file with the contents of our module. - -Note that in these files, you don’t need to re-declare the module: that’s -already been done with the initial `mod` declaration. - -Using these two techniques, we can break up our crate into two directories and -seven files: - -```bash -$ tree . -. -├── Cargo.lock -├── Cargo.toml -├── src -│   ├── english -│   │   ├── farewells.rs -│   │   ├── greetings.rs -│   │   └── mod.rs -│   ├── japanese -│   │   ├── farewells.rs -│   │   ├── greetings.rs -│   │   └── mod.rs -│   └── lib.rs -└── target - └── debug - ├── build - ├── deps - ├── examples - ├── libphrases-a7448e02a0468eaa.rlib - └── native -``` - -`src/lib.rs` is our crate root, and looks like this: - -```rust,ignore -mod english; -mod japanese; -``` - -These two declarations tell Rust to look for - -- either `src/english.rs` or `src/english/mod.rs`, and -- either `src/japanese.rs` or `src/japanese/mod.rs`, - -depending on our preference. In this case, because our modules have sub-modules, -we’ve chosen the `mod.rs` approach. Both `src/english/mod.rs` and -`src/japanese/mod.rs` look like this: - -```rust,ignore -mod greetings; -mod farewells; -``` - -Again, these declarations tell Rust to look for - -- `src/english/greetings.rs` or `src/english/greetings/mod.rs`, -- `src/english/farewells.rs` or `src/english/farewells/mod.rs`, -- `src/japanese/greetings.rs` or `src/japanese/greetings/mod.rs`, -- and `src/japanese/farewells.rs` or `src/japanese/farewells/mod.rs`. - -Because these sub-modules don’t have -their own sub-modules, we’ve chosen to make them -`src/english/greetings.rs`, `src/english/farewells.rs`, -`src/japanese/greetings.rs` and `src/japanese/farewells.rs`. Whew! - -The contents of `src/english/greetings.rs`, -`src/english/farewells.rs`, `src/japanese/greetings.rs` and -`src/japanese/farewells.rs` are all empty at the moment. Let’s add -some functions. - -Put this in `src/english/greetings.rs`: - -```rust -fn hello() -> String { - "Hello!".to_string() -} -``` - -Put this in `src/english/farewells.rs`: - -```rust -fn goodbye() -> String { - "Goodbye.".to_string() -} -``` - -Put this in `src/japanese/greetings.rs`: - -```rust -fn hello() -> String { - "こんにちは".to_string() -} -``` - -Of course, you can copy and paste this from this web page, or type -something else. It’s not important that you actually put ‘konnichiwa’ to learn -about the module system. - -Put this in `src/japanese/farewells.rs`: - -```rust -fn goodbye() -> String { - "さようなら".to_string() -} -``` - -(This is ‘Sayōnara’, if you’re curious.) - -Now that we have some functionality in our crate, let’s try to use it from -another crate. - -# Importing External Crates - -We have a library crate. Let’s make an executable crate that imports and uses -our library. - -Make a `src/main.rs` and put this in it (it won’t quite compile yet): - -```rust,ignore -extern crate phrases; - -fn main() { - println!("Hello in English: {}", phrases::english::greetings::hello()); - println!("Goodbye in English: {}", phrases::english::farewells::goodbye()); - - println!("Hello in Japanese: {}", phrases::japanese::greetings::hello()); - println!("Goodbye in Japanese: {}", phrases::japanese::farewells::goodbye()); -} -``` - -The `extern crate` declaration tells Rust that we need to compile and link to -the `phrases` crate. We can then use `phrases`’ modules in this one. As we -mentioned earlier, you can use double colons to refer to sub-modules and the -functions inside of them. - -(Note: when importing a crate that has dashes in its name "like-this", which is -not a valid Rust identifier, it will be converted by changing the dashes to -underscores, so you would write `extern crate like_this;`.) - -Also, Cargo assumes that `src/main.rs` is the crate root of a binary crate, -rather than a library crate. Our package now has two crates: `src/lib.rs` and -`src/main.rs`. This pattern is quite common for executable crates: most -functionality is in a library crate, and the executable crate uses that -library. This way, other programs can also use the library crate, and it’s also -a nice separation of concerns. - -This doesn’t quite work yet, though. We get four errors that look similar to -this: - -```bash -$ cargo build - Compiling phrases v0.0.1 (file:///home/you/projects/phrases) -src/main.rs:4:38: 4:72 error: function `hello` is private -src/main.rs:4 println!("Hello in English: {}", phrases::english::greetings::hello()); - ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -note: in expansion of format_args! -:2:25: 2:58 note: expansion site -:1:1: 2:62 note: in expansion of print! -:3:1: 3:54 note: expansion site -:1:1: 3:58 note: in expansion of println! -phrases/src/main.rs:4:5: 4:76 note: expansion site -``` - -By default, everything is private in Rust. Let’s talk about this in some more -depth. - -# Exporting a Public Interface - -Rust allows you to precisely control which aspects of your interface are -public, and so private is the default. To make things public, you use the `pub` -keyword. Let’s focus on the `english` module first, so let’s reduce our `src/main.rs` -to only this: - -```rust,ignore -extern crate phrases; - -fn main() { - println!("Hello in English: {}", phrases::english::greetings::hello()); - println!("Goodbye in English: {}", phrases::english::farewells::goodbye()); -} -``` - -In our `src/lib.rs`, let’s add `pub` to the `english` module declaration: - -```rust,ignore -pub mod english; -mod japanese; -``` - -And in our `src/english/mod.rs`, let’s make both `pub`: - -```rust,ignore -pub mod greetings; -pub mod farewells; -``` - -In our `src/english/greetings.rs`, let’s add `pub` to our `fn` declaration: - -```rust,ignore -pub fn hello() -> String { - "Hello!".to_string() -} -``` - -And also in `src/english/farewells.rs`: - -```rust,ignore -pub fn goodbye() -> String { - "Goodbye.".to_string() -} -``` - -Now, our crate compiles, albeit with warnings about not using the `japanese` -functions: - -```bash -$ cargo run - Compiling phrases v0.0.1 (file:///home/you/projects/phrases) -src/japanese/greetings.rs:1:1: 3:2 warning: function is never used: `hello`, #[warn(dead_code)] on by default -src/japanese/greetings.rs:1 fn hello() -> String { -src/japanese/greetings.rs:2 "こんにちは".to_string() -src/japanese/greetings.rs:3 } -src/japanese/farewells.rs:1:1: 3:2 warning: function is never used: `goodbye`, #[warn(dead_code)] on by default -src/japanese/farewells.rs:1 fn goodbye() -> String { -src/japanese/farewells.rs:2 "さようなら".to_string() -src/japanese/farewells.rs:3 } - Running `target/debug/phrases` -Hello in English: Hello! -Goodbye in English: Goodbye. -``` - -`pub` also applies to `struct`s and their member fields. In keeping with Rust’s -tendency toward safety, simply making a `struct` public won't automatically -make its members public: you must mark the fields individually with `pub`. - -Now that our functions are public, we can use them. Great! However, typing out -`phrases::english::greetings::hello()` is very long and repetitive. Rust has -another keyword for importing names into the current scope, so that you can -refer to them with shorter names. Let’s talk about `use`. - -# Importing Modules with `use` - -Rust has a `use` keyword, which allows us to import names into our local scope. -Let’s change our `src/main.rs` to look like this: - -```rust,ignore -extern crate phrases; - -use phrases::english::greetings; -use phrases::english::farewells; - -fn main() { - println!("Hello in English: {}", greetings::hello()); - println!("Goodbye in English: {}", farewells::goodbye()); -} -``` - -The two `use` lines import each module into the local scope, so we can refer to -the functions by a much shorter name. By convention, when importing functions, it’s -considered best practice to import the module, rather than the function directly. In -other words, you _can_ do this: - -```rust,ignore -extern crate phrases; - -use phrases::english::greetings::hello; -use phrases::english::farewells::goodbye; - -fn main() { - println!("Hello in English: {}", hello()); - println!("Goodbye in English: {}", goodbye()); -} -``` - -But it is not idiomatic. This is significantly more likely to introduce a -naming conflict. In our short program, it’s not a big deal, but as it grows, it -becomes a problem. If we have conflicting names, Rust will give a compilation -error. For example, if we made the `japanese` functions public, and tried to do -this: - -```rust,ignore -extern crate phrases; - -use phrases::english::greetings::hello; -use phrases::japanese::greetings::hello; - -fn main() { - println!("Hello in English: {}", hello()); - println!("Hello in Japanese: {}", hello()); -} -``` - -Rust will give us a compile-time error: - -```text - Compiling phrases v0.0.1 (file:///home/you/projects/phrases) -src/main.rs:4:5: 4:40 error: a value named `hello` has already been imported in this module [E0252] -src/main.rs:4 use phrases::japanese::greetings::hello; - ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -error: aborting due to previous error -Could not compile `phrases`. -``` - -If we’re importing multiple names from the same module, we don’t have to type it out -twice. Instead of this: - -```rust,ignore -use phrases::english::greetings; -use phrases::english::farewells; -``` - -We can use this shortcut: - -```rust,ignore -use phrases::english::{greetings, farewells}; -``` - -## Re-exporting with `pub use` - -You don’t only use `use` to shorten identifiers. You can also use it inside of your crate -to re-export a function inside another module. This allows you to present an external -interface that may not directly map to your internal code organization. - -Let’s look at an example. Modify your `src/main.rs` to read like this: - -```rust,ignore -extern crate phrases; - -use phrases::english::{greetings,farewells}; -use phrases::japanese; - -fn main() { - println!("Hello in English: {}", greetings::hello()); - println!("Goodbye in English: {}", farewells::goodbye()); - - println!("Hello in Japanese: {}", japanese::hello()); - println!("Goodbye in Japanese: {}", japanese::goodbye()); -} -``` - -Then, modify your `src/lib.rs` to make the `japanese` mod public: - -```rust,ignore -pub mod english; -pub mod japanese; -``` - -Next, make the two functions public, first in `src/japanese/greetings.rs`: - -```rust,ignore -pub fn hello() -> String { - "こんにちは".to_string() -} -``` - -And then in `src/japanese/farewells.rs`: - -```rust,ignore -pub fn goodbye() -> String { - "さようなら".to_string() -} -``` - -Finally, modify your `src/japanese/mod.rs` to read like this: - -```rust,ignore -pub use self::greetings::hello; -pub use self::farewells::goodbye; - -mod greetings; -mod farewells; -``` - -The `pub use` declaration brings the function into scope at this part of our -module hierarchy. Because we’ve `pub use`d this inside of our `japanese` -module, we now have a `phrases::japanese::hello()` function and a -`phrases::japanese::goodbye()` function, even though the code for them lives in -`phrases::japanese::greetings::hello()` and -`phrases::japanese::farewells::goodbye()`. Our internal organization doesn’t -define our external interface. - -Here we have a `pub use` for each function we want to bring into the -`japanese` scope. We could alternatively use the wildcard syntax to include -everything from `greetings` into the current scope: `pub use self::greetings::*`. - -What about the `self`? Well, by default, `use` declarations are absolute paths, -starting from your crate root. `self` makes that path relative to your current -place in the hierarchy instead. There’s one more special form of `use`: you can -`use super::` to reach one level up the tree from your current location. Some -people like to think of `self` as `.` and `super` as `..`, from many shells’ -display for the current directory and the parent directory. - -Outside of `use`, paths are relative: `foo::bar()` refers to a function inside -of `foo` relative to where we are. If that’s prefixed with `::`, as in -`::foo::bar()`, it refers to a different `foo`, an absolute path from your -crate root. - -This will build and run: - -```bash -$ cargo run - Compiling phrases v0.0.1 (file:///home/you/projects/phrases) - Running `target/debug/phrases` -Hello in English: Hello! -Goodbye in English: Goodbye. -Hello in Japanese: こんにちは -Goodbye in Japanese: さようなら -``` - -## Complex imports - -Rust offers several advanced options that can add compactness and -convenience to your `extern crate` and `use` statements. Here is an example: - -```rust,ignore -extern crate phrases as sayings; - -use sayings::japanese::greetings as ja_greetings; -use sayings::japanese::farewells::*; -use sayings::english::{self, greetings as en_greetings, farewells as en_farewells}; - -fn main() { - println!("Hello in English; {}", en_greetings::hello()); - println!("And in Japanese: {}", ja_greetings::hello()); - println!("Goodbye in English: {}", english::farewells::goodbye()); - println!("Again: {}", en_farewells::goodbye()); - println!("And in Japanese: {}", goodbye()); -} -``` - -What's going on here? - -First, both `extern crate` and `use` allow renaming the thing that is being -imported. So the crate is still called "phrases", but here we will refer -to it as "sayings". Similarly, the first `use` statement pulls in the -`japanese::greetings` module from the crate, but makes it available as -`ja_greetings` as opposed to simply `greetings`. This can help to avoid -ambiguity when importing similarly-named items from different places. - -The second `use` statement uses a star glob to bring in all public symbols from -the `sayings::japanese::farewells` module. As you can see we can later refer to -the Japanese `goodbye` function with no module qualifiers. This kind of glob -should be used sparingly. It’s worth noting that it only imports the public -symbols, even if the code doing the globbing is in the same module. - -The third `use` statement bears more explanation. It's using "brace expansion" -globbing to compress three `use` statements into one (this sort of syntax -may be familiar if you've written Linux shell scripts before). The -uncompressed form of this statement would be: - -```rust,ignore -use sayings::english; -use sayings::english::greetings as en_greetings; -use sayings::english::farewells as en_farewells; -``` - -As you can see, the curly brackets compress `use` statements for several items -under the same path, and in this context `self` refers back to that path. -Note: The curly brackets cannot be nested or mixed with star globbing. +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). diff --git a/first-edition/src/deref-coercions.md b/first-edition/src/deref-coercions.md index e62c50ac8d..1e43ff4531 100644 --- a/first-edition/src/deref-coercions.md +++ b/first-edition/src/deref-coercions.md @@ -1,119 +1,10 @@ # `Deref` coercions -The standard library provides a special trait, [`Deref`][deref]. It’s normally -used to overload `*`, the dereference operator: +The first edition of the book is no longer distributed with Rust's documentation. -```rust -use std::ops::Deref; +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. -struct DerefExample { - value: T, -} - -impl Deref for DerefExample { - type Target = T; - - fn deref(&self) -> &T { - &self.value - } -} - -fn main() { - let x = DerefExample { value: 'a' }; - assert_eq!('a', *x); -} -``` - -[deref]: ../../std/ops/trait.Deref.html - -This is useful for writing custom pointer types. However, there’s a language -feature related to `Deref`: ‘deref coercions’. Here’s the rule: If you have a -type `U`, and it implements `Deref`, values of `&U` will -automatically coerce to a `&T`. Here’s an example: - -```rust -fn foo(s: &str) { - // Borrow a string for a second. -} - -// String implements Deref. -let owned = "Hello".to_string(); - -// Therefore, this works: -foo(&owned); -``` - -Using an ampersand in front of a value takes a reference to it. So `owned` is a -`String`, `&owned` is an `&String`, and since `impl Deref for -String`, `&String` will deref to `&str`, which `foo()` takes. - -That’s it. This rule is one of the only places in which Rust does an automatic -conversion for you, but it adds a lot of flexibility. For example, the `Rc` -type implements `Deref`, so this works: - -```rust -use std::rc::Rc; - -fn foo(s: &str) { - // Borrow a string for a second. -} - -// String implements Deref. -let owned = "Hello".to_string(); -let counted = Rc::new(owned); - -// Therefore, this works: -foo(&counted); -``` - -All we’ve done is wrap our `String` in an `Rc`. But we can now pass the -`Rc` around anywhere we’d have a `String`. The signature of `foo` -didn’t change, but works just as well with either type. This example has two -conversions: `&Rc` to `&String` and then `&String` to `&str`. Rust will do -this as many times as possible until the types match. - -Another very common implementation provided by the standard library is: - -```rust -fn foo(s: &[i32]) { - // Borrow a slice for a second. -} - -// Vec implements Deref. -let owned = vec![1, 2, 3]; - -foo(&owned); -``` - -Vectors can `Deref` to a slice. - -## Deref and method calls - -`Deref` will also kick in when calling a method. Consider the following -example. - -```rust -struct Foo; - -impl Foo { - fn foo(&self) { println!("Foo"); } -} - -let f = &&Foo; - -f.foo(); -``` - -Even though `f` is a `&&Foo` and `foo` takes `&self`, this works. That’s -because these things are the same: - -```rust,ignore -f.foo(); -(&f).foo(); -(&&f).foo(); -(&&&&&&&&f).foo(); -``` - -A value of type `&&&&&&&&&&&&&&&&Foo` can still have methods defined on `Foo` -called, because the compiler will insert as many * operations as necessary to -get it right. And since it’s inserting `*`s, that uses `Deref`. +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). diff --git a/first-edition/src/documentation.md b/first-edition/src/documentation.md index 6a2c85035a..ac9ecba807 100644 --- a/first-edition/src/documentation.md +++ b/first-edition/src/documentation.md @@ -1,655 +1,10 @@ # Documentation -Documentation is an important part of any software project, and it's -first-class in Rust. Let's talk about the tooling Rust gives you to -document your project. +The first edition of the book is no longer distributed with Rust's documentation. -## About `rustdoc` +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. -The Rust distribution includes a tool, `rustdoc`, that generates documentation. -`rustdoc` is also used by Cargo through `cargo doc`. - -Documentation can be generated in two ways: from source code, and from -standalone Markdown files. - -## Documenting source code - -The primary way of documenting a Rust project is through annotating the source -code. You can use documentation comments for this purpose: - -```rust,ignore -/// Constructs a new `Rc`. -/// -/// # Examples -/// -/// ``` -/// use std::rc::Rc; -/// -/// let five = Rc::new(5); -/// ``` -pub fn new(value: T) -> Rc { - // Implementation goes here. -} -``` - -This code generates documentation that looks [like this][rc-new]. I've left the -implementation out, with a regular comment in its place. - -The first thing to notice about this annotation is that it uses -`///` instead of `//`. The triple slash -indicates a documentation comment. - -Documentation comments are written in Markdown. - -Rust keeps track of these comments, and uses them when generating -documentation. This is important when documenting things like enums: - -```rust -/// The `Option` type. See [the module level documentation](index.html) for more. -enum Option { - /// No value - None, - /// Some value `T` - Some(T), -} -``` - -The above works, but this does not: - -```rust,ignore -/// The `Option` type. See [the module level documentation](index.html) for more. -enum Option { - None, /// No value - Some(T), /// Some value `T` -} -``` - -You'll get an error: - -```text -hello.rs:4:1: 4:2 error: expected ident, found `}` -hello.rs:4 } - ^ -``` - -This [unfortunate error](https://github.com/rust-lang/rust/issues/22547) is -correct; documentation comments apply to the thing after them, and there's -nothing after that last comment. - -[rc-new]: ../../std/rc/struct.Rc.html#method.new - -### Writing documentation comments - -Anyway, let's cover each part of this comment in detail: - -```rust -/// Constructs a new `Rc`. -# fn foo() {} -``` - -The first line of a documentation comment should be a short summary of its -functionality. One sentence. Just the basics. High level. - -```rust -/// -/// Other details about constructing `Rc`s, maybe describing complicated -/// semantics, maybe additional options, all kinds of stuff. -/// -# fn foo() {} -``` - -Our original example had just a summary line, but if we had more things to say, -we could have added more explanation in a new paragraph. - -#### Special sections - -Next, are special sections. These are indicated with a header, `#`. There -are four kinds of headers that are commonly used. They aren't special syntax, -just convention, for now. - -```rust -/// # Panics -# fn foo() {} -``` - -Unrecoverable misuses of a function (i.e. programming errors) in Rust are -usually indicated by panics, which kill the whole current thread at the very -least. If your function has a non-trivial contract like this, that is -detected/enforced by panics, documenting it is very important. - -```rust -/// # Errors -# fn foo() {} -``` - -If your function or method returns a `Result`, then describing the -conditions under which it returns `Err(E)` is a nice thing to do. This is -slightly less important than `Panics`, because failure is encoded into the type -system, but it's still a good thing to do. - -```rust -/// # Safety -# fn foo() {} -``` - -If your function is `unsafe`, you should explain which invariants the caller is -responsible for upholding. - -```rust -/// # Examples -/// -/// ``` -/// use std::rc::Rc; -/// -/// let five = Rc::new(5); -/// ``` -# fn foo() {} -``` - -Fourth, `Examples`. Include one or more examples of using your function or -method, and your users will love you for it. These examples go inside of -code block annotations, which we'll talk about in a moment, and can have -more than one section: - -```rust -/// # Examples -/// -/// Simple `&str` patterns: -/// -/// ``` -/// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect(); -/// assert_eq!(v, vec!["Mary", "had", "a", "little", "lamb"]); -/// ``` -/// -/// More complex patterns with a lambda: -/// -/// ``` -/// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).collect(); -/// assert_eq!(v, vec!["abc", "def", "ghi"]); -/// ``` -# fn foo() {} -``` - -#### Code block annotations - -To write some Rust code in a comment, use the triple graves: - -```rust -/// ``` -/// println!("Hello, world"); -/// ``` -# fn foo() {} -``` - -This will add code highlighting. If you are only showing plain text, put `text` -instead of `rust` after the triple graves (see below). - -## Documentation as tests - -Let's discuss our sample example documentation: - -```rust -/// ``` -/// println!("Hello, world"); -/// ``` -# fn foo() {} -``` - -You'll notice that you don't need a `fn main()` or anything here. `rustdoc` will -automatically add a `main()` wrapper around your code, using heuristics to attempt -to put it in the right place. For example: - -```rust -/// ``` -/// use std::rc::Rc; -/// -/// let five = Rc::new(5); -/// ``` -# fn foo() {} -``` - -This will end up testing: - -```rust -fn main() { - use std::rc::Rc; - let five = Rc::new(5); -} -``` - -Here's the full algorithm rustdoc uses to preprocess examples: - -1. Any leading `#![foo]` attributes are left intact as crate attributes. -2. Some common `allow` attributes are inserted, including - `unused_variables`, `unused_assignments`, `unused_mut`, - `unused_attributes`, and `dead_code`. Small examples often trigger - these lints. -3. If the example does not contain `extern crate`, then `extern crate - ;` is inserted (note the lack of `#[macro_use]`). -4. Finally, if the example does not contain `fn main`, the remainder of the - text is wrapped in `fn main() { your_code }`. - -This generated `fn main` can be a problem! If you have `extern crate` or a `mod` -statements in the example code that are referred to by `use` statements, they will -fail to resolve unless you include at least `fn main() {}` to inhibit step 4. -`#[macro_use] extern crate` also does not work except at the crate root, so when -testing macros an explicit `main` is always required. It doesn't have to clutter -up your docs, though -- keep reading! - -Sometimes this algorithm isn't enough, though. For example, all of these code samples -with `///` we've been talking about? The raw text: - -```text -/// Some documentation. -# fn foo() {} -``` - -looks different than the output: - -```rust -/// Some documentation. -# fn foo() {} -``` - -Yes, that's right: you can add lines that start with `# `, and they will -be hidden from the output, but will be used when compiling your code. You -can use this to your advantage. In this case, documentation comments need -to apply to some kind of function, so if I want to show you just a -documentation comment, I need to add a little function definition below -it. At the same time, it's only there to satisfy the compiler, so hiding -it makes the example more clear. You can use this technique to explain -longer examples in detail, while still preserving the testability of your -documentation. - -For example, imagine that we wanted to document this code: - -```rust -let x = 5; -let y = 6; -println!("{}", x + y); -``` - -We might want the documentation to end up looking like this: - -> First, we set `x` to five: -> -> ```rust -> let x = 5; -> # let y = 6; -> # println!("{}", x + y); -> ``` -> -> Next, we set `y` to six: -> -> ```rust -> # let x = 5; -> let y = 6; -> # println!("{}", x + y); -> ``` -> -> Finally, we print the sum of `x` and `y`: -> -> ```rust -> # let x = 5; -> # let y = 6; -> println!("{}", x + y); -> ``` - -To keep each code block testable, we want the whole program in each block, but -we don't want the reader to see every line every time. Here's what we put in -our source code: - -```text - First, we set `x` to five: - - ```rust - let x = 5; - # let y = 6; - # println!("{}", x + y); - ``` - - Next, we set `y` to six: - - ```rust - # let x = 5; - let y = 6; - # println!("{}", x + y); - ``` - - Finally, we print the sum of `x` and `y`: - - ```rust - # let x = 5; - # let y = 6; - println!("{}", x + y); - ``` -``` - -By repeating all parts of the example, you can ensure that your example still -compiles, while only showing the parts that are relevant to that part of your -explanation. - -### Documenting macros - -Here’s an example of documenting a macro: - -```rust -/// Panic with a given message unless an expression evaluates to true. -/// -/// # Examples -/// -/// ``` -/// # #[macro_use] extern crate foo; -/// # fn main() { -/// panic_unless!(1 + 1 == 2, “Math is broken.”); -/// # } -/// ``` -/// -/// ```rust,should_panic -/// # #[macro_use] extern crate foo; -/// # fn main() { -/// panic_unless!(true == false, “I’m broken.”); -/// # } -/// ``` -#[macro_export] -macro_rules! panic_unless { - ($condition:expr, $($rest:expr),+) => ({ if ! $condition { panic!($($rest),+); } }); -} -# fn main() {} -``` - -You’ll note three things: we need to add our own `extern crate` line, so that -we can add the `#[macro_use]` attribute. Second, we’ll need to add our own -`main()` as well (for reasons discussed above). Finally, a judicious use of -`#` to comment out those two things, so they don’t show up in the output. - -Another case where the use of `#` is handy is when you want to ignore -error handling. Lets say you want the following, - -```rust,ignore -/// use std::io; -/// let mut input = String::new(); -/// try!(io::stdin().read_line(&mut input)); -``` - -The problem is that `try!` returns a `Result` and test functions -don't return anything so this will give a mismatched types error. - -```rust,ignore -/// A doc test using try! -/// -/// ``` -/// use std::io; -/// # fn foo() -> io::Result<()> { -/// let mut input = String::new(); -/// try!(io::stdin().read_line(&mut input)); -/// # Ok(()) -/// # } -/// ``` -# fn foo() {} -``` - -You can get around this by wrapping the code in a function. This catches -and swallows the `Result` when running tests on the docs. This -pattern appears regularly in the standard library. - -### Running documentation tests - -To run the tests, either: - -```bash -$ rustdoc --test path/to/my/crate/root.rs -# or -$ cargo test -``` - -That's right, `cargo test` tests embedded documentation too. **However, -`cargo test` will not test binary crates, only library ones.** This is -due to the way `rustdoc` works: it links against the library to be tested, -but with a binary, there’s nothing to link to. - -There are a few more annotations that are useful to help `rustdoc` do the right -thing when testing your code: - -```rust -/// ```rust,ignore -/// fn foo() { -/// ``` -# fn foo() {} -``` - -The `ignore` directive tells Rust to ignore your code. This is almost never -what you want, as it's the most generic. Instead, consider annotating it -with `text` if it's not code, or using `#`s to get a working example that -only shows the part you care about. - -```rust -/// ```rust,should_panic -/// assert!(false); -/// ``` -# fn foo() {} -``` - -`should_panic` tells `rustdoc` that the code should compile correctly, but -not actually pass as a test. - -```rust -/// ```rust,no_run -/// loop { -/// println!("Hello, world"); -/// } -/// ``` -# fn foo() {} -``` - -The `no_run` attribute will compile your code, but not run it. This is -important for examples such as "Here's how to retrieve a web page," -which you would want to ensure compiles, but might be run in a test -environment that has no network access. - -### Documenting modules - -Rust has another kind of doc comment, `//!`. This comment doesn't document the next item, but the enclosing item. In other words: - -```rust -mod foo { - //! This is documentation for the `foo` module. - //! - //! # Examples - - // ... -} -``` - -This is where you'll see `//!` used most often: for module documentation. If -you have a module in `foo.rs`, you'll often open its code and see this: - -```rust -//! A module for using `foo`s. -//! -//! The `foo` module contains a lot of useful functionality blah blah blah... -``` - -### Crate documentation - -Crates can be documented by placing an inner doc comment (`//!`) at the -beginning of the crate root, aka `lib.rs`: - -```rust -//! This is documentation for the `foo` crate. -//! -//! The foo crate is meant to be used for bar. -``` - -### Documentation comment style - -Check out [RFC 505][rfc505] for full conventions around the style and format of -documentation. - -[rfc505]: https://github.com/rust-lang/rfcs/blob/master/text/0505-api-comment-conventions.md - -## Other documentation - -All of this behavior works in non-Rust source files too. Because comments -are written in Markdown, they're often `.md` files. - -When you write documentation in Markdown files, you don't need to prefix -the documentation with comments. For example: - -```rust -/// # Examples -/// -/// ``` -/// use std::rc::Rc; -/// -/// let five = Rc::new(5); -/// ``` -# fn foo() {} -``` - -is: - -~~~markdown -# Examples - -``` -use std::rc::Rc; - -let five = Rc::new(5); -``` -~~~ - -when it's in a Markdown file. There is one wrinkle though: Markdown files need -to have a title like this: - -```markdown -% The title - -This is the example documentation. -``` - -This `%` line needs to be the very first line of the file. - -## `doc` attributes - -At a deeper level, documentation comments are syntactic sugar for documentation -attributes: - -```rust -/// this -# fn foo() {} - -#[doc="this"] -# fn bar() {} -``` - -are the same, as are these: - -```rust -//! this - -#![doc="this"] -``` - -You won't often see this attribute used for writing documentation, but it -can be useful when changing some options, or when writing a macro. - -### Re-exports - -`rustdoc` will show the documentation for a public re-export in both places: - -```rust,ignore -extern crate foo; - -pub use foo::bar; -``` - -This will create documentation for `bar` both inside the documentation for the -crate `foo`, as well as the documentation for your crate. It will use the same -documentation in both places. - -This behavior can be suppressed with `no_inline`: - -```rust,ignore -extern crate foo; - -#[doc(no_inline)] -pub use foo::bar; -``` - -## Missing documentation - -Sometimes you want to make sure that every single public thing in your project -is documented, especially when you are working on a library. Rust allows you to -to generate warnings or errors, when an item is missing documentation. -To generate warnings you use `warn`: - -```rust,ignore -#![warn(missing_docs)] -``` - -And to generate errors you use `deny`: - -```rust,ignore -#![deny(missing_docs)] -``` - -There are cases where you want to disable these warnings/errors to explicitly -leave something undocumented. This is done by using `allow`: - -```rust -#[allow(missing_docs)] -struct Undocumented; -``` - -You might even want to hide items from the documentation completely: - -```rust -#[doc(hidden)] -struct Hidden; -``` - -### Controlling HTML - -You can control a few aspects of the HTML that `rustdoc` generates through the -`#![doc]` version of the attribute: - -```rust,ignore -#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", - html_favicon_url = "https://www.rust-lang.org/favicon.ico", - html_root_url = "https://doc.rust-lang.org/")] -``` - -This sets a few different options, with a logo, favicon, and a root URL. - -### Configuring documentation tests - -You can also configure the way that `rustdoc` tests your documentation examples -through the `#![doc(test(..))]` attribute. - -```rust -#![doc(test(attr(allow(unused_variables), deny(warnings))))] -``` - -This allows unused variables within the examples, but will fail the test for any -other lint warning thrown. - -## Generation options - -`rustdoc` also contains a few other options on the command line, for further customization: - -- `--html-in-header FILE`: includes the contents of FILE at the end of the - `...` section. -- `--html-before-content FILE`: includes the contents of FILE directly after - ``, before the rendered content (including the search bar). -- `--html-after-content FILE`: includes the contents of FILE after all the rendered content. - -## Security note - -The Markdown in documentation comments is placed without processing into -the final webpage. Be careful with literal HTML: - -```rust -/// -# fn foo() {} -``` +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). diff --git a/first-edition/src/drop.md b/first-edition/src/drop.md index 1d8c9a3afb..1abde150e8 100644 --- a/first-edition/src/drop.md +++ b/first-edition/src/drop.md @@ -1,67 +1,10 @@ # Drop -Now that we’ve discussed traits, let’s talk about a particular trait provided -by the Rust standard library, [`Drop`][drop]. The `Drop` trait provides a way -to run some code when a value goes out of scope. For example: +The first edition of the book is no longer distributed with Rust's documentation. -[drop]: ../../std/ops/trait.Drop.html +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. -```rust -struct HasDrop; - -impl Drop for HasDrop { - fn drop(&mut self) { - println!("Dropping!"); - } -} - -fn main() { - let x = HasDrop; - - // Do stuff. - -} // `x` goes out of scope here. -``` - -When `x` goes out of scope at the end of `main()`, the code for `Drop` will -run. `Drop` has one method, which is also called `drop()`. It takes a mutable -reference to `self`. - -That’s it! The mechanics of `Drop` are very simple, but there are some -subtleties. For example, values are dropped in the opposite order they are -declared. Here’s another example: - -```rust -struct Firework { - strength: i32, -} - -impl Drop for Firework { - fn drop(&mut self) { - println!("BOOM times {}!!!", self.strength); - } -} - -fn main() { - let firecracker = Firework { strength: 1 }; - let tnt = Firework { strength: 100 }; -} -``` - -This will output: - -```text -BOOM times 100!!! -BOOM times 1!!! -``` - -The `tnt` goes off before the `firecracker` does, because it was declared -afterwards. Last in, first out. - -So what is `Drop` good for? Generally, `Drop` is used to clean up any resources -associated with a `struct`. For example, the [`Arc` type][arc] is a -reference-counted type. When `Drop` is called, it will decrement the reference -count, and if the total number of references is zero, will clean up the -underlying value. - -[arc]: ../../std/sync/struct.Arc.html +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). diff --git a/first-edition/src/effective-rust.md b/first-edition/src/effective-rust.md index ce2dfe4eae..1087c65410 100644 --- a/first-edition/src/effective-rust.md +++ b/first-edition/src/effective-rust.md @@ -1,8 +1,10 @@ # Effective Rust -So you’ve learned how to write some Rust code. But there’s a difference between -writing *any* Rust code and writing *good* Rust code. +The first edition of the book is no longer distributed with Rust's documentation. -This chapter consists of relatively independent tutorials which show you how to -take your Rust to the next level. Common patterns and standard library features -will be introduced. Read these sections in any order of your choosing. +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). \ No newline at end of file diff --git a/first-edition/src/enums.md b/first-edition/src/enums.md index 9cf5e6bfa2..e26e198203 100644 --- a/first-edition/src/enums.md +++ b/first-edition/src/enums.md @@ -1,107 +1,10 @@ # Enums -An `enum` in Rust is a type that represents data that is one of -several possible variants. Each variant in the `enum` can optionally -have data associated with it: +The first edition of the book is no longer distributed with Rust's documentation. -```rust -enum Message { - Quit, - ChangeColor(i32, i32, i32), - Move { x: i32, y: i32 }, - Write(String), -} -``` +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. -The syntax for defining variants resembles the syntaxes used to define structs: -you can have variants with no data (like unit-like structs), variants with named -data, and variants with unnamed data (like tuple structs). Unlike -separate struct definitions, however, an `enum` is a single type. A -value of the enum can match any of the variants. For this reason, an -enum is sometimes called a ‘sum type’: the set of possible values of the -enum is the sum of the sets of possible values for each variant. - -We use the `::` syntax to use the name of each variant: they’re scoped by the name -of the `enum` itself. This allows both of these to work: - -```rust -# enum Message { -# Move { x: i32, y: i32 }, -# } -let x: Message = Message::Move { x: 3, y: 4 }; - -enum BoardGameTurn { - Move { squares: i32 }, - Pass, -} - -let y: BoardGameTurn = BoardGameTurn::Move { squares: 1 }; -``` - -Both variants are named `Move`, but since they’re scoped to the name of -the enum, they can both be used without conflict. - -A value of an `enum` type contains information about which variant it is, -in addition to any data associated with that variant. This is sometimes -referred to as a ‘tagged union’, since the data includes a ‘tag’ -indicating what type it is. The compiler uses this information to -enforce that you’re accessing the data in the enum safely. For instance, -you can’t simply try to destructure a value as if it were one of the -possible variants: - -```rust,ignore -fn process_color_change(msg: Message) { - let Message::ChangeColor(r, g, b) = msg; // This causes a compile-time error. -} -``` - -Not supporting these operations may seem rather limiting, but it’s a limitation -which we can overcome. There are two ways: by implementing equality ourselves, -or by pattern matching variants with [`match`][match] expressions, which you’ll -learn in the next section. We don’t know enough about Rust to implement -equality yet, but we’ll find out in the [`traits`][traits] section. - -[match]: match.html -[traits]: traits.html - -# Constructors as functions - -An `enum` constructor can also be used like a function. For example: - -```rust -# enum Message { -# Write(String), -# } -let m = Message::Write("Hello, world".to_string()); -``` - -is the same as - -```rust -# enum Message { -# Write(String), -# } -fn foo(x: String) -> Message { - Message::Write(x) -} - -let x = foo("Hello, world".to_string()); -``` - -This is not immediately useful to us, but when we get to -[`closures`][closures], we’ll talk about passing functions as arguments to -other functions. For example, with [`iterators`][iterators], we can do this -to convert a vector of `String`s into a vector of `Message::Write`s: - -```rust -# enum Message { -# Write(String), -# } - -let v = vec!["Hello".to_string(), "World".to_string()]; - -let v1: Vec = v.into_iter().map(Message::Write).collect(); -``` - -[closures]: closures.html -[iterators]: iterators.html +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). diff --git a/first-edition/src/error-handling.md b/first-edition/src/error-handling.md index e2f3995c5f..35b780ae7d 100644 --- a/first-edition/src/error-handling.md +++ b/first-edition/src/error-handling.md @@ -1,2213 +1,10 @@ # Error Handling -Like most programming languages, Rust encourages the programmer to handle -errors in a particular way. Generally speaking, error handling is divided into -two broad categories: exceptions and return values. Rust opts for return -values. +The first edition of the book is no longer distributed with Rust's documentation. -In this section, we intend to provide a comprehensive treatment of how to deal -with errors in Rust. More than that, we will attempt to introduce error handling -one piece at a time so that you'll come away with a solid working knowledge of -how everything fits together. +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. -When done naïvely, error handling in Rust can be verbose and annoying. This -section will explore those stumbling blocks and demonstrate how to use the -standard library to make error handling concise and ergonomic. - -# Table of Contents - -This section is very long, mostly because we start at the very beginning with -sum types and combinators, and try to motivate the way Rust does error handling -incrementally. As such, programmers with experience in other expressive type -systems may want to jump around. - -* [The Basics](#the-basics) - * [Unwrapping explained](#unwrapping-explained) - * [The `Option` type](#the-option-type) - * [Composing `Option` values](#composing-optiont-values) - * [The `Result` type](#the-result-type) - * [Parsing integers](#parsing-integers) - * [The `Result` type alias idiom](#the-result-type-alias-idiom) - * [A brief interlude: unwrapping isn't evil](#a-brief-interlude-unwrapping-isnt-evil) -* [Working with multiple error types](#working-with-multiple-error-types) - * [Composing `Option` and `Result`](#composing-option-and-result) - * [The limits of combinators](#the-limits-of-combinators) - * [Early returns](#early-returns) - * [The `try!` macro](#the-try-macro) - * [Defining your own error type](#defining-your-own-error-type) -* [Standard library traits used for error handling](#standard-library-traits-used-for-error-handling) - * [The `Error` trait](#the-error-trait) - * [The `From` trait](#the-from-trait) - * [The real `try!` macro](#the-real-try-macro) - * [Composing custom error types](#composing-custom-error-types) - * [Advice for library writers](#advice-for-library-writers) -* [Case study: A program to read population data](#case-study-a-program-to-read-population-data) - * [Initial setup](#initial-setup) - * [Argument parsing](#argument-parsing) - * [Writing the logic](#writing-the-logic) - * [Error handling with `Box`](#error-handling-with-boxerror) - * [Reading from stdin](#reading-from-stdin) - * [Error handling with a custom type](#error-handling-with-a-custom-type) - * [Adding functionality](#adding-functionality) -* [The short story](#the-short-story) - -# The Basics - -You can think of error handling as using *case analysis* to determine whether -a computation was successful or not. As you will see, the key to ergonomic error -handling is reducing the amount of explicit case analysis the programmer has to -do while keeping code composable. - -Keeping code composable is important, because without that requirement, we -could [`panic`](../../std/macro.panic.html) whenever we -come across something unexpected. (`panic` causes the current task to unwind, -and in most cases, the entire program aborts.) Here's an example: - -```rust,should_panic -// Guess a number between 1 and 10. -// If it matches the number we had in mind, return `true`. Else, return `false`. -fn guess(n: i32) -> bool { - if n < 1 || n > 10 { - panic!("Invalid number: {}", n); - } - n == 5 -} - -fn main() { - guess(11); -} -``` - -If you try running this code, the program will crash with a message like this: - -```text -thread 'main' panicked at 'Invalid number: 11', src/bin/panic-simple.rs:5 -``` - -Here's another example that is slightly less contrived. A program that accepts -an integer as an argument, doubles it and prints it. - - - -```rust,should_panic -use std::env; - -fn main() { - let mut argv = env::args(); - let arg: String = argv.nth(1).unwrap(); // error 1 - let n: i32 = arg.parse().unwrap(); // error 2 - println!("{}", 2 * n); -} -``` - -If you give this program zero arguments (error 1) or if the first argument -isn't an integer (error 2), the program will panic just like in the first -example. - -You can think of this style of error handling as similar to a bull running -through a china shop. The bull will get to where it wants to go, but it will -trample everything in the process. - -## Unwrapping explained - -In the previous example, we claimed -that the program would simply panic if it reached one of the two error -conditions, yet, the program does not include an explicit call to `panic` like -the first example. This is because the -panic is embedded in the calls to `unwrap`. - -To “unwrap” something in Rust is to say, “Give me the result of the -computation, and if there was an error, panic and stop the program.” -It would be better if we showed the code for unwrapping because it is so -simple, but to do that, we will first need to explore the `Option` and `Result` -types. Both of these types have a method called `unwrap` defined on them. - -### The `Option` type - -The `Option` type is [defined in the standard library][5]: - -```rust -enum Option { - None, - Some(T), -} -``` - -The `Option` type is a way to use Rust's type system to express the -*possibility of absence*. Encoding the possibility of absence into the type -system is an important concept because it will cause the compiler to force the -programmer to handle that absence. Let's take a look at an example that tries -to find a character in a string: - - - -```rust -// Searches `haystack` for the Unicode character `needle`. If one is found, the -// byte offset of the character is returned. Otherwise, `None` is returned. -fn find(haystack: &str, needle: char) -> Option { - for (offset, c) in haystack.char_indices() { - if c == needle { - return Some(offset); - } - } - None -} -``` - -Notice that when this function finds a matching character, it doesn't only -return the `offset`. Instead, it returns `Some(offset)`. `Some` is a variant or -a *value constructor* for the `Option` type. You can think of it as a function -with the type `fn(value: T) -> Option`. Correspondingly, `None` is also a -value constructor, except it has no arguments. You can think of `None` as a -function with the type `fn() -> Option`. - -This might seem like much ado about nothing, but this is only half of the -story. The other half is *using* the `find` function we've written. Let's try -to use it to find the extension in a file name. - -```rust -# fn find(haystack: &str, needle: char) -> Option { haystack.find(needle) } -fn main() { - let file_name = "foobar.rs"; - match find(file_name, '.') { - None => println!("No file extension found."), - Some(i) => println!("File extension: {}", &file_name[i+1..]), - } -} -``` - -This code uses [pattern matching][1] to do *case -analysis* on the `Option` returned by the `find` function. In fact, case -analysis is the only way to get at the value stored inside an `Option`. This -means that you, as the programmer, must handle the case when an `Option` is -`None` instead of `Some(t)`. - -But wait, what about `unwrap`, which we used [previously](#code-unwrap-double)? -There was no case analysis there! Instead, the case analysis was put inside the -`unwrap` method for you. You could define it yourself if you want: - - - -```rust -enum Option { - None, - Some(T), -} - -impl Option { - fn unwrap(self) -> T { - match self { - Option::Some(val) => val, - Option::None => - panic!("called `Option::unwrap()` on a `None` value"), - } - } -} -``` - -The `unwrap` method *abstracts away the case analysis*. This is precisely the thing -that makes `unwrap` ergonomic to use. Unfortunately, that `panic!` means that -`unwrap` is not composable: it is the bull in the china shop. - -### Composing `Option` values - -In an [example from before](#code-option-ex-string-find), -we saw how to use `find` to discover the extension in a file name. Of course, -not all file names have a `.` in them, so it's possible that the file name has -no extension. This *possibility of absence* is encoded into the types using -`Option`. In other words, the compiler will force us to address the -possibility that an extension does not exist. In our case, we only print out a -message saying as such. - -Getting the extension of a file name is a pretty common operation, so it makes -sense to put it into a function: - -```rust -# fn find(haystack: &str, needle: char) -> Option { haystack.find(needle) } -// Returns the extension of the given file name, where the extension is defined -// as all characters following the first `.`. -// If `file_name` has no `.`, then `None` is returned. -fn extension_explicit(file_name: &str) -> Option<&str> { - match find(file_name, '.') { - None => None, - Some(i) => Some(&file_name[i+1..]), - } -} -``` - -(Pro-tip: don't use this code. Use the -[`extension`](../../std/path/struct.Path.html#method.extension) -method in the standard library instead.) - -The code stays simple, but the important thing to notice is that the type of -`find` forces us to consider the possibility of absence. This is a good thing -because it means the compiler won't let us accidentally forget about the case -where a file name doesn't have an extension. On the other hand, doing explicit -case analysis like we've done in `extension_explicit` every time can get a bit -tiresome. - -In fact, the case analysis in `extension_explicit` follows a very common -pattern: *map* a function on to the value inside of an `Option`, unless the -option is `None`, in which case, return `None`. - -Rust has parametric polymorphism, so it is very easy to define a combinator -that abstracts this pattern: - - - -```rust -fn map(option: Option, f: F) -> Option where F: FnOnce(T) -> A { - match option { - None => None, - Some(value) => Some(f(value)), - } -} -``` - -Indeed, `map` is [defined as a method][2] on `Option` in the standard library. -As a method, it has a slightly different signature: methods take `self`, `&self`, -or `&mut self` as their first argument. - -Armed with our new combinator, we can rewrite our `extension_explicit` method -to get rid of the case analysis: - -```rust -# fn find(haystack: &str, needle: char) -> Option { haystack.find(needle) } -// Returns the extension of the given file name, where the extension is defined -// as all characters following the first `.`. -// If `file_name` has no `.`, then `None` is returned. -fn extension(file_name: &str) -> Option<&str> { - find(file_name, '.').map(|i| &file_name[i+1..]) -} -``` - -One other pattern we commonly find is assigning a default value to the case -when an `Option` value is `None`. For example, maybe your program assumes that -the extension of a file is `rs` even if none is present. As you might imagine, -the case analysis for this is not specific to file extensions - it can work -with any `Option`: - -```rust -fn unwrap_or(option: Option, default: T) -> T { - match option { - None => default, - Some(value) => value, - } -} -``` - -Like with `map` above, the standard library implementation is a method instead -of a free function. - -The trick here is that the default value must have the same type as the value -that might be inside the `Option`. Using it is dead simple in our case: - -```rust -# fn find(haystack: &str, needle: char) -> Option { -# for (offset, c) in haystack.char_indices() { -# if c == needle { -# return Some(offset); -# } -# } -# None -# } -# -# fn extension(file_name: &str) -> Option<&str> { -# find(file_name, '.').map(|i| &file_name[i+1..]) -# } -fn main() { - assert_eq!(extension("foobar.csv").unwrap_or("rs"), "csv"); - assert_eq!(extension("foobar").unwrap_or("rs"), "rs"); -} -``` - -(Note that `unwrap_or` is [defined as a method][3] on `Option` in the -standard library, so we use that here instead of the free-standing function we -defined above. Don't forget to check out the more general [`unwrap_or_else`][4] -method.) - -There is one more combinator that we think is worth paying special attention to: -`and_then`. It makes it easy to compose distinct computations that admit the -*possibility of absence*. For example, much of the code in this section is -about finding an extension given a file name. In order to do this, you first -need the file name which is typically extracted from a file *path*. While most -file paths have a file name, not *all* of them do. For example, `.`, `..` or -`/`. - -So, we are tasked with the challenge of finding an extension given a file -*path*. Let's start with explicit case analysis: - -```rust -# fn extension(file_name: &str) -> Option<&str> { None } -fn file_path_ext_explicit(file_path: &str) -> Option<&str> { - match file_name(file_path) { - None => None, - Some(name) => match extension(name) { - None => None, - Some(ext) => Some(ext), - } - } -} - -fn file_name(file_path: &str) -> Option<&str> { - // Implementation elided. - unimplemented!() -} -``` - -You might think that we could use the `map` combinator to reduce the case -analysis, but its type doesn't quite fit... - -```rust,ignore -fn file_path_ext(file_path: &str) -> Option<&str> { - file_name(file_path).map(|x| extension(x)) // This causes a compilation error. -} -``` - -The `map` function here wraps the value returned by the `extension` function -inside an `Option<_>` and since the `extension` function itself returns an -`Option<&str>` the expression `file_name(file_path).map(|x| extension(x))` -actually returns an `Option>`. - -But since `file_path_ext` just returns `Option<&str>` (and not -`Option>`) we get a compilation error. - -The result of the function taken by map as input is *always* [rewrapped with -`Some`](#code-option-map). Instead, we need something like `map`, but which -allows the caller to return a `Option<_>` directly without wrapping it in -another `Option<_>`. - -Its generic implementation is even simpler than `map`: - -```rust -fn and_then(option: Option, f: F) -> Option - where F: FnOnce(T) -> Option { - match option { - None => None, - Some(value) => f(value), - } -} -``` - -Now we can rewrite our `file_path_ext` function without explicit case analysis: - -```rust -# fn extension(file_name: &str) -> Option<&str> { None } -# fn file_name(file_path: &str) -> Option<&str> { None } -fn file_path_ext(file_path: &str) -> Option<&str> { - file_name(file_path).and_then(extension) -} -``` - -Side note: Since `and_then` essentially works like `map` but returns an -`Option<_>` instead of an `Option>` it is known as `flatmap` in some -other languages. - -The `Option` type has many other combinators [defined in the standard -library][5]. It is a good idea to skim this list and familiarize -yourself with what's available—they can often reduce case analysis -for you. Familiarizing yourself with these combinators will pay -dividends because many of them are also defined (with similar -semantics) for `Result`, which we will talk about next. - -Combinators make using types like `Option` ergonomic because they reduce -explicit case analysis. They are also composable because they permit the caller -to handle the possibility of absence in their own way. Methods like `unwrap` -remove choices because they will panic if `Option` is `None`. - -## The `Result` type - -The `Result` type is also -[defined in the standard library][6]: - - - -```rust -enum Result { - Ok(T), - Err(E), -} -``` - -The `Result` type is a richer version of `Option`. Instead of expressing the -possibility of *absence* like `Option` does, `Result` expresses the possibility -of *error*. Usually, the *error* is used to explain why the execution of some -computation failed. This is a strictly more general form of `Option`. Consider -the following type alias, which is semantically equivalent to the real -`Option` in every way: - -```rust -type Option = Result; -``` - -This fixes the second type parameter of `Result` to always be `()` (pronounced -“unit” or “empty tuple”). Exactly one value inhabits the `()` type: `()`. (Yup, -the type and value level terms have the same notation!) - -The `Result` type is a way of representing one of two possible outcomes in a -computation. By convention, one outcome is meant to be expected or “`Ok`” while -the other outcome is meant to be unexpected or “`Err`”. - -Just like `Option`, the `Result` type also has an -[`unwrap` method -defined][7] -in the standard library. Let's define it: - -```rust -# enum Result { Ok(T), Err(E) } -impl Result { - fn unwrap(self) -> T { - match self { - Result::Ok(val) => val, - Result::Err(err) => - panic!("called `Result::unwrap()` on an `Err` value: {:?}", err), - } - } -} -``` - -This is effectively the same as our [definition for -`Option::unwrap`](#code-option-def-unwrap), except it includes the -error value in the `panic!` message. This makes debugging easier, but -it also requires us to add a [`Debug`][8] constraint on the `E` type -parameter (which represents our error type). Since the vast majority -of types should satisfy the `Debug` constraint, this tends to work out -in practice. (`Debug` on a type simply means that there's a reasonable -way to print a human-readable description of values with that type.) - -OK, let's move on to an example. - -### Parsing integers - -The Rust standard library makes converting strings to integers dead simple. -It's so easy in fact, that it is very tempting to write something like the -following: - -```rust -fn double_number(number_str: &str) -> i32 { - 2 * number_str.parse::().unwrap() -} - -fn main() { - let n: i32 = double_number("10"); - assert_eq!(n, 20); -} -``` - -At this point, you should be skeptical of calling `unwrap`. For example, if -the string doesn't parse as a number, you'll get a panic: - -```text -thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }', /home/rustbuild/src/rust-buildbot/slave/beta-dist-rustc-linux/build/src/libcore/result.rs:729 -``` - -This is rather unsightly, and if this happened inside a library you're -using, you might be understandably annoyed. Instead, we should try to -handle the error in our function and let the caller decide what to -do. This means changing the return type of `double_number`. But to -what? Well, that requires looking at the signature of the [`parse` -method][9] in the standard library: - -```rust,ignore -impl str { - fn parse(&self) -> Result; -} -``` - -Hmm. So we at least know that we need to use a `Result`. Certainly, it's -possible that this could have returned an `Option`. After all, a string either -parses as a number or it doesn't, right? That's certainly a reasonable way to -go, but the implementation internally distinguishes *why* the string didn't -parse as an integer. (Whether it's an empty string, an invalid digit, too big -or too small.) Therefore, using a `Result` makes sense because we want to -provide more information than simply “absence.” We want to say *why* the -parsing failed. You should try to emulate this line of reasoning when faced -with a choice between `Option` and `Result`. If you can provide detailed error -information, then you probably should. (We'll see more on this later.) - -OK, but how do we write our return type? The `parse` method as defined -above is generic over all the different number types defined in the -standard library. We could (and probably should) also make our -function generic, but let's favor explicitness for the moment. We only -care about `i32`, so we need to [find its implementation of -`FromStr`](../../std/primitive.i32.html) (do a `CTRL-F` in your browser -for “FromStr”) and look at its [associated type][10] `Err`. We did -this so we can find the concrete error type. In this case, it's -[`std::num::ParseIntError`](../../std/num/struct.ParseIntError.html). -Finally, we can rewrite our function: - -```rust -use std::num::ParseIntError; - -fn double_number(number_str: &str) -> Result { - match number_str.parse::() { - Ok(n) => Ok(2 * n), - Err(err) => Err(err), - } -} - -fn main() { - match double_number("10") { - Ok(n) => assert_eq!(n, 20), - Err(err) => println!("Error: {:?}", err), - } -} -``` - -This is a little better, but now we've written much more code! The case -analysis has once again bitten us. - -Combinators to the rescue! Just like `Option`, `Result` has lots of combinators -defined as methods. There is a large intersection of common combinators between -`Result` and `Option`. In particular, `map` is part of that intersection: - -```rust -use std::num::ParseIntError; - -fn double_number(number_str: &str) -> Result { - number_str.parse::().map(|n| 2 * n) -} - -fn main() { - match double_number("10") { - Ok(n) => assert_eq!(n, 20), - Err(err) => println!("Error: {:?}", err), - } -} -``` - -The usual suspects are all there for `Result`, including -[`unwrap_or`](../../std/result/enum.Result.html#method.unwrap_or) and -[`and_then`](../../std/result/enum.Result.html#method.and_then). -Additionally, since `Result` has a second type parameter, there are -combinators that affect only the error type, such as -[`map_err`](../../std/result/enum.Result.html#method.map_err) (instead of -`map`) and [`or_else`](../../std/result/enum.Result.html#method.or_else) -(instead of `and_then`). - -### The `Result` type alias idiom - -In the standard library, you may frequently see types like -`Result`. But wait, [we defined `Result`](#code-result-def) to -have two type parameters. How can we get away with only specifying -one? The key is to define a `Result` type alias that *fixes* one of -the type parameters to a particular type. Usually the fixed type is -the error type. For example, our previous example parsing integers -could be rewritten like this: - -```rust -use std::num::ParseIntError; -use std::result; - -type Result = result::Result; - -fn double_number(number_str: &str) -> Result { - unimplemented!(); -} -``` - -Why would we do this? Well, if we have a lot of functions that could return -`ParseIntError`, then it's much more convenient to define an alias that always -uses `ParseIntError` so that we don't have to write it out all the time. - -The most prominent place this idiom is used in the standard library is -with [`io::Result`](../../std/io/type.Result.html). Typically, one writes -`io::Result`, which makes it clear that you're using the `io` -module's type alias instead of the plain definition from -`std::result`. (This idiom is also used for -[`fmt::Result`](../../std/fmt/type.Result.html).) - -## A brief interlude: unwrapping isn't evil - -If you've been following along, you might have noticed that I've taken a pretty -hard line against calling methods like `unwrap` that could `panic` and abort -your program. *Generally speaking*, this is good advice. - -However, `unwrap` can still be used judiciously. What exactly justifies use of -`unwrap` is somewhat of a grey area and reasonable people can disagree. I'll -summarize some of my *opinions* on the matter. - -* **In examples and quick 'n' dirty code.** Sometimes you're writing examples - or a quick program, and error handling simply isn't important. Beating the - convenience of `unwrap` can be hard in such scenarios, so it is very - appealing. -* **When panicking indicates a bug in the program.** When the invariants of - your code should prevent a certain case from happening (like, say, popping - from an empty stack), then panicking can be permissible. This is because it - exposes a bug in your program. This can be explicit, like from an `assert!` - failing, or it could be because your index into an array was out of bounds. - -This is probably not an exhaustive list. Moreover, when using an -`Option`, it is often better to use its -[`expect`](../../std/option/enum.Option.html#method.expect) -method. `expect` does exactly the same thing as `unwrap`, except it -prints a message you give to `expect`. This makes the resulting panic -a bit nicer to deal with, since it will show your message instead of -“called unwrap on a `None` value.” - -My advice boils down to this: use good judgment. There's a reason why the words -“never do X” or “Y is considered harmful” don't appear in my writing. There are -trade-offs to all things, and it is up to you as the programmer to determine -what is acceptable for your use cases. My goal is only to help you evaluate -trade-offs as accurately as possible. - -Now that we've covered the basics of error handling in Rust, and -explained unwrapping, let's start exploring more of the standard -library. - -# Working with multiple error types - -Thus far, we've looked at error handling where everything was either an -`Option` or a `Result`. But what happens when you have both an -`Option` and a `Result`? Or what if you have a `Result` and a -`Result`? Handling *composition of distinct error types* is the next -challenge in front of us, and it will be the major theme throughout the rest of -this section. - -## Composing `Option` and `Result` - -So far, I've talked about combinators defined for `Option` and combinators -defined for `Result`. We can use these combinators to compose results of -different computations without doing explicit case analysis. - -Of course, in real code, things aren't always as clean. Sometimes you have a -mix of `Option` and `Result` types. Must we resort to explicit case analysis, -or can we continue using combinators? - -For now, let's revisit one of the first examples in this section: - -```rust,should_panic -use std::env; - -fn main() { - let mut argv = env::args(); - let arg: String = argv.nth(1).unwrap(); // error 1 - let n: i32 = arg.parse().unwrap(); // error 2 - println!("{}", 2 * n); -} -``` - -Given our new found knowledge of `Option`, `Result` and their various -combinators, we should try to rewrite this so that errors are handled properly -and the program doesn't panic if there's an error. - -The tricky aspect here is that `argv.nth(1)` produces an `Option` while -`arg.parse()` produces a `Result`. These aren't directly composable. When faced -with both an `Option` and a `Result`, the solution is *usually* to convert the -`Option` to a `Result`. In our case, the absence of a command line parameter -(from `env::args()`) means the user didn't invoke the program correctly. We -could use a `String` to describe the error. Let's try: - - - -```rust -use std::env; - -fn double_arg(mut argv: env::Args) -> Result { - argv.nth(1) - .ok_or("Please give at least one argument".to_owned()) - .and_then(|arg| arg.parse::().map_err(|err| err.to_string())) - .map(|n| 2 * n) -} - -fn main() { - match double_arg(env::args()) { - Ok(n) => println!("{}", n), - Err(err) => println!("Error: {}", err), - } -} -``` - -There are a couple new things in this example. The first is the use of the -[`Option::ok_or`](../../std/option/enum.Option.html#method.ok_or) -combinator. This is one way to convert an `Option` into a `Result`. The -conversion requires you to specify what error to use if `Option` is `None`. -Like the other combinators we've seen, its definition is very simple: - -```rust -fn ok_or(option: Option, err: E) -> Result { - match option { - Some(val) => Ok(val), - None => Err(err), - } -} -``` - -The other new combinator used here is -[`Result::map_err`](../../std/result/enum.Result.html#method.map_err). -This is like `Result::map`, except it maps a function on to the *error* -portion of a `Result` value. If the `Result` is an `Ok(...)` value, then it is -returned unmodified. - -We use `map_err` here because it is necessary for the error types to remain -the same (because of our use of `and_then`). Since we chose to convert the -`Option` (from `argv.nth(1)`) to a `Result`, we must -also convert the `ParseIntError` from `arg.parse()` to a `String`. - -## The limits of combinators - -Doing IO and parsing input is a very common task, and it's one that I -personally have done a lot of in Rust. Therefore, we will use (and continue to -use) IO and various parsing routines to exemplify error handling. - -Let's start simple. We are tasked with opening a file, reading all of its -contents and converting its contents to a number. Then we multiply it by `2` -and print the output. - -Although I've tried to convince you not to use `unwrap`, it can be useful -to first write your code using `unwrap`. It allows you to focus on your problem -instead of the error handling, and it exposes the points where proper error -handling need to occur. Let's start there so we can get a handle on the code, -and then refactor it to use better error handling. - -```rust,should_panic -use std::fs::File; -use std::io::Read; -use std::path::Path; - -fn file_double>(file_path: P) -> i32 { - let mut file = File::open(file_path).unwrap(); // error 1 - let mut contents = String::new(); - file.read_to_string(&mut contents).unwrap(); // error 2 - let n: i32 = contents.trim().parse().unwrap(); // error 3 - 2 * n -} - -fn main() { - let doubled = file_double("foobar"); - println!("{}", doubled); -} -``` - -(N.B. The `AsRef` is used because those are the -[same bounds used on -`std::fs::File::open`](../../std/fs/struct.File.html#method.open). -This makes it ergonomic to use any kind of string as a file path.) - -There are three different errors that can occur here: - -1. A problem opening the file. -2. A problem reading data from the file. -3. A problem parsing the data as a number. - -The first two problems are described via the -[`std::io::Error`](../../std/io/struct.Error.html) type. We know this -because of the return types of -[`std::fs::File::open`](../../std/fs/struct.File.html#method.open) and -[`std::io::Read::read_to_string`](../../std/io/trait.Read.html#method.read_to_string). -(Note that they both use the [`Result` type alias -idiom](#the-result-type-alias-idiom) described previously. If you -click on the `Result` type, you'll [see the type -alias](../../std/io/type.Result.html), and consequently, the underlying -`io::Error` type.) The third problem is described by the -[`std::num::ParseIntError`](../../std/num/struct.ParseIntError.html) -type. The `io::Error` type in particular is *pervasive* throughout the -standard library. You will see it again and again. - -Let's start the process of refactoring the `file_double` function. To make this -function composable with other components of the program, it should *not* panic -if any of the above error conditions are met. Effectively, this means that the -function should *return an error* if any of its operations fail. Our problem is -that the return type of `file_double` is `i32`, which does not give us any -useful way of reporting an error. Thus, we must start by changing the return -type from `i32` to something else. - -The first thing we need to decide: should we use `Option` or `Result`? We -certainly could use `Option` very easily. If any of the three errors occur, we -could simply return `None`. This will work *and it is better than panicking*, -but we can do much better. Instead, we should pass some detail about the error -that occurred. Since we want to express the *possibility of error*, we should -use `Result`. But what should `E` be? Since two *different* types of -errors can occur, we need to convert them to a common type. One such type is -`String`. Let's see how that impacts our code: - -```rust -use std::fs::File; -use std::io::Read; -use std::path::Path; - -fn file_double>(file_path: P) -> Result { - File::open(file_path) - .map_err(|err| err.to_string()) - .and_then(|mut file| { - let mut contents = String::new(); - file.read_to_string(&mut contents) - .map_err(|err| err.to_string()) - .map(|_| contents) - }) - .and_then(|contents| { - contents.trim().parse::() - .map_err(|err| err.to_string()) - }) - .map(|n| 2 * n) -} - -fn main() { - match file_double("foobar") { - Ok(n) => println!("{}", n), - Err(err) => println!("Error: {}", err), - } -} -``` - -This code looks a bit hairy. It can take quite a bit of practice before code -like this becomes easy to write. The way we write it is by *following the -types*. As soon as we changed the return type of `file_double` to -`Result`, we had to start looking for the right combinators. In -this case, we only used three different combinators: `and_then`, `map` and -`map_err`. - -`and_then` is used to chain multiple computations where each computation could -return an error. After opening the file, there are two more computations that -could fail: reading from the file and parsing the contents as a number. -Correspondingly, there are two calls to `and_then`. - -`map` is used to apply a function to the `Ok(...)` value of a `Result`. For -example, the very last call to `map` multiplies the `Ok(...)` value (which is -an `i32`) by `2`. If an error had occurred before that point, this operation -would have been skipped because of how `map` is defined. - -`map_err` is the trick that makes all of this work. `map_err` is like -`map`, except it applies a function to the `Err(...)` value of a `Result`. In -this case, we want to convert all of our errors to one type: `String`. Since -both `io::Error` and `num::ParseIntError` implement `ToString`, we can call the -`to_string()` method to convert them. - -With all of that said, the code is still hairy. Mastering use of combinators is -important, but they have their limits. Let's try a different approach: early -returns. - -## Early returns - -I'd like to take the code from the previous section and rewrite it using *early -returns*. Early returns let you exit the function early. We can't return early -in `file_double` from inside another closure, so we'll need to revert back to -explicit case analysis. - -```rust -use std::fs::File; -use std::io::Read; -use std::path::Path; - -fn file_double>(file_path: P) -> Result { - let mut file = match File::open(file_path) { - Ok(file) => file, - Err(err) => return Err(err.to_string()), - }; - let mut contents = String::new(); - if let Err(err) = file.read_to_string(&mut contents) { - return Err(err.to_string()); - } - let n: i32 = match contents.trim().parse() { - Ok(n) => n, - Err(err) => return Err(err.to_string()), - }; - Ok(2 * n) -} - -fn main() { - match file_double("foobar") { - Ok(n) => println!("{}", n), - Err(err) => println!("Error: {}", err), - } -} -``` - -Reasonable people can disagree over whether this code is better than the code -that uses combinators, but if you aren't familiar with the combinator approach, -this code looks simpler to read to me. It uses explicit case analysis with -`match` and `if let`. If an error occurs, it simply stops executing the -function and returns the error (by converting it to string). - -Isn't this a step backwards though? Previously, we said that the key to -ergonomic error handling is reducing explicit case analysis, yet we've reverted -back to explicit case analysis here. It turns out, there are *multiple* ways to -reduce explicit case analysis. Combinators aren't the only way. - -## The `try!` macro - -A cornerstone of error handling in Rust is the `try!` macro. The `try!` macro -abstracts case analysis like combinators, but unlike combinators, it also -abstracts *control flow*. Namely, it can abstract the *early return* pattern -seen above. - -Here is a simplified definition of a `try!` macro: - - - -```rust -macro_rules! try { - ($e:expr) => (match $e { - Ok(val) => val, - Err(err) => return Err(err), - }); -} -``` - -(The [real definition](../../std/macro.try.html) is a bit more -sophisticated. We will address that later.) - -Using the `try!` macro makes it very easy to simplify our last example. Since -it does the case analysis and the early return for us, we get tighter code that -is easier to read: - -```rust -use std::fs::File; -use std::io::Read; -use std::path::Path; - -fn file_double>(file_path: P) -> Result { - let mut file = try!(File::open(file_path).map_err(|e| e.to_string())); - let mut contents = String::new(); - try!(file.read_to_string(&mut contents).map_err(|e| e.to_string())); - let n = try!(contents.trim().parse::().map_err(|e| e.to_string())); - Ok(2 * n) -} - -fn main() { - match file_double("foobar") { - Ok(n) => println!("{}", n), - Err(err) => println!("Error: {}", err), - } -} -``` - -The `map_err` calls are still necessary given -[our definition of `try!`](#code-try-def-simple). -This is because the error types still need to be converted to `String`. -The good news is that we will soon learn how to remove those `map_err` calls! -The bad news is that we will need to learn a bit more about a couple important -traits in the standard library before we can remove the `map_err` calls. - -## Defining your own error type - -Before we dive into some of the standard library error traits, I'd like to wrap -up this section by removing the use of `String` as our error type in the -previous examples. - -Using `String` as we did in our previous examples is convenient because it's -easy to convert errors to strings, or even make up your own errors as strings -on the spot. However, using `String` for your errors has some downsides. - -The first downside is that the error messages tend to clutter your -code. It's possible to define the error messages elsewhere, but unless -you're unusually disciplined, it is very tempting to embed the error -message into your code. Indeed, we did exactly this in a [previous -example](#code-error-double-string). - -The second and more important downside is that `String`s are *lossy*. That is, -if all errors are converted to strings, then the errors we pass to the caller -become completely opaque. The only reasonable thing the caller can do with a -`String` error is show it to the user. Certainly, inspecting the string to -determine the type of error is not robust. (Admittedly, this downside is far -more important inside of a library as opposed to, say, an application.) - -For example, the `io::Error` type embeds an -[`io::ErrorKind`](../../std/io/enum.ErrorKind.html), -which is *structured data* that represents what went wrong during an IO -operation. This is important because you might want to react differently -depending on the error. (e.g., A `BrokenPipe` error might mean quitting your -program gracefully while a `NotFound` error might mean exiting with an error -code and showing an error to the user.) With `io::ErrorKind`, the caller can -examine the type of an error with case analysis, which is strictly superior -to trying to tease out the details of an error inside of a `String`. - -Instead of using a `String` as an error type in our previous example of reading -an integer from a file, we can define our own error type that represents errors -with *structured data*. We endeavor to not drop information from underlying -errors in case the caller wants to inspect the details. - -The ideal way to represent *one of many possibilities* is to define our own -sum type using `enum`. In our case, an error is either an `io::Error` or a -`num::ParseIntError`, so a natural definition arises: - -```rust -use std::io; -use std::num; - -// We derive `Debug` because all types should probably derive `Debug`. -// This gives us a reasonable human-readable description of `CliError` values. -#[derive(Debug)] -enum CliError { - Io(io::Error), - Parse(num::ParseIntError), -} -``` - -Tweaking our code is very easy. Instead of converting errors to strings, we -simply convert them to our `CliError` type using the corresponding value -constructor: - -```rust -# #[derive(Debug)] -# enum CliError { Io(::std::io::Error), Parse(::std::num::ParseIntError) } -use std::fs::File; -use std::io::Read; -use std::path::Path; - -fn file_double>(file_path: P) -> Result { - let mut file = try!(File::open(file_path).map_err(CliError::Io)); - let mut contents = String::new(); - try!(file.read_to_string(&mut contents).map_err(CliError::Io)); - let n: i32 = try!(contents.trim().parse().map_err(CliError::Parse)); - Ok(2 * n) -} - -fn main() { - match file_double("foobar") { - Ok(n) => println!("{}", n), - Err(err) => println!("Error: {:?}", err), - } -} -``` - -The only change here is switching `map_err(|e| e.to_string())` (which converts -errors to strings) to `map_err(CliError::Io)` or `map_err(CliError::Parse)`. -The *caller* gets to decide the level of detail to report to the user. In -effect, using a `String` as an error type removes choices from the caller while -using a custom `enum` error type like `CliError` gives the caller all of the -conveniences as before in addition to *structured data* describing the error. - -A rule of thumb is to define your own error type, but a `String` error type -will do in a pinch, particularly if you're writing an application. If you're -writing a library, defining your own error type should be strongly preferred so -that you don't remove choices from the caller unnecessarily. - -# Standard library traits used for error handling - -The standard library defines two integral traits for error handling: -[`std::error::Error`](../../std/error/trait.Error.html) and -[`std::convert::From`](../../std/convert/trait.From.html). While `Error` -is designed specifically for generically describing errors, the `From` -trait serves a more general role for converting values between two -distinct types. - -## The `Error` trait - -The `Error` trait is [defined in the standard -library](../../std/error/trait.Error.html): - -```rust -use std::fmt::{Debug, Display}; - -trait Error: Debug + Display { - /// A short description of the error. - fn description(&self) -> &str; - - /// The lower level cause of this error, if any. - fn cause(&self) -> Option<&Error> { None } -} -``` - -This trait is super generic because it is meant to be implemented for *all* -types that represent errors. This will prove useful for writing composable code -as we'll see later. Otherwise, the trait allows you to do at least the -following things: - -* Obtain a `Debug` representation of the error. -* Obtain a user-facing `Display` representation of the error. -* Obtain a short description of the error (via the `description` method). -* Inspect the causal chain of an error, if one exists (via the `cause` method). - -The first two are a result of `Error` requiring impls for both `Debug` and -`Display`. The latter two are from the two methods defined on `Error`. The -power of `Error` comes from the fact that all error types impl `Error`, which -means errors can be existentially quantified as a -[trait object](trait-objects.html). -This manifests as either `Box` or `&Error`. Indeed, the `cause` method -returns an `&Error`, which is itself a trait object. We'll revisit the -`Error` trait's utility as a trait object later. - -For now, it suffices to show an example implementing the `Error` trait. Let's -use the error type we defined in the -[previous section](#defining-your-own-error-type): - -```rust -use std::io; -use std::num; - -// We derive `Debug` because all types should probably derive `Debug`. -// This gives us a reasonable human-readable description of `CliError` values. -#[derive(Debug)] -enum CliError { - Io(io::Error), - Parse(num::ParseIntError), -} -``` - -This particular error type represents the possibility of two types of errors -occurring: an error dealing with I/O or an error converting a string to a -number. The error could represent as many error types as you want by adding new -variants to the `enum` definition. - -Implementing `Error` is pretty straight-forward. It's mostly going to be a lot -explicit case analysis. - -```rust,ignore -use std::error; -use std::fmt; - -impl fmt::Display for CliError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - // Both underlying errors already impl `Display`, so we defer to - // their implementations. - CliError::Io(ref err) => write!(f, "IO error: {}", err), - CliError::Parse(ref err) => write!(f, "Parse error: {}", err), - } - } -} - -impl error::Error for CliError { - fn description(&self) -> &str { - // Both underlying errors already impl `Error`, so we defer to their - // implementations. - match *self { - CliError::Io(ref err) => err.description(), - CliError::Parse(ref err) => err.description(), - } - } - - fn cause(&self) -> Option<&error::Error> { - match *self { - // N.B. Both of these implicitly cast `err` from their concrete - // types (either `&io::Error` or `&num::ParseIntError`) - // to a trait object `&Error`. This works because both error types - // implement `Error`. - CliError::Io(ref err) => Some(err), - CliError::Parse(ref err) => Some(err), - } - } -} -``` - -We note that this is a very typical implementation of `Error`: match on your -different error types and satisfy the contracts defined for `description` and -`cause`. - -## The `From` trait - -The `std::convert::From` trait is -[defined in the standard -library](../../std/convert/trait.From.html): - - - -```rust -trait From { - fn from(T) -> Self; -} -``` - -Deliciously simple, yes? `From` is very useful because it gives us a generic -way to talk about conversion *from* a particular type `T` to some other type -(in this case, “some other type” is the subject of the impl, or `Self`). -The crux of `From` is the -[set of implementations provided by the standard -library](../../std/convert/trait.From.html). - -Here are a few simple examples demonstrating how `From` works: - -```rust -let string: String = From::from("foo"); -let bytes: Vec = From::from("foo"); -let cow: ::std::borrow::Cow = From::from("foo"); -``` - -OK, so `From` is useful for converting between strings. But what about errors? -It turns out, there is one critical impl: - -```rust,ignore -impl<'a, E: Error + 'a> From for Box -``` - -This impl says that for *any* type that impls `Error`, we can convert it to a -trait object `Box`. This may not seem terribly surprising, but it is -useful in a generic context. - -Remember the two errors we were dealing with previously? Specifically, -`io::Error` and `num::ParseIntError`. Since both impl `Error`, they work with -`From`: - -```rust -use std::error::Error; -use std::fs; -use std::io; -use std::num; - -// We have to jump through some hoops to actually get error values: -let io_err: io::Error = io::Error::last_os_error(); -let parse_err: num::ParseIntError = "not a number".parse::().unwrap_err(); - -// OK, here are the conversions: -let err1: Box = From::from(io_err); -let err2: Box = From::from(parse_err); -``` - -There is a really important pattern to recognize here. Both `err1` and `err2` -have the *same type*. This is because they are existentially quantified types, -or trait objects. In particular, their underlying type is *erased* from the -compiler's knowledge, so it truly sees `err1` and `err2` as exactly the same. -Additionally, we constructed `err1` and `err2` using precisely the same -function call: `From::from`. This is because `From::from` is overloaded on both -its argument and its return type. - -This pattern is important because it solves a problem we had earlier: it gives -us a way to reliably convert errors to the same type using the same function. - -Time to revisit an old friend; the `try!` macro. - -## The real `try!` macro - -Previously, we presented this definition of `try!`: - -```rust -macro_rules! try { - ($e:expr) => (match $e { - Ok(val) => val, - Err(err) => return Err(err), - }); -} -``` - -This is not its real definition. Its real definition is -[in the standard library](../../std/macro.try.html): - - - -```rust -macro_rules! try { - ($e:expr) => (match $e { - Ok(val) => val, - Err(err) => return Err(::std::convert::From::from(err)), - }); -} -``` - -There's one tiny but powerful change: the error value is passed through -`From::from`. This makes the `try!` macro much more powerful because it gives -you automatic type conversion for free. - -Armed with our more powerful `try!` macro, let's take a look at code we wrote -previously to read a file and convert its contents to an integer: - -```rust -use std::fs::File; -use std::io::Read; -use std::path::Path; - -fn file_double>(file_path: P) -> Result { - let mut file = try!(File::open(file_path).map_err(|e| e.to_string())); - let mut contents = String::new(); - try!(file.read_to_string(&mut contents).map_err(|e| e.to_string())); - let n = try!(contents.trim().parse::().map_err(|e| e.to_string())); - Ok(2 * n) -} -``` - -Earlier, we promised that we could get rid of the `map_err` calls. Indeed, all -we have to do is pick a type that `From` works with. As we saw in the previous -section, `From` has an impl that lets it convert any error type into a -`Box`: - -```rust -use std::error::Error; -use std::fs::File; -use std::io::Read; -use std::path::Path; - -fn file_double>(file_path: P) -> Result> { - let mut file = try!(File::open(file_path)); - let mut contents = String::new(); - try!(file.read_to_string(&mut contents)); - let n = try!(contents.trim().parse::()); - Ok(2 * n) -} -``` - -We are getting very close to ideal error handling. Our code has very little -overhead as a result from error handling because the `try!` macro encapsulates -three things simultaneously: - -1. Case analysis. -2. Control flow. -3. Error type conversion. - -When all three things are combined, we get code that is unencumbered by -combinators, calls to `unwrap` or case analysis. - -There's one little nit left: the `Box` type is *opaque*. If we -return a `Box` to the caller, the caller can't (easily) inspect -underlying error type. The situation is certainly better than `String` -because the caller can call methods like -[`description`](../../std/error/trait.Error.html#tymethod.description) -and [`cause`](../../std/error/trait.Error.html#method.cause), but the -limitation remains: `Box` is opaque. (N.B. This isn't entirely -true because Rust does have runtime reflection, which is useful in -some scenarios that are [beyond the scope of this -section](https://crates.io/crates/error).) - -It's time to revisit our custom `CliError` type and tie everything together. - -## Composing custom error types - -In the last section, we looked at the real `try!` macro and how it does -automatic type conversion for us by calling `From::from` on the error value. -In particular, we converted errors to `Box`, which works, but the type -is opaque to callers. - -To fix this, we use the same remedy that we're already familiar with: a custom -error type. Once again, here is the code that reads the contents of a file and -converts it to an integer: - -```rust -use std::fs::File; -use std::io::{self, Read}; -use std::num; -use std::path::Path; - -// We derive `Debug` because all types should probably derive `Debug`. -// This gives us a reasonable human-readable description of `CliError` values. -#[derive(Debug)] -enum CliError { - Io(io::Error), - Parse(num::ParseIntError), -} - -fn file_double_verbose>(file_path: P) -> Result { - let mut file = try!(File::open(file_path).map_err(CliError::Io)); - let mut contents = String::new(); - try!(file.read_to_string(&mut contents).map_err(CliError::Io)); - let n: i32 = try!(contents.trim().parse().map_err(CliError::Parse)); - Ok(2 * n) -} -``` - -Notice that we still have the calls to `map_err`. Why? Well, recall the -definitions of [`try!`](#code-try-def) and [`From`](#code-from-def). The -problem is that there is no `From` impl that allows us to convert from error -types like `io::Error` and `num::ParseIntError` to our own custom `CliError`. -Of course, it is easy to fix this! Since we defined `CliError`, we can impl -`From` with it: - -```rust -# #[derive(Debug)] -# enum CliError { Io(io::Error), Parse(num::ParseIntError) } -use std::io; -use std::num; - -impl From for CliError { - fn from(err: io::Error) -> CliError { - CliError::Io(err) - } -} - -impl From for CliError { - fn from(err: num::ParseIntError) -> CliError { - CliError::Parse(err) - } -} -``` - -All these impls are doing is teaching `From` how to create a `CliError` from -other error types. In our case, construction is as simple as invoking the -corresponding value constructor. Indeed, it is *typically* this easy. - -We can finally rewrite `file_double`: - -```rust -# use std::io; -# use std::num; -# enum CliError { Io(::std::io::Error), Parse(::std::num::ParseIntError) } -# impl From for CliError { -# fn from(err: io::Error) -> CliError { CliError::Io(err) } -# } -# impl From for CliError { -# fn from(err: num::ParseIntError) -> CliError { CliError::Parse(err) } -# } - -use std::fs::File; -use std::io::Read; -use std::path::Path; - -fn file_double>(file_path: P) -> Result { - let mut file = try!(File::open(file_path)); - let mut contents = String::new(); - try!(file.read_to_string(&mut contents)); - let n: i32 = try!(contents.trim().parse()); - Ok(2 * n) -} -``` - -The only thing we did here was remove the calls to `map_err`. They are no -longer needed because the `try!` macro invokes `From::from` on the error value. -This works because we've provided `From` impls for all the error types that -could appear. - -If we modified our `file_double` function to perform some other operation, say, -convert a string to a float, then we'd need to add a new variant to our error -type: - -```rust -use std::io; -use std::num; - -enum CliError { - Io(io::Error), - ParseInt(num::ParseIntError), - ParseFloat(num::ParseFloatError), -} -``` - -And add a new `From` impl: - -```rust -# enum CliError { -# Io(::std::io::Error), -# ParseInt(num::ParseIntError), -# ParseFloat(num::ParseFloatError), -# } - -use std::num; - -impl From for CliError { - fn from(err: num::ParseFloatError) -> CliError { - CliError::ParseFloat(err) - } -} -``` - -And that's it! - -## Advice for library writers - -If your library needs to report custom errors, then you should -probably define your own error type. It's up to you whether or not to -expose its representation (like -[`ErrorKind`](../../std/io/enum.ErrorKind.html)) or keep it hidden (like -[`ParseIntError`](../../std/num/struct.ParseIntError.html)). Regardless -of how you do it, it's usually good practice to at least provide some -information about the error beyond its `String` -representation. But certainly, this will vary depending on use cases. - -At a minimum, you should probably implement the -[`Error`](../../std/error/trait.Error.html) -trait. This will give users of your library some minimum flexibility for -[composing errors](#the-real-try-macro). Implementing the `Error` trait also -means that users are guaranteed the ability to obtain a string representation -of an error (because it requires impls for both `fmt::Debug` and -`fmt::Display`). - -Beyond that, it can also be useful to provide implementations of `From` on your -error types. This allows you (the library author) and your users to -[compose more detailed errors](#composing-custom-error-types). For example, -[`csv::Error`](http://burntsushi.net/rustdoc/csv/enum.Error.html) -provides `From` impls for both `io::Error` and `byteorder::Error`. - -Finally, depending on your tastes, you may also want to define a -[`Result` type alias](#the-result-type-alias-idiom), particularly if your -library defines a single error type. This is used in the standard library -for [`io::Result`](../../std/io/type.Result.html) -and [`fmt::Result`](../../std/fmt/type.Result.html). - -# Case study: A program to read population data - -This section was long, and depending on your background, it might be -rather dense. While there is plenty of example code to go along with -the prose, most of it was specifically designed to be pedagogical. So, -we're going to do something new: a case study. - -For this, we're going to build up a command line program that lets you -query world population data. The objective is simple: you give it a location -and it will tell you the population. Despite the simplicity, there is a lot -that can go wrong! - -The data we'll be using comes from the [Data Science -Toolkit][11]. I've prepared some data from it for this exercise. You -can either grab the [world population data][12] (41MB gzip compressed, -145MB uncompressed) or only the [US population data][13] (2.2MB gzip -compressed, 7.2MB uncompressed). - -Up until now, we've kept the code limited to Rust's standard library. For a real -task like this though, we'll want to at least use something to parse CSV data, -parse the program arguments and decode that stuff into Rust types automatically. For that, we'll use the -[`csv`](https://crates.io/crates/csv), -and [`rustc-serialize`](https://crates.io/crates/rustc-serialize) crates. - -## Initial setup - -We're not going to spend a lot of time on setting up a project with -Cargo because it is already covered well in [the Cargo -section](getting-started.html#hello-cargo) and [Cargo's documentation][14]. - -To get started from scratch, run `cargo new --bin city-pop` and make sure your -`Cargo.toml` looks something like this: - -```text -[package] -name = "city-pop" -version = "0.1.0" -authors = ["Andrew Gallant "] - -[[bin]] -name = "city-pop" - -[dependencies] -csv = "0.*" -rustc-serialize = "0.*" -getopts = "0.*" -``` - -You should already be able to run: - -```text -cargo build --release -./target/release/city-pop -# Outputs: Hello, world! -``` - -## Argument parsing - -Let's get argument parsing out of the way. We won't go into too much -detail on Getopts, but there is [some good documentation][15] -describing it. The short story is that Getopts generates an argument -parser and a help message from a vector of options (The fact that it -is a vector is hidden behind a struct and a set of methods). Once the -parsing is done, the parser returns a struct that records matches -for defined options, and remaining "free" arguments. -From there, we can get information about the flags, for -instance, whether they were passed in, and what arguments they -had. Here's our program with the appropriate `extern crate` -statements, and the basic argument setup for Getopts: - -```rust,ignore -extern crate getopts; -extern crate rustc_serialize; - -use getopts::Options; -use std::env; - -fn print_usage(program: &str, opts: Options) { - println!("{}", opts.usage(&format!("Usage: {} [options] ", program))); -} - -fn main() { - let args: Vec = env::args().collect(); - let program = &args[0]; - - let mut opts = Options::new(); - opts.optflag("h", "help", "Show this usage message."); - - let matches = match opts.parse(&args[1..]) { - Ok(m) => { m } - Err(e) => { panic!(e.to_string()) } - }; - if matches.opt_present("h") { - print_usage(&program, opts); - return; - } - let data_path = &matches.free[0]; - let city: &str = &matches.free[1]; - - // Do stuff with information. -} -``` - -First, we get a vector of the arguments passed into our program. We -then store the first one, knowing that it is our program's name. Once -that's done, we set up our argument flags, in this case a simplistic -help message flag. Once we have the argument flags set up, we use -`Options.parse` to parse the argument vector (starting from index one, -because index 0 is the program name). If this was successful, we -assign matches to the parsed object, if not, we panic. Once past that, -we test if the user passed in the help flag, and if so print the usage -message. The option help messages are constructed by Getopts, so all -we have to do to print the usage message is tell it what we want it to -print for the program name and template. If the user has not passed in -the help flag, we assign the proper variables to their corresponding -arguments. - -## Writing the logic - -We all write code differently, but error handling is usually the last thing we -want to think about. This isn't great for the overall design of a program, but -it can be useful for rapid prototyping. Because Rust forces us to be explicit -about error handling (by making us call `unwrap`), it is easy to see which -parts of our program can cause errors. - -In this case study, the logic is really simple. All we need to do is parse the -CSV data given to us and print out a field in matching rows. Let's do it. (Make -sure to add `extern crate csv;` to the top of your file.) - -```rust,ignore -use std::fs::File; - -// This struct represents the data in each row of the CSV file. -// Type based decoding absolves us of a lot of the nitty-gritty error -// handling, like parsing strings as integers or floats. -#[derive(Debug, RustcDecodable)] -struct Row { - country: String, - city: String, - accent_city: String, - region: String, - - // Not every row has data for the population, latitude or longitude! - // So we express them as `Option` types, which admits the possibility of - // absence. The CSV parser will fill in the correct value for us. - population: Option, - latitude: Option, - longitude: Option, -} - -fn print_usage(program: &str, opts: Options) { - println!("{}", opts.usage(&format!("Usage: {} [options] ", program))); -} - -fn main() { - let args: Vec = env::args().collect(); - let program = &args[0]; - - let mut opts = Options::new(); - opts.optflag("h", "help", "Show this usage message."); - - let matches = match opts.parse(&args[1..]) { - Ok(m) => { m } - Err(e) => { panic!(e.to_string()) } - }; - - if matches.opt_present("h") { - print_usage(&program, opts); - return; - } - - let data_path = &matches.free[0]; - let city: &str = &matches.free[1]; - - let file = File::open(data_path).unwrap(); - let mut rdr = csv::Reader::from_reader(file); - - for row in rdr.decode::() { - let row = row.unwrap(); - - if row.city == city { - println!("{}, {}: {:?}", - row.city, row.country, - row.population.expect("population count")); - } - } -} -``` - -Let's outline the errors. We can start with the obvious: the three places that -`unwrap` is called: - -1. [`File::open`](../../std/fs/struct.File.html#method.open) - can return an - [`io::Error`](../../std/io/struct.Error.html). -2. [`csv::Reader::decode`](http://burntsushi.net/rustdoc/csv/struct.Reader.html#method.decode) - decodes one record at a time, and - [decoding a - record](http://burntsushi.net/rustdoc/csv/struct.DecodedRecords.html) - (look at the `Item` associated type on the `Iterator` impl) - can produce a - [`csv::Error`](http://burntsushi.net/rustdoc/csv/enum.Error.html). -3. If `row.population` is `None`, then calling `expect` will panic. - -Are there any others? What if we can't find a matching city? Tools like `grep` -will return an error code, so we probably should too. So we have logic errors -specific to our problem, IO errors and CSV parsing errors. We're going to -explore two different ways to approach handling these errors. - -I'd like to start with `Box`. Later, we'll see how defining our own -error type can be useful. - -## Error handling with `Box` - -`Box` is nice because it *just works*. You don't need to define your own -error types and you don't need any `From` implementations. The downside is that -since `Box` is a trait object, it *erases the type*, which means the -compiler can no longer reason about its underlying type. - -[Previously](#the-limits-of-combinators) we started refactoring our code by -changing the type of our function from `T` to `Result`. In -this case, `OurErrorType` is only `Box`. But what's `T`? And can we add -a return type to `main`? - -The answer to the second question is no, we can't. That means we'll need to -write a new function. But what is `T`? The simplest thing we can do is to -return a list of matching `Row` values as a `Vec`. (Better code would -return an iterator, but that is left as an exercise to the reader.) - -Let's refactor our code into its own function, but keep the calls to `unwrap`. -Note that we opt to handle the possibility of a missing population count by -simply ignoring that row. - -```rust,ignore -use std::path::Path; - -struct Row { - // This struct remains unchanged. -} - -struct PopulationCount { - city: String, - country: String, - // This is no longer an `Option` because values of this type are only - // constructed if they have a population count. - count: u64, -} - -fn print_usage(program: &str, opts: Options) { - println!("{}", opts.usage(&format!("Usage: {} [options] ", program))); -} - -fn search>(file_path: P, city: &str) -> Vec { - let mut found = vec![]; - let file = File::open(file_path).unwrap(); - let mut rdr = csv::Reader::from_reader(file); - for row in rdr.decode::() { - let row = row.unwrap(); - match row.population { - None => { } // Skip it. - Some(count) => if row.city == city { - found.push(PopulationCount { - city: row.city, - country: row.country, - count: count, - }); - }, - } - } - found -} - -fn main() { - let args: Vec = env::args().collect(); - let program = &args[0]; - - let mut opts = Options::new(); - opts.optflag("h", "help", "Show this usage message."); - - let matches = match opts.parse(&args[1..]) { - Ok(m) => { m } - Err(e) => { panic!(e.to_string()) } - }; - - if matches.opt_present("h") { - print_usage(&program, opts); - return; - } - - let data_path = &matches.free[0]; - let city: &str = &matches.free[1]; - - for pop in search(data_path, city) { - println!("{}, {}: {:?}", pop.city, pop.country, pop.count); - } -} - -``` - -While we got rid of one use of `expect` (which is a nicer variant of `unwrap`), -we still should handle the absence of any search results. - -To convert this to proper error handling, we need to do the following: - -1. Change the return type of `search` to be `Result, - Box>`. -2. Use the [`try!` macro](#code-try-def) so that errors are returned to the - caller instead of panicking the program. -3. Handle the error in `main`. - -Let's try it: - -```rust,ignore -use std::error::Error; - -// The rest of the code before this is unchanged. - -fn search> - (file_path: P, city: &str) - -> Result, Box> { - let mut found = vec![]; - let file = try!(File::open(file_path)); - let mut rdr = csv::Reader::from_reader(file); - for row in rdr.decode::() { - let row = try!(row); - match row.population { - None => { } // Skip it. - Some(count) => if row.city == city { - found.push(PopulationCount { - city: row.city, - country: row.country, - count: count, - }); - }, - } - } - if found.is_empty() { - Err(From::from("No matching cities with a population were found.")) - } else { - Ok(found) - } -} -``` - -Instead of `x.unwrap()`, we now have `try!(x)`. Since our function returns a -`Result`, the `try!` macro will return early from the function if an -error occurs. - -At the end of `search` we also convert a plain string to an error type -by using the [corresponding `From` impls](../../std/convert/trait.From.html): - -```rust,ignore -// We are making use of this impl in the code above, since we call `From::from` -// on a `&'static str`. -impl<'a> From<&'a str> for Box - -// But this is also useful when you need to allocate a new string for an -// error message, usually with `format!`. -impl From for Box -``` - -Since `search` now returns a `Result`, `main` should use case analysis -when calling `search`: - -```rust,ignore -... - match search(data_path, city) { - Ok(pops) => { - for pop in pops { - println!("{}, {}: {:?}", pop.city, pop.country, pop.count); - } - } - Err(err) => println!("{}", err) - } -... -``` - -Now that we've seen how to do proper error handling with `Box`, let's -try a different approach with our own custom error type. But first, let's take -a quick break from error handling and add support for reading from `stdin`. - -## Reading from stdin - -In our program, we accept a single file for input and do one pass over the -data. This means we probably should be able to accept input on stdin. But maybe -we like the current format too—so let's have both! - -Adding support for stdin is actually quite easy. There are only three things we -have to do: - -1. Tweak the program arguments so that a single parameter—the - city—can be accepted while the population data is read from stdin. -2. Modify the program so that an option `-f` can take the file, if it - is not passed into stdin. -3. Modify the `search` function to take an *optional* file path. When `None`, - it should know to read from stdin. - -First, here's the new usage: - -```rust,ignore -fn print_usage(program: &str, opts: Options) { - println!("{}", opts.usage(&format!("Usage: {} [options] ", program))); -} -``` -Of course we need to adapt the argument handling code: - -```rust,ignore -... - let mut opts = Options::new(); - opts.optopt("f", "file", "Choose an input file, instead of using STDIN.", "NAME"); - opts.optflag("h", "help", "Show this usage message."); - ... - let data_path = matches.opt_str("f"); - - let city = if !matches.free.is_empty() { - &matches.free[0] - } else { - print_usage(&program, opts); - return; - }; - - match search(&data_path, city) { - Ok(pops) => { - for pop in pops { - println!("{}, {}: {:?}", pop.city, pop.country, pop.count); - } - } - Err(err) => println!("{}", err) - } -... -``` - -We've made the user experience a bit nicer by showing the usage message, -instead of a panic from an out-of-bounds index, when `city`, the -remaining free argument, is not present. - -Modifying `search` is slightly trickier. The `csv` crate can build a -parser out of -[any type that implements `io::Read`](http://burntsushi.net/rustdoc/csv/struct.Reader.html#method.from_reader). -But how can we use the same code over both types? There's actually a -couple ways we could go about this. One way is to write `search` such -that it is generic on some type parameter `R` that satisfies -`io::Read`. Another way is to use trait objects: - -```rust,ignore -use std::io; - -// The rest of the code before this is unchanged. - -fn search> - (file_path: &Option

, city: &str) - -> Result, Box> { - let mut found = vec![]; - let input: Box = match *file_path { - None => Box::new(io::stdin()), - Some(ref file_path) => Box::new(try!(File::open(file_path))), - }; - let mut rdr = csv::Reader::from_reader(input); - // The rest remains unchanged! -} -``` - -## Error handling with a custom type - -Previously, we learned how to -[compose errors using a custom error type](#composing-custom-error-types). -We did this by defining our error type as an `enum` and implementing `Error` -and `From`. - -Since we have three distinct errors (IO, CSV parsing and not found), let's -define an `enum` with three variants: - -```rust,ignore -#[derive(Debug)] -enum CliError { - Io(io::Error), - Csv(csv::Error), - NotFound, -} -``` - -And now for impls on `Display` and `Error`: - -```rust,ignore -use std::fmt; - -impl fmt::Display for CliError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - CliError::Io(ref err) => err.fmt(f), - CliError::Csv(ref err) => err.fmt(f), - CliError::NotFound => write!(f, "No matching cities with a \ - population were found."), - } - } -} - -impl Error for CliError { - fn description(&self) -> &str { - match *self { - CliError::Io(ref err) => err.description(), - CliError::Csv(ref err) => err.description(), - CliError::NotFound => "not found", - } - } - - fn cause(&self) -> Option<&Error> { - match *self { - CliError::Io(ref err) => Some(err), - CliError::Csv(ref err) => Some(err), - // Our custom error doesn't have an underlying cause, - // but we could modify it so that it does. - CliError::NotFound => None, - } - } -} -``` - -Before we can use our `CliError` type in our `search` function, we need to -provide a couple `From` impls. How do we know which impls to provide? Well, -we'll need to convert from both `io::Error` and `csv::Error` to `CliError`. -Those are the only external errors, so we'll only need two `From` impls for -now: - -```rust,ignore -impl From for CliError { - fn from(err: io::Error) -> CliError { - CliError::Io(err) - } -} - -impl From for CliError { - fn from(err: csv::Error) -> CliError { - CliError::Csv(err) - } -} -``` - -The `From` impls are important because of how -[`try!` is defined](#code-try-def). In particular, if an error occurs, -`From::from` is called on the error, which in this case, will convert it to our -own error type `CliError`. - -With the `From` impls done, we only need to make two small tweaks to our -`search` function: the return type and the “not found” error. Here it is in -full: - -```rust,ignore -fn search> - (file_path: &Option

, city: &str) - -> Result, CliError> { - let mut found = vec![]; - let input: Box = match *file_path { - None => Box::new(io::stdin()), - Some(ref file_path) => Box::new(try!(File::open(file_path))), - }; - let mut rdr = csv::Reader::from_reader(input); - for row in rdr.decode::() { - let row = try!(row); - match row.population { - None => { } // Skip it. - Some(count) => if row.city == city { - found.push(PopulationCount { - city: row.city, - country: row.country, - count: count, - }); - }, - } - } - if found.is_empty() { - Err(CliError::NotFound) - } else { - Ok(found) - } -} -``` - -No other changes are necessary. - -## Adding functionality - -Writing generic code is great, because generalizing stuff is cool, and -it can then be useful later. But sometimes, the juice isn't worth the -squeeze. Look at what we just did in the previous step: - -1. Defined a new error type. -2. Added impls for `Error`, `Display` and two for `From`. - -The big downside here is that our program didn't improve a whole lot. -There is quite a bit of overhead to representing errors with `enum`s, -especially in short programs like this. - -*One* useful aspect of using a custom error type like we've done here is that -the `main` function can now choose to handle errors differently. Previously, -with `Box`, it didn't have much of a choice: just print the message. -We're still doing that here, but what if we wanted to, say, add a `--quiet` -flag? The `--quiet` flag should silence any verbose output. - -Right now, if the program doesn't find a match, it will output a message saying -so. This can be a little clumsy, especially if you intend for the program to -be used in shell scripts. - -So let's start by adding the flags. Like before, we need to tweak the usage -string and add a flag to the Option variable. Once we've done that, Getopts does the rest: - -```rust,ignore -... - let mut opts = Options::new(); - opts.optopt("f", "file", "Choose an input file, instead of using STDIN.", "NAME"); - opts.optflag("h", "help", "Show this usage message."); - opts.optflag("q", "quiet", "Silences errors and warnings."); -... -``` - -Now we only need to implement our “quiet” functionality. This requires us to -tweak the case analysis in `main`: - -```rust,ignore -use std::process; -... - match search(&data_path, city) { - Err(CliError::NotFound) if matches.opt_present("q") => process::exit(1), - Err(err) => panic!("{}", err), - Ok(pops) => for pop in pops { - println!("{}, {}: {:?}", pop.city, pop.country, pop.count); - } - } -... -``` - -Certainly, we don't want to be quiet if there was an IO error or if the data -failed to parse. Therefore, we use case analysis to check if the error type is -`NotFound` *and* if `--quiet` has been enabled. If the search failed, we still -quit with an exit code (following `grep`'s convention). - -If we had stuck with `Box`, then it would be pretty tricky to implement -the `--quiet` functionality. - -This pretty much sums up our case study. From here, you should be ready to go -out into the world and write your own programs and libraries with proper error -handling. - -# The Short Story - -Since this section is long, it is useful to have a quick summary for error -handling in Rust. These are some good “rules of thumb." They are emphatically -*not* commandments. There are probably good reasons to break every one of these -heuristics! - -* If you're writing short example code that would be overburdened by error - handling, it's probably fine to use `unwrap` (whether that's - [`Result::unwrap`](../../std/result/enum.Result.html#method.unwrap), - [`Option::unwrap`](../../std/option/enum.Option.html#method.unwrap) - or preferably - [`Option::expect`](../../std/option/enum.Option.html#method.expect)). - Consumers of your code should know to use proper error handling. (If they - don't, send them here!) -* If you're writing a quick 'n' dirty program, don't feel ashamed if you use - `unwrap`. Be warned: if it winds up in someone else's hands, don't be - surprised if they are agitated by poor error messages! -* If you're writing a quick 'n' dirty program and feel ashamed about panicking - anyway, then use either a `String` or a `Box` for your - error type. -* Otherwise, in a program, define your own error types with appropriate - [`From`](../../std/convert/trait.From.html) - and - [`Error`](../../std/error/trait.Error.html) - impls to make the [`try!`](../../std/macro.try.html) - macro more ergonomic. -* If you're writing a library and your code can produce errors, define your own - error type and implement the - [`std::error::Error`](../../std/error/trait.Error.html) - trait. Where appropriate, implement - [`From`](../../std/convert/trait.From.html) to make both - your library code and the caller's code easier to write. (Because of Rust's - coherence rules, callers will not be able to impl `From` on your error type, - so your library should do it.) -* Learn the combinators defined on - [`Option`](../../std/option/enum.Option.html) - and - [`Result`](../../std/result/enum.Result.html). - Using them exclusively can be a bit tiring at times, but I've personally - found a healthy mix of `try!` and combinators to be quite appealing. - `and_then`, `map` and `unwrap_or` are my favorites. - -[1]: patterns.html -[2]: ../../std/option/enum.Option.html#method.map -[3]: ../../std/option/enum.Option.html#method.unwrap_or -[4]: ../../std/option/enum.Option.html#method.unwrap_or_else -[5]: ../../std/option/enum.Option.html -[6]: ../../std/result/index.html -[7]: ../../std/result/enum.Result.html#method.unwrap -[8]: ../../std/fmt/trait.Debug.html -[9]: ../../std/primitive.str.html#method.parse -[10]: associated-types.html -[11]: https://github.com/petewarden/dstkdata -[12]: http://burntsushi.net/stuff/worldcitiespop.csv.gz -[13]: http://burntsushi.net/stuff/uscitiespop.csv.gz -[14]: http://doc.crates.io/guide.html -[15]: http://doc.rust-lang.org/getopts/getopts/index.html +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). \ No newline at end of file diff --git a/first-edition/src/ffi.md b/first-edition/src/ffi.md index e01bf1830e..2adaff9d8f 100644 --- a/first-edition/src/ffi.md +++ b/first-edition/src/ffi.md @@ -1,758 +1,10 @@ # Foreign Function Interface -# Introduction +The first edition of the book is no longer distributed with Rust's documentation. -This guide will use the [snappy](https://github.com/google/snappy) -compression/decompression library as an introduction to writing bindings for -foreign code. Rust is currently unable to call directly into a C++ library, but -snappy includes a C interface (documented in -[`snappy-c.h`](https://github.com/google/snappy/blob/master/snappy-c.h)). +If you came here via a link or web search, you may want to check out [the current +version of the book](../ch19-01-unsafe-rust.html#calling-rust-functions-from-other-languages) instead. -## A note about libc - -Many of these examples use [the `libc` crate][libc], which provides various -type definitions for C types, among other things. If you’re trying these -examples yourself, you’ll need to add `libc` to your `Cargo.toml`: - -```toml -[dependencies] -libc = "0.2.0" -``` - -[libc]: https://crates.io/crates/libc - -and add `extern crate libc;` to your crate root. - -## Calling foreign functions - -The following is a minimal example of calling a foreign function which will -compile if snappy is installed: - -```rust,ignore -extern crate libc; -use libc::size_t; - -#[link(name = "snappy")] -extern { - fn snappy_max_compressed_length(source_length: size_t) -> size_t; -} - -fn main() { - let x = unsafe { snappy_max_compressed_length(100) }; - println!("max compressed length of a 100 byte buffer: {}", x); -} -``` - -The `extern` block is a list of function signatures in a foreign library, in -this case with the platform's C ABI. The `#[link(...)]` attribute is used to -instruct the linker to link against the snappy library so the symbols are -resolved. - -Foreign functions are assumed to be unsafe so calls to them need to be wrapped -with `unsafe {}` as a promise to the compiler that everything contained within -truly is safe. C libraries often expose interfaces that aren't thread-safe, and -almost any function that takes a pointer argument isn't valid for all possible -inputs since the pointer could be dangling, and raw pointers fall outside of -Rust's safe memory model. - -When declaring the argument types to a foreign function, the Rust compiler -cannot check if the declaration is correct, so specifying it correctly is part -of keeping the binding correct at runtime. - -The `extern` block can be extended to cover the entire snappy API: - -```rust,ignore -extern crate libc; -use libc::{c_int, size_t}; - -#[link(name = "snappy")] -extern { - fn snappy_compress(input: *const u8, - input_length: size_t, - compressed: *mut u8, - compressed_length: *mut size_t) -> c_int; - fn snappy_uncompress(compressed: *const u8, - compressed_length: size_t, - uncompressed: *mut u8, - uncompressed_length: *mut size_t) -> c_int; - fn snappy_max_compressed_length(source_length: size_t) -> size_t; - fn snappy_uncompressed_length(compressed: *const u8, - compressed_length: size_t, - result: *mut size_t) -> c_int; - fn snappy_validate_compressed_buffer(compressed: *const u8, - compressed_length: size_t) -> c_int; -} -# fn main() {} -``` - -# Creating a safe interface - -The raw C API needs to be wrapped to provide memory safety and make use of higher-level concepts -like vectors. A library can choose to expose only the safe, high-level interface and hide the unsafe -internal details. - -Wrapping the functions which expect buffers involves using the `slice::raw` module to manipulate Rust -vectors as pointers to memory. Rust's vectors are guaranteed to be a contiguous block of memory. The -length is the number of elements currently contained, and the capacity is the total size in elements of -the allocated memory. The length is less than or equal to the capacity. - -```rust,ignore -# extern crate libc; -# use libc::{c_int, size_t}; -# unsafe fn snappy_validate_compressed_buffer(_: *const u8, _: size_t) -> c_int { 0 } -# fn main() {} -pub fn validate_compressed_buffer(src: &[u8]) -> bool { - unsafe { - snappy_validate_compressed_buffer(src.as_ptr(), src.len() as size_t) == 0 - } -} -``` - -The `validate_compressed_buffer` wrapper above makes use of an `unsafe` block, but it makes the -guarantee that calling it is safe for all inputs by leaving off `unsafe` from the function -signature. - -The `snappy_compress` and `snappy_uncompress` functions are more complex, since a buffer has to be -allocated to hold the output too. - -The `snappy_max_compressed_length` function can be used to allocate a vector with the maximum -required capacity to hold the compressed output. The vector can then be passed to the -`snappy_compress` function as an output parameter. An output parameter is also passed to retrieve -the true length after compression for setting the length. - -```rust,ignore -# extern crate libc; -# use libc::{size_t, c_int}; -# unsafe fn snappy_compress(a: *const u8, b: size_t, c: *mut u8, -# d: *mut size_t) -> c_int { 0 } -# unsafe fn snappy_max_compressed_length(a: size_t) -> size_t { a } -# fn main() {} -pub fn compress(src: &[u8]) -> Vec { - unsafe { - let srclen = src.len() as size_t; - let psrc = src.as_ptr(); - - let mut dstlen = snappy_max_compressed_length(srclen); - let mut dst = Vec::with_capacity(dstlen as usize); - let pdst = dst.as_mut_ptr(); - - snappy_compress(psrc, srclen, pdst, &mut dstlen); - dst.set_len(dstlen as usize); - dst - } -} -``` - -Decompression is similar, because snappy stores the uncompressed size as part of the compression -format and `snappy_uncompressed_length` will retrieve the exact buffer size required. - -```rust,ignore -# extern crate libc; -# use libc::{size_t, c_int}; -# unsafe fn snappy_uncompress(compressed: *const u8, -# compressed_length: size_t, -# uncompressed: *mut u8, -# uncompressed_length: *mut size_t) -> c_int { 0 } -# unsafe fn snappy_uncompressed_length(compressed: *const u8, -# compressed_length: size_t, -# result: *mut size_t) -> c_int { 0 } -# fn main() {} -pub fn uncompress(src: &[u8]) -> Option> { - unsafe { - let srclen = src.len() as size_t; - let psrc = src.as_ptr(); - - let mut dstlen: size_t = 0; - snappy_uncompressed_length(psrc, srclen, &mut dstlen); - - let mut dst = Vec::with_capacity(dstlen as usize); - let pdst = dst.as_mut_ptr(); - - if snappy_uncompress(psrc, srclen, pdst, &mut dstlen) == 0 { - dst.set_len(dstlen as usize); - Some(dst) - } else { - None // SNAPPY_INVALID_INPUT - } - } -} -``` - -Then, we can add some tests to show how to use them. - -```rust,ignore -# extern crate libc; -# use libc::{c_int, size_t}; -# unsafe fn snappy_compress(input: *const u8, -# input_length: size_t, -# compressed: *mut u8, -# compressed_length: *mut size_t) -# -> c_int { 0 } -# unsafe fn snappy_uncompress(compressed: *const u8, -# compressed_length: size_t, -# uncompressed: *mut u8, -# uncompressed_length: *mut size_t) -# -> c_int { 0 } -# unsafe fn snappy_max_compressed_length(source_length: size_t) -> size_t { 0 } -# unsafe fn snappy_uncompressed_length(compressed: *const u8, -# compressed_length: size_t, -# result: *mut size_t) -# -> c_int { 0 } -# unsafe fn snappy_validate_compressed_buffer(compressed: *const u8, -# compressed_length: size_t) -# -> c_int { 0 } -# fn main() { } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn valid() { - let d = vec![0xde, 0xad, 0xd0, 0x0d]; - let c: &[u8] = &compress(&d); - assert!(validate_compressed_buffer(c)); - assert!(uncompress(c) == Some(d)); - } - - #[test] - fn invalid() { - let d = vec![0, 0, 0, 0]; - assert!(!validate_compressed_buffer(&d)); - assert!(uncompress(&d).is_none()); - } - - #[test] - fn empty() { - let d = vec![]; - assert!(!validate_compressed_buffer(&d)); - assert!(uncompress(&d).is_none()); - let c = compress(&d); - assert!(validate_compressed_buffer(&c)); - assert!(uncompress(&c) == Some(d)); - } -} -``` - -# Destructors - -Foreign libraries often hand off ownership of resources to the calling code. -When this occurs, we must use Rust's destructors to provide safety and guarantee -the release of these resources (especially in the case of panic). - -For more about destructors, see the [Drop trait](../../std/ops/trait.Drop.html). - -# Callbacks from C code to Rust functions - -Some external libraries require the usage of callbacks to report back their -current state or intermediate data to the caller. -It is possible to pass functions defined in Rust to an external library. -The requirement for this is that the callback function is marked as `extern` -with the correct calling convention to make it callable from C code. - -The callback function can then be sent through a registration call -to the C library and afterwards be invoked from there. - -A basic example is: - -Rust code: - -```rust,no_run -extern fn callback(a: i32) { - println!("I'm called from C with value {0}", a); -} - -#[link(name = "extlib")] -extern { - fn register_callback(cb: extern fn(i32)) -> i32; - fn trigger_callback(); -} - -fn main() { - unsafe { - register_callback(callback); - trigger_callback(); // Triggers the callback. - } -} -``` - -C code: - -```c -typedef void (*rust_callback)(int32_t); -rust_callback cb; - -int32_t register_callback(rust_callback callback) { - cb = callback; - return 1; -} - -void trigger_callback() { - cb(7); // Will call callback(7) in Rust. -} -``` - -In this example Rust's `main()` will call `trigger_callback()` in C, -which would, in turn, call back to `callback()` in Rust. - - -## Targeting callbacks to Rust objects - -The former example showed how a global function can be called from C code. -However it is often desired that the callback is targeted to a special -Rust object. This could be the object that represents the wrapper for the -respective C object. - -This can be achieved by passing a raw pointer to the object down to the -C library. The C library can then include the pointer to the Rust object in -the notification. This will allow the callback to unsafely access the -referenced Rust object. - -Rust code: - -```rust,no_run -#[repr(C)] -struct RustObject { - a: i32, - // Other members... -} - -extern "C" fn callback(target: *mut RustObject, a: i32) { - println!("I'm called from C with value {0}", a); - unsafe { - // Update the value in RustObject with the value received from the callback: - (*target).a = a; - } -} - -#[link(name = "extlib")] -extern { - fn register_callback(target: *mut RustObject, - cb: extern fn(*mut RustObject, i32)) -> i32; - fn trigger_callback(); -} - -fn main() { - // Create the object that will be referenced in the callback: - let mut rust_object = Box::new(RustObject { a: 5 }); - - unsafe { - register_callback(&mut *rust_object, callback); - trigger_callback(); - } -} -``` - -C code: - -```c -typedef void (*rust_callback)(void*, int32_t); -void* cb_target; -rust_callback cb; - -int32_t register_callback(void* callback_target, rust_callback callback) { - cb_target = callback_target; - cb = callback; - return 1; -} - -void trigger_callback() { - cb(cb_target, 7); // Will call callback(&rustObject, 7) in Rust. -} -``` - -## Asynchronous callbacks - -In the previously given examples the callbacks are invoked as a direct reaction -to a function call to the external C library. -The control over the current thread is switched from Rust to C to Rust for the -execution of the callback, but in the end the callback is executed on the -same thread that called the function which triggered the callback. - -Things get more complicated when the external library spawns its own threads -and invokes callbacks from there. -In these cases access to Rust data structures inside the callbacks is -especially unsafe and proper synchronization mechanisms must be used. -Besides classical synchronization mechanisms like mutexes, one possibility in -Rust is to use channels (in `std::sync::mpsc`) to forward data from the C -thread that invoked the callback into a Rust thread. - -If an asynchronous callback targets a special object in the Rust address space -it is also absolutely necessary that no more callbacks are performed by the -C library after the respective Rust object gets destroyed. -This can be achieved by unregistering the callback in the object's -destructor and designing the library in a way that guarantees that no -callback will be performed after deregistration. - -# Linking - -The `link` attribute on `extern` blocks provides the basic building block for -instructing rustc how it will link to native libraries. There are two accepted -forms of the link attribute today: - -* `#[link(name = "foo")]` -* `#[link(name = "foo", kind = "bar")]` - -In both of these cases, `foo` is the name of the native library that we're -linking to, and in the second case `bar` is the type of native library that the -compiler is linking to. There are currently three known types of native -libraries: - -* Dynamic - `#[link(name = "readline")]` -* Static - `#[link(name = "my_build_dependency", kind = "static")]` -* Frameworks - `#[link(name = "CoreFoundation", kind = "framework")]` - -Note that frameworks are only available on macOS targets. - -The different `kind` values are meant to differentiate how the native library -participates in linkage. From a linkage perspective, the Rust compiler creates -two flavors of artifacts: partial (rlib/staticlib) and final (dylib/binary). -Native dynamic library and framework dependencies are propagated to the final -artifact boundary, while static library dependencies are not propagated at -all, because the static libraries are integrated directly into the subsequent -artifact. - -A few examples of how this model can be used are: - -* A native build dependency. Sometimes some C/C++ glue is needed when writing - some Rust code, but distribution of the C/C++ code in a library format is - a burden. In this case, the code will be archived into `libfoo.a` and then the - Rust crate would declare a dependency via `#[link(name = "foo", kind = - "static")]`. - - Regardless of the flavor of output for the crate, the native static library - will be included in the output, meaning that distribution of the native static - library is not necessary. - -* A normal dynamic dependency. Common system libraries (like `readline`) are - available on a large number of systems, and often a static copy of these - libraries cannot be found. When this dependency is included in a Rust crate, - partial targets (like rlibs) will not link to the library, but when the rlib - is included in a final target (like a binary), the native library will be - linked in. - -On macOS, frameworks behave with the same semantics as a dynamic library. - -# Unsafe blocks - -Some operations, like dereferencing raw pointers or calling functions that have been marked -unsafe are only allowed inside unsafe blocks. Unsafe blocks isolate unsafety and are a promise to -the compiler that the unsafety does not leak out of the block. - -Unsafe functions, on the other hand, advertise it to the world. An unsafe function is written like -this: - -```rust -unsafe fn kaboom(ptr: *const i32) -> i32 { *ptr } -``` - -This function can only be called from an `unsafe` block or another `unsafe` function. - -# Accessing foreign globals - -Foreign APIs often export a global variable which could do something like track -global state. In order to access these variables, you declare them in `extern` -blocks with the `static` keyword: - -```rust,ignore -extern crate libc; - -#[link(name = "readline")] -extern { - static rl_readline_version: libc::c_int; -} - -fn main() { - println!("You have readline version {} installed.", - unsafe { rl_readline_version as i32 }); -} -``` - -Alternatively, you may need to alter global state provided by a foreign -interface. To do this, statics can be declared with `mut` so we can mutate -them. - -```rust,ignore -extern crate libc; - -use std::ffi::CString; -use std::ptr; - -#[link(name = "readline")] -extern { - static mut rl_prompt: *const libc::c_char; -} - -fn main() { - let prompt = CString::new("[my-awesome-shell] $").unwrap(); - unsafe { - rl_prompt = prompt.as_ptr(); - - println!("{:?}", rl_prompt); - - rl_prompt = ptr::null(); - } -} -``` - -Note that all interaction with a `static mut` is unsafe, both reading and -writing. Dealing with global mutable state requires a great deal of care. - -# Foreign calling conventions - -Most foreign code exposes a C ABI, and Rust uses the platform's C calling convention by default when -calling foreign functions. Some foreign functions, most notably the Windows API, use other calling -conventions. Rust provides a way to tell the compiler which convention to use: - -```rust,ignore -extern crate libc; - -#[cfg(all(target_os = "win32", target_arch = "x86"))] -#[link(name = "kernel32")] -#[allow(non_snake_case)] -extern "stdcall" { - fn SetEnvironmentVariableA(n: *const u8, v: *const u8) -> libc::c_int; -} -# fn main() { } -``` - -This applies to the entire `extern` block. The list of supported ABI constraints -are: - -* `stdcall` -* `aapcs` -* `cdecl` -* `fastcall` -* `vectorcall` -This is currently hidden behind the `abi_vectorcall` gate and is subject to change. -* `Rust` -* `rust-intrinsic` -* `system` -* `C` -* `win64` -* `sysv64` - -Most of the ABIs in this list are self-explanatory, but the `system` ABI may -seem a little odd. This constraint selects whatever the appropriate ABI is for -interoperating with the target's libraries. For example, on win32 with a x86 -architecture, this means that the ABI used would be `stdcall`. On x86_64, -however, windows uses the `C` calling convention, so `C` would be used. This -means that in our previous example, we could have used `extern "system" { ... }` -to define a block for all windows systems, not only x86 ones. - -# Interoperability with foreign code - -Rust guarantees that the layout of a `struct` is compatible with the platform's -representation in C only if the `#[repr(C)]` attribute is applied to it. -`#[repr(C, packed)]` can be used to lay out struct members without padding. -`#[repr(C)]` can also be applied to an enum. - -Rust's owned boxes (`Box`) use non-nullable pointers as handles which point -to the contained object. However, they should not be manually created because -they are managed by internal allocators. References can safely be assumed to be -non-nullable pointers directly to the type. However, breaking the borrow -checking or mutability rules is not guaranteed to be safe, so prefer using raw -pointers (`*`) if that's needed because the compiler can't make as many -assumptions about them. - -Vectors and strings share the same basic memory layout, and utilities are -available in the `vec` and `str` modules for working with C APIs. However, -strings are not terminated with `\0`. If you need a NUL-terminated string for -interoperability with C, you should use the `CString` type in the `std::ffi` -module. - -The [`libc` crate on crates.io][libc] includes type aliases and function -definitions for the C standard library in the `libc` module, and Rust links -against `libc` and `libm` by default. - -# Variadic functions - -In C, functions can be 'variadic', meaning they accept a variable number of arguments. This can -be achieved in Rust by specifying `...` within the argument list of a foreign function declaration: - -```rust,no_run -extern { - fn foo(x: i32, ...); -} - -fn main() { - unsafe { - foo(10, 20, 30, 40, 50); - } -} -``` - -Normal Rust functions can *not* be variadic: - -```rust,ignore -// This will not compile - -fn foo(x: i32, ...) { } -``` - -# The "nullable pointer optimization" - -Certain Rust types are defined to never be `null`. This includes references (`&T`, -`&mut T`), boxes (`Box`), and function pointers (`extern "abi" fn()`). When -interfacing with C, pointers that might be `null` are often used, which would seem to -require some messy `transmute`s and/or unsafe code to handle conversions to/from Rust types. -However, the language provides a workaround. - -As a special case, an `enum` is eligible for the "nullable pointer optimization" if it contains -exactly two variants, one of which contains no data and the other contains a field of one of the -non-nullable types listed above. This means no extra space is required for a discriminant; rather, -the empty variant is represented by putting a `null` value into the non-nullable field. This is -called an "optimization", but unlike other optimizations it is guaranteed to apply to eligible -types. - -The most common type that takes advantage of the nullable pointer optimization is `Option`, -where `None` corresponds to `null`. So `Option c_int>` is a correct way -to represent a nullable function pointer using the C ABI (corresponding to the C type -`int (*)(int)`). - -Here is a contrived example. Let's say some C library has a facility for registering a -callback, which gets called in certain situations. The callback is passed a function pointer -and an integer and it is supposed to run the function with the integer as a parameter. So -we have function pointers flying across the FFI boundary in both directions. - -```rust,ignore -extern crate libc; -use libc::c_int; - -# #[cfg(hidden)] -extern "C" { - /// Registers the callback. - fn register(cb: Option c_int>, c_int) -> c_int>); -} -# unsafe fn register(_: Option c_int>, -# c_int) -> c_int>) -# {} - -/// This fairly useless function receives a function pointer and an integer -/// from C, and returns the result of calling the function with the integer. -/// In case no function is provided, it squares the integer by default. -extern "C" fn apply(process: Option c_int>, int: c_int) -> c_int { - match process { - Some(f) => f(int), - None => int * int - } -} - -fn main() { - unsafe { - register(Some(apply)); - } -} -``` - -And the code on the C side looks like this: - -```c -void register(void (*f)(void (*)(int), int)) { - ... -} -``` - -No `transmute` required! - -# Calling Rust code from C - -You may wish to compile Rust code in a way so that it can be called from C. This is -fairly easy, but requires a few things: - -```rust -#[no_mangle] -pub extern fn hello_rust() -> *const u8 { - "Hello, world!\0".as_ptr() -} -# fn main() {} -``` - -The `extern` makes this function adhere to the C calling convention, as -discussed above in "[Foreign Calling -Conventions](ffi.html#foreign-calling-conventions)". The `no_mangle` -attribute turns off Rust's name mangling, so that it is easier to link to. - -# FFI and panics - -It’s important to be mindful of `panic!`s when working with FFI. A `panic!` -across an FFI boundary is undefined behavior. If you’re writing code that may -panic, you should run it in a closure with [`catch_unwind`]: - -```rust -use std::panic::catch_unwind; - -#[no_mangle] -pub extern fn oh_no() -> i32 { - let result = catch_unwind(|| { - panic!("Oops!"); - }); - match result { - Ok(_) => 0, - Err(_) => 1, - } -} - -fn main() {} -``` - -Please note that [`catch_unwind`] will only catch unwinding panics, not -those who abort the process. See the documentation of [`catch_unwind`] -for more information. - -[`catch_unwind`]: ../../std/panic/fn.catch_unwind.html - -# Representing opaque structs - -Sometimes, a C library wants to provide a pointer to something, but not let you -know the internal details of the thing it wants. The simplest way is to use a -`void *` argument: - -```c -void foo(void *arg); -void bar(void *arg); -``` - -We can represent this in Rust with the `c_void` type: - -```rust,ignore -extern crate libc; - -extern "C" { - pub fn foo(arg: *mut libc::c_void); - pub fn bar(arg: *mut libc::c_void); -} -# fn main() {} -``` - -This is a perfectly valid way of handling the situation. However, we can do a bit -better. To solve this, some C libraries will instead create a `struct`, where -the details and memory layout of the struct are private. This gives some amount -of type safety. These structures are called ‘opaque’. Here’s an example, in C: - -```c -struct Foo; /* Foo is a structure, but its contents are not part of the public interface */ -struct Bar; -void foo(struct Foo *arg); -void bar(struct Bar *arg); -``` - -To do this in Rust, let’s create our own opaque types: - -```rust -#[repr(C)] pub struct Foo { private: [u8; 0] } -#[repr(C)] pub struct Bar { private: [u8; 0] } - -extern "C" { - pub fn foo(arg: *mut Foo); - pub fn bar(arg: *mut Bar); -} -# fn main() {} -``` - -By including a private field and no constructor, -we create an opaque type that we can’t instantiate outside of this module. -An empty array is both zero-size and compatible with `#[repr(C)]`. -But because our `Foo` and `Bar` types are -different, we’ll get type safety between the two of them, so we cannot -accidentally pass a pointer to `Foo` to `bar()`. +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). diff --git a/first-edition/src/functions.md b/first-edition/src/functions.md index 96c8e9f5d6..b6af0f670f 100644 --- a/first-edition/src/functions.md +++ b/first-edition/src/functions.md @@ -1,336 +1,10 @@ # Functions -Every Rust program has at least one function, the `main` function: +The first edition of the book is no longer distributed with Rust's documentation. -```rust -fn main() { -} -``` +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. -This is the simplest possible function declaration. As we mentioned before, -`fn` says ‘this is a function’, followed by the name, some parentheses because -this function takes no arguments, and then some curly braces to indicate the -body. Here’s a function named `foo`: - -```rust -fn foo() { -} -``` - -So, what about taking arguments? Here’s a function that prints a number: - -```rust -fn print_number(x: i32) { - println!("x is: {}", x); -} -``` - -Here’s a complete program that uses `print_number`: - -```rust -fn main() { - print_number(5); -} - -fn print_number(x: i32) { - println!("x is: {}", x); -} -``` - -As you can see, function arguments work very similar to `let` declarations: -you add a type to the argument name, after a colon. - -Here’s a complete program that adds two numbers together and prints them: - -```rust -fn main() { - print_sum(5, 6); -} - -fn print_sum(x: i32, y: i32) { - println!("sum is: {}", x + y); -} -``` - -You separate arguments with a comma, both when you call the function, as well -as when you declare it. - -Unlike `let`, you _must_ declare the types of function arguments. This does -not work: - -```rust,ignore -fn print_sum(x, y) { - println!("sum is: {}", x + y); -} -``` - -You get this error: - -```text -expected one of `!`, `:`, or `@`, found `)` -fn print_sum(x, y) { -``` - -This is a deliberate design decision. While full-program inference is possible, -languages which have it, like Haskell, often suggest that documenting your -types explicitly is a best-practice. We agree that forcing functions to declare -types while allowing for inference inside of function bodies is a wonderful -sweet spot between full inference and no inference. - -What about returning a value? Here’s a function that adds one to an integer: - -```rust -fn add_one(x: i32) -> i32 { - x + 1 -} -``` - -Rust functions return exactly one value, and you declare the type after an -‘arrow’, which is a dash (`-`) followed by a greater-than sign (`>`). The last -line of a function determines what it returns. You’ll note the lack of a -semicolon here. If we added it in: - -```rust,ignore -fn add_one(x: i32) -> i32 { - x + 1; -} -``` - -We would get an error: - -```text -error: not all control paths return a value -fn add_one(x: i32) -> i32 { - x + 1; -} - -help: consider removing this semicolon: - x + 1; - ^ -``` - -This reveals two interesting things about Rust: it is an expression-based -language, and semicolons are different from semicolons in other ‘curly brace -and semicolon’-based languages. These two things are related. - -## Expressions vs. Statements - -Rust is primarily an expression-based language. There are only two kinds of -statements, and everything else is an expression. - -So what's the difference? Expressions return a value, and statements do not. -That’s why we end up with ‘not all control paths return a value’ here: the -statement `x + 1;` doesn’t return a value. There are two kinds of statements in -Rust: ‘declaration statements’ and ‘expression statements’. Everything else is -an expression. Let’s talk about declaration statements first. - -In some languages, variable bindings can be written as expressions, not -statements. Like Ruby: - -```ruby -x = y = 5 -``` - -In Rust, however, using `let` to introduce a binding is _not_ an expression. The -following will produce a compile-time error: - -```rust,ignore -let x = (let y = 5); // Expected identifier, found keyword `let`. -``` - -The compiler is telling us here that it was expecting to see the beginning of -an expression, and a `let` can only begin a statement, not an expression. - -Note that assigning to an already-bound variable (e.g. `y = 5`) is still an -expression, although its value is not particularly useful. Unlike other -languages where an assignment evaluates to the assigned value (e.g. `5` in the -previous example), in Rust the value of an assignment is an empty tuple `()` -because the assigned value can have [only one owner](ownership.html), and any -other returned value would be too surprising: - -```rust -let mut y = 5; - -let x = (y = 6); // `x` has the value `()`, not `6`. -``` - -The second kind of statement in Rust is the *expression statement*. Its -purpose is to turn any expression into a statement. In practical terms, Rust's -grammar expects statements to follow other statements. This means that you use -semicolons to separate expressions from each other. This means that Rust -looks a lot like most other languages that require you to use semicolons -at the end of every line, and you will see semicolons at the end of almost -every line of Rust code you see. - -What is this exception that makes us say "almost"? You saw it already, in this -code: - -```rust -fn add_one(x: i32) -> i32 { - x + 1 -} -``` - -Our function claims to return an `i32`, but with a semicolon, it would return -`()` instead. Rust realizes this probably isn’t what we want, and suggests -removing the semicolon in the error we saw before. - -## Early returns - -But what about early returns? Rust does have a keyword for that, `return`: - -```rust -fn foo(x: i32) -> i32 { - return x; - - // We never run this code! - x + 1 -} -``` - -Using a `return` as the last line of a function works, but is considered poor -style: - -```rust -fn foo(x: i32) -> i32 { - return x + 1; -} -``` - -The previous definition without `return` may look a bit strange if you haven’t -worked in an expression-based language before, but it becomes intuitive over -time. - -## Diverging functions - -Rust has some special syntax for ‘diverging functions’, which are functions that -do not return: - -```rust -fn diverges() -> ! { - panic!("This function never returns!"); -} -``` - -`panic!` is a macro, similar to `println!()` that we’ve already seen. Unlike -`println!()`, `panic!()` causes the current thread of execution to crash with -the given message. Because this function will cause a crash, it will never -return, and so it has the type ‘`!`’, which is read ‘diverges’. - -If you add a main function that calls `diverges()` and run it, you’ll get -some output that looks like this: - -```text -thread ‘main’ panicked at ‘This function never returns!’, hello.rs:2 -``` - -If you want more information, you can get a backtrace by setting the -`RUST_BACKTRACE` environment variable: - -```text -$ RUST_BACKTRACE=1 ./diverges -thread 'main' panicked at 'This function never returns!', hello.rs:2 -Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace. -stack backtrace: - hello::diverges - at ./hello.rs:2 - hello::main - at ./hello.rs:6 -``` - -If you want the complete backtrace and filenames: - -```text -$ RUST_BACKTRACE=full ./diverges -thread 'main' panicked at 'This function never returns!', hello.rs:2 -stack backtrace: - 1: 0x7f402773a829 - sys::backtrace::write::h0942de78b6c02817K8r - 2: 0x7f402773d7fc - panicking::on_panic::h3f23f9d0b5f4c91bu9w - 3: 0x7f402773960e - rt::unwind::begin_unwind_inner::h2844b8c5e81e79558Bw - 4: 0x7f4027738893 - rt::unwind::begin_unwind::h4375279447423903650 - 5: 0x7f4027738809 - diverges::h2266b4c4b850236beaa - 6: 0x7f40277389e5 - main::h19bb1149c2f00ecfBaa - 7: 0x7f402773f514 - rt::unwind::try::try_fn::h13186883479104382231 - 8: 0x7f402773d1d8 - __rust_try - 9: 0x7f402773f201 - rt::lang_start::ha172a3ce74bb453aK5w - 10: 0x7f4027738a19 - main - 11: 0x7f402694ab44 - __libc_start_main - 12: 0x7f40277386c8 - - 13: 0x0 - -``` - -If you need to override an already set `RUST_BACKTRACE`, -in cases when you cannot just unset the variable, -then set it to `0` to avoid getting a backtrace. -Any other value (even no value at all) turns on backtrace. - -```text -$ export RUST_BACKTRACE=1 -... -$ RUST_BACKTRACE=0 ./diverges -thread 'main' panicked at 'This function never returns!', hello.rs:2 -note: Run with `RUST_BACKTRACE=1` for a backtrace. -``` - -`RUST_BACKTRACE` also works with Cargo’s `run` command: - -```text -$ RUST_BACKTRACE=full cargo run - Running `target/debug/diverges` -thread 'main' panicked at 'This function never returns!', hello.rs:2 -stack backtrace: - 1: 0x7f402773a829 - sys::backtrace::write::h0942de78b6c02817K8r - 2: 0x7f402773d7fc - panicking::on_panic::h3f23f9d0b5f4c91bu9w - 3: 0x7f402773960e - rt::unwind::begin_unwind_inner::h2844b8c5e81e79558Bw - 4: 0x7f4027738893 - rt::unwind::begin_unwind::h4375279447423903650 - 5: 0x7f4027738809 - diverges::h2266b4c4b850236beaa - 6: 0x7f40277389e5 - main::h19bb1149c2f00ecfBaa - 7: 0x7f402773f514 - rt::unwind::try::try_fn::h13186883479104382231 - 8: 0x7f402773d1d8 - __rust_try - 9: 0x7f402773f201 - rt::lang_start::ha172a3ce74bb453aK5w - 10: 0x7f4027738a19 - main - 11: 0x7f402694ab44 - __libc_start_main - 12: 0x7f40277386c8 - - 13: 0x0 - -``` - -A diverging function can be used as any type: - -```rust,should_panic -# fn diverges() -> ! { -# panic!("This function never returns!"); -# } -let x: i32 = diverges(); -let x: String = diverges(); -``` - -## Function pointers - -We can also create variable bindings which point to functions: - -```rust -let f: fn(i32) -> i32; -``` - -`f` is a variable binding which points to a function that takes an `i32` as -an argument and returns an `i32`. For example: - -```rust -fn plus_one(i: i32) -> i32 { - i + 1 -} - -// Without type inference: -let f: fn(i32) -> i32 = plus_one; - -// With type inference: -let f = plus_one; -``` - -We can then use `f` to call the function: - -```rust -# fn plus_one(i: i32) -> i32 { i + 1 } -# let f = plus_one; -let six = f(5); -``` +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). diff --git a/first-edition/src/generics.md b/first-edition/src/generics.md index 891380c2d0..953ba03e27 100644 --- a/first-edition/src/generics.md +++ b/first-edition/src/generics.md @@ -1,190 +1,10 @@ # Generics -Sometimes, when writing a function or data type, we may want it to work for -multiple types of arguments. In Rust, we can do this with generics. -Generics are called ‘parametric polymorphism’ in type theory, -which means that they are types or functions that have multiple forms (‘poly’ -is multiple, ‘morph’ is form) over a given parameter (‘parametric’). +The first edition of the book is no longer distributed with Rust's documentation. -Anyway, enough type theory, let’s check out some generic code. Rust’s -standard library provides a type, `Option`, that’s generic: +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. -```rust -enum Option { - Some(T), - None, -} -``` - -The `` part, which you’ve seen a few times before, indicates that this is -a generic data type. Inside the declaration of our `enum`, wherever we see a `T`, -we substitute that type for the same type used in the generic. Here’s an -example of using `Option`, with some extra type annotations: - -```rust -let x: Option = Some(5); -``` - -In the type declaration, we say `Option`. Note how similar this looks to -`Option`. So, in this particular `Option`, `T` has the value of `i32`. On -the right-hand side of the binding, we make a `Some(T)`, where `T` is `5`. -Since that’s an `i32`, the two sides match, and Rust is happy. If they didn’t -match, we’d get an error: - -```rust,ignore -let x: Option = Some(5); -// error: mismatched types: expected `core::option::Option`, -// found `core::option::Option<_>` (expected f64 but found integral variable) -``` - -That doesn’t mean we can’t make `Option`s that hold an `f64`! They have -to match up: - -```rust -let x: Option = Some(5); -let y: Option = Some(5.0f64); -``` - -This is just fine. One definition, multiple uses. - -Generics don’t have to only be generic over one type. Consider another type from Rust’s standard library that’s similar, `Result`: - -```rust -enum Result { - Ok(T), - Err(E), -} -``` - -This type is generic over _two_ types: `T` and `E`. By the way, the capital letters -can be any letter you’d like. We could define `Result` as: - -```rust -enum Result { - Ok(A), - Err(Z), -} -``` - -if we wanted to. Convention says that the first generic parameter should be -`T`, for ‘type’, and that we use `E` for ‘error’. Rust doesn’t care, however. - -The `Result` type is intended to be used to return the result of a -computation, and to have the ability to return an error if it didn’t work out. - -## Generic functions - -We can write functions that take generic types with a similar syntax: - -```rust -fn takes_anything(x: T) { - // Do something with `x`. -} -``` - -The syntax has two parts: the `` says “this function is generic over one -type, `T`”, and the `x: T` says “x has the type `T`.” - -Multiple arguments can have the same generic type: - -```rust -fn takes_two_of_the_same_things(x: T, y: T) { - // ... -} -``` - -We could write a version that takes multiple types: - -```rust -fn takes_two_things(x: T, y: U) { - // ... -} -``` - -## Generic structs - -You can store a generic type in a `struct` as well: - -```rust -struct Point { - x: T, - y: T, -} - -let int_origin = Point { x: 0, y: 0 }; -let float_origin = Point { x: 0.0, y: 0.0 }; -``` - -Similar to functions, the `` is where we declare the generic parameters, -and we then use `x: T` in the type declaration, too. - -When you want to add an implementation for the generic `struct`, you -declare the type parameter after the `impl`: - -```rust -# struct Point { -# x: T, -# y: T, -# } -# -impl Point { - fn swap(&mut self) { - std::mem::swap(&mut self.x, &mut self.y); - } -} -``` - -So far you’ve seen generics that take absolutely any type. These are useful in -many cases: you’ve already seen `Option`, and later you’ll meet universal -container types like [`Vec`][Vec]. On the other hand, often you want to -trade that flexibility for increased expressive power. Read about [trait -bounds][traits] to see why and how. - -## Resolving ambiguities - -Most of the time when generics are involved, the compiler can infer the -generic parameters automatically: - -```rust -// v must be a Vec but we don't know what T is yet -let mut v = Vec::new(); -// v just got a bool value, so T must be bool! -v.push(true); -// Debug-print v -println!("{:?}", v); -``` - -Sometimes though, the compiler needs a little help. For example, had we -omitted the last line, we would get a compile error: - -```rust,ignore -let v = Vec::new(); -// ^^^^^^^^ cannot infer type for `T` -// -// note: type annotations or generic parameter binding required -println!("{:?}", v); -``` - -We can solve this using either a type annotation: - -```rust -let v: Vec = Vec::new(); -println!("{:?}", v); -``` - -or by binding the generic parameter `T` via the so-called -[‘turbofish’][turbofish] `::<>` syntax: - -```rust -let v = Vec::::new(); -println!("{:?}", v); -``` - -The second approach is useful in situations where we don’t want to bind the -result to a variable. It can also be used to bind generic parameters in -functions or methods. See [Iterators § Consumers](iterators.html#consumers) -for an example. - -[traits]: traits.html -[Vec]: ../../std/vec/struct.Vec.html -[turbofish]: ../../std/iter/trait.Iterator.html#method.collect +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). diff --git a/first-edition/src/getting-started.md b/first-edition/src/getting-started.md index 06ea24fef3..cd3ccf7757 100644 --- a/first-edition/src/getting-started.md +++ b/first-edition/src/getting-started.md @@ -1,550 +1,10 @@ # Getting Started -This first chapter of the book will get us going with Rust and its tooling. -First, we’ll install Rust. Then, the classic ‘Hello World’ program. Finally, -we’ll talk about Cargo, Rust’s build system and package manager. +The first edition of the book is no longer distributed with Rust's documentation. -We’ll be showing off a number of commands using a terminal, and those lines all -start with `$`. You don't need to type in the `$`s, they are there to indicate -the start of each command. We’ll see many tutorials and examples around the web -that follow this convention: `$` for commands run as our regular user, and `#` -for commands we should be running as an administrator. +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. -# Installing Rust - -The first step to using Rust is to install it. Generally speaking, you’ll need -an Internet connection to run the commands in this section, as we’ll be -downloading Rust from the Internet. - -The Rust compiler runs on, and compiles to, a great number of platforms, but is -best supported on Linux, Mac, and Windows, on the x86 and x86-64 CPU -architecture. There are official builds of the Rust compiler and standard -library for these platforms and more. [For full details on Rust platform support -see the website][platform-support]. - -[platform-support]: https://forge.rust-lang.org/platform-support.html - -## Installing Rust - -All you need to do on Unix systems like Linux and macOS is open a -terminal and type this: - -```bash -$ curl https://sh.rustup.rs -sSf | sh -``` - -It will download a script, and start the installation. If everything -goes well, you’ll see this appear: - -```text -Rust is installed now. Great! -``` - -Installing on Windows is nearly as easy: download and run -[rustup-init.exe]. It will start the installation in a console and -present the above message on success. - -For other installation options and information, visit the [install] -page of the Rust website. - -[rustup-init.exe]: https://win.rustup.rs -[install]: https://www.rust-lang.org/install.html - -## Uninstalling - -Uninstalling Rust is as easy as installing it: - -```bash -$ rustup self uninstall -``` - -## Troubleshooting - -If we've got Rust installed, we can open up a shell, and type this: - -```bash -$ rustc --version -``` - -You should see the version number, commit hash, and commit date. - -If you do, Rust has been installed successfully! Congrats! - -If you don't, that probably means that the `PATH` environment variable -doesn't include Cargo's binary directory, `~/.cargo/bin` on Unix, or -`%USERPROFILE%\.cargo\bin` on Windows. This is the directory where -Rust development tools live, and most Rust developers keep it in their -`PATH` environment variable, which makes it possible to run `rustc` on -the command line. Due to differences in operating systems, command -shells, and bugs in installation, you may need to restart your shell, -log out of the system, or configure `PATH` manually as appropriate for -your operating environment. - -Rust does not do its own linking, and so you’ll need to have a linker -installed. Doing so will depend on your specific system. For -Linux-based systems, Rust will attempt to call `cc` for linking. On -`windows-msvc` (Rust built on Windows with Microsoft Visual Studio), -this depends on having [Microsoft Visual C++ Build Tools][msvbt] -installed. These do not need to be in `%PATH%` as `rustc` will find -them automatically. In general, if you have your linker in a -non-traditional location you can call `rustc -linker=/path/to/cc`, where `/path/to/cc` should point to your linker path. - -[msvbt]: http://landinghub.visualstudio.com/visual-cpp-build-tools - -If you are still stuck, there are a number of places where we can get -help. The easiest is -[the #rust-beginners IRC channel on irc.mozilla.org][irc-beginners] -and for general discussion -[the #rust IRC channel on irc.mozilla.org][irc], which we -can access through [Mibbit][mibbit]. Then we'll be chatting with other -Rustaceans (a silly nickname we call ourselves) who can help us out. Other great -resources include [the user’s forum][users] and [Stack Overflow][stackoverflow]. - -[irc-beginners]: irc://irc.mozilla.org/#rust-beginners -[irc]: irc://irc.mozilla.org/#rust -[mibbit]: http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust-beginners,%23rust -[users]: https://users.rust-lang.org/ -[stackoverflow]: http://stackoverflow.com/questions/tagged/rust - -This installer also installs a copy of the documentation locally, so we can -read it offline. It's only a `rustup doc` away! - -# Hello, world! - -Now that you have Rust installed, we'll help you write your first Rust program. -It's traditional when learning a new language to write a little program to -print the text “Hello, world!” to the screen, and in this section, we'll follow -that tradition. - -The nice thing about starting with such a simple program is that you can -quickly verify that your compiler is installed, and that it's working properly. -Printing information to the screen is also a pretty common thing to do, so -practicing it early on is good. - -> Note: This book assumes basic familiarity with the command line. Rust itself -> makes no specific demands about your editing, tooling, or where your code -> lives, so if you prefer an IDE to the command line, that's an option. You may -> want to check out [SolidOak], which was built specifically with Rust in mind. -> There are a number of extensions in development by the community, and the -> Rust team ships plugins for [various editors]. Configuring your editor or -> IDE is out of the scope of this tutorial, so check the documentation for your -> specific setup. - -[SolidOak]: https://github.com/oakes/SolidOak -[various editors]: https://github.com/rust-lang/rust/blob/master/src/etc/CONFIGS.md - -## Creating a Project File - -First, make a file to put your Rust code in. Rust doesn't care where your code -lives, but for this book, I suggest making a *projects* directory in your home -directory, and keeping all your projects there. Open a terminal and enter the -following commands to make a directory for this particular project: - -```bash -$ mkdir ~/projects -$ cd ~/projects -$ mkdir hello_world -$ cd hello_world -``` - -> Note: If you’re on Windows and not using PowerShell, the `~` may not work. -> Consult the documentation for your shell for more details. - -## Writing and Running a Rust Program - -We need to create a source file for our Rust program. Rust files always end -in a *.rs* extension. If you are using more than one word in your filename, -use an underscore to separate them; for example, you would use -*my_program.rs* rather than *myprogram.rs*. - -Now, make a new file and call it *main.rs*. Open the file and type -the following code: - -```rust -fn main() { - println!("Hello, world!"); -} -``` - -Save the file, and go back to your terminal window. On Linux or macOS, enter the -following commands: - -```bash -$ rustc main.rs -$ ./main -Hello, world! -``` - -In Windows, replace `main` with `main.exe`. Regardless of your operating -system, you should see the string `Hello, world!` print to the terminal. If you -did, then congratulations! You've officially written a Rust program. That makes -you a Rust programmer! Welcome. - -## Anatomy of a Rust Program - -Now, let’s go over what just happened in your "Hello, world!" program in -detail. Here's the first piece of the puzzle: - -```rust -fn main() { - -} -``` - -These lines define a *function* in Rust. The `main` function is special: it's -the beginning of every Rust program. The first line says, “I’m declaring a -function named `main` that takes no arguments and returns nothing.” If there -were arguments, they would go inside the parentheses (`(` and `)`), and because -we aren’t returning anything from this function, we can omit the return type -entirely. - -Also note that the function body is wrapped in curly braces (`{` and `}`). Rust -requires these around all function bodies. It's considered good style to put -the opening curly brace on the same line as the function declaration, with one -space in between. - -Inside the `main()` function: - -```rust - println!("Hello, world!"); -``` - -This line does all of the work in this little program: it prints text to the -screen. There are a number of details that are important here. The first is -that it’s indented with four spaces, not tabs. - -The second important part is the `println!()` line. This is calling a Rust -*[macro]*, which is how metaprogramming is done in Rust. If it were calling a -function instead, it would look like this: `println()` (without the !). We'll -discuss Rust macros in more detail later, but for now you only need to -know that when you see a `!` that means that you’re calling a macro instead of -a normal function. - - -[macro]: macros.html - -Next is `"Hello, world!"` which is a *string*. Strings are a surprisingly -complicated topic in a systems programming language, and this is a *[statically -allocated]* string. We pass this string as an argument to `println!`, which -prints the string to the screen. Easy enough! - -[statically allocated]: the-stack-and-the-heap.html - -The line ends with a semicolon (`;`). Rust is an *[expression-oriented -language]*, which means that most things are expressions, rather than -statements. The `;` indicates that this expression is over, and the next one is -ready to begin. Most lines of Rust code end with a `;`. - -[expression-oriented language]: glossary.html#expression-oriented-language - -## Compiling and Running Are Separate Steps - -In "Writing and Running a Rust Program", we showed you how to run a newly -created program. We'll break that process down and examine each step now. - -Before running a Rust program, you have to compile it. You can use the Rust -compiler by entering the `rustc` command and passing it the name of your source -file, like this: - -```bash -$ rustc main.rs -``` - -If you come from a C or C++ background, you'll notice that this is similar to -`gcc` or `clang`. After compiling successfully, Rust should output a binary -executable, which you can see on Linux or macOS by entering the `ls` command in -your shell as follows: - -```bash -$ ls -main main.rs -``` - -On Windows, you'd enter: - -```bash -$ dir -main.exe -main.rs -``` - -This shows we have two files: the source code, with an `.rs` extension, and the -executable (`main.exe` on Windows, `main` everywhere else). All that's left to -do from here is run the `main` or `main.exe` file, like this: - -```bash -$ ./main # or .\main.exe on Windows -``` - -If *main.rs* were your "Hello, world!" program, this would print `Hello, -world!` to your terminal. - -If you come from a dynamic language like Ruby, Python, or JavaScript, you may -not be used to compiling and running a program being separate steps. Rust is an -*ahead-of-time compiled* language, which means that you can compile a program, -give it to someone else, and they can run it even without Rust installed. If -you give someone a `.rb` or `.py` or `.js` file, on the other hand, they need -to have a Ruby, Python, or JavaScript implementation installed (respectively), -but you only need one command to both compile and run your program. Everything -is a tradeoff in language design. - -Just compiling with `rustc` is fine for simple programs, but as your project -grows, you'll want to be able to manage all of the options your project has, -and make it easy to share your code with other people and projects. Next, I'll -introduce you to a tool called Cargo, which will help you write real-world Rust -programs. - -# Hello, Cargo! - -Cargo is Rust’s build system and package manager, and Rustaceans use Cargo to -manage their Rust projects. Cargo manages three things: building your code, -downloading the libraries your code depends on, and building those libraries. -We call libraries your code needs ‘dependencies’ since your code depends on -them. - -The simplest Rust programs don’t have any dependencies, so right now, you'd -only use the first part of its functionality. As you write more complex Rust -programs, you’ll want to add dependencies, and if you start off using Cargo, -that will be a lot easier to do. - -As the vast, vast majority of Rust projects use Cargo, we will assume that -you’re using it for the rest of the book. Cargo comes installed with Rust -itself, if you used the official installers. If you installed Rust through some -other means, you can check if you have Cargo installed by typing: - -```bash -$ cargo --version -``` - -Into a terminal. If you see a version number, great! If you see an error like -‘`command not found`’, then you should look at the documentation for the system -in which you installed Rust, to determine if Cargo is separate. - -## Converting to Cargo - -Let’s convert the Hello World program to Cargo. To Cargo-fy a project, you need -to do three things: - -1. Put your source file in the right directory. -2. Get rid of the old executable (`main.exe` on Windows, `main` everywhere - else). -3. Make a Cargo configuration file. - -Let's get started! - -### Creating a Source Directory and Removing the Old Executable - -First, go back to your terminal, move to your *hello_world* directory, and -enter the following commands: - -```bash -$ mkdir src -$ mv main.rs src/main.rs # or 'move main.rs src/main.rs' on Windows -$ rm main # or 'del main.exe' on Windows -``` - -Cargo expects your source files to live inside a *src* directory, so do that -first. This leaves the top-level project directory (in this case, -*hello_world*) for READMEs, license information, and anything else not related -to your code. In this way, using Cargo helps you keep your projects nice and -tidy. There's a place for everything, and everything is in its place. - -Now, move *main.rs* into the *src* directory, and delete the compiled file you -created with `rustc`. As usual, replace `main` with `main.exe` if you're on -Windows. - -This example retains `main.rs` as the source filename because it's creating an -executable. If you wanted to make a library instead, you'd name the file -`lib.rs`. This convention is used by Cargo to successfully compile your -projects, but it can be overridden if you wish. - -### Creating a Configuration File - -Next, create a new file inside your *hello_world* directory, and call it -`Cargo.toml`. - -Make sure to capitalize the `C` in `Cargo.toml`, or Cargo won't know what to do -with the configuration file. - -This file is in the *[TOML]* (Tom's Obvious, Minimal Language) format. TOML is -similar to INI, but has some extra goodies, and is used as Cargo’s -configuration format. - -[TOML]: https://github.com/toml-lang/toml - -Inside this file, type the following information: - -```toml -[package] - -name = "hello_world" -version = "0.0.1" -authors = [ "Your name " ] -``` - -The first line, `[package]`, indicates that the following statements are -configuring a package. As we add more information to this file, we’ll add other -sections, but for now, we only have the package configuration. - -The other three lines set the three bits of configuration that Cargo needs to -know to compile your program: its name, what version it is, and who wrote it. - -Once you've added this information to the *Cargo.toml* file, save it to finish -creating the configuration file. - -## Building and Running a Cargo Project - -With your *Cargo.toml* file in place in your project's root directory, you -should be ready to build and run your Hello World program! To do so, enter the -following commands: - -```bash -$ cargo build - Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world) -$ ./target/debug/hello_world -Hello, world! -``` - -Bam! If all goes well, `Hello, world!` should print to the terminal once more. - -You just built a project with `cargo build` and ran it with -`./target/debug/hello_world`, but you can actually do both in one step with -`cargo run` as follows: - -```bash -$ cargo run - Running `target/debug/hello_world` -Hello, world! -``` - -The `run` command comes in handy when you need to rapidly iterate on a -project. - -Notice that this example didn’t re-build the project. Cargo figured out that -the file hasn’t changed, and so it just ran the binary. If you'd modified your -source code, Cargo would have rebuilt the project before running it, and you -would have seen something like this: - -```bash -$ cargo run - Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world) - Running `target/debug/hello_world` -Hello, world! -``` - -Cargo checks to see if any of your project’s files have been modified, and only -rebuilds your project if they’ve changed since the last time you built it. - -With simple projects, Cargo doesn't bring a whole lot over just using `rustc`, -but it will become useful in the future. This is especially true when you start -using crates; these are synonymous with a ‘library’ or ‘package’ in other -programming languages. For complex projects composed of multiple crates, it’s -much easier to let Cargo coordinate the build. Using Cargo, you can run `cargo -build`, and it should work the right way. - -### Building for Release - -When your project is ready for release, you can use `cargo build ---release` to compile your project with optimizations. These optimizations make -your Rust code run faster, but turning them on makes your program take longer -to compile. This is why there are two different profiles, one for development, -and one for building the final program you’ll give to a user. - -### What Is That `Cargo.lock`? - -Running `cargo build` also causes Cargo to create a new file called -*Cargo.lock*, which looks like this: - -```toml -[root] -name = "hello_world" -version = "0.0.1" -``` - -Cargo uses the *Cargo.lock* file to keep track of dependencies in your -application. This is the Hello World project's *Cargo.lock* file. This project -doesn't have dependencies, so the file is a bit sparse. Realistically, you -won't ever need to touch this file yourself; just let Cargo handle it. - -That’s it! If you've been following along, you should have successfully built -`hello_world` with Cargo. - -Even though the project is simple, it now uses much of the real tooling you’ll -use for the rest of your Rust career. In fact, you can expect to start -virtually all Rust projects with some variation on the following commands: - -```bash -$ git clone someurl.com/foo -$ cd foo -$ cargo build -``` - -## Making A New Cargo Project the Easy Way - -You don’t have to go through that previous process every time you want to start -a new project! Cargo can quickly make a bare-bones project directory that you -can start developing in right away. - -To start a new project with Cargo, enter `cargo new` at the command line: - -```bash -$ cargo new hello_world --bin -``` - -This command passes `--bin` because the goal is to get straight to making an -executable application, as opposed to a library. Executables are often called -*binaries* (as in `/usr/bin`, if you’re on a Unix system). - -Cargo has generated two files and one directory for us: a `Cargo.toml` and a -*src* directory with a *main.rs* file inside. These should look familiar, -they’re exactly what we created by hand, above. - -This output is all you need to get started. First, open `Cargo.toml`. It should -look something like this: - -```toml -[package] - -name = "hello_world" -version = "0.1.0" -authors = ["Your Name "] - -[dependencies] -``` - -Do not worry about the `[dependencies]` line, we will come back to it later. - -Cargo has populated *Cargo.toml* with reasonable defaults based on the arguments -you gave it and your `git` global configuration. You may notice that Cargo has -also initialized the `hello_world` directory as a `git` repository. - -Here’s what should be in `src/main.rs`: - -```rust -fn main() { - println!("Hello, world!"); -} -``` - -Cargo has generated a "Hello World!" for you, and you’re ready to start coding! - -> Note: If you want to look at Cargo in more detail, check out the official [Cargo -guide], which covers all of its features. - -[Cargo guide]: http://doc.crates.io/guide.html - -# Closing Thoughts - -This chapter covered the basics that will serve you well through the rest of -this book, and the rest of your time with Rust. Now that you’ve got the tools -down, we'll cover more about the Rust language itself. - -You have two options: Dive into a project with ‘[Tutorial: Guessing Game][guessinggame]’, or -start from the bottom and work your way up with ‘[Syntax and -Semantics][syntax]’. More experienced systems programmers will probably prefer -‘Tutorial: Guessing Game’, while those from dynamic backgrounds may enjoy either. Different -people learn differently! Choose whatever’s right for you. - -[guessinggame]: guessing-game.html -[syntax]: syntax-and-semantics.html +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). diff --git a/first-edition/src/glossary.md b/first-edition/src/glossary.md index 389530355a..03a2833e40 100644 --- a/first-edition/src/glossary.md +++ b/first-edition/src/glossary.md @@ -1,85 +1,10 @@ # Glossary -Not every Rustacean has a background in systems programming, nor in computer -science, so we've added explanations of terms that might be unfamiliar. +The first edition of the book is no longer distributed with Rust's documentation. -### Abstract Syntax Tree +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. -When a compiler is compiling your program, it does a number of different things. -One of the things that it does is turn the text of your program into an -‘abstract syntax tree’, or ‘AST’. This tree is a representation of the structure -of your program. For example, `2 + 3` can be turned into a tree: - -```text - + - / \ -2 3 -``` - -And `2 + (3 * 4)` would look like this: - -```text - + - / \ -2 * - / \ - 3 4 -``` - -### Arity - -Arity refers to the number of arguments a function or operation takes. - -```rust -let x = (2, 3); -let y = (4, 6); -let z = (8, 2, 6); -``` - -In the example above `x` and `y` have arity 2. `z` has arity 3. - -### Bounds - -Bounds are constraints on a type or [trait][traits]. For example, if a bound -is placed on the argument a function takes, types passed to that function -must abide by that constraint. - -[traits]: traits.html - -### Combinators - -Combinators are higher-order functions that apply only functions and -earlier defined combinators to provide a result from its arguments. -They can be used to manage control flow in a modular fashion. - -### DST (Dynamically Sized Type) - -A type without a statically known size or alignment. ([more info][link]) - -[link]: ../../nomicon/exotic-sizes.html#dynamically-sized-types-dsts - -### Expression - -In computer programming, an expression is a combination of values, constants, -variables, operators and functions that evaluate to a single value. For example, -`2 + (3 * 4)` is an expression that returns the value 14. It is worth noting -that expressions can have side-effects. For example, a function included in an -expression might perform actions other than simply returning a value. - -### Expression-Oriented Language - -In early programming languages, [expressions][expression] and -[statements][statement] were two separate syntactic categories: expressions had -a value and statements did things. However, later languages blurred this -distinction, allowing expressions to do things and statements to have a value. -In an expression-oriented language, (nearly) every statement is an expression -and therefore returns a value. Consequently, these expression statements can -themselves form part of larger expressions. - -[expression]: glossary.html#expression -[statement]: glossary.html#statement - -### Statement - -In computer programming, a statement is the smallest standalone element of a -programming language that commands a computer to perform an action. +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). \ No newline at end of file diff --git a/first-edition/src/guessing-game.md b/first-edition/src/guessing-game.md index 3d375e5b9c..3191cc9724 100644 --- a/first-edition/src/guessing-game.md +++ b/first-edition/src/guessing-game.md @@ -1,1379 +1,10 @@ # Guessing Game -# Jogo de Adivinhação -Let’s learn some Rust! For our first project, we’ll implement a classic -beginner programming problem: the guessing game. Here’s how it works: Our -program will generate a random integer between one and a hundred. It will then -prompt us to enter a guess. Upon entering our guess, it will tell us if we’re -too low or too high. Once we guess correctly, it will congratulate us. Sounds -good? -Vamos aprender um pouco de Rust! Para nosso primeiro projeto, vamos -implementar um clássico problema de programação para iniciantes: o -jogo de adivinhação. Eis como ele funciona: nosso programa gerará um -inteiro aleatório entre um e cem. Ele então aguardará entrarmos um -palpite. Entrando nosso palpite, ele nos informará se estamos muito -baixos ou muito altos. Uma vez que palpitemos corretamente, ele nos -congratulará. Parece uma boa? +The first edition of the book is no longer distributed with Rust's documentation. -Along the way, we’ll learn a little bit about Rust. The next chapter, ‘Syntax -and Semantics’, will dive deeper into each part. -Ao longo do caminho, aprenderemos um pouco sobre Rust. No capítulo -seguinte, 'Sintaxe e Semântica', mergulharemos mais fundo em cada -parte. +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. -# Set up -# Configurando - -Let’s set up a new project. Go to your projects directory. Remember how we had -to create our directory structure and a `Cargo.toml` for `hello_world`? Cargo -has a command that does that for us. Let’s give it a shot: -Vamos configurar um novo projeto, Vá ao seu diretório de -projetos. Lembra como tínhamos que criar nossa estrutura de diretórios -e um `Cargo.toml` para o `hello_world`? Cargo tem um comando que faz -isto por nós. Vamos dar uma olhada: - -```bash -$ cd ~/projects -$ cargo new guessing_game --bin - Created binary (application) `guessing_game` project -$ cd guessing_game -``` - -We pass the name of our project to `cargo new`, and then the `--bin` flag, -since we’re making a binary, rather than a library. -Passamos o nome de nosso projeto para `cargo new`, e então a opção de -comando `--bin`, já que estamos fazendo um binário em vez de uma -biblioteca. - -Check out the generated `Cargo.toml`: -Confira o arquivo gerado `Cargo.toml`: - -```toml -[package] - -name = "guessing_game" -version = "0.1.0" -authors = ["Your Name "] -``` - -Cargo gets this information from your environment. If it’s not correct, go ahead -and fix that. -Cargo obtém essa informação a partir de seu ambiente. Se ela não -estiver correta, vá em frente e faça os reparos necessários. - -Finally, Cargo generated a ‘Hello, world!’ for us. Check out `src/main.rs`: -Finalmente, Cargo gerou um ‘Hello, world!’ para nós. Confira em `src/main.rs`: - -```rust -fn main() { - println!("Hello, world!"); -} -``` - -Let’s try compiling what Cargo gave us: -Vamos tentar compilar o que o Cargo nos forneceu: - -```{bash} -$ cargo build - Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) - Finished debug [unoptimized + debuginfo] target(s) in 0.53 secs -``` - -Excellent! Open up your `src/main.rs` again. We’ll be writing all of -our code in this file. -Excelente! Abra novamente o arquivo `src/main.rs`. Escreveremos todo -nosso código nele. - -Remember the `run` command from last chapter? Try it out again here: -Lembram do comando `run` do capítulo anterior? Teste-o novamente aqui: - -```bash -$ cargo run - Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) - Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target/debug/guessing_game` -Hello, world! -``` - -Great! Our game is just the kind of project `run` is good for: we need -to quickly test each iteration before moving on to the next one. -Muito bom! Nosso jogo é exatamente o tipo de projeto para o qual `run` -vem a calhar: nós precisamos testar rapidamente cada iteração antes de -movermos para a próxima. - -# Processing a Guess -# Processando o Palpite - -Let’s get to it! The first thing we need to do for our guessing game is -allow our player to input a guess. Put this in your `src/main.rs`: -Vamos lá! A primeira coisa que precisamos fazer no nosso jogo de -adivinhação é permitir que o jogador entre com um palpite. Escreva -isso no arquivo `src/main.rs`: - -```rust,no_run -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); -} -``` - -There’s a lot here! Let’s go over it, bit by bit. -Tem bastante coisa aqui! Vamos passar por este código, uma parte de -cada vez: - -```rust,ignore -use std::io; -``` - -We’ll need to take user input, and then print the result as output. As such, we -need the `io` library from the standard library. Rust only imports a few things -by default into every program, [the ‘prelude’][prelude]. If it’s not in the -prelude, you’ll have to `use` it directly. There is also a second ‘prelude’, the -[`io` prelude][ioprelude], which serves a similar function: you import it, and it -imports a number of useful, `io`-related things. -Precisaremos obter entrada do usuário, e então imprimir o resultado -como saída. Para tal, precisaremos da biblioteca padrão `io`. Rust -importa apenas algumas poucas coisas por padrão em cada programa, [o -'prelúdio'][prelude]. Se algo não está no prelúdio, você tem que -importá-lo diretamente via `use`. Existe também um segundo 'prelúdio', -o [prelúdio `io`][ioprelude], que serve a uma função similar: você o -importa e ele importa algumas coisas importantes relacionadas a E/S. - -[prelude]: ../../std/prelude/index.html -[ioprelude]: ../../std/io/prelude/index.html - -```rust,ignore -fn main() { -``` - -As you’ve seen before, the `main()` function is the entry point into your -program. The `fn` syntax declares a new function, the `()`s indicate that -there are no arguments, and `{` starts the body of the function. Because -we didn’t include a return type, it’s assumed to be `()`, an empty -[tuple][tuples]. -Como você já deve ter visto antes, a função `main()` é o ponto de -entrada de seu programa. A sintaxe `fn` declara uma nova função, o -`()` indica que não há argumentos, e o `{` inicia o corpo da -função. Como não incluímos um tipo de retorno, este tipo é assumido -como `()`, uma [tupla][tuples] vazia. - -[tuples]: primitive-types.html#tuples - -```rust,ignore - println!("Guess the number!"); - - println!("Please input your guess."); -``` - -We previously learned that `println!()` is a [macro][macros] that -prints a [string][strings] to the screen. -Já aprendemos antes que `println!()` é uma [macro][macros] que imprime -uma [string][strings] na tela. - -[macros]: macros.html -[strings]: strings.html - -```rust,ignore - let mut guess = String::new(); -``` - -Now we’re getting interesting! There’s a lot going on in this little line. -The first thing to notice is that this is a [let statement][let], which is -used to create ‘variable bindings’. They take this form: -Agora está ficando interessante! Tem muita coisa acontecendo nesta -pequena linha. A primeira coisa é notar que este é uma [declaração -let][let], usada para criar 'vinculação de variáveis'. Declarações -`let` tomam este formato: - -```rust,ignore -let foo = bar; -``` - -[let]: variable-bindings.html - -This will create a new binding named `foo`, and bind it to the value `bar`. In -many languages, this is called a ‘variable’, but Rust’s variable bindings have -a few tricks up their sleeves. -Isto cria um novo vínculo de nome `foo`, e o vincula ao valor -`bar`. Em muitas linguagens isto é chamado de 'variável', mas as -vinculações de variáveis em Rust têm alguns truques nas mangas. - -For example, they’re [immutable][immutable] by default. That’s why our example -uses `mut`: it makes a binding mutable, rather than immutable. `let` doesn’t -take a name on the left hand side of the assignment, it actually accepts a -‘[pattern][patterns]’. We’ll use patterns later. It’s easy enough -to use for now: -Por exemplo, elas são [imutáveis][immutable] por padrão. É por isso -que nosso exemplo usa `mut`: ele torna o vínculo mutável, em vez de -imutável. `let`não toma um nome do lado esquerdo da atribuição, ele na -realidade aceita um '[padrão][patterns]'. Nós usaremos padrões mais -tarde. Isto é fácil o suficiente para usar por enquanto: - -```rust -let foo = 5; // `foo` is immutable. -let mut bar = 5; // `bar` is mutable. -let foo = 5; // `foo` é imutável -let mut bar = 5; // `bar` é mutável -``` - -[immutable]: mutability.html -[patterns]: patterns.html - -Oh, and `//` will start a comment, until the end of the line. Rust ignores -everything in [comments][comments]. -Ah! E o `//` inicia um comentário, até o fim da linha. Rust ignora -tudo nos [comentários][comments]. - -[comments]: comments.html - -So now we know that `let mut guess` will introduce a mutable binding named -`guess`, but we have to look at the other side of the `=` for what it’s -bound to: `String::new()`. -Agora então sabemos que `let mut guess` introduzirá um vínculo mutável -de nome `guess`, mas temos que observar o outro lado do `=` pelo que -ele está vinculado: `String::new()`. - -`String` is a string type, provided by the standard library. A -[`String`][string] is a growable, UTF-8 encoded bit of text. -`String` é um tipo string (grosso modo, uma cadeia de caracteres), -fornecido pela biblioteca padrão. Uma [`String`][string] é uma parcela -de texto encodada em UTF-8, que pode modificar de tamanho. - -[string]: ../../std/string/struct.String.html - -The `::new()` syntax uses `::` because this is an ‘associated function’ of -a particular type. That is to say, it’s associated with `String` itself, -rather than a particular instance of a `String`. Some languages call this a -‘static method’. -A sintaxe `::new()` usa `::` porque esta é uma 'função associada' de -um tipo particular. Quer dizer, é associada ao próprio tipo `String` -em vez de uma instância particular de `String`. Algumas linguagens -dão a isso o nome 'método estático'. - -This function is named `new()`, because it creates a new, empty `String`. -You’ll find a `new()` function on many types, as it’s a common name for making -a new value of some kind. -Esta função é chamada `new()` porque ela cria uma nova `String` -vazia. Você encontrará uma função `new()` em muitos tipos, já que ela -é um nome comum para produzir um novo valor de algum tipo. - -Let’s move forward: -Prossigamos: - -```rust,ignore - io::stdin().read_line(&mut guess) - .expect("Failed to read line"); -``` - -That’s a lot more! Let’s go bit-by-bit. The first line has two parts. Here’s -the first: -Aqui tem bem mais coisa! Vamos prosseguir uma parte por vez. A -primeira linha tem duas partes; eis a primeira: - -```rust,ignore -io::stdin() -``` - -Remember how we `use`d `std::io` on the first line of the program? We’re now -calling an associated function on it. If we didn’t `use std::io`, we could -have written this line as `std::io::stdin()`. -Lembra como usamos o `std::io` na primeira linha do programa? Agora -estamos chamando uma função associada nele. Se não usássemos o `use -std::io`, teríamos que escrever esta linha como `std::io::stdin()`. - -This particular function returns a handle to the standard input for your -terminal. More specifically, a [std::io::Stdin][iostdin]. -Esta função em particular retorna um manipulador (*handle*) para a -entrada padrão do seu terminal. Mais especificamente, um -[std::io::Stdin][iostdin]. - -[iostdin]: ../../std/io/struct.Stdin.html - -The next part will use this handle to get input from the user: -A próxima parte usará esse *handle* para obter entrada do usuário: - -```rust,ignore -.read_line(&mut guess) -``` - -Here, we call the [`read_line`] method on our handle. -[Methods][method] are like associated functions, but are only available on a -particular instance of a type, rather than the type itself. We’re also passing -one argument to `read_line()`: `&mut guess`. -Aqui, nós chamamos o método [`read_line`] do nosso -*handle*. [Métodos][method] são como funções associadas, mas só estão -disponíveis em uma instância particular de um tipo, em vez de no -próprio tipo. Também estamos passando um argumento para `read_line()`: -`&mut guess`. - -[`read_line`]: ../../std/io/struct.Stdin.html#method.read_line -[method]: method-syntax.html - -Remember how we bound `guess` above? We said it was mutable. However, -`read_line` doesn’t take a `String` as an argument: it takes a `&mut String`. -Rust has a feature called ‘[references][references]’, which allows you to have -multiple references to one piece of data, which can reduce copying. References -are a complex feature, as one of Rust’s major selling points is how safe and -easy it is to use references. We don’t need to know a lot of those details to -finish our program right now, though. For now, all we need to know is that -like `let` bindings, references are immutable by default. Hence, we need to -write `&mut guess`, rather than `&guess`. - -Why does `read_line()` take a mutable reference to a string? Its job is -to take what the user types into standard input, and place that into a -string. So it takes that string as an argument, and in order to add -the input, it needs to be mutable. -Lembra como vinculamos `guess` acima? Dissemos que ele era -mutável. Porém, `read_line` não toma um `String` como argumento; ele -toma um `&mut String`. - -Rust tem uma característica chamada ‘[referência][references]’, que -permite que tenhamos múltiplas referências a uma peça de dado, o que -pode reduzir as cópias. Referências são uma característica complexa, -já que uma das maiores vantagens de Rust é o quão seguro e fácil é -usar referências. Porém, não precisamos conhecer muitos desses detalhes para -finalizar nosso programa agora. Por enquanto, tudo que precisamos -saber é que como as vinculações `let`, referências são imutáveis por -padrão. Por isso, precisamos escrever `&mut guess`, em vez de -`&guess`. - -Por que `read_line()` toma uma referência mutável a uma string? O -trabalho de `read_line()` é tomar o que o usuário escreve na entrada -padrão, e colocar isso numa string. Então ele toma uma string como -argumento, e para adicionar a entrada, ela precisa ser mutável. - -[references]: references-and-borrowing.html - -But we’re not quite done with this line of code, though. While it’s -a single line of text, it’s only the first part of the single logical line of -code: -Mas não finalizamos completamente com esta linha de código, -porém. Enquanto esta é uma simples linha de texto, é apenas a primeira -parte de uma linha lógica de código: - -```rust,ignore - .expect("Failed to read line"); -``` - -When you call a method with the `.foo()` syntax, you may introduce a newline -and other whitespace. This helps you split up long lines. We _could_ have -done: -Quando você chama um método com a sintaxe `.foo()`, você pode -introduzir uma nova linha e outro espaço em branco. Isto te ajuda a -dividir linhas compridas. Poderíamos ter feito assim: - -```rust,ignore - io::stdin().read_line(&mut guess).expect("Failed to read line"); -``` - -But that gets hard to read. So we’ve split it up, two lines for two method -calls. We already talked about `read_line()`, but what about `expect()`? Well, -we already mentioned that `read_line()` puts what the user types into the `&mut -String` we pass it. But it also returns a value: in this case, an -[`io::Result`][ioresult]. Rust has a number of types named `Result` in its -standard library: a generic [`Result`][result], and then specific versions for -sub-libraries, like `io::Result`. -Mas isto fica difícil de ler. Então dividimos a linha, duas linhas -para duas chamadas de métodos. Já comentamos sobre `read_line()`, mas -e quanto ao `expect()`? Bem, nós já mencionamos que `read_line()` -coloca o que o usuário escreve no `&mut String` que passamos. Mas ela -também retorna um valor; neste caso, um [`io::Result`][ioresult]. Rust -tem uma quantidade de tipos com o nome `Result` em sua biblioteca -padrão: um [`Result`][result] genérico, e daí as versões específicas -de sub-bibliotecas, como `io::Result`. - -[ioresult]: ../../std/io/type.Result.html -[result]: ../../std/result/enum.Result.html - -The purpose of these `Result` types is to encode error handling information. -Values of the `Result` type, like any type, have methods defined on them. In -this case, `io::Result` has an [`expect()` method][expect] that takes a value -it’s called on, and if it isn’t a successful one, [`panic!`][panic]s with a -message you passed it. A `panic!` like this will cause our program to crash, -displaying the message. -O propósito destes tipos `Result` é encodar informação de manipulação -de erros. Valores do tipo `Result`, como qualquer tipo, têm métodos -definidos para eles. Neste caso, `io::Result` tem um método -[`expect()`][expect] que toma o valor que foi chamado, e se ele não é -um valor bem-sucedido, cai em pânico ([`panic!`][panic]) com a -mensagem que você passou. Um `panic!` deste fará o programa 'quebrar', -exibindo a mensagem. - -[expect]: ../../std/result/enum.Result.html#method.expect -[panic]: error-handling.html - -If we do not call `expect()`, our program will compile, but -we’ll get a warning: -Se não chamarmos `expect()`, nosso programa compilará, mas obteremos -um alerta: - -```bash -$ cargo build - Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) -warning: unused result which must be used, #[warn(unused_must_use)] on by default - --> src/main.rs:10:5 - | -10 | io::stdin().read_line(&mut guess); - | ^ - - Finished debug [unoptimized + debuginfo] target(s) in 0.42 secs -``` - -Rust warns us that we haven’t used the `Result` value. This warning comes from -a special annotation that `io::Result` has. Rust is trying to tell you that -you haven’t handled a possible error. The right way to suppress the error is -to actually write error handling. Luckily, if we want to crash if there’s -a problem, we can use `expect()`. If we can recover from the -error somehow, we’d do something else, but we’ll save that for a future -project. -Rust alerta que não usamos o valor `Result`. Este alerta vem de uma -anotação especial que `io::Result` tem. Rust está tentando te avisar -que você não lidou com um possível erro. A maneira correta de suprimir -o erro é realmente escrevendo o manipulador de erro. Por sorte, se -queremos quebrar o programa acaso ocorra um problema, podemos usar -`expect()`. Se podemos de alguma forma recuperar do erro, podemos -fazer outra coisa, mas guardaremos isso para um projeto futuro. - -There’s only one line of this first example left: -Há apenas uma linha sobrando neste primeiro exemplo: - -```rust,ignore - println!("You guessed: {}", guess); -} -``` - -This prints out the string we saved our input in. The `{}`s are a placeholder, -and so we pass it `guess` as an argument. If we had multiple `{}`s, we would -pass multiple arguments: -Esta imprime a string na qual salvamos nossa entrada. O `{}` é um -gabarito, e assim podemos passar `guess` como argumento. Se tivermos -múltiplos `{}`, poderíamos passar múltiplos argumentos: - -```rust -let x = 5; -let y = 10; - -println!("x and y: {} and {}", x, y); -``` - -Easy. -Fácil. - -Anyway, that’s the tour. We can run what we have with `cargo run`: -De qualquer forma, este é um *tour*. Podemos rodar o que temos com `cargo run`: - -```bash -$ cargo run - Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) - Finished debug [unoptimized + debuginfo] target(s) in 0.44 secs - Running `target/debug/guessing_game` -Guess the number! -Please input your guess. -6 -You guessed: 6 -``` - -All right! Our first part is done: we can get input from the keyboard, -and then print it back out. -Tudo certo! Nossa primeira parte está feita: podemos coletar entrada -do teclado, e daí imprimi-lo de volta. - -# Generating a secret number -# Gerando um número secreto - -Next, we need to generate a secret number. Rust does not yet include random -number functionality in its standard library. The Rust team does, however, -provide a [`rand` crate][randcrate]. A ‘crate’ is a package of Rust code. -We’ve been building a ‘binary crate’, which is an executable. `rand` is a -‘library crate’, which contains code that’s intended to be used with other -programs. -A seguir, precisamos gerar um número secreto. Rust ainda não inclui -uma funcionalidade de geração de números aleatórios em sua biblioteca -padrão. Porém, o time Rust fornece uma [*crate* `rand`][randcrate]. Um -*crate* (caixote) é um pacote de código Rust. Nós estamos construindo -um *crate* binário, que é um executável. Já `rand` é um *crate* -biblioteca, que contém código cujo objetivo é ser usado por outros -programas. - -[randcrate]: https://crates.io/crates/rand - -Using external crates is where Cargo really shines. Before we can write -the code using `rand`, we need to modify our `Cargo.toml`. Open it up, and -add these few lines at the bottom: -É no uso de *crates* externas que Cargo realmente brilha. Antes que -possamos escrever o código usando `rand`, precisamos modificar nosso -`Cargo.toml`. Abra-o, e adicione estas linhas no final: - -```toml -[dependencies] - -rand = "0.3.0" -``` - -The `[dependencies]` section of `Cargo.toml` is like the `[package]` section: -everything that follows it is part of it, until the next section starts. -Cargo uses the dependencies section to know what dependencies on external -crates you have, and what versions you require. In this case, we’ve specified version `0.3.0`, -which Cargo understands to be any release that’s compatible with this specific version. -Cargo understands [Semantic Versioning][semver], which is a standard for writing version -numbers. A bare number like above is actually shorthand for `^0.3.0`, -meaning "anything compatible with 0.3.0". -If we wanted to use only `0.3.0` exactly, we could say `rand = "=0.3.0"` -(note the two equal signs). -We could also use a range of versions. -[Cargo’s documentation][cargodoc] contains more details. -A seção `[dependencies]` do arquivo `Cargo.toml` é como a seção -`[package]`: tudo que a segue é parte dela, até a próxima seção -iniciar. Cargo usa a seção de dependências para saber que dependências -em *crates* externas você tem, e que versões você exige. Neste caso, -especificamos a versão `0.3.0`, a qual Cargo entende como qualquer -versão que seja compatível com esta em específico. Cargo compreende -[versões semânticas][semver], um padrão para escrever números de -versão. Um número limpo como este é na verdade uma forma curta de -escrever `^0.3.0`, o que significa "qualquer uma compatível com -0.3.0". Se quiséssemos usar somente a versão `0.3.0` exatamente, -poderíamos ter escrito `rand = "=0.3.0"` (note os dois sinais de -igual). Poderíamos também usar um intervalo de versões. A [documentação -do Cargo ][cargodoc] contém mais detalhes. - -[semver]: http://semver.org -[cargodoc]: http://doc.crates.io/specifying-dependencies.html - -Now, without changing any of our code, let’s build our project: -Agora, sem mudar código algum, vamos montar nosso projeto: - -```bash -$ cargo build - Updating registry `https://github.com/rust-lang/crates.io-index` - Downloading rand v0.3.14 - Downloading libc v0.2.17 - Compiling libc v0.2.17 - Compiling rand v0.3.14 - Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) - Finished debug [unoptimized + debuginfo] target(s) in 5.88 secs -``` - -(You may see different versions, of course.) -(É claro, você pode acabar vendo versões diferentes.) - -Lots of new output! Now that we have an external dependency, Cargo fetches the -latest versions of everything from the registry, which is a copy of data from -[Crates.io][cratesio]. Crates.io is where people in the Rust ecosystem -post their open source Rust projects for others to use. -Muita saída nova! Agora que temos uma dependência externa nova, Cargo -busca as versões mais recentes de tudo no registro, o qual é uma cópia -de dados do [Crates.io][cratesio]. Crates.io é onde as pessoas do -ecossistema Rust postam seus projetos *opensource* para que os outros -usem. - -[cratesio]: https://crates.io - -After updating the registry, Cargo checks our `[dependencies]` and downloads -any we don’t have yet. In this case, while we only said we wanted to depend on -`rand`, we’ve also grabbed a copy of `libc`. This is because `rand` depends on -`libc` to work. After downloading them, it compiles them, and then compiles -our project. -Após atualizar o registro, Cargo confere as dependências em -`[dependencies]` e baixa as que ainda não foram baixadas. Neste caso, -enquanto nós apenas dizemos que queremos `rand` como dependência, nós -também pegamos uma cópia da `libc`. Isto é porque `rand` depende de -`libc` para funcionar. Depois de baixá-las, o Cargo as compila e -então compila nosso projeto. - -If we run `cargo build` again, we’ll get different output: -Se executarmos `cargo build` novamente, obteremos uma saída diferente: - -```bash -$ cargo build - Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs -``` - -That’s right, nothing was done! Cargo knows that our project has been built, and that -all of its dependencies are built, and so there’s no reason to do all that -stuff. With nothing to do, it simply exits. If we open up `src/main.rs` again, -make a trivial change, and then save it again, we’ll only see two lines: -Isso mesmo, nada foi feito! Cargo sabe que nosso projeto foi -construído, e que todas as dependências foram montadas, e portanto não -há razão para refazer tudo. Sem nada a fazer, ele simplesmente sai. Se -abríssemos `src/main.rs` novamente, e fizéssemos uma modificação -trivial, veríamos apenas duas linhas: - -```bash -$ cargo build - Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) - Finished debug [unoptimized + debuginfo] target(s) in 0.45 secs -``` - -So, we told Cargo we wanted any `0.3.x` version of `rand`, and so it fetched the latest -version at the time this was written, `v0.3.14`. But what happens when next -week, version `v0.3.15` comes out, with an important bugfix? While getting -bugfixes is important, what if `0.3.15` contains a regression that breaks our -code? - -The answer to this problem is the `Cargo.lock` file you’ll now find in your -project directory. When you build your project for the first time, Cargo -figures out all of the versions that fit your criteria, and then writes them -to the `Cargo.lock` file. When you build your project in the future, Cargo -will see that the `Cargo.lock` file exists, and then use that specific version -rather than do all the work of figuring out versions again. This lets you -have a repeatable build automatically. In other words, we’ll stay at `0.3.14` -until we explicitly upgrade, and so will anyone who we share our code with, -thanks to the lock file. - -What about when we _do_ want to use `v0.3.15`? Cargo has another command, -`update`, which says ‘ignore the lock, figure out all the latest versions that -fit what we’ve specified. If that works, write those versions out to the lock -file’. But, by default, Cargo will only look for versions larger than `0.3.0` -and smaller than `0.4.0`. If we want to move to `0.4.x`, we’d have to update -the `Cargo.toml` directly. When we do, the next time we `cargo build`, Cargo -will update the index and re-evaluate our `rand` requirements. - -There’s a lot more to say about [Cargo][doccargo] and [its -ecosystem][doccratesio], but for now, that’s all we need to know. Cargo makes -it really easy to re-use libraries, and so Rustaceans tend to write smaller -projects which are assembled out of a number of sub-packages. -Então, nós instruímos o Cargo que queremos qualquer versão `0.3.x` de -`rand`, e assim ele busca a versão mais recente desde quando este -texto foi escrito, `0.3.14`. Mas, o que acontece quando semana que -vem chegar a versão `0.3.15` com um *bugfix* importante? Enquanto -obter *bugfixes* é importante, e se `0.3.15` contiver uma regressão -que quebra nosso código? - -A resposta para isso está no arquivo `Cargo.lock` que você agora verá -no diretório do seu projeto. Quando você monta seu projeto pela -primeira vez, Cargo anota todas as versões que preenchem os critérios -e então as escreve no arquivo `Cargo.lock`. Quando você montar seu -projeto futuramente, Cargo verá que o arquivo `Cargo.lock` existe, e -então usará aquela versão específica em vez de refazer todo o trabalho -de anotar as versões. Isto te permite ter uma montagem repetível -automaticamente. Em outras palavras, continuaremos com a versão -`0.3.14` até que façamos uma atualização explícita, e assim com todos -com quem dividirmos nosso código, graças ao arquivo de trava (*lock file*) -`Cargo.lock`. - -E quando quisermos usar a versão `0.3.15`? Cargo tem outro comando, -`update`, que diz 'ignore o *lock file*, anote quais as novas versões -que se encaixam no que foi especificado; se isto funcionar, escreva -estas novas versões no *lock file*'. Mas, por padrão, Cargo procurará -pelas versões maiores ou iguais a `0.3.0` e estritamente menores que -`0.4.0`. Se nós quisermos mover para a `0.4.x`, teremos então que -atualizar o arquivo `Cargo.toml` diretamente. Quando fizermos isso, na -próxima ver que executarmos `cargo build`, Cargo atualizará o índice e -re-evaluará nossos requerimentos sobre `rand`; - -Há muito mais o que ser dito sobre [Cargo][doccargo] e [seu -ecossistema][doccratesio], mas por ora isto é tudo que precisamos -saber. Cargo torna realmente fácil reutilizar bibliotecas, e portanto -*rustáceos* tendem a escrever projetos menores que são montados em um -número de sub-pacotes. - -[doccargo]: http://doc.crates.io -[doccratesio]: http://doc.crates.io/crates-io.html - -Let’s get on to actually _using_ `rand`. Here’s our next step: -Agora vamos de fato _usar_ `rand`. Eis nosso próximo passo: - -```rust,ignore -extern crate rand; - -use std::io; -use rand::Rng; - -fn main() { - println!("Guess the number!"); - - let secret_number = rand::thread_rng().gen_range(1, 101); - - 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); -} -``` - -The first thing we’ve done is change the first line. It now says -`extern crate rand`. Because we declared `rand` in our `[dependencies]`, we -can use `extern crate` to let Rust know we’ll be making use of it. This also -does the equivalent of a `use rand;` as well, so we can make use of anything -in the `rand` crate by prefixing it with `rand::`. -A primeira coisa que fizemos foi modificar a primeira linha. Agora ela -diz `extern crate rand`. Como declaramos `rand` no `[dependencies]`, -nós podemos usar `extern crate` para deixar Rust saber que faremos uso -dela. Isto também faz o equivalente de um `use rand;` também, assim -podemos fazer uso de qualquer coisa na *crate* `rand` prefixando-a com -`rand::`. - -Next, we added another `use` line: `use rand::Rng`. We’re going to use a -method in a moment, and it requires that `Rng` be in scope to work. The basic -idea is this: methods are defined on something called ‘traits’, and for the -method to work, it needs the trait to be in scope. For more about the -details, read the [traits][traits] section. -A seguir, adicionamos outra linha `use` : `use rand::Rng`. Usaremos um -método em um momento, e ele requer que `Rng` esteja no escopo para -funcionar. A ideia básica é: métodos são definidos em alguma coisa -chamada 'tratos', e para o método funcionar, ele precisa que o trato -esteja no escopo. Para mais sobre os detalhes, leia a seção de -[tratos][traits]. - -[traits]: traits.html - -There are two other lines we added, in the middle: -Tem outras duas linhas que adicionamos no meio: - -```rust,ignore - let secret_number = rand::thread_rng().gen_range(1, 101); - - println!("The secret number is: {}", secret_number); -``` - -We use the `rand::thread_rng()` function to get a copy of the random number -generator, which is local to the particular [thread][concurrency] of execution -we’re in. Because we `use rand::Rng`’d above, it has a `gen_range()` method -available. This method takes two arguments, and generates a number between -them. It’s inclusive on the lower bound, but exclusive on the upper bound, -so we need `1` and `101` to get a number ranging from one to a hundred. -Nós usamos a função `rand::thread_rng()` para obter uma cópia do -gerador de números aleatórios, que é local à [*thread*][concurrency] -particular de execução na qual estamos. Como usamos o `use rand::Rng` -acima, ele tem um método `gen_range()` disponível. Este método toma -dois argumentos, e gera um número aleatório entre eles. Este método -inclui o limitante inferior mas exclui o superior, então precisamos de -`1` e `101` para obter um número de um a cem. - -[concurrency]: concurrency.html - -The second line prints out the secret number. This is useful while -we’re developing our program, so we can easily test it out. But we’ll be -deleting it for the final version. It’s not much of a game if it prints out -the answer when you start it up! -A segunda linha imprime o número secreto. Isto é útil enquanto estamos -desenvolvendo o programa, de forma que possamos facilmente -testá-lo. Mas o retiraremos na versão final. Um jogo não é muito -interessante se ele imprime a resposta quando o executamos! - -Try running our new program a few times: -Tente rodar nosso novo programa algumas vezes: - -```bash -$ cargo run - Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) - Finished debug [unoptimized + debuginfo] target(s) in 0.55 secs - Running `target/debug/guessing_game` -Guess the number! -The secret number is: 7 -Please input your guess. -4 -You guessed: 4 -$ cargo run - Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target/debug/guessing_game` -Guess the number! -The secret number is: 83 -Please input your guess. -5 -You guessed: 5 -``` - -Great! Next up: comparing our guess to the secret number. -Muito bom! A seguir: comparar nosso palpite com o número secreto. - -# Comparing guesses -# Comparando os Palpites - -Now that we’ve got user input, let’s compare our guess to the secret number. -Here’s our next step, though it doesn’t quite compile yet: -Agora que obtivemos a entrada do usuário, vamos comparar nosso palpite -com o número secreto. Este é nosso próximo passo, apesar de ainda não -compilar: - -```rust,ignore -extern crate rand; - -use std::io; -use std::cmp::Ordering; -use rand::Rng; - -fn main() { - println!("Guess the number!"); - - let secret_number = rand::thread_rng().gen_range(1, 101); - - 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); - - match guess.cmp(&secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => println!("You win!"), - } -} -``` - -A few new bits here. The first is another `use`. We bring a type called -`std::cmp::Ordering` into scope. Then, five new lines at the bottom that use -it: -Algumas coisinhas novas aqui. A primeira é outro `use`. Nós trouxemos -um tipo chamado `std::cmp::Ordering` para o escopo. Então, cinco novas -linhas no topo que o usam: - -```rust,ignore -match guess.cmp(&secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => println!("You win!"), -} -``` - -The `cmp()` method can be called on anything that can be compared, and it -takes a reference to the thing you want to compare it to. It returns the -`Ordering` type we `use`d earlier. We use a [`match`][match] statement to -determine exactly what kind of `Ordering` it is. `Ordering` is an -[`enum`][enum], short for ‘enumeration’, which looks like this: -O método `cmp()` pode ser chamado em qualquer coisa que possa ser -comparada, e ele toma uma referência à coisa com a qual você quer -comparar. Ele retorna o tipo `Ordering` que usamos antes. Nós usamos -uma declaração [`match`][match] para determinar exatamente o tipo de -`Ordering` que ele é. `Ordering` é uma [`enum`][enum], contração de -'enumeração', que se parece com isso: - -```rust -enum Foo { - Bar, - Baz, -} -``` - -[match]: match.html -[enum]: enums.html - -With this definition, anything of type `Foo` can be either a -`Foo::Bar` or a `Foo::Baz`. We use the `::` to indicate the -namespace for a particular `enum` variant. -Com esta definição, qualquer coisa do tipo `Foo` pode ser ou um -`Foo::Bar` ou um `Foo::Baz`. Usamos um `::` para indicar um -*namespace* (espaço de nomes) para uma variante `enum` particular. - -The [`Ordering`][ordering] `enum` has three possible variants: `Less`, `Equal`, -and `Greater`. The `match` statement takes a value of a type, and lets you -create an ‘arm’ for each possible value. Since we have three types of -`Ordering`, we have three arms: -A `enum` [`Ordering`][ordering] tem três variantes possíveis: `Less`, -`Equal` e `Greater` (respectivamente, 'menor', 'igual' e 'maior'). A -declaração `match` toma um valor de um tipo, e te permite criar um -'braço', um ramo, para cada valor possível. Desde que temos três tipos -de `Ordering`, teremos três ramos: - -```rust,ignore -match guess.cmp(&secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => println!("You win!"), -} -``` - -[ordering]: ../../std/cmp/enum.Ordering.html - -If it’s `Less`, we print `Too small!`, if it’s `Greater`, `Too big!`, and if -`Equal`, `You win!`. `match` is really useful, and is used often in Rust. -Se for o `Less`, imprimimos `Too small!`; se for `Greater`, `Too -big!`.; e se for `Equal`, `You win!`. `match` é realmente útil, e -usado com frequência em Rust. - -I did mention that this won’t quite compile yet, though. Let’s try it: -Eu mencionei que isto não compilaria ainda, porém. Vamos tentar: - -```bash -$ cargo build - Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) -error[E0308]: mismatched types - --> src/main.rs:23:21 - | -23 | match guess.cmp(&secret_number) { - | ^^^^^^^^^^^^^^ expected struct `std::string::String`, found integral variable - | - = note: expected type `&std::string::String` - = note: found type `&{integer}` - -error: aborting due to previous error - -error: Could not compile `guessing_game`. - -To learn more, run the command again with --verbose. -``` - -Whew! This is a big error. The core of it is that we have ‘mismatched types’. -Rust has a strong, static type system. However, it also has type inference. -When we wrote `let guess = String::new()`, Rust was able to infer that `guess` -should be a `String`, and so it doesn’t make us write out the type. And with -our `secret_number`, there are a number of types which can have a value -between one and a hundred: `i32`, a thirty-two-bit number, or `u32`, an -unsigned thirty-two-bit number, or `i64`, a sixty-four-bit number or others. -So far, that hasn’t mattered, and so Rust defaults to an `i32`. However, here, -Rust doesn’t know how to compare the `guess` and the `secret_number`. They -need to be the same type. Ultimately, we want to convert the `String` we -read as input into a real number type, for comparison. We can do that -with two more lines. Here’s our new program: -Nossa! Este é um erro grande. O núcleo dele é que temos 'tipos -incompatíveis'. Rust tem um sistema de tipos forte e estático. Porém, -Rust também tem inferência de tipo. Quando escrevemos `let guess = -String::new()`, Rust foi capaz de inferir que `guess` deveria ser um -`String`, então ele não nos faz escrever o tipo. e com nossos -`secret_number`, existe uma quantidade de tipos que podem ter valor -de um a cem: `i32`, um número de 32 bits, ou `u32`, um número de 32 -bits sem sinal (*unsigned*), ou `i64`, um número de 64 bits, ou -outros. Até aqui, isto não teve importância, e portanto Rust -estabelece como padrão o `i32`. Porém, agora, Rust não sabe como -comparar o `guess` e o `secret_number`. Eles precisam ser do mesmo -tipo. Em última análise, queremos converter o `String` que lemos como -entrada em um tipo real de número, para comparação. Podemos fazer isso -com mais duas linhas. Eis nosso novo programa: - -```rust,ignore -extern crate rand; - -use std::io; -use std::cmp::Ordering; -use rand::Rng; - -fn main() { - println!("Guess the number!"); - - let secret_number = rand::thread_rng().gen_range(1, 101); - - 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"); - - 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!"), - } -} -``` - -The new two lines: -As duas linhas novas: - -```rust,ignore - let guess: u32 = guess.trim().parse() - .expect("Please type a number!"); -``` - -Wait a minute, I thought we already had a `guess`? We do, but Rust allows us -to ‘shadow’ the previous `guess` with a new one. This is often used in this -exact situation, where `guess` starts as a `String`, but we want to convert it -to an `u32`. Shadowing lets us re-use the `guess` name, rather than forcing us -to come up with two unique names like `guess_str` and `guess`, or something -else. -Espera um minuto, eu pensei que já tínhamos um `guess`, não? Sim, -tínhamos, porém Rust nos permite "sombrear" o `guess` anterior com um -novo. Isto é usado comumente nesta exata situação, onde `guess` começa -como `String` mas queremos convertê-lo para `u32`. O sombreamento nos -permite reutilizar o nome `guess`, em vez de forçar-nos a ficar com -dois nomes únicos como `guess_str` e `guess`, ou algo mais. - -We bind `guess` to an expression that looks like something we wrote earlier: -Nós vinculamos `guess` a uma expressão que parece com algo que -escrevemos anteriormente: - -```rust,ignore -guess.trim().parse() -``` - -Here, `guess` refers to the old `guess`, the one that was a `String` with our -input in it. The `trim()` method on `String`s will eliminate any white space at -the beginning and end of our string. This is important, as we had to press the -‘return’ key to satisfy `read_line()`. This means that if we type `5` and hit -return, `guess` looks like this: `5\n`. The `\n` represents ‘newline’, the -enter key. `trim()` gets rid of this, leaving our string with only the `5`. The -[`parse()` method on strings][parse] parses a string into some kind of number. -Since it can parse a variety of numbers, we need to give Rust a hint as to the -exact type of number we want. Hence, `let guess: u32`. The colon (`:`) after -`guess` tells Rust we’re going to annotate its type. `u32` is an unsigned, -thirty-two bit integer. Rust has [a number of built-in number types][number], -but we’ve chosen `u32`. It’s a good default choice for a small positive number. -Aqui, `guess` refere-se à antiga `guess`, aquela que era uma `string` -com nossa entrada nela. O método `trim()` em `String`s eliminará -quaisquer espaços em branco no início ou no fim da nossa string. Isto -é importante, dado que temos que pressionar a tecla 'return' (mais -conhecida como 'Enter') para satisfazer `read_line()`. Isto significa -que se escrevermos `5` e apertarmos 'return', `guess` se parecerá com -isso: `5\n`. O `\n` representa 'nova linha' (*newline*), a tecla -Enter. 'trim()' elimina isso, deixando em nossa string apenas o '5'. O -método [`parse()` em strings][parse] analisa uma string para algum -tipo de número. Dado que ele pode interpretar uma variedade de -números, precisamos dar ao Rust uma dica de qual exato número nós -queremos. Daí, `let guess: u32`. O dois-pontos (`:`) depois de `guess` -informa o Rust que estamos anotando seu tipo. `u32` é um inteiro de 32 -bits sem sinal. Rust tem [uma variedade de tipos de números já -embutida][number], mas escolhemos `u32`. É uma boa escolha padrão para -um número positivo pequeno. - -[parse]: ../../std/primitive.str.html#method.parse -[number]: primitive-types.html#numeric-types - -Just like `read_line()`, our call to `parse()` could cause an error. What if -our string contained `A👍%`? There’d be no way to convert that to a number. As -such, we’ll do the same thing we did with `read_line()`: use the `expect()` -method to crash if there’s an error. -A exemplo de `read_line()`, nossa chamada para `parse()` pode causar -um erro. E se nossa string contiver `A👍%`? Não tem como converter -isto em um número. Como tal, faremos o mesmo que fizemos com -`read_line()`: usar o método `expect()` para quebrar se tivermos um -erro. - -Let’s try our program out! -Vamos tentar executar nosso programa! - -```bash -$ cargo run - Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) - Finished debug [unoptimized + debuginfo] target(s) in 0.57 secs - Running `target/guessing_game` -Guess the number! -The secret number is: 58 -Please input your guess. - 76 -You guessed: 76 -Too big! -``` - -Nice! You can see I even added spaces before my guess, and it still figured -out that I guessed 76. Run the program a few times, and verify that guessing -the number works, as well as guessing a number too small. -Boa! Você pode ver que eu até acrescentei espaços antes do meu -palpite, e o programa mesmo assim concluiu que eu palpitei 76. Execute -o programa mais algumas vezes, e verifique que palpitar o número -funciona, bem como palpitar um número muito pequeno. - -Now we’ve got most of the game working, but we can only make one guess. Let’s -change that by adding loops! -Agora nós conseguimos a maior parte do jogo funcionando, mas só -podemos oferecer um palpite. Vamos mudar isso adicionando laços! - -# Looping -# *Looping* - -The `loop` keyword gives us an infinite loop. Let’s add that in: -A palavra-chave `loop` nos fornece um laço (*loop*) infinito. Vamos -adicioná-la ao programa: - -```rust,ignore -extern crate rand; - -use std::io; -use std::cmp::Ordering; -use rand::Rng; - -fn main() { - println!("Guess the number!"); - - let secret_number = rand::thread_rng().gen_range(1, 101); - - 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); - - match guess.cmp(&secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => println!("You win!"), - } - } -} -``` - -And try it out. But wait, didn’t we just add an infinite loop? Yup. Remember -our discussion about `parse()`? If we give a non-number answer, we’ll `panic!` -and quit. Observe: -E tente usar. Mas espere, não acabamos de criar um laço infinito? -Sim. Lembra nossa discussão sobre `parse()`? Se fornecermos uma -resposta não-numérica, ele vai entrar em `panic!` e sair. Observe: - -```bash -$ cargo run - Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) - Finished debug [unoptimized + debuginfo] target(s) in 0.58 secs - Running `target/guessing_game` -Guess the number! -The secret number is: 59 -Please input your guess. -45 -You guessed: 45 -Too small! -Please input your guess. -60 -You guessed: 60 -Too big! -Please input your guess. -59 -You guessed: 59 -You win! -Please input your guess. -quit -thread 'main' panicked at 'Please type a number!' -``` - -Ha! `quit` actually quits. As does any other non-number input. Well, this is -suboptimal to say the least. First, let’s actually quit when you win the game: -Ha! `quit` de fato sai. Assim como qualquer outra entrada -não-numérica. Bem, isto é sub-ótimo, para falar o mínimo. Primeiro, -vamos realmente sair quando vencermos o jogo: - -```rust,ignore -extern crate rand; - -use std::io; -use std::cmp::Ordering; -use rand::Rng; - -fn main() { - println!("Guess the number!"); - - let secret_number = rand::thread_rng().gen_range(1, 101); - - 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); - - match guess.cmp(&secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => { - println!("You win!"); - break; - } - } - } -} -``` - -By adding the `break` line after the `You win!`, we’ll exit the loop when we -win. Exiting the loop also means exiting the program, since it’s the last -thing in `main()`. We have only one more tweak to make: when someone inputs a -non-number, we don’t want to quit, we want to ignore it. We can do that -like this: -Adicionando a linha `break` após o `You win!`, podemos sair do laço -quando vencermos. Nós temos apenas mais um ajuste para fazer: quando -alguém insere um não-número, não queremos sair, mas ignorá-lo. Podemos -fazer isso dessa forma: - -```rust,ignore -extern crate rand; - -use std::io; -use std::cmp::Ordering; -use rand::Rng; - -fn main() { - println!("Guess the number!"); - - let secret_number = rand::thread_rng().gen_range(1, 101); - - 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 = 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; - } - } - } -} -``` - -These are the lines that changed: -Estas são as linhas modificadas: - -```rust,ignore -let guess: u32 = match guess.trim().parse() { - Ok(num) => num, - Err(_) => continue, -}; -``` -This is how you generally move from ‘crash on error’ to ‘actually handle the -error’, by switching from `expect()` to a `match` statement. A `Result` is -returned by `parse()`, this is an `enum` like `Ordering`, but in this case, -each variant has some data associated with it: `Ok` is a success, and `Err` is a -failure. Each contains more information: the successfully parsed integer, or an -error type. In this case, we `match` on `Ok(num)`, which sets the name `num` to -the unwrapped `Ok` value (the integer), and then we return it on the -right-hand side. In the `Err` case, we don’t care what kind of error it is, so -we just use the catch all `_` instead of a name. This catches everything that -isn't `Ok`, and `continue` lets us move to the next iteration of the loop; in -effect, this enables us to ignore all errors and continue with our program. - -Now we should be good! Let’s try: -É desta forma que geralmente mudamos de 'quebrar em caso de erro' para -'realmente lidar com os erros', mudando de `expect()` para uma -declaração `match`. Um `Result` é retornado por `parse()`, ele é um -`enum` como `Ordering`, mas neste caso cada variante tem algum dado -associado a ela: `Ok` é sucesso, e `Err` é falha. Cada um contém mais -informação: o número analisado com sucesso ou um tipo erro. Neste -caso, fazemos o `match` em `Ok(num)`, que estabelece o nome `num` para -o valor não-envelopado (*unwrapped*) em `Ok` (o inteiro), e então o -retornamos para o lado direito. No caso de `Err`, não estamos -interessados no tipo de erro que seja, então apenas usamos o símbolo -`_` para capturar todas as ocorrências em vez de um nome. Isto captura -tudo que não seja `Ok`, e o `continue` nos permite mover para a -próxima iteração do laço; com efeito, permite que ignoremos todos os -erros e continuemos a execução do nosso programa. - -Agora devemos estar bem! Vamos tentar: - -```bash -$ cargo run - Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) - Finished debug [unoptimized + debuginfo] target(s) in 0.57 secs - Running `target/guessing_game` -Guess the number! -The secret number is: 61 -Please input your guess. -10 -You guessed: 10 -Too small! -Please input your guess. -99 -You guessed: 99 -Too big! -Please input your guess. -foo -Please input your guess. -61 -You guessed: 61 -You win! -``` - -Awesome! With one tiny last tweak, we have finished the guessing game. Can you -think of what it is? That’s right, we don’t want to print out the secret -number. It was good for testing, but it kind of ruins the game. Here’s our -final source: -Demais! Com apenas um último ajuste, terminaremos o jogo de -adivinhação. Consegue imaginar qual seja? Isso mesmo, não precisamos -imprimir o número secreto. Isto foi bom para testar, mas meio que -estraga o jogo. Eis nosso código final: - -```rust,ignore -extern crate rand; - -use std::io; -use std::cmp::Ordering; -use rand::Rng; - -fn main() { - println!("Guess the number!"); - - let secret_number = rand::thread_rng().gen_range(1, 101); - - 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; - } - } - } -} -``` - -# Complete! -# Completo! - -This project showed you a lot: `let`, `match`, methods, associated -functions, using external crates, and more. -Este projeto te mostrou muita coisa: `let`, `match`, métodos, funções -associadas, uso de *crates* externos etc.; - -At this point, you have successfully built the Guessing Game! Congratulations! -Neste ponto, você construiu com sucesso um Jogo de Adivinhação! -Parabéns! +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). diff --git a/first-edition/src/if-let.md b/first-edition/src/if-let.md index 9eeac3d687..b4a95d24f9 100644 --- a/first-edition/src/if-let.md +++ b/first-edition/src/if-let.md @@ -1,84 +1,10 @@ # if let -`if let` permits [patterns][patterns] matching within the condition of an [if][if] statement. -This allows us to reduce the overhead of certain kinds of [pattern][patterns] matches -and express them in a more convenient way. +The first edition of the book is no longer distributed with Rust's documentation. -For example, let’s say we have some sort of `Option`. We want to call a function -on it if it’s `Some`, but do nothing if it’s `None`. That looks like this: +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. -```rust -# let option = Some(5); -# fn foo(x: i32) { } -match option { - Some(x) => { foo(x) }, - None => {}, -} -``` - -We don’t have to use `match` here, for example, we could use `if`: - -```rust -# let option = Some(5); -# fn foo(x: i32) { } -if option.is_some() { - let x = option.unwrap(); - foo(x); -} -``` - -Neither of these options is particularly appealing. We can use `if let` to -do the same thing in a nicer way: - -```rust -# let option = Some(5); -# fn foo(x: i32) { } -if let Some(x) = option { - foo(x); -} -``` - -If a [pattern][patterns] matches successfully, it binds any appropriate parts of -the value to the identifiers in the pattern, then evaluates the expression. If -the pattern doesn’t match, nothing happens. - -If you want to do something else when the pattern does not match, you can -use `else`: - -```rust -# let option = Some(5); -# fn foo(x: i32) { } -# fn bar() { } -if let Some(x) = option { - foo(x); -} else { - bar(); -} -``` - -## `while let` - -In a similar fashion, `while let` can be used when you want to conditionally -loop as long as a value matches a certain pattern. It turns code like this: - -```rust -let mut v = vec![1, 3, 5, 7, 11]; -loop { - match v.pop() { - Some(x) => println!("{}", x), - None => break, - } -} -``` - -Into code like this: - -```rust -let mut v = vec![1, 3, 5, 7, 11]; -while let Some(x) = v.pop() { - println!("{}", x); -} -``` - -[patterns]: patterns.html -[if]: if.html +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). diff --git a/first-edition/src/if.md b/first-edition/src/if.md index d74503757b..bd8f8e6c77 100644 --- a/first-edition/src/if.md +++ b/first-edition/src/if.md @@ -1,73 +1,10 @@ # if -Rust’s take on `if` is not particularly complex, but it’s much more like the -`if` you’ll find in a dynamically typed language than in a more traditional -systems language. So let’s talk about it, to make sure you grasp the nuances. +The first edition of the book is no longer distributed with Rust's documentation. -`if` is a specific form of a more general concept, the ‘branch’, whose name comes -from a branch in a tree: a decision point, where depending on a choice, -multiple paths can be taken. +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. -In the case of `if`, there is one choice that leads down two paths: - -```rust -let x = 5; - -if x == 5 { - println!("x is five!"); -} -``` - -If we changed the value of `x` to something else, this line would not print. -More specifically, if the expression after the `if` evaluates to `true`, then -the block is executed. If it’s `false`, then it is not. - -If you want something to happen in the `false` case, use an `else`: - -```rust -let x = 5; - -if x == 5 { - println!("x is five!"); -} else { - println!("x is not five :("); -} -``` - -If there is more than one case, use an `else if`: - -```rust -let x = 5; - -if x == 5 { - println!("x is five!"); -} else if x == 6 { - println!("x is six!"); -} else { - println!("x is not five or six :("); -} -``` - -This is all pretty standard. However, you can also do this: - -```rust -let x = 5; - -let y = if x == 5 { - 10 -} else { - 15 -}; // y: i32 -``` - -Which we can (and probably should) write like this: - -```rust -let x = 5; - -let y = if x == 5 { 10 } else { 15 }; // y: i32 -``` - -This works because `if` is an expression. The value of the expression is the -value of the last expression in whichever branch was chosen. An `if` without an -`else` always results in `()` as the value. +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). diff --git a/first-edition/src/iterators.md b/first-edition/src/iterators.md index 588e983cb2..d4dbd1e299 100644 --- a/first-edition/src/iterators.md +++ b/first-edition/src/iterators.md @@ -1,343 +1,10 @@ # Iterators -Let's talk about loops. +The first edition of the book is no longer distributed with Rust's documentation. -Remember Rust's `for` loop? Here's an example: +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. -```rust -for x in 0..10 { - println!("{}", x); -} -``` - -Now that you know more Rust, we can talk in detail about how this works. -Ranges (the `0..10`) are 'iterators'. An iterator is something that we can -call the `.next()` method on repeatedly, and it gives us a sequence of things. - -A range with two dots like `0..10` is inclusive on the left (so it -starts at 0) and exclusive on the right (so it ends at 9). A mathematician -would write "[0, 10)". - -Like this: - -```rust -let mut range = 0..10; - -loop { - match range.next() { - Some(x) => { - println!("{}", x); - }, - None => { break } - } -} -``` - -We make a mutable binding to the range, which is our iterator. We then `loop`, -with an inner `match`. This `match` is used on the result of `range.next()`, -which gives us a reference to the next value of the iterator. `next` returns an -`Option`, in this case, which will be `Some(i32)` when we have a value and -`None` once we run out. If we get `Some(i32)`, we print it out, and if we get -`None`, we `break` out of the loop. - -This code sample is basically the same as our `for` loop version. The `for` -loop is a handy way to write this `loop`/`match`/`break` construct. - -`for` loops aren't the only thing that uses iterators, however. Writing your -own iterator involves implementing the `Iterator` trait. While doing that is -outside of the scope of this guide, Rust provides a number of useful iterators -to accomplish various tasks. But first, a few notes about limitations of ranges. - -Ranges are very primitive, and we often can use better alternatives. Consider the -following Rust anti-pattern: using ranges to emulate a C-style `for` loop. Let’s -suppose you needed to iterate over the contents of a vector. You may be tempted -to write this: - -```rust -let nums = vec![1, 2, 3]; - -for i in 0..nums.len() { - println!("{}", nums[i]); -} -``` - -This is strictly worse than using an actual iterator. You can iterate over vectors -directly, so write this: - -```rust -let nums = vec![1, 2, 3]; - -for num in &nums { - println!("{}", num); -} -``` - -There are two reasons for this. First, this more directly expresses what we -mean. We iterate through the entire vector, rather than iterating through -indexes, and then indexing the vector. Second, this version is more efficient: -the first version will have extra bounds checking because it used indexing, -`nums[i]`. But since we yield a reference to each element of the vector in turn -with the iterator, there's no bounds checking in the second example. This is -very common with iterators: we can ignore unnecessary bounds checks, but still -know that we're safe. - -There's another detail here that's not 100% clear because of how `println!` -works. `num` is actually of type `&i32`. That is, it's a reference to an `i32`, -not an `i32` itself. `println!` handles the dereferencing for us, so we don't -see it. This code works fine too: - -```rust -let nums = vec![1, 2, 3]; - -for num in &nums { - println!("{}", *num); -} -``` - -Now we're explicitly dereferencing `num`. Why does `&nums` give us -references? Firstly, because we explicitly asked it to with -`&`. Secondly, if it gave us the data itself, we would have to be its -owner, which would involve making a copy of the data and giving us the -copy. With references, we're only borrowing a reference to the data, -and so it's only passing a reference, without needing to do the move. - -So, now that we've established that ranges are often not what you want, let's -talk about what you do want instead. - -There are three broad classes of things that are relevant here: iterators, -*iterator adaptors*, and *consumers*. Here's some definitions: - -* *iterators* give you a sequence of values. -* *iterator adaptors* operate on an iterator, producing a new iterator with a - different output sequence. -* *consumers* operate on an iterator, producing some final set of values. - -Let's talk about consumers first, since you've already seen an iterator, ranges. - -## Consumers - -A *consumer* operates on an iterator, returning some kind of value or values. -The most common consumer is `collect()`. This code doesn't quite compile, -but it shows the intention: - -```rust,ignore -let one_to_one_hundred = (1..101).collect(); -``` - -As you can see, we call `collect()` on our iterator. `collect()` takes -as many values as the iterator will give it, and returns a collection -of the results. So why won't this compile? Rust can't determine what -type of things you want to collect, and so you need to let it know. -Here's the version that does compile: - -```rust -let one_to_one_hundred = (1..101).collect::>(); -``` - -If you remember, the [`::<>` syntax](generics.html#resolving-ambiguities) -allows us to give a type hint that tells the compiler we want a vector of -integers. You don't always need to use the whole type, though. Using a `_` -will let you provide a partial hint: - -```rust -let one_to_one_hundred = (1..101).collect::>(); -``` - -This says "Collect into a `Vec`, please, but infer what the `T` is for me." -`_` is sometimes called a "type placeholder" for this reason. - -`collect()` is the most common consumer, but there are others too. `find()` -is one: - -```rust -let greater_than_forty_two = (0..100) - .find(|x| *x > 42); - -match greater_than_forty_two { - Some(_) => println!("Found a match!"), - None => println!("No match found :("), -} -``` - -`find` takes a closure, and works on a reference to each element of an -iterator. This closure returns `true` if the element is the element we're -looking for, and `false` otherwise. `find` returns the first element satisfying -the specified predicate. Because we might not find a matching element, `find` -returns an `Option` rather than the element itself. - -Another important consumer is `fold`. Here's what it looks like: - -```rust -let sum = (1..4).fold(0, |sum, x| sum + x); -``` - -`fold()` is a consumer that looks like this: -`fold(base, |accumulator, element| ...)`. It takes two arguments: the first -is an element called the *base*. The second is a closure that itself takes two -arguments: the first is called the *accumulator*, and the second is an -*element*. Upon each iteration, the closure is called, and the result is the -value of the accumulator on the next iteration. On the first iteration, the -base is assigned the value of the accumulator. - -Okay, that's a bit confusing. Let's examine the values of all of these things -in this iterator: - -| base | accumulator | element | closure result | -|------|-------------|---------|----------------| -| 0 | 0 | 1 | 1 | -| 0 | 1 | 2 | 3 | -| 0 | 3 | 3 | 6 | - -We called `fold()` with these arguments: - -```rust -# (1..4) -.fold(0, |sum, x| sum + x); -``` - -So, `0` is our base, `sum` is our accumulator, and `x` is our element. On the -first iteration, we set `sum` to `0`, and `x` is the first element of `nums`, -`1`. We then add `sum` and `x`, which gives us `0 + 1 = 1`. On the second -iteration, that value becomes our accumulator, `sum`, and the element is -the second element of the array, `2`. `1 + 2 = 3`, and so that becomes -the value of the accumulator for the last iteration. On that iteration, -`x` is the last element, `3`, and `3 + 3 = 6`, which is our final -result for our sum. `1 + 2 + 3 = 6`, and that's the result we got. - -Whew. `fold` can be a bit strange the first few times you see it, but once it -clicks, you can use it all over the place. Any time you have a list of things, -and you want a single result, `fold` is appropriate. - -Consumers are important due to one additional property of iterators we haven't -talked about yet: laziness. Let's talk some more about iterators, and you'll -see why consumers matter. - -## Iterators - -As we've said before, an iterator is something that we can call the -`.next()` method on repeatedly, and it gives us a sequence of things. -Because you need to call the method, this means that iterators -can be *lazy* and not generate all of the values upfront. This code, -for example, does not actually generate the numbers `1-99`, instead -creating a value that merely represents the sequence: - -```rust -let nums = 1..100; -``` - -Since we didn't do anything with the range, it didn't generate the sequence. -Let's add the consumer: - -```rust -let nums = (1..100).collect::>(); -``` - -Now, `collect()` will require that the range gives it some numbers, and so -it will do the work of generating the sequence. - -Ranges are one of two basic iterators that you'll see. The other is `iter()`. -`iter()` can turn a vector into a simple iterator that gives you each element -in turn: - -```rust -let nums = vec![1, 2, 3]; - -for num in nums.iter() { - println!("{}", num); -} -``` - -These two basic iterators should serve you well. There are some more -advanced iterators, including ones that are infinite. - -That's enough about iterators. Iterator adaptors are the last concept -we need to talk about with regards to iterators. Let's get to it! - -## Iterator adaptors - -*Iterator adaptors* take an iterator and modify it somehow, producing -a new iterator. The simplest one is called `map`: - -```rust,ignore -(1..100).map(|x| x + 1); -``` - -`map` is called upon another iterator, and produces a new iterator where each -element reference has the closure it's been given as an argument called on it. -So this would give us the numbers from `2-100`. Well, almost! If you -compile the example, you'll get a warning: - -```text -warning: unused result which must be used: iterator adaptors are lazy and - do nothing unless consumed, #[warn(unused_must_use)] on by default -(1..100).map(|x| x + 1); - ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -``` - -Laziness strikes again! That closure will never execute. This example -doesn't print any numbers: - -```rust,ignore -(1..100).map(|x| println!("{}", x)); -``` - -If you are trying to execute a closure on an iterator for its side effects, -use `for` instead. - -There are tons of interesting iterator adaptors. `take(n)` will return an -iterator over the next `n` elements of the original iterator. Let's try it out -with an infinite iterator: - -```rust -for i in (1..).take(5) { - println!("{}", i); -} -``` - -This will print - -```text -1 -2 -3 -4 -5 -``` - -`filter()` is an adapter that takes a closure as an argument. This closure -returns `true` or `false`. The new iterator `filter()` produces -only the elements that the closure returns `true` for: - -```rust -for i in (1..100).filter(|&x| x % 2 == 0) { - println!("{}", i); -} -``` - -This will print all of the even numbers between one and a hundred. -(Note that, unlike `map`, the closure passed to `filter` is passed a reference -to the element instead of the element itself. The filter predicate here uses -the `&x` pattern to extract the integer. The filter closure is passed a -reference because it returns `true` or `false` instead of the element, -so the `filter` implementation must retain ownership to put the elements -into the newly constructed iterator.) - -You can chain all three things together: start with an iterator, adapt it -a few times, and then consume the result. Check it out: - -```rust -(1..) - .filter(|&x| x % 2 == 0) - .filter(|&x| x % 3 == 0) - .take(5) - .collect::>(); -``` - -This will give you a vector containing `6`, `12`, `18`, `24`, and `30`. - -This is just a small taste of what iterators, iterator adaptors, and consumers -can help you with. There are a number of really useful iterators, and you can -write your own as well. Iterators provide a safe, efficient way to manipulate -all kinds of lists. They're a little unusual at first, but if you play with -them, you'll get hooked. For a full list of the different iterators and -consumers, check out the [iterator module documentation](../../std/iter/index.html). +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). diff --git a/first-edition/src/lifetimes.md b/first-edition/src/lifetimes.md index 8947deaadb..2208c966e3 100644 --- a/first-edition/src/lifetimes.md +++ b/first-edition/src/lifetimes.md @@ -1,428 +1,10 @@ # Lifetimes -This is the last of three sections presenting Rust’s ownership system. This is one of -Rust’s most distinct and compelling features, with which Rust developers should -become quite acquainted. Ownership is how Rust achieves its largest goal, -memory safety. There are a few distinct concepts, each with its own chapter: +The first edition of the book is no longer distributed with Rust's documentation. -* [ownership][ownership], the key concept -* [borrowing][borrowing], and their associated feature ‘references’ -* lifetimes, which you’re reading now +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. -These three chapters are related, and in order. You’ll need all three to fully -understand the ownership system. - -[ownership]: ownership.html -[borrowing]: references-and-borrowing.html - -# Meta - -Before we get to the details, two important notes about the ownership system. - -Rust has a focus on safety and speed. It accomplishes these goals through many -‘zero-cost abstractions’, which means that in Rust, abstractions cost as little -as possible in order to make them work. The ownership system is a prime example -of a zero-cost abstraction. All of the analysis we’ll talk about in this guide -is _done at compile time_. You do not pay any run-time cost for any of these -features. - -However, this system does have a certain cost: learning curve. Many new users -to Rust experience something we like to call ‘fighting with the borrow -checker’, where the Rust compiler refuses to compile a program that the author -thinks is valid. This often happens because the programmer’s mental model of -how ownership should work doesn’t match the actual rules that Rust implements. -You probably will experience similar things at first. There is good news, -however: more experienced Rust developers report that once they work with the -rules of the ownership system for a period of time, they fight the borrow -checker less and less. - -With that in mind, let’s learn about lifetimes. - -# Lifetimes - -Lending out a reference to a resource that someone else owns can be -complicated. For example, imagine this set of operations: - -1. I acquire a handle to some kind of resource. -2. I lend you a reference to the resource. -3. I decide I’m done with the resource, and deallocate it, while you still have - your reference. -4. You decide to use the resource. - -Uh oh! Your reference is pointing to an invalid resource. This is called a -dangling pointer or ‘use after free’, when the resource is memory. A small -example of such a situation would be: - -```rust,ignore -let r; // Introduce reference: `r`. -{ - let i = 1; // Introduce scoped value: `i`. - r = &i; // Store reference of `i` in `r`. -} // `i` goes out of scope and is dropped. - -println!("{}", r); // `r` still refers to `i`. -``` - -To fix this, we have to make sure that step four never happens after step -three. In the small example above the Rust compiler is able to report the issue -as it can see the lifetimes of the various values in the function. - -When we have a function that takes arguments by reference the situation becomes -more complex. Consider the following example: - -```rust,ignore -fn skip_prefix(line: &str, prefix: &str) -> &str { - // ... -# line -} - -let line = "lang:en=Hello World!"; -let lang = "en"; - -let v; -{ - let p = format!("lang:{}=", lang); // -+ `p` comes into scope. - v = skip_prefix(line, p.as_str()); // | -} // -+ `p` goes out of scope. -println!("{}", v); -``` - -Here we have a function `skip_prefix` which takes two `&str` references -as parameters and returns a single `&str` reference. We call it -by passing in references to `line` and `p`: Two variables with different -lifetimes. Now the safety of the `println!`-line depends on whether the -reference returned by `skip_prefix` function references the still living -`line` or the already dropped `p` string. - -Because of the above ambiguity, Rust will refuse to compile the example -code. To get it to compile we need to tell the compiler more about the -lifetimes of the references. This can be done by making the lifetimes -explicit in the function declaration: - -```rust -fn skip_prefix<'a, 'b>(line: &'a str, prefix: &'b str) -> &'a str { - // ... -# line -} -``` - -Let's examine the changes without going too deep into the syntax for now - -we'll get to that later. The first change was adding the `<'a, 'b>` after the -method name. This introduces two lifetime parameters: `'a` and `'b`. Next, each -reference in the function signature was associated with one of the lifetime -parameters by adding the lifetime name after the `&`. This tells the compiler -how the lifetimes between different references are related. - -As a result the compiler is now able to deduce that the return value of -`skip_prefix` has the same lifetime as the `line` parameter, which makes the `v` -reference safe to use even after the `p` goes out of scope in the original -example. - -In addition to the compiler being able to validate the usage of `skip_prefix` -return value, it can also ensure that the implementation follows the contract -established by the function declaration. This is useful especially when you are -implementing traits that are introduced [later in the book][traits]. - -**Note** It's important to understand that lifetime annotations are -_descriptive_, not _prescriptive_. This means that how long a reference is valid -is determined by the code, not by the annotations. The annotations, however, -give information about lifetimes to the compiler that uses them to check the -validity of references. The compiler can do so without annotations in simple -cases, but needs the programmer's support in complex scenarios. - -[traits]: traits.html - -# Syntax - -The `'a` reads ‘the lifetime a’. Technically, every reference has some lifetime -associated with it, but the compiler lets you elide (i.e. omit, see -["Lifetime Elision"][lifetime-elision] below) them in common cases. Before we -get to that, though, let’s look at a short example with explicit lifetimes: - -[lifetime-elision]: #lifetime-elision - -```rust,ignore -fn bar<'a>(...) -``` - -We previously talked a little about [function syntax][functions], but we didn’t -discuss the `<>`s after a function’s name. A function can have ‘generic -parameters’ between the `<>`s, of which lifetimes are one kind. We’ll discuss -other kinds of generics [later in the book][generics], but for now, let’s -focus on the lifetimes aspect. - -[functions]: functions.html -[generics]: generics.html - -We use `<>` to declare our lifetimes. This says that `bar` has one lifetime, -`'a`. If we had two reference parameters with different lifetimes, it would -look like this: - - -```rust,ignore -fn bar<'a, 'b>(...) -``` - -Then in our parameter list, we use the lifetimes we’ve named: - -```rust,ignore -...(x: &'a i32) -``` - -If we wanted a `&mut` reference, we’d do this: - -```rust,ignore -...(x: &'a mut i32) -``` - -If you compare `&mut i32` to `&'a mut i32`, they’re the same, it’s that -the lifetime `'a` has snuck in between the `&` and the `mut i32`. We read `&mut -i32` as ‘a mutable reference to an `i32`’ and `&'a mut i32` as ‘a mutable -reference to an `i32` with the lifetime `'a`’. - -# In `struct`s - -You’ll also need explicit lifetimes when working with [`struct`][structs]s that -contain references: - -```rust -struct Foo<'a> { - x: &'a i32, -} - -fn main() { - let y = &5; // This is the same as `let _y = 5; let y = &_y;`. - let f = Foo { x: y }; - - println!("{}", f.x); -} -``` - -[structs]: structs.html - -As you can see, `struct`s can also have lifetimes. In a similar way to functions, - -```rust -struct Foo<'a> { -# x: &'a i32, -# } -``` - -declares a lifetime, and - -```rust -# struct Foo<'a> { -x: &'a i32, -# } -``` - -uses it. So why do we need a lifetime here? We need to ensure that any reference -to a `Foo` cannot outlive the reference to an `i32` it contains. - -## `impl` blocks - -Let’s implement a method on `Foo`: - -```rust -struct Foo<'a> { - x: &'a i32, -} - -impl<'a> Foo<'a> { - fn x(&self) -> &'a i32 { self.x } -} - -fn main() { - let y = &5; // This is the same as `let _y = 5; let y = &_y;`. - let f = Foo { x: y }; - - println!("x is: {}", f.x()); -} -``` - -As you can see, we need to declare a lifetime for `Foo` in the `impl` line. We repeat -`'a` twice, like on functions: `impl<'a>` defines a lifetime `'a`, and `Foo<'a>` -uses it. - -## Multiple lifetimes - -If you have multiple references, you can use the same lifetime multiple times: - -```rust -fn x_or_y<'a>(x: &'a str, y: &'a str) -> &'a str { -# x -# } -``` - -This says that `x` and `y` both are alive for the same scope, and that the -return value is also alive for that scope. If you wanted `x` and `y` to have -different lifetimes, you can use multiple lifetime parameters: - -```rust -fn x_or_y<'a, 'b>(x: &'a str, y: &'b str) -> &'a str { -# x -# } -``` - -In this example, `x` and `y` have different valid scopes, but the return value -has the same lifetime as `x`. - -## Thinking in scopes - -A way to think about lifetimes is to visualize the scope that a reference is -valid for. For example: - -```rust -fn main() { - let y = &5; // -+ `y` comes into scope. - // | - // Stuff... // | - // | -} // -+ `y` goes out of scope. -``` - -Adding in our `Foo`: - -```rust -struct Foo<'a> { - x: &'a i32, -} - -fn main() { - let y = &5; // -+ `y` comes into scope. - let f = Foo { x: y }; // -+ `f` comes into scope. - // | - // Stuff... // | - // | -} // -+ `f` and `y` go out of scope. -``` - -Our `f` lives within the scope of `y`, so everything works. What if it didn’t? -This code won’t work: - -```rust,ignore -struct Foo<'a> { - x: &'a i32, -} - -fn main() { - let x; // -+ `x` comes into scope. - // | - { // | - let y = &5; // ---+ `y` comes into scope. - let f = Foo { x: y }; // ---+ `f` comes into scope. - x = &f.x; // | | This causes an error. - } // ---+ `f` and y go out of scope. - // | - println!("{}", x); // | -} // -+ `x` goes out of scope. -``` - -Whew! As you can see here, the scopes of `f` and `y` are smaller than the scope -of `x`. But when we do `x = &f.x`, we make `x` a reference to something that’s -about to go out of scope. - -Named lifetimes are a way of giving these scopes a name. Giving something a -name is the first step towards being able to talk about it. - -## 'static - -The lifetime named ‘static’ is a special lifetime. It signals that something -has the lifetime of the entire program. Most Rust programmers first come across -`'static` when dealing with strings: - -```rust -let x: &'static str = "Hello, world."; -``` - -String literals have the type `&'static str` because the reference is always -alive: they are baked into the data segment of the final binary. Another -example are globals: - -```rust -static FOO: i32 = 5; -let x: &'static i32 = &FOO; -``` - -This adds an `i32` to the data segment of the binary, and `x` is a reference -to it. - -## Lifetime Elision - -Rust supports powerful local type inference in the bodies of functions, but it -deliberately does not perform any reasoning about types for item signatures. -However, for ergonomic reasons, a very restricted secondary inference algorithm called -“lifetime elision” does apply when judging lifetimes. Lifetime elision is concerned solely with inferring -lifetime parameters using three easily memorizable and unambiguous rules. This means lifetime elision -acts as a shorthand for writing an item signature, while not hiding -away the actual types involved as full local inference would if applied to it. - -When talking about lifetime elision, we use the terms *input lifetime* and -*output lifetime*. An *input lifetime* is a lifetime associated with a parameter -of a function, and an *output lifetime* is a lifetime associated with the return -value of a function. For example, this function has an input lifetime: - -```rust,ignore -fn foo<'a>(bar: &'a str) -``` - -This one has an output lifetime: - -```rust,ignore -fn foo<'a>() -> &'a str -``` - -This one has a lifetime in both positions: - -```rust,ignore -fn foo<'a>(bar: &'a str) -> &'a str -``` - -Here are the three rules: - -* Each elided lifetime in a function’s arguments becomes a distinct lifetime - parameter. - -* If there is exactly one input lifetime, elided or not, that lifetime is - assigned to all elided lifetimes in the return values of that function. - -* If there are multiple input lifetimes, but one of them is `&self` or `&mut - self`, the lifetime of `self` is assigned to all elided output lifetimes. - -Otherwise, it is an error to elide an output lifetime. - -### Examples - -Here are some examples of functions with elided lifetimes. We’ve paired each -example of an elided lifetime with its expanded form. - -```rust,ignore -fn print(s: &str); // elided -fn print<'a>(s: &'a str); // expanded - -fn debug(lvl: u32, s: &str); // elided -fn debug<'a>(lvl: u32, s: &'a str); // expanded -``` - -In the preceding example, `lvl` doesn’t need a lifetime because it’s not a -reference (`&`). Only things relating to references (such as a `struct` -which contains a reference) need lifetimes. - -```rust,ignore -fn substr(s: &str, until: u32) -> &str; // elided -fn substr<'a>(s: &'a str, until: u32) -> &'a str; // expanded - -fn get_str() -> &str; // ILLEGAL, no inputs - -fn frob(s: &str, t: &str) -> &str; // ILLEGAL, two inputs -fn frob<'a, 'b>(s: &'a str, t: &'b str) -> &str; // Expanded: Output lifetime is ambiguous - -fn get_mut(&mut self) -> &mut T; // elided -fn get_mut<'a>(&'a mut self) -> &'a mut T; // expanded - -fn args(&mut self, args: &[T]) -> &mut Command; // elided -fn args<'a, 'b, T: ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command; // expanded - -fn new(buf: &mut [u8]) -> BufWriter; // elided -fn new<'a>(buf: &'a mut [u8]) -> BufWriter<'a>; // expanded -``` +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). diff --git a/first-edition/src/loops.md b/first-edition/src/loops.md index 20e6eeef30..07ecd33424 100644 --- a/first-edition/src/loops.md +++ b/first-edition/src/loops.md @@ -1,215 +1,10 @@ # Loops -Rust currently provides three approaches to performing some kind of iterative activity. They are: `loop`, `while` and `for`. Each approach has its own set of uses. +The first edition of the book is no longer distributed with Rust's documentation. -## loop +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. -The infinite `loop` is the simplest form of loop available in Rust. Using the keyword `loop`, Rust provides a way to loop indefinitely until some terminating statement is reached. Rust's infinite `loop`s look like this: - -```rust,ignore -loop { - println!("Loop forever!"); -} -``` - -## while - -Rust also has a `while` loop. It looks like this: - -```rust -let mut x = 5; // mut x: i32 -let mut done = false; // mut done: bool - -while !done { - x += x - 3; - - println!("{}", x); - - if x % 5 == 0 { - done = true; - } -} -``` - -`while` loops are the correct choice when you’re not sure how many times -you need to loop. - -If you need an infinite loop, you may be tempted to write this: - -```rust,ignore -while true { -``` - -However, `loop` is far better suited to handle this case: - -```rust,ignore -loop { -``` - -Rust’s control-flow analysis treats this construct differently than a `while -true`, since we know that it will always loop. In general, the more information -we can give to the compiler, the better it can do with safety and code -generation, so you should always prefer `loop` when you plan to loop -infinitely. - -## for - -The `for` loop is used to loop a particular number of times. Rust’s `for` loops -work a bit differently than in other systems languages, however. Rust’s `for` -loop doesn’t look like this “C-style” `for` loop: - -```c -for (x = 0; x < 10; x++) { - printf( "%d\n", x ); -} -``` - -Instead, it looks like this: - -```rust -for x in 0..10 { - println!("{}", x); // x: i32 -} -``` - -In slightly more abstract terms, - -```rust,ignore -for var in expression { - code -} -``` - -The expression is an item that can be converted into an [iterator] using -[`IntoIterator`]. The iterator gives back a series of elements, one element per -iteration of the loop. That value is then bound to the name `var`, which is -valid for the loop body. Once the body is over, the next value is fetched from -the iterator, and we loop another time. When there are no more values, the `for` -loop is over. - -[iterator]: iterators.html -[`IntoIterator`]: ../../std/iter/trait.IntoIterator.html - -In our example, `0..10` is an expression that takes a start and an end position, -and gives an iterator over those values. The upper bound is exclusive, though, -so our loop will print `0` through `9`, not `10`. - -Rust does not have the “C-style” `for` loop on purpose. Manually controlling -each element of the loop is complicated and error prone, even for experienced C -developers. - -### Enumerate - -When you need to keep track of how many times you have already looped, you can -use the `.enumerate()` function. - -#### On ranges: - -```rust -for (index, value) in (5..10).enumerate() { - println!("index = {} and value = {}", index, value); -} -``` - -Outputs: - -```text -index = 0 and value = 5 -index = 1 and value = 6 -index = 2 and value = 7 -index = 3 and value = 8 -index = 4 and value = 9 -``` - -Don't forget to add the parentheses around the range. - -#### On iterators: - -```rust -let lines = "hello\nworld".lines(); - -for (linenumber, line) in lines.enumerate() { - println!("{}: {}", linenumber, line); -} -``` - -Outputs: - -```text -0: hello -1: world -``` - -## Ending iteration early - -Let’s take a look at that `while` loop we had earlier: - -```rust -let mut x = 5; -let mut done = false; - -while !done { - x += x - 3; - - println!("{}", x); - - if x % 5 == 0 { - done = true; - } -} -``` - -We had to keep a dedicated `mut` boolean variable binding, `done`, to know -when we should exit out of the loop. Rust has two keywords to help us with -modifying iteration: `break` and `continue`. - -In this case, we can write the loop in a better way with `break`: - -```rust -let mut x = 5; - -loop { - x += x - 3; - - println!("{}", x); - - if x % 5 == 0 { break; } -} -``` - -We now loop forever with `loop` and use `break` to break out early. Issuing an explicit `return` statement will also serve to terminate the loop early. - -`continue` is similar, but instead of ending the loop, it goes to the next -iteration. This will only print the odd numbers: - -```rust -for x in 0..10 { - if x % 2 == 0 { continue; } - - println!("{}", x); -} -``` - -## Loop labels - -You may also encounter situations where you have nested loops and need to -specify which one your `break` or `continue` statement is for. Like most -other languages, Rust's `break` or `continue` apply to the innermost loop. -In a situation where you would like to `break` or `continue` for one -of the outer loops, you can use labels to specify which loop the `break` or -`continue` statement applies to. - -In the example below, we `continue` to the next iteration of `outer` loop -when `x` is even, while we `continue` to the next iteration of `inner` -loop when y is even. So it will execute the `println!` when both `x` and -`y` are odd. - -```rust -'outer: for x in 0..10 { - 'inner: for y in 0..10 { - if x % 2 == 0 { continue 'outer; } // Continues the loop over `x`. - if y % 2 == 0 { continue 'inner; } // Continues the loop over `y`. - println!("x: {}, y: {}", x, y); - } -} -``` +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). diff --git a/first-edition/src/macros.md b/first-edition/src/macros.md index f7499bff35..6bafdc1e43 100644 --- a/first-edition/src/macros.md +++ b/first-edition/src/macros.md @@ -1,786 +1,10 @@ # Macros -By now you’ve learned about many of the tools Rust provides for abstracting and -reusing code. These units of code reuse have a rich semantic structure. For -example, functions have a type signature, type parameters have trait bounds, -and overloaded functions must belong to a particular trait. +The first edition of the book is no longer distributed with Rust's documentation. -This structure means that Rust’s core abstractions have powerful compile-time -correctness checking. But this comes at the price of reduced flexibility. If -you visually identify a pattern of repeated code, you may find it’s difficult -or cumbersome to express that pattern as a generic function, a trait, or -anything else within Rust’s semantics. +If you came here via a link or web search, you may want to check out [the current +version of the book](../ch19-06-macros.html) instead. -Macros allow us to abstract at a syntactic level. A macro invocation is -shorthand for an "expanded" syntactic form. This expansion happens early in -compilation, before any static checking. As a result, macros can capture many -patterns of code reuse that Rust’s core abstractions cannot. - -The drawback is that macro-based code can be harder to understand, because -fewer of the built-in rules apply. Like an ordinary function, a well-behaved -macro can be used without understanding its implementation. However, it can be -difficult to design a well-behaved macro! Additionally, compiler errors in -macro code are harder to interpret, because they describe problems in the -expanded code, not the source-level form that developers use. - -These drawbacks make macros something of a "feature of last resort". That’s not -to say that macros are bad; they are part of Rust because sometimes they’re -needed for truly concise, well-abstracted code. Just keep this tradeoff in -mind. - -# Defining a macro - -You may have seen the `vec!` macro, used to initialize a [vector][vector] with -any number of elements. - -[vector]: vectors.html - -```rust -let x: Vec = vec![1, 2, 3]; -# assert_eq!(x, [1, 2, 3]); -``` - -This can’t be an ordinary function, because it takes any number of arguments. -But we can imagine it as syntactic shorthand for - -```rust -let x: Vec = { - let mut temp_vec = Vec::new(); - temp_vec.push(1); - temp_vec.push(2); - temp_vec.push(3); - temp_vec -}; -# assert_eq!(x, [1, 2, 3]); -``` - -We can implement this shorthand, using a macro: [^actual] - -[^actual]: The actual definition of `vec!` in libcollections differs from the - one presented here, for reasons of efficiency and reusability. - - -```rust -macro_rules! vec { - ( $( $x:expr ),* ) => { - { - let mut temp_vec = Vec::new(); - $( - temp_vec.push($x); - )* - temp_vec - } - }; -} -# fn main() { -# assert_eq!(vec![1,2,3], [1, 2, 3]); -# } -``` - -Whoa, that’s a lot of new syntax! Let’s break it down. - -```rust,ignore -macro_rules! vec { ... } -``` - -This says we’re defining a macro named `vec`, much as `fn vec` would define a -function named `vec`. In prose, we informally write a macro’s name with an -exclamation point, e.g. `vec!`. The exclamation point is part of the invocation -syntax and serves to distinguish a macro from an ordinary function. - -## Matching - -The macro is defined through a series of rules, which are pattern-matching -cases. Above, we had - -```rust,ignore -( $( $x:expr ),* ) => { ... }; -``` - -This is like a `match` expression arm, but the matching happens on Rust syntax -trees, at compile time. The semicolon is optional on the last (here, only) -case. The "pattern" on the left-hand side of `=>` is known as a ‘matcher’. -These have [their own little grammar] within the language. - -[their own little grammar]: ../../reference/macros.html - -The matcher `$x:expr` will match any Rust expression, binding that syntax tree -to the ‘metavariable’ `$x`. The identifier `expr` is a ‘fragment specifier’; -the full possibilities are enumerated later in this chapter. -Surrounding the matcher with `$(...),*` will match zero or more expressions, -separated by commas. - -Aside from the special matcher syntax, any Rust tokens that appear in a matcher -must match exactly. For example, - -```rust,ignore -macro_rules! foo { - (x => $e:expr) => (println!("mode X: {}", $e)); - (y => $e:expr) => (println!("mode Y: {}", $e)); -} - -fn main() { - foo!(y => 3); -} -``` - -will print - -```text -mode Y: 3 -``` - -With - -```rust,ignore -foo!(z => 3); -``` - -we get the compiler error - -```text -error: no rules expected the token `z` -``` - -## Expansion - -The right-hand side of a macro rule is ordinary Rust syntax, for the most part. -But we can splice in bits of syntax captured by the matcher. From the original -example: - -```rust,ignore -$( - temp_vec.push($x); -)* -``` - -Each matched expression `$x` will produce a single `push` statement in the -macro expansion. The repetition in the expansion proceeds in "lockstep" with -repetition in the matcher (more on this in a moment). - -Because `$x` was already declared as matching an expression, we don’t repeat -`:expr` on the right-hand side. Also, we don’t include a separating comma as -part of the repetition operator. Instead, we have a terminating semicolon -within the repeated block. - -Another detail: the `vec!` macro has *two* pairs of braces on the right-hand -side. They are often combined like so: - -```rust,ignore -macro_rules! foo { - () => {{ - ... - }} -} -``` - -The outer braces are part of the syntax of `macro_rules!`. In fact, you can use -`()` or `[]` instead. They simply delimit the right-hand side as a whole. - -The inner braces are part of the expanded syntax. Remember, the `vec!` macro is -used in an expression context. To write an expression with multiple statements, -including `let`-bindings, we use a block. If your macro expands to a single -expression, you don’t need this extra layer of braces. - -Note that we never *declared* that the macro produces an expression. In fact, -this is not determined until we use the macro as an expression. With care, you -can write a macro whose expansion works in several contexts. For example, -shorthand for a data type could be valid as either an expression or a pattern. - -## Repetition - -The repetition operator follows two principal rules: - -1. `$(...)*` walks through one "layer" of repetitions, for all of the `$name`s - it contains, in lockstep, and -2. each `$name` must be under at least as many `$(...)*`s as it was matched - against. If it is under more, it’ll be duplicated, as appropriate. - -This baroque macro illustrates the duplication of variables from outer -repetition levels. - -```rust -macro_rules! o_O { - ( - $( - $x:expr; [ $( $y:expr ),* ] - );* - ) => { - &[ $($( $x + $y ),*),* ] - } -} - -fn main() { - let a: &[i32] - = o_O!(10; [1, 2, 3]; - 20; [4, 5, 6]); - - assert_eq!(a, [11, 12, 13, 24, 25, 26]); -} -``` - -That’s most of the matcher syntax. These examples use `$(...)*`, which is a -"zero or more" match. Alternatively you can write `$(...)+` for a "one or -more" match. Both forms optionally include a separator, which can be any token -except `+` or `*`. - -This system is based on -"[Macro-by-Example](https://www.cs.indiana.edu/ftp/techreports/TR206.pdf)" -(PDF link). - -# Hygiene - -Some languages implement macros using simple text substitution, which leads to -various problems. For example, this C program prints `13` instead of the -expected `25`. - -```text -#define FIVE_TIMES(x) 5 * x - -int main() { - printf("%d\n", FIVE_TIMES(2 + 3)); - return 0; -} -``` - -After expansion we have `5 * 2 + 3`, and multiplication has greater precedence -than addition. If you’ve used C macros a lot, you probably know the standard -idioms for avoiding this problem, as well as five or six others. In Rust, we -don’t have to worry about it. - -```rust -macro_rules! five_times { - ($x:expr) => (5 * $x); -} - -fn main() { - assert_eq!(25, five_times!(2 + 3)); -} -``` - -The metavariable `$x` is parsed as a single expression node, and keeps its -place in the syntax tree even after substitution. - -Another common problem in macro systems is ‘variable capture’. Here’s a C -macro using a block with multiple statements. - -```text -#define LOG(msg) do { \ - int state = get_log_state(); \ - if (state > 0) { \ - printf("log(%d): %s\n", state, msg); \ - } \ -} while (0) -``` - -Here’s a simple use case that goes terribly wrong: - -```text -const char *state = "reticulating splines"; -LOG(state); -``` - -This expands to - -```text -const char *state = "reticulating splines"; -do { - int state = get_log_state(); - if (state > 0) { - printf("log(%d): %s\n", state, state); - } -} while (0); -``` - -The second variable named `state` shadows the first one. This is a problem -because the print statement should refer to both of them. - -The equivalent Rust macro has the desired behavior. - -```rust -# fn get_log_state() -> i32 { 3 } -macro_rules! log { - ($msg:expr) => {{ - let state: i32 = get_log_state(); - if state > 0 { - println!("log({}): {}", state, $msg); - } - }}; -} - -fn main() { - let state: &str = "reticulating splines"; - log!(state); -} -``` - -This works because Rust has a [hygienic macro system]. Each macro expansion -happens in a distinct ‘syntax context’, and each variable is tagged with the -syntax context where it was introduced. It’s as though the variable `state` -inside `main` is painted a different "color" from the variable `state` inside -the macro, and therefore they don’t conflict. - -[hygienic macro system]: https://en.wikipedia.org/wiki/Hygienic_macro - -This also restricts the ability of macros to introduce new bindings at the -invocation site. Code such as the following will not work: - -```rust,ignore -macro_rules! foo { - () => (let x = 3;); -} - -fn main() { - foo!(); - println!("{}", x); -} -``` - -Instead you need to pass the variable name into the invocation, so that it’s -tagged with the right syntax context. - -```rust -macro_rules! foo { - ($v:ident) => (let $v = 3;); -} - -fn main() { - foo!(x); - println!("{}", x); -} -``` - -This holds for `let` bindings and loop labels, but not for [items][items]. -So the following code does compile: - -```rust -macro_rules! foo { - () => (fn x() { }); -} - -fn main() { - foo!(); - x(); -} -``` - -[items]: ../../reference/items.html - -# Recursive macros - -A macro’s expansion can include more macro invocations, including invocations -of the very same macro being expanded. These recursive macros are useful for -processing tree-structured input, as illustrated by this (simplistic) HTML -shorthand: - -```rust -# #![allow(unused_must_use)] -macro_rules! write_html { - ($w:expr, ) => (()); - - ($w:expr, $e:tt) => (write!($w, "{}", $e)); - - ($w:expr, $tag:ident [ $($inner:tt)* ] $($rest:tt)*) => {{ - write!($w, "<{}>", stringify!($tag)); - write_html!($w, $($inner)*); - write!($w, "", stringify!($tag)); - write_html!($w, $($rest)*); - }}; -} - -fn main() { -# // FIXME(#21826) - use std::fmt::Write; - let mut out = String::new(); - - write_html!(&mut out, - html[ - head[title["Macros guide"]] - body[h1["Macros are the best!"]] - ]); - - assert_eq!(out, - "Macros guide\ -

Macros are the best!

"); -} -``` - -# Debugging macro code - -To see the results of expanding macros, run `rustc --pretty expanded`. The -output represents a whole crate, so you can also feed it back in to `rustc`, -which will sometimes produce better error messages than the original -compilation. Note that the `--pretty expanded` output may have a different -meaning if multiple variables of the same name (but different syntax contexts) -are in play in the same scope. In this case `--pretty expanded,hygiene` will -tell you about the syntax contexts. - -`rustc` provides two syntax extensions that help with macro debugging. For now, -they are unstable and require feature gates. - -* `log_syntax!(...)` will print its arguments to standard output, at compile - time, and "expand" to nothing. - -* `trace_macros!(true)` will enable a compiler message every time a macro is - expanded. Use `trace_macros!(false)` later in expansion to turn it off. - -# Syntactic requirements - -Even when Rust code contains un-expanded macros, it can be parsed as a full -[syntax tree][ast]. This property can be very useful for editors and other -tools that process code. It also has a few consequences for the design of -Rust’s macro system. - -[ast]: glossary.html#abstract-syntax-tree - -One consequence is that Rust must determine, when it parses a macro invocation, -whether the macro stands in for - -* zero or more items, -* zero or more methods, -* an expression, -* a statement, or -* a pattern. - -A macro invocation within a block could stand for some items, or for an -expression / statement. Rust uses a simple rule to resolve this ambiguity. A -macro invocation that stands for items must be either - -* delimited by curly braces, e.g. `foo! { ... }`, or -* terminated by a semicolon, e.g. `foo!(...);` - -Another consequence of pre-expansion parsing is that the macro invocation must -consist of valid Rust tokens. Furthermore, parentheses, brackets, and braces -must be balanced within a macro invocation. For example, `foo!([)` is -forbidden. This allows Rust to know where the macro invocation ends. - -More formally, the macro invocation body must be a sequence of ‘token trees’. -A token tree is defined recursively as either - -* a sequence of token trees surrounded by matching `()`, `[]`, or `{}`, or -* any other single token. - -Within a matcher, each metavariable has a ‘fragment specifier’, identifying -which syntactic form it matches. - -* `ident`: an identifier. Examples: `x`; `foo`. -* `path`: a qualified name. Example: `T::SpecialA`. -* `expr`: an expression. Examples: `2 + 2`; `if true { 1 } else { 2 }`; `f(42)`. -* `ty`: a type. Examples: `i32`; `Vec<(char, String)>`; `&T`. -* `pat`: a pattern. Examples: `Some(t)`; `(17, 'a')`; `_`. -* `stmt`: a single statement. Example: `let x = 3`. -* `block`: a brace-delimited sequence of statements and optionally an expression. Example: - `{ log(error, "hi"); return 12; }`. -* `item`: an [item][item]. Examples: `fn foo() { }`; `struct Bar;`. -* `meta`: a "meta item", as found in attributes. Example: `cfg(target_os = "windows")`. -* `tt`: a single token tree. - -There are additional rules regarding the next token after a metavariable: - -* `expr` and `stmt` variables may only be followed by one of: `=> , ;` -* `ty` and `path` variables may only be followed by one of: `=> , = | ; : > [ { as where` -* `pat` variables may only be followed by one of: `=> , = | if in` -* Other variables may be followed by any token. - -These rules provide some flexibility for Rust’s syntax to evolve without -breaking existing macros. - -The macro system does not deal with parse ambiguity at all. For example, the -grammar `$($i:ident)* $e:expr` will always fail to parse, because the parser would -be forced to choose between parsing `$i` and parsing `$e`. Changing the -invocation syntax to put a distinctive token in front can solve the problem. In -this case, you can write `$(I $i:ident)* E $e:expr`. - -[item]: ../../reference/items.html - -# Scoping and macro import/export - -Macros are expanded at an early stage in compilation, before name resolution. -One downside is that scoping works differently for macros, compared to other -constructs in the language. - -Definition and expansion of macros both happen in a single depth-first, -lexical-order traversal of a crate’s source. So a macro defined at module scope -is visible to any subsequent code in the same module, which includes the body -of any subsequent child `mod` items. If you want to use your macro, which is -defined in a different module, you need to use `macro_use` attribute *before* -using the macro. Let's say our macros are defined in module `macros` and we -would like to use them inside module `client`. This is the required module -definition order: - -```rust -#[macro_use] -mod macros; -mod client; -``` - -The opposite order would result in a compilation failure: - -```rust -mod client; -#[macro_use] -mod macros; -``` - -```bash -error: cannot find macro `my_macro!` in this scope -``` - -A macro defined within the body of a single `fn`, or anywhere else not at -module scope, is visible only within that item. - -If a module has the `macro_use` attribute, its macros are also visible in its -parent module after the child’s `mod` item. If the parent also has `macro_use` -then the macros will be visible in the grandparent after the parent’s `mod` -item, and so forth. - -The `macro_use` attribute can also appear on `extern crate`. In this context -it controls which macros are loaded from the external crate, e.g. - -```rust,ignore -#[macro_use(foo, bar)] -extern crate baz; -``` - -If the attribute is given simply as `#[macro_use]`, all macros are loaded. If -there is no `#[macro_use]` attribute then no macros are loaded. Only macros -defined with the `#[macro_export]` attribute may be loaded. - -To load a crate’s macros without linking it into the output, use `#[no_link]` -as well. - -An example: - -```rust -macro_rules! m1 { () => (()) } - -// Visible here: `m1`. - -mod foo { - // Visible here: `m1`. - - #[macro_export] - macro_rules! m2 { () => (()) } - - // Visible here: `m1`, `m2`. -} - -// Visible here: `m1`. - -macro_rules! m3 { () => (()) } - -// Visible here: `m1`, `m3`. - -#[macro_use] -mod bar { - // Visible here: `m1`, `m3`. - - macro_rules! m4 { () => (()) } - - // Visible here: `m1`, `m3`, `m4`. -} - -// Visible here: `m1`, `m3`, `m4`. -# fn main() { } -``` - -When this library is loaded with `#[macro_use] extern crate`, only `m2` will -be imported. - -The Rust Reference has a [listing of macro-related -attributes](../../reference/attributes.html#macro-related-attributes). - -# The variable `$crate` - -A further difficulty occurs when a macro is used in multiple crates. Say that -`mylib` defines - -```rust -pub fn increment(x: u32) -> u32 { - x + 1 -} - -#[macro_export] -macro_rules! inc_a { - ($x:expr) => ( ::increment($x) ) -} - -#[macro_export] -macro_rules! inc_b { - ($x:expr) => ( ::mylib::increment($x) ) -} -# fn main() { } -``` - -`inc_a` only works within `mylib`, while `inc_b` only works outside the -library. Furthermore, `inc_b` will break if the user imports `mylib` under -another name. - -Rust does not (yet) have a hygiene system for crate references, but it does -provide a simple workaround for this problem. Within a macro imported from a -crate named `foo`, the special macro variable `$crate` will expand to `::foo`. -By contrast, when a macro is defined and then used in the same crate, `$crate` -will expand to nothing. This means we can write - -```rust -#[macro_export] -macro_rules! inc { - ($x:expr) => ( $crate::increment($x) ) -} -# fn main() { } -``` - -to define a single macro that works both inside and outside our library. The -function name will expand to either `::increment` or `::mylib::increment`. - -To keep this system simple and correct, `#[macro_use] extern crate ...` may -only appear at the root of your crate, not inside `mod`. - -# The deep end - -The introductory chapter mentioned recursive macros, but it did not give the -full story. Recursive macros are useful for another reason: Each recursive -invocation gives you another opportunity to pattern-match the macro’s -arguments. - -As an extreme example, it is possible, though hardly advisable, to implement -the [Bitwise Cyclic Tag](https://esolangs.org/wiki/Bitwise_Cyclic_Tag) automaton -within Rust’s macro system. - -```rust -macro_rules! bct { - // cmd 0: d ... => ... - (0, $($ps:tt),* ; $_d:tt) - => (bct!($($ps),*, 0 ; )); - (0, $($ps:tt),* ; $_d:tt, $($ds:tt),*) - => (bct!($($ps),*, 0 ; $($ds),*)); - - // cmd 1p: 1 ... => 1 ... p - (1, $p:tt, $($ps:tt),* ; 1) - => (bct!($($ps),*, 1, $p ; 1, $p)); - (1, $p:tt, $($ps:tt),* ; 1, $($ds:tt),*) - => (bct!($($ps),*, 1, $p ; 1, $($ds),*, $p)); - - // cmd 1p: 0 ... => 0 ... - (1, $p:tt, $($ps:tt),* ; $($ds:tt),*) - => (bct!($($ps),*, 1, $p ; $($ds),*)); - - // Halt on empty data string: - ( $($ps:tt),* ; ) - => (()); -} -``` - -Exercise: use macros to reduce duplication in the above definition of the -`bct!` macro. - -# Common macros - -Here are some common macros you’ll see in Rust code. - -## panic! - -This macro causes the current thread to panic. You can give it a message -to panic with: - -```rust,should_panic -panic!("oh no!"); -``` - -## vec! - -The `vec!` macro is used throughout the book, so you’ve probably seen it -already. It creates `Vec`s with ease: - -```rust -let v = vec![1, 2, 3, 4, 5]; -``` - -It also lets you make vectors with repeating values. For example, a hundred -zeroes: - -```rust -let v = vec![0; 100]; -``` - -## assert! and assert_eq! - -These two macros are used in tests. `assert!` takes a boolean. `assert_eq!` -takes two values and checks them for equality. `true` passes, `false` `panic!`s. -Like this: - -```rust,should_panic -// A-ok! - -assert!(true); -assert_eq!(5, 3 + 2); - -// Nope :( - -assert!(5 < 3); -assert_eq!(5, 3); -``` - -## try! - -`try!` is used for error handling. It takes something that can return a -`Result`, and gives `T` if it’s a `Ok`, and `return`s with the -`Err(E)` if it’s that. Like this: - -```rust,no_run -use std::fs::File; - -fn foo() -> std::io::Result<()> { - let f = try!(File::create("foo.txt")); - - Ok(()) -} -``` - -This is cleaner than doing this: - -```rust,no_run -use std::fs::File; - -fn foo() -> std::io::Result<()> { - let f = File::create("foo.txt"); - - let f = match f { - Ok(t) => t, - Err(e) => return Err(e), - }; - - Ok(()) -} -``` - -## unreachable! - -This macro is used when you think some code should never execute: - -```rust -if false { - unreachable!(); -} -``` - -Sometimes, the compiler may make you have a different branch that you know -will never, ever run. In these cases, use this macro, so that if you end -up wrong, you’ll get a `panic!` about it. - -```rust -let x: Option = None; - -match x { - Some(_) => unreachable!(), - None => println!("I know x is None!"), -} -``` - -## unimplemented! - -The `unimplemented!` macro can be used when you’re trying to get your functions -to typecheck, and don’t want to worry about writing out the body of the -function. One example of this situation is implementing a trait with multiple -required methods, where you want to tackle one at a time. Define the others -as `unimplemented!` until you’re ready to write them. +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). diff --git a/first-edition/src/match.md b/first-edition/src/match.md index b1e26a9c9d..b9808193e2 100644 --- a/first-edition/src/match.md +++ b/first-edition/src/match.md @@ -1,100 +1,10 @@ # Match -Often, a simple [`if`][if]/`else` isn’t enough, because you have more than two -possible options. Also, conditions can get quite complex. Rust -has a keyword, `match`, that allows you to replace complicated `if`/`else` -groupings with something more powerful. Check it out: +The first edition of the book is no longer distributed with Rust's documentation. -```rust -let x = 5; +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. -match x { - 1 => println!("one"), - 2 => println!("two"), - 3 => println!("three"), - 4 => println!("four"), - 5 => println!("five"), - _ => println!("something else"), -} -``` - -[if]: if.html - -`match` takes an expression and then branches based on its value. Each ‘arm’ of -the branch is of the form `val => expression`. When the value matches, that arm’s -expression will be evaluated. It’s called `match` because of the term ‘pattern -matching’, which `match` is an implementation of. There’s a [separate section on -patterns][patterns] that covers all the patterns that are possible here. - -[patterns]: patterns.html - -One of the many advantages of `match` is it enforces ‘exhaustiveness checking’. -For example if we remove the last arm with the underscore `_`, the compiler will -give us an error: - -```text -error: non-exhaustive patterns: `_` not covered -``` - -Rust is telling us that we forgot some value. The compiler infers from `x` that it -can have any 32bit integer value; for example -2,147,483,648 to 2,147,483,647. The `_` acts -as a 'catch-all', and will catch all possible values that *aren't* specified in -an arm of `match`. As you can see in the previous example, we provide `match` -arms for integers 1-5, if `x` is 6 or any other value, then it is caught by `_`. - -`match` is also an expression, which means we can use it on the right-hand -side of a `let` binding or directly where an expression is used: - -```rust -let x = 5; - -let number = match x { - 1 => "one", - 2 => "two", - 3 => "three", - 4 => "four", - 5 => "five", - _ => "something else", -}; -``` - -Sometimes it’s a nice way of converting something from one type to another; in -this example the integers are converted to `String`. - -# Matching on enums - -Another important use of the `match` keyword is to process the possible -variants of an enum: - -```rust -enum Message { - Quit, - ChangeColor(i32, i32, i32), - Move { x: i32, y: i32 }, - Write(String), -} - -fn quit() { /* ... */ } -fn change_color(r: i32, g: i32, b: i32) { /* ... */ } -fn move_cursor(x: i32, y: i32) { /* ... */ } - -fn process_message(msg: Message) { - match msg { - Message::Quit => quit(), - Message::ChangeColor(r, g, b) => change_color(r, g, b), - Message::Move { x, y: new_name_for_y } => move_cursor(x, new_name_for_y), - Message::Write(s) => println!("{}", s), - }; -} -``` - -Again, the Rust compiler checks exhaustiveness, so it demands that you -have a match arm for every variant of the enum. If you leave one off, it -will give you a compile-time error unless you use `_` or provide all possible -arms. - -Unlike the previous uses of `match`, you can’t use the normal `if` -statement to do this. You can use the [`if let`][if-let] statement, -which can be seen as an abbreviated form of `match`. - -[if-let]: if-let.html +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). diff --git a/first-edition/src/method-syntax.md b/first-edition/src/method-syntax.md index 0404a5c992..74c232bf93 100644 --- a/first-edition/src/method-syntax.md +++ b/first-edition/src/method-syntax.md @@ -1,259 +1,10 @@ # Method Syntax -Functions are great, but if you want to call a bunch of them on some data, it -can be awkward. Consider this code: +The first edition of the book is no longer distributed with Rust's documentation. -```rust,ignore -baz(bar(foo)); -``` +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. -We would read this left-to-right, and so we see ‘baz bar foo’. But this isn’t the -order that the functions would get called in, that’s inside-out: ‘foo bar baz’. -Wouldn’t it be nice if we could do this instead? - -```rust,ignore -foo.bar().baz(); -``` - -Luckily, as you may have guessed with the leading question, you can! Rust provides -the ability to use this ‘method call syntax’ via the `impl` keyword. - -# Method calls - -Here’s how it works: - -```rust -struct Circle { - x: f64, - y: f64, - radius: f64, -} - -impl Circle { - fn area(&self) -> f64 { - std::f64::consts::PI * (self.radius * self.radius) - } -} - -fn main() { - let c = Circle { x: 0.0, y: 0.0, radius: 2.0 }; - println!("{}", c.area()); -} -``` - -This will print `12.566371`. - -We’ve made a `struct` that represents a circle. We then write an `impl` block, -and inside it, define a method, `area`. - -Methods take a special first parameter, of which there are three variants: -`self`, `&self`, and `&mut self`. You can think of this first parameter as -being the `foo` in `foo.bar()`. The three variants correspond to the three -kinds of things `foo` could be: `self` if it’s a value on the stack, -`&self` if it’s a reference, and `&mut self` if it’s a mutable reference. -Because we took the `&self` parameter to `area`, we can use it like any -other parameter. Because we know it’s a `Circle`, we can access the `radius` -like we would with any other `struct`. - -We should default to using `&self`, as you should prefer borrowing over taking -ownership, as well as taking immutable references over mutable ones. Here’s an -example of all three variants: - -```rust -struct Circle { - x: f64, - y: f64, - radius: f64, -} - -impl Circle { - fn reference(&self) { - println!("taking self by reference!"); - } - - fn mutable_reference(&mut self) { - println!("taking self by mutable reference!"); - } - - fn takes_ownership(self) { - println!("taking ownership of self!"); - } -} -``` - -You can use as many `impl` blocks as you’d like. The previous example could -have also been written like this: - -```rust -struct Circle { - x: f64, - y: f64, - radius: f64, -} - -impl Circle { - fn reference(&self) { - println!("taking self by reference!"); - } -} - -impl Circle { - fn mutable_reference(&mut self) { - println!("taking self by mutable reference!"); - } -} - -impl Circle { - fn takes_ownership(self) { - println!("taking ownership of self!"); - } -} -``` - -# Chaining method calls - -So, now we know how to call a method, such as `foo.bar()`. But what about our -original example, `foo.bar().baz()`? This is called ‘method chaining’. Let’s -look at an example: - -```rust -struct Circle { - x: f64, - y: f64, - radius: f64, -} - -impl Circle { - fn area(&self) -> f64 { - std::f64::consts::PI * (self.radius * self.radius) - } - - fn grow(&self, increment: f64) -> Circle { - Circle { x: self.x, y: self.y, radius: self.radius + increment } - } -} - -fn main() { - let c = Circle { x: 0.0, y: 0.0, radius: 2.0 }; - println!("{}", c.area()); - - let d = c.grow(2.0).area(); - println!("{}", d); -} -``` - -Check the return type: - -```rust -# struct Circle; -# impl Circle { -fn grow(&self, increment: f64) -> Circle { -# Circle } } -``` - -We say we’re returning a `Circle`. With this method, we can grow a new -`Circle` to any arbitrary size. - -# Associated functions - -You can also define associated functions that do not take a `self` parameter. -Here’s a pattern that’s very common in Rust code: - -```rust -struct Circle { - x: f64, - y: f64, - radius: f64, -} - -impl Circle { - fn new(x: f64, y: f64, radius: f64) -> Circle { - Circle { - x: x, - y: y, - radius: radius, - } - } -} - -fn main() { - let c = Circle::new(0.0, 0.0, 2.0); -} -``` - -This ‘associated function’ builds a new `Circle` for us. Note that associated -functions are called with the `Struct::function()` syntax, rather than the -`ref.method()` syntax. Some other languages call associated functions ‘static -methods’. - -# Builder Pattern - -Let’s say that we want our users to be able to create `Circle`s, but we will -allow them to only set the properties they care about. Otherwise, the `x` -and `y` attributes will be `0.0`, and the `radius` will be `1.0`. Rust doesn’t -have method overloading, named arguments, or variable arguments. We employ -the builder pattern instead. It looks like this: - -```rust -struct Circle { - x: f64, - y: f64, - radius: f64, -} - -impl Circle { - fn area(&self) -> f64 { - std::f64::consts::PI * (self.radius * self.radius) - } -} - -struct CircleBuilder { - x: f64, - y: f64, - radius: f64, -} - -impl CircleBuilder { - fn new() -> CircleBuilder { - CircleBuilder { x: 0.0, y: 0.0, radius: 1.0, } - } - - fn x(&mut self, coordinate: f64) -> &mut CircleBuilder { - self.x = coordinate; - self - } - - fn y(&mut self, coordinate: f64) -> &mut CircleBuilder { - self.y = coordinate; - self - } - - fn radius(&mut self, radius: f64) -> &mut CircleBuilder { - self.radius = radius; - self - } - - fn finalize(&self) -> Circle { - Circle { x: self.x, y: self.y, radius: self.radius } - } -} - -fn main() { - let c = CircleBuilder::new() - .x(1.0) - .y(2.0) - .radius(2.0) - .finalize(); - - println!("area: {}", c.area()); - println!("x: {}", c.x); - println!("y: {}", c.y); -} -``` - -What we’ve done here is make another `struct`, `CircleBuilder`. We’ve defined our -builder methods on it. We’ve also defined our `area()` method on `Circle`. We -also made one more method on `CircleBuilder`: `finalize()`. This method creates -our final `Circle` from the builder. Now, we’ve used the type system to enforce -our concerns: we can use the methods on `CircleBuilder` to constrain making -`Circle`s in any way we choose. +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). diff --git a/first-edition/src/mutability.md b/first-edition/src/mutability.md index 7625e0630a..2f557de1de 100644 --- a/first-edition/src/mutability.md +++ b/first-edition/src/mutability.md @@ -1,181 +1,10 @@ # Mutability -Mutability, the ability to change something, works a bit differently in Rust -than in other languages. The first aspect of mutability is its non-default -status: +The first edition of the book is no longer distributed with Rust's documentation. -```rust,ignore -let x = 5; -x = 6; // Error! -``` +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. -We can introduce mutability with the `mut` keyword: - -```rust -let mut x = 5; - -x = 6; // No problem! -``` - -This is a mutable [variable binding][vb]. When a binding is mutable, it means -you’re allowed to change what the binding points to. So in the above example, -it’s not so much that the value at `x` is changing, but that the binding -changed from one `i32` to another. - -[vb]: variable-bindings.html - -You can also create a [reference][ref] to it, using `&x`, but if you want to use the reference to change it, you will need a mutable reference: - -```rust -let mut x = 5; -let y = &mut x; -``` - -[ref]: references-and-borrowing.html - -`y` is an immutable binding to a mutable reference, which means that you can’t bind 'y' to something else (`y = &mut z`), but `y` can be used to bind `x` to something else (`*y = 5`). A subtle distinction. - -Of course, if you need both: - -```rust -let mut x = 5; -let mut y = &mut x; -``` - -Now `y` can be bound to another value, and the value it’s referencing can be -changed. - -It’s important to note that `mut` is part of a [pattern][pattern], so you -can do things like this: - -```rust -let (mut x, y) = (5, 6); - -fn foo(mut x: i32) { -# } -``` - -Note that here, the `x` is mutable, but not the `y`. - -[pattern]: patterns.html - -# Interior vs. Exterior Mutability - -However, when we say something is ‘immutable’ in Rust, that doesn’t mean that -it’s not able to be changed: we are referring to its ‘exterior mutability’ that -in this case is immutable. Consider, for example, [`Arc`][arc]: - -```rust -use std::sync::Arc; - -let x = Arc::new(5); -let y = x.clone(); -``` - -[arc]: ../../std/sync/struct.Arc.html - -When we call `clone()`, the `Arc` needs to update the reference count. Yet -we’ve not used any `mut`s here, `x` is an immutable binding, and we didn’t take -`&mut 5` or anything. So what gives? - -To understand this, we have to go back to the core of Rust’s guiding -philosophy, memory safety, and the mechanism by which Rust guarantees it, the -[ownership][ownership] system, and more specifically, [borrowing][borrowing]: - -> You may have one or the other of these two kinds of borrows, but not both at -> the same time: -> -> * one or more references (`&T`) to a resource, -> * exactly one mutable reference (`&mut T`). - -[ownership]: ownership.html -[borrowing]: references-and-borrowing.html#borrowing - -So, that’s the real definition of ‘immutability’: is this safe to have two -pointers to? In `Arc`’s case, yes: the mutation is entirely contained inside -the structure itself. It’s not user facing. For this reason, it hands out `&T` -with `clone()`. If it handed out `&mut T`s, though, that would be a problem. - -Other types, like the ones in the [`std::cell`][stdcell] module, have the -opposite: interior mutability. For example: - -```rust -use std::cell::RefCell; - -let x = RefCell::new(42); - -let y = x.borrow_mut(); -``` - -[stdcell]: ../../std/cell/index.html - -RefCell hands out `&mut` references to what’s inside of it with the -`borrow_mut()` method. Isn’t that dangerous? What if we do: - -```rust,ignore -use std::cell::RefCell; - -let x = RefCell::new(42); - -let y = x.borrow_mut(); -let z = x.borrow_mut(); -# (y, z); -``` - -This will in fact panic, at runtime. This is what `RefCell` does: it enforces -Rust’s borrowing rules at runtime, and `panic!`s if they’re violated. This -allows us to get around another aspect of Rust’s mutability rules. Let’s talk -about it first. - -## Field-level mutability - -Mutability is a property of either a borrow (`&mut`) or a binding (`let mut`). -This means that, for example, you cannot have a [`struct`][struct] with -some fields mutable and some immutable: - -```rust,ignore -struct Point { - x: i32, - mut y: i32, // Nope. -} -``` - -The mutability of a struct is in its binding: - -```rust,ignore -struct Point { - x: i32, - y: i32, -} - -let mut a = Point { x: 5, y: 6 }; - -a.x = 10; - -let b = Point { x: 5, y: 6 }; - -b.x = 10; // Error: cannot assign to immutable field `b.x`. -``` - -[struct]: structs.html - -However, by using [`Cell`][cell], you can emulate field-level mutability: - -```rust -use std::cell::Cell; - -struct Point { - x: i32, - y: Cell, -} - -let point = Point { x: 5, y: Cell::new(6) }; - -point.y.set(7); - -println!("y: {:?}", point.y); -``` - -[cell]: ../../std/cell/struct.Cell.html - -This will print `y: Cell { value: 7 }`. We’ve successfully updated `y`. +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). diff --git a/first-edition/src/operators-and-overloading.md b/first-edition/src/operators-and-overloading.md index ed202f3d7d..921a2a6854 100644 --- a/first-edition/src/operators-and-overloading.md +++ b/first-edition/src/operators-and-overloading.md @@ -1,135 +1,10 @@ # Operators and Overloading -Rust allows for a limited form of operator overloading. There are certain -operators that are able to be overloaded. To support a particular operator -between types, there’s a specific trait that you can implement, which then -overloads the operator. +The first edition of the book is no longer distributed with Rust's documentation. -For example, the `+` operator can be overloaded with the `Add` trait: +If you came here via a link or web search, you may want to check out [the current +version of the book](../ch19-03-advanced-traits.html#default-generic-type-parameters-and-operator-overloading) instead. -```rust -use std::ops::Add; - -#[derive(Debug)] -struct Point { - x: i32, - y: i32, -} - -impl Add for Point { - type Output = Point; - - fn add(self, other: Point) -> Point { - Point { x: self.x + other.x, y: self.y + other.y } - } -} - -fn main() { - let p1 = Point { x: 1, y: 0 }; - let p2 = Point { x: 2, y: 3 }; - - let p3 = p1 + p2; - - println!("{:?}", p3); -} -``` - -In `main`, we can use `+` on our two `Point`s, since we’ve implemented -`Add` for `Point`. - -There are a number of operators that can be overloaded this way, and all of -their associated traits live in the [`std::ops`][stdops] module. Check out its -documentation for the full list. - -[stdops]: ../../std/ops/index.html - -Implementing these traits follows a pattern. Let’s look at [`Add`][add] in more -detail: - -```rust -# mod foo { -pub trait Add { - type Output; - - fn add(self, rhs: RHS) -> Self::Output; -} -# } -``` - -[add]: ../../std/ops/trait.Add.html - -There’s three types in total involved here: the type you `impl Add` for, `RHS`, -which defaults to `Self`, and `Output`. For an expression `let z = x + y`, `x` -is the `Self` type, `y` is the RHS, and `z` is the `Self::Output` type. - -```rust -# struct Point; -# use std::ops::Add; -impl Add for Point { - type Output = f64; - - fn add(self, rhs: i32) -> f64 { - // Add an i32 to a Point and get an f64. -# 1.0 - } -} -``` - -will let you do this: - -```rust,ignore -let p: Point = // ... -let x: f64 = p + 2i32; -``` - -# Using operator traits in generic structs - -Now that we know how operator traits are defined, we can define our `HasArea` -trait and `Square` struct from the [traits chapter][traits] more generically: - -[traits]: traits.html - -```rust -use std::ops::Mul; - -trait HasArea { - fn area(&self) -> T; -} - -struct Square { - x: T, - y: T, - side: T, -} - -impl HasArea for Square - where T: Mul + Copy { - fn area(&self) -> T { - self.side * self.side - } -} - -fn main() { - let s = Square { - x: 0.0f64, - y: 0.0f64, - side: 12.0f64, - }; - - println!("Area of s: {}", s.area()); -} -``` - -For `HasArea` and `Square`, we declare a type parameter `T` and replace -`f64` with it. The `impl` needs more involved modifications: - -```rust,ignore -impl HasArea for Square - where T: Mul + Copy { ... } -``` - -The `area` method requires that we can multiply the sides, so we declare that -type `T` must implement `std::ops::Mul`. Like `Add`, mentioned above, `Mul` -itself takes an `Output` parameter: since we know that numbers don't change -type when multiplied, we also set it to `T`. `T` must also support copying, so -Rust doesn't try to move `self.side` into the return value. +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). diff --git a/first-edition/src/ownership.md b/first-edition/src/ownership.md index 21ebd6333f..70fbe48476 100644 --- a/first-edition/src/ownership.md +++ b/first-edition/src/ownership.md @@ -1,295 +1,10 @@ # Ownership -This is the first of three sections presenting Rust’s ownership system. This is one of -Rust’s most distinct and compelling features, with which Rust developers should -become quite acquainted. Ownership is how Rust achieves its largest goal, -memory safety. There are a few distinct concepts, each with its own -chapter: +The first edition of the book is no longer distributed with Rust's documentation. -* ownership, which you’re reading now -* [borrowing][borrowing], and their associated feature ‘references’ -* [lifetimes][lifetimes], an advanced concept of borrowing - -These three chapters are related, and in order. You’ll need all three to fully -understand the ownership system. - -[borrowing]: references-and-borrowing.html -[lifetimes]: lifetimes.html - -# Meta - -Before we get to the details, two important notes about the ownership system. - -Rust has a focus on safety and speed. It accomplishes these goals through many -‘zero-cost abstractions’, which means that in Rust, abstractions cost as little -as possible in order to make them work. The ownership system is a prime example -of a zero-cost abstraction. All of the analysis we’ll talk about in this guide -is _done at compile time_. You do not pay any run-time cost for any of these -features. - -However, this system does have a certain cost: learning curve. Many new users -to Rust experience something we like to call ‘fighting with the borrow -checker’, where the Rust compiler refuses to compile a program that the author -thinks is valid. This often happens because the programmer’s mental model of -how ownership should work doesn’t match the actual rules that Rust implements. -You probably will experience similar things at first. There is good news, -however: more experienced Rust developers report that once they work with the -rules of the ownership system for a period of time, they fight the borrow -checker less and less. - -With that in mind, let’s learn about ownership. - -# Ownership - -[Variable bindings][bindings] have a property in Rust: they ‘have ownership’ -of what they’re bound to. This means that when a binding goes out of scope, -Rust will free the bound resources. For example: - -```rust -fn foo() { - let v = vec![1, 2, 3]; -} -``` - -When `v` comes into scope, a new [vector][vectors] is created on [the stack][stack], -and it allocates space on [the heap][heap] for its elements. When `v` goes out -of scope at the end of `foo()`, Rust will clean up everything related to the -vector, even the heap-allocated memory. This happens deterministically, at the -end of the scope. - -We covered [vectors] in the previous chapter; we use them -here as an example of a type that allocates space on the heap at runtime. They -behave like [arrays], except their size may change by `push()`ing more -elements onto them. - -Vectors have a [generic type][generics] `Vec`, so in this example `v` will have type -`Vec`. We'll cover [generics] in detail in a later chapter. - -[arrays]: primitive-types.html#arrays -[vectors]: vectors.html -[heap]: the-stack-and-the-heap.html#the-heap -[stack]: the-stack-and-the-heap.html#the-stack -[bindings]: variable-bindings.html -[generics]: generics.html - -# Move semantics - -There’s some more subtlety here, though: Rust ensures that there is _exactly -one_ binding to any given resource. For example, if we have a vector, we can -assign it to another binding: - -```rust -let v = vec![1, 2, 3]; - -let v2 = v; -``` - -But, if we try to use `v` afterwards, we get an error: - -```rust,ignore -let v = vec![1, 2, 3]; - -let v2 = v; - -println!("v[0] is: {}", v[0]); -``` - -It looks like this: - -```text -error: use of moved value: `v` -println!("v[0] is: {}", v[0]); - ^ -``` - -A similar thing happens if we define a function which takes ownership, and -try to use something after we’ve passed it as an argument: - -```rust,ignore -fn take(v: Vec) { - // What happens here isn’t important. -} - -let v = vec![1, 2, 3]; - -take(v); - -println!("v[0] is: {}", v[0]); -``` - -Same error: ‘use of moved value’. When we transfer ownership to something else, -we say that we’ve ‘moved’ the thing we refer to. You don’t need some sort of -special annotation here, it’s the default thing that Rust does. - -## The details - -The reason that we cannot use a binding after we’ve moved it is subtle, but -important. - -When we write code like this: - -```rust -let x = 10; -``` - -Rust allocates memory for an integer [i32] on the [stack][sh], copies the bit -pattern representing the value of 10 to the allocated memory and binds the -variable name x to this memory region for future reference. - -[i32]: primitive-types.html#numeric-types - -Now consider the following code fragment: - -```rust -let v = vec![1, 2, 3]; - -let mut v2 = v; -``` - -The first line allocates memory for the vector object `v` on the stack like -it does for `x` above. But in addition to that it also allocates some memory -on the [heap][sh] for the actual data (`[1, 2, 3]`). Rust copies the address -of this heap allocation to an internal pointer, which is part of the vector -object placed on the stack (let's call it the data pointer). - -It is worth pointing out (even at the risk of stating the obvious) that the -vector object and its data live in separate memory regions instead of being a -single contiguous memory allocation (due to reasons we will not go into at -this point of time). These two parts of the vector (the one on the stack and -one on the heap) must agree with each other at all times with regards to -things like the length, capacity, etc. - -When we move `v` to `v2`, Rust actually does a bitwise copy of the vector -object `v` into the stack allocation represented by `v2`. This shallow copy -does not create a copy of the heap allocation containing the actual data. -Which means that there would be two pointers to the contents of the vector -both pointing to the same memory allocation on the heap. It would violate -Rust’s safety guarantees by introducing a data race if one could access both -`v` and `v2` at the same time. - -For example if we truncated the vector to just two elements through `v2`: - -```rust -# let v = vec![1, 2, 3]; -# let mut v2 = v; -v2.truncate(2); -``` - -and `v` were still accessible we'd end up with an invalid vector since `v` -would not know that the heap data has been truncated. Now, the part of the -vector `v` on the stack does not agree with the corresponding part on the -heap. `v` still thinks there are three elements in the vector and will -happily let us access the non existent element `v[2]` but as you might -already know this is a recipe for disaster. Especially because it might lead -to a segmentation fault or worse allow an unauthorized user to read from -memory to which they don't have access. - -This is why Rust forbids using `v` after we’ve done the move. - -[sh]: the-stack-and-the-heap.html - -It’s also important to note that optimizations may remove the actual copy of -the bytes on the stack, depending on circumstances. So it may not be as -inefficient as it initially seems. - -## `Copy` types - -We’ve established that when ownership is transferred to another binding, you -cannot use the original binding. However, there’s a [trait][traits] that changes this -behavior, and it’s called `Copy`. We haven’t discussed traits yet, but for now, -you can think of them as an annotation to a particular type that adds extra -behavior. For example: - -```rust -let v = 1; - -let v2 = v; - -println!("v is: {}", v); -``` - -In this case, `v` is an `i32`, which implements the `Copy` trait. This means -that, just like a move, when we assign `v` to `v2`, a copy of the data is made. -But, unlike a move, we can still use `v` afterward. This is because an `i32` -has no pointers to data somewhere else, copying it is a full copy. - -All primitive types implement the `Copy` trait and their ownership is -therefore not moved like one would assume, following the ‘ownership rules’. -To give an example, the two following snippets of code only compile because the -`i32` and `bool` types implement the `Copy` trait. - -```rust -fn main() { - let a = 5; - - let _y = double(a); - println!("{}", a); -} - -fn double(x: i32) -> i32 { - x * 2 -} -``` - -```rust -fn main() { - let a = true; - - let _y = change_truth(a); - println!("{}", a); -} - -fn change_truth(x: bool) -> bool { - !x -} -``` - -If we had used types that do not implement the `Copy` trait, -we would have gotten a compile error because we tried to use a moved value. - -```text -error: use of moved value: `a` -println!("{}", a); - ^ -``` - -We will discuss how to make your own types `Copy` in the [traits][traits] -section. - -[traits]: traits.html - -# More than ownership - -Of course, if we had to hand ownership back with every function we wrote: - -```rust -fn foo(v: Vec) -> Vec { - // Do stuff with `v`. - - // Hand back ownership. - v -} -``` - -This would get very tedious. It gets worse the more things we want to take ownership of: - -```rust -fn foo(v1: Vec, v2: Vec) -> (Vec, Vec, i32) { - // Do stuff with `v1` and `v2`. - - // Hand back ownership, and the result of our function. - (v1, v2, 42) -} - -let v1 = vec![1, 2, 3]; -let v2 = vec![1, 2, 3]; - -let (v1, v2, answer) = foo(v1, v2); -``` - -Ugh! The return type, return line, and calling the function gets way more -complicated. - -Luckily, Rust offers a feature which helps us solve this problem. -It’s called borrowing and is the topic of the next section! +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). diff --git a/first-edition/src/patterns.md b/first-edition/src/patterns.md index 1983927085..d722d397e9 100644 --- a/first-edition/src/patterns.md +++ b/first-edition/src/patterns.md @@ -1,411 +1,10 @@ # Patterns -Patterns are quite common in Rust. We use them in [variable -bindings][bindings], [match expressions][match], and other places, too. Let’s go -on a whirlwind tour of all of the things patterns can do! +The first edition of the book is no longer distributed with Rust's documentation. -[bindings]: variable-bindings.html -[match]: match.html +If you came here via a link or web search, you may want to check out [the current +version of the book](../ch18-03-pattern-syntax.html) instead. -A quick refresher: you can match against literals directly, and `_` acts as an -‘any’ case: - -```rust -let x = 1; - -match x { - 1 => println!("one"), - 2 => println!("two"), - 3 => println!("three"), - _ => println!("anything"), -} -``` - -This prints `one`. - -It's possible to create a binding for the value in the any case: - -```rust -let x = 1; - -match x { - y => println!("x: {} y: {}", x, y), -} -``` - -This prints: - -```text -x: 1 y: 1 -``` - -Note it is an error to have both a catch-all `_` and a catch-all binding in the same match block: - -```rust -let x = 1; - -match x { - y => println!("x: {} y: {}", x, y), - _ => println!("anything"), // this causes an error as it is unreachable -} -``` - -There’s one pitfall with patterns: like anything that introduces a new binding, -they introduce shadowing. For example: - -```rust -let x = 1; -let c = 'c'; - -match c { - x => println!("x: {} c: {}", x, c), -} - -println!("x: {}", x) -``` - -This prints: - -```text -x: c c: c -x: 1 -``` - -In other words, `x =>` matches the pattern and introduces a new binding named -`x`. This new binding is in scope for the match arm and takes on the value of -`c`. Notice that the value of `x` outside the scope of the match has no bearing -on the value of `x` within it. Because we already have a binding named `x`, this -new `x` shadows it. - -# Multiple patterns - -You can match multiple patterns with `|`: - -```rust -let x = 1; - -match x { - 1 | 2 => println!("one or two"), - 3 => println!("three"), - _ => println!("anything"), -} -``` - -This prints `one or two`. - -# Destructuring - -If you have a compound data type, like a [`struct`][struct], you can destructure it -inside of a pattern: - -```rust -struct Point { - x: i32, - y: i32, -} - -let origin = Point { x: 0, y: 0 }; - -match origin { - Point { x, y } => println!("({},{})", x, y), -} -``` - -[struct]: structs.html - -We can use `:` to give a value a different name. - -```rust -struct Point { - x: i32, - y: i32, -} - -let origin = Point { x: 0, y: 0 }; - -match origin { - Point { x: x1, y: y1 } => println!("({},{})", x1, y1), -} -``` - -If we only care about some of the values, we don’t have to give them all names: - -```rust -struct Point { - x: i32, - y: i32, -} - -let point = Point { x: 2, y: 3 }; - -match point { - Point { x, .. } => println!("x is {}", x), -} -``` - -This prints `x is 2`. - -You can do this kind of match on any member, not only the first: - -```rust -struct Point { - x: i32, - y: i32, -} - -let point = Point { x: 2, y: 3 }; - -match point { - Point { y, .. } => println!("y is {}", y), -} -``` - -This prints `y is 3`. - -This ‘destructuring’ behavior works on any compound data type, like -[tuples][tuples] or [enums][enums]. - -[tuples]: primitive-types.html#tuples -[enums]: enums.html - -# Ignoring bindings - -You can use `_` in a pattern to disregard the type and value. -For example, here’s a `match` against a `Result`: - -```rust -# let some_value: Result = Err("There was an error"); -match some_value { - Ok(value) => println!("got a value: {}", value), - Err(_) => println!("an error occurred"), -} -``` - -In the first arm, we bind the value inside the `Ok` variant to `value`. But -in the `Err` arm, we use `_` to disregard the specific error, and print -a general error message. - -`_` is valid in any pattern that creates a binding. This can be useful to -ignore parts of a larger structure: - -```rust -fn coordinate() -> (i32, i32, i32) { - // Generate and return some sort of triple tuple. -# (1, 2, 3) -} - -let (x, _, z) = coordinate(); -``` - -Here, we bind the first and last element of the tuple to `x` and `z`, but -ignore the middle element. - -It’s worth noting that using `_` never binds the value in the first place, -which means that the value does not move: - -```rust -let tuple: (u32, String) = (5, String::from("five")); - -// Here, tuple is moved, because the String moved: -let (x, _s) = tuple; - -// The next line would give "error: use of partially moved value: `tuple`". -// println!("Tuple is: {:?}", tuple); - -// However, - -let tuple = (5, String::from("five")); - -// Here, tuple is _not_ moved, as the String was never moved, and u32 is Copy: -let (x, _) = tuple; - -// That means this works: -println!("Tuple is: {:?}", tuple); -``` - -This also means that any temporary variables will be dropped at the end of the -statement: - -```rust -// Here, the String created will be dropped immediately, as it’s not bound: - -let _ = String::from(" hello ").trim(); -``` - -You can also use `..` in a pattern to disregard multiple values: - -```rust -enum OptionalTuple { - Value(i32, i32, i32), - Missing, -} - -let x = OptionalTuple::Value(5, -2, 3); - -match x { - OptionalTuple::Value(..) => println!("Got a tuple!"), - OptionalTuple::Missing => println!("No such luck."), -} -``` - -This prints `Got a tuple!`. - -# ref and ref mut - -If you want to get a [reference][ref], use the `ref` keyword: - -```rust -let x = 5; - -match x { - ref r => println!("Got a reference to {}", r), -} -``` - -This prints `Got a reference to 5`. - -[ref]: references-and-borrowing.html - -Here, the `r` inside the `match` has the type `&i32`. In other words, the `ref` -keyword _creates_ a reference, for use in the pattern. If you need a mutable -reference, `ref mut` will work in the same way: - -```rust -let mut x = 5; - -match x { - ref mut mr => println!("Got a mutable reference to {}", mr), -} -``` - -# Ranges - -You can match a range of values with `...`: - -```rust -let x = 1; - -match x { - 1 ... 5 => println!("one through five"), - _ => println!("anything"), -} -``` - -This prints `one through five`. - -Ranges are mostly used with integers and `char`s: - -```rust -let x = '💅'; - -match x { - 'a' ... 'j' => println!("early letter"), - 'k' ... 'z' => println!("late letter"), - _ => println!("something else"), -} -``` - -This prints `something else`. - -# Bindings - -You can bind values to names with `@`: - -```rust -let x = 1; - -match x { - e @ 1 ... 5 => println!("got a range element {}", e), - _ => println!("anything"), -} -``` - -This prints `got a range element 1`. This is useful when you want to -do a complicated match of part of a data structure: - -```rust -#[derive(Debug)] -struct Person { - name: Option, -} - -let name = "Steve".to_string(); -let x: Option = Some(Person { name: Some(name) }); -match x { - Some(Person { name: ref a @ Some(_), .. }) => println!("{:?}", a), - _ => {} -} -``` - -This prints `Some("Steve")`: we’ve bound the inner `name` to `a`. - -If you use `@` with `|`, you need to make sure the name is bound in each part -of the pattern: - -```rust -let x = 5; - -match x { - e @ 1 ... 5 | e @ 8 ... 10 => println!("got a range element {}", e), - _ => println!("anything"), -} -``` - -# Guards - -You can introduce ‘match guards’ with `if`: - -```rust -enum OptionalInt { - Value(i32), - Missing, -} - -let x = OptionalInt::Value(5); - -match x { - OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"), - OptionalInt::Value(..) => println!("Got an int!"), - OptionalInt::Missing => println!("No such luck."), -} -``` - -This prints `Got an int!`. - -If you’re using `if` with multiple patterns, the `if` applies to both sides: - -```rust -let x = 4; -let y = false; - -match x { - 4 | 5 if y => println!("yes"), - _ => println!("no"), -} -``` - -This prints `no`, because the `if` applies to the whole of `4 | 5`, and not to -only the `5`. In other words, the precedence of `if` behaves like this: - -```text -(4 | 5) if y => ... -``` - -not this: - -```text -4 | (5 if y) => ... -``` - -# Mix and Match - -Whew! That’s a lot of different ways to match things, and they can all be -mixed and matched, depending on what you’re doing: - -```rust,ignore -match x { - Foo { x: Some(ref name), y: None } => ... -} -``` - -Patterns are very powerful. Make good use of them. +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). diff --git a/first-edition/src/primitive-types.md b/first-edition/src/primitive-types.md index 93220a2ba8..39ee0b2d1e 100644 --- a/first-edition/src/primitive-types.md +++ b/first-edition/src/primitive-types.md @@ -1,305 +1,10 @@ # Primitive Types -The Rust language has a number of types that are considered ‘primitive’. This -means that they’re built-in to the language. Rust is structured in such a way -that the standard library also provides a number of useful types built on top -of these ones, as well, but these are the most primitive. +The first edition of the book is no longer distributed with Rust's documentation. -# Booleans +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. -Rust has a built-in boolean type, named `bool`. It has two values, `true` and `false`: - -```rust -let x = true; - -let y: bool = false; -``` - -A common use of booleans is in [`if` conditionals][if]. - -[if]: if.html - -You can find more documentation for `bool`s [in the standard library -documentation][bool]. - -[bool]: ../../std/primitive.bool.html - -# `char` - -The `char` type represents a single Unicode scalar value. You can create `char`s -with a single tick: (`'`) - -```rust -let x = 'x'; -let two_hearts = '💕'; -``` - -Unlike some other languages, this means that Rust’s `char` is not a single byte, -but four. - -You can find more documentation for `char`s [in the standard library -documentation][char]. - -[char]: ../../std/primitive.char.html - -# Numeric types - -Rust has a variety of numeric types in a few categories: signed and unsigned, -fixed and variable, floating-point and integer. - -These types consist of two parts: the category, and the size. For example, -`u16` is an unsigned type with sixteen bits of size. More bits lets you have -bigger numbers. - -If a number literal has nothing to cause its type to be inferred, it defaults: - -```rust -let x = 42; // `x` has type `i32`. - -let y = 1.0; // `y` has type `f64`. -``` - -Here’s a list of the different numeric types, with links to their documentation -in the standard library: - -* [i8](../../std/primitive.i8.html) -* [i16](../../std/primitive.i16.html) -* [i32](../../std/primitive.i32.html) -* [i64](../../std/primitive.i64.html) -* [u8](../../std/primitive.u8.html) -* [u16](../../std/primitive.u16.html) -* [u32](../../std/primitive.u32.html) -* [u64](../../std/primitive.u64.html) -* [isize](../../std/primitive.isize.html) -* [usize](../../std/primitive.usize.html) -* [f32](../../std/primitive.f32.html) -* [f64](../../std/primitive.f64.html) - -Let’s go over them by category: - -## Signed and Unsigned - -Integer types come in two varieties: signed and unsigned. To understand the -difference, let’s consider a number with four bits of size. A signed, four-bit -number would let you store numbers from `-8` to `+7`. Signed numbers use -“two’s complement representation”. An unsigned four bit number, since it does -not need to store negatives, can store values from `0` to `+15`. - -Unsigned types use a `u` for their category, and signed types use `i`. The `i` -is for ‘integer’. So `u8` is an eight-bit unsigned number, and `i8` is an -eight-bit signed number. - -## Fixed-size types - -Fixed-size types have a specific number of bits in their representation. Valid -bit sizes are `8`, `16`, `32`, and `64`. So, `u32` is an unsigned, 32-bit integer, -and `i64` is a signed, 64-bit integer. - -## Variable-size types - -Rust also provides types whose particular size depends on the underlying machine -architecture. Their range is sufficient to express the size of any collection, so -these types have ‘size’ as the category. They come in signed and unsigned varieties -which account for two types: `isize` and `usize`. - -## Floating-point types - -Rust also has two floating point types: `f32` and `f64`. These correspond to -IEEE-754 single and double precision numbers. - -# Arrays - -Like many programming languages, Rust has list types to represent a sequence of -things. The most basic is the *array*, a fixed-size list of elements of the -same type. By default, arrays are immutable. - -```rust -let a = [1, 2, 3]; // a: [i32; 3] -let mut m = [1, 2, 3]; // m: [i32; 3] -``` - -Arrays have type `[T; N]`. We’ll talk about this `T` notation [in the generics -section][generics]. The `N` is a compile-time constant, for the length of the -array. - -There’s a shorthand for initializing each element of an array to the same -value. In this example, each element of `a` will be initialized to `0`: - -```rust -let a = [0; 20]; // a: [i32; 20] -``` - -You can get the number of elements in an array `a` with `a.len()`: - -```rust -let a = [1, 2, 3]; - -println!("a has {} elements", a.len()); -``` - -You can access a particular element of an array with *subscript notation*: - -```rust -let names = ["Graydon", "Brian", "Niko"]; // names: [&str; 3] - -println!("The second name is: {}", names[1]); -``` - -Subscripts start at zero, like in most programming languages, so the first name -is `names[0]` and the second name is `names[1]`. The above example prints -`The second name is: Brian`. If you try to use a subscript that is not in the -array, you will get an error: array access is bounds-checked at run-time. Such -errant access is the source of many bugs in other systems programming -languages. - -You can find more documentation for `array`s [in the standard library -documentation][array]. - -[array]: ../../std/primitive.array.html - -# Slices - -A ‘slice’ is a reference to (or “view” into) another data structure. They are -useful for allowing safe, efficient access to a portion of an array without -copying. For example, you might want to reference only one line of a file read -into memory. By nature, a slice is not created directly, but from an existing -variable binding. Slices have a defined length, and can be mutable or immutable. - -Internally, slices are represented as a pointer to the beginning of the data -and a length. - -## Slicing syntax - -You can use a combo of `&` and `[]` to create a slice from various things. The -`&` indicates that slices are similar to [references], which we will cover in -detail later in this section. The `[]`s, with a range, let you define the -length of the slice: - -```rust -let a = [0, 1, 2, 3, 4]; -let complete = &a[..]; // A slice containing all of the elements in `a`. -let middle = &a[1..4]; // A slice of `a`: only the elements `1`, `2`, and `3`. -``` - -Slices have type `&[T]`. We’ll talk about that `T` when we cover -[generics][generics]. - -[generics]: generics.html - -You can find more documentation for slices [in the standard library -documentation][slice]. - -[slice]: ../../std/primitive.slice.html - -# `str` - -Rust’s `str` type is the most primitive string type. As an [unsized type][dst], -it’s not very useful by itself, but becomes useful when placed behind a -reference, like `&str`. We'll elaborate further when we cover -[Strings][strings] and [references]. - -[dst]: unsized-types.html -[strings]: strings.html -[references]: references-and-borrowing.html - -You can find more documentation for `str` [in the standard library -documentation][str]. - -[str]: ../../std/primitive.str.html - -# Tuples - -A tuple is an ordered list of fixed size. Like this: - -```rust -let x = (1, "hello"); -``` - -The parentheses and commas form this two-length tuple. Here’s the same code, but -with the type annotated: - -```rust -let x: (i32, &str) = (1, "hello"); -``` - -As you can see, the type of a tuple looks like the tuple, but with each -position having a type name rather than the value. Careful readers will also -note that tuples are heterogeneous: we have an `i32` and a `&str` in this tuple. -In systems programming languages, strings are a bit more complex than in other -languages. For now, read `&str` as a *string slice*, and we’ll learn more -soon. - -You can assign one tuple into another, if they have the same contained types -and [arity]. Tuples have the same arity when they have the same length. - -[arity]: glossary.html#arity - -```rust -let mut x = (1, 2); // x: (i32, i32) -let y = (2, 3); // y: (i32, i32) - -x = y; -``` - -You can access the fields in a tuple through a *destructuring let*. Here’s -an example: - -```rust -let (x, y, z) = (1, 2, 3); - -println!("x is {}", x); -``` - -Remember [before][let] when I said the left-hand side of a `let` statement was more -powerful than assigning a binding? Here we are. We can put a pattern on -the left-hand side of the `let`, and if it matches up to the right-hand side, -we can assign multiple bindings at once. In this case, `let` “destructures” -or “breaks up” the tuple, and assigns the bits to three bindings. - -[let]: variable-bindings.html - -This pattern is very powerful, and we’ll see it repeated more later. - -You can disambiguate a single-element tuple from a value in parentheses with a -comma: - -```rust -(0,); // A single-element tuple. -(0); // A zero in parentheses. -``` - -## Tuple Indexing - -You can also access fields of a tuple with indexing syntax: - - -```rust -let tuple = (1, 2, 3); - -let x = tuple.0; -let y = tuple.1; -let z = tuple.2; - -println!("x is {}", x); -``` - -Like array indexing, it starts at zero, but unlike array indexing, it uses a -`.`, rather than `[]`s. - -You can find more documentation for tuples [in the standard library -documentation][tuple]. - -[tuple]: ../../std/primitive.tuple.html - -# Functions - -Functions also have a type! They look like this: - -```rust -fn foo(x: i32) -> i32 { x } - -let x: fn(i32) -> i32 = foo; -``` - -In this case, `x` is a ‘function pointer’ to a function that takes an `i32` and -returns an `i32`. +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). diff --git a/first-edition/src/procedural-macros.md b/first-edition/src/procedural-macros.md index 07ea9ed189..9778383d80 100644 --- a/first-edition/src/procedural-macros.md +++ b/first-edition/src/procedural-macros.md @@ -1,286 +1,10 @@ # Procedural Macros (and custom Derive) -As you've seen throughout the rest of the book, Rust provides a mechanism -called "derive" that lets you implement traits easily. For example, +The first edition of the book is no longer distributed with Rust's documentation. -```rust -#[derive(Debug)] -struct Point { - x: i32, - y: i32, -} -``` +If you came here via a link or web search, you may want to check out [the current +version of the book](../ch19-06-macros.html?highlight=procedural#procedural-macros-for-generating-code-from-attributes) instead. -is a lot simpler than - -```rust -struct Point { - x: i32, - y: i32, -} - -use std::fmt; - -impl fmt::Debug for Point { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y) - } -} -``` - -Rust includes several traits that you can derive, but it also lets you define -your own. We can accomplish this task through a feature of Rust called -"procedural macros." Eventually, procedural macros will allow for all sorts of -advanced metaprogramming in Rust, but today, they're only for custom derive. - -Let's build a very simple trait, and derive it with custom derive. - -## Hello World - -So the first thing we need to do is start a new crate for our project. - -```bash -$ cargo new --bin hello-world -``` - -All we want is to be able to call `hello_world()` on a derived type. Something -like this: - -```rust,ignore -#[derive(HelloWorld)] -struct Pancakes; - -fn main() { - Pancakes::hello_world(); -} -``` - -With some kind of nice output, like `Hello, World! My name is Pancakes.`. - -Let's go ahead and write up what we think our macro will look like from a user -perspective. In `src/main.rs` we write: - -```rust,ignore -#[macro_use] -extern crate hello_world_derive; - -trait HelloWorld { - fn hello_world(); -} - -#[derive(HelloWorld)] -struct FrenchToast; - -#[derive(HelloWorld)] -struct Waffles; - -fn main() { - FrenchToast::hello_world(); - Waffles::hello_world(); -} -``` - -Great. So now we just need to actually write the procedural macro. At the -moment, procedural macros need to be in their own crate. Eventually, this -restriction may be lifted, but for now, it's required. As such, there's a -convention; for a crate named `foo`, a custom derive procedural macro is called -`foo-derive`. Let's start a new crate called `hello-world-derive` inside our -`hello-world` project. - -```bash -$ cargo new hello-world-derive -``` - -To make sure that our `hello-world` crate is able to find this new crate we've -created, we'll add it to our toml: - -```toml -[dependencies] -hello-world-derive = { path = "hello-world-derive" } -``` - -As for the source of our `hello-world-derive` crate, here's an example: - -```rust,ignore -extern crate proc_macro; -extern crate syn; -#[macro_use] -extern crate quote; - -use proc_macro::TokenStream; - -#[proc_macro_derive(HelloWorld)] -pub fn hello_world(input: TokenStream) -> TokenStream { - // Construct a string representation of the type definition - let s = input.to_string(); - - // Parse the string representation - let ast = syn::parse_derive_input(&s).unwrap(); - - // Build the impl - let gen = impl_hello_world(&ast); - - // Return the generated impl - gen.parse().unwrap() -} -``` - -So there is a lot going on here. We have introduced two new crates: [`syn`] and -[`quote`]. As you may have noticed, `input: TokenSteam` is immediately converted -to a `String`. This `String` is a string representation of the Rust code for which -we are deriving `HelloWorld`. At the moment, the only thing you can do with a -`TokenStream` is convert it to a string. A richer API will exist in the future. - -So what we really need is to be able to _parse_ Rust code into something -usable. This is where `syn` comes to play. `syn` is a crate for parsing Rust -code. The other crate we've introduced is `quote`. It's essentially the dual of -`syn` as it will make generating Rust code really easy. We could write this -stuff on our own, but it's much simpler to use these libraries. Writing a full -parser for Rust code is no simple task. - -[`syn`]: https://crates.io/crates/syn -[`quote`]: https://crates.io/crates/quote - -The comments seem to give us a pretty good idea of our overall strategy. We -are going to take a `String` of the Rust code for the type we are deriving, parse -it using `syn`, construct the implementation of `hello_world` (using `quote`), -then pass it back to Rust compiler. - -One last note: you'll see some `unwrap()`s there. If you want to provide an -error for a procedural macro, then you should `panic!` with the error message. -In this case, we're keeping it as simple as possible. - -Great, so let's write `impl_hello_world(&ast)`. - -```rust,ignore -fn impl_hello_world(ast: &syn::DeriveInput) -> quote::Tokens { - let name = &ast.ident; - quote! { - impl HelloWorld for #name { - fn hello_world() { - println!("Hello, World! My name is {}", stringify!(#name)); - } - } - } -} -``` - -So this is where quotes comes in. The `ast` argument is a struct that gives us -a representation of our type (which can be either a `struct` or an `enum`). -Check out the [docs](https://docs.rs/syn/0.11.11/syn/struct.DeriveInput.html), -there is some useful information there. We are able to get the name of the -type using `ast.ident`. The `quote!` macro lets us write up the Rust code -that we wish to return and convert it into `Tokens`. `quote!` lets us use some -really cool templating mechanics; we simply write `#name` and `quote!` will -replace it with the variable named `name`. You can even do some repetition -similar to regular macros work. You should check out the -[docs](https://docs.rs/quote) for a good introduction. - -So I think that's it. Oh, well, we do need to add dependencies for `syn` and -`quote` in the `Cargo.toml` for `hello-world-derive`. - -```toml -[dependencies] -syn = "0.11.11" -quote = "0.3.15" -``` - -That should be it. Let's try to compile `hello-world`. - -```bash -error: the `#[proc_macro_derive]` attribute is only usable with crates of the `proc-macro` crate type - --> hello-world-derive/src/lib.rs:8:3 - | -8 | #[proc_macro_derive(HelloWorld)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -``` - -Oh, so it appears that we need to declare that our `hello-world-derive` crate is -a `proc-macro` crate type. How do we do this? Like this: - -```toml -[lib] -proc-macro = true -``` - -Ok so now, let's compile `hello-world`. Executing `cargo run` now yields: - -```bash -Hello, World! My name is FrenchToast -Hello, World! My name is Waffles -``` - -We've done it! - -## Custom Attributes - -In some cases it might make sense to allow users some kind of configuration. -For example, the user might want to overwrite the name that is printed in the `hello_world()` method. - -This can be achieved with custom attributes: - -```rust,ignore -#[derive(HelloWorld)] -#[HelloWorldName = "the best Pancakes"] -struct Pancakes; - -fn main() { - Pancakes::hello_world(); -} -``` - -If we try to compile this though, the compiler will respond with an error: - -```bash -error: The attribute `HelloWorldName` is currently unknown to the compiler and may have meaning added to it in the future (see issue #29642) -``` - -The compiler needs to know that we're handling this attribute and to not respond with an error. -This is done in the `hello-world-derive` crate by adding `attributes` to the `proc_macro_derive` attribute: - -```rust,ignore -#[proc_macro_derive(HelloWorld, attributes(HelloWorldName))] -pub fn hello_world(input: TokenStream) -> TokenStream -``` - -Multiple attributes can be specified that way. - -## Raising Errors - -Let's assume that we do not want to accept enums as input to our custom derive method. - -This condition can be easily checked with the help of `syn`. -But how do we tell the user, that we do not accept enums? -The idiomatic way to report errors in procedural macros is to panic: - -```rust,ignore -fn impl_hello_world(ast: &syn::DeriveInput) -> quote::Tokens { - let name = &ast.ident; - // Check if derive(HelloWorld) was specified for a struct - if let syn::Body::Struct(_) = ast.body { - // Yes, this is a struct - quote! { - impl HelloWorld for #name { - fn hello_world() { - println!("Hello, World! My name is {}", stringify!(#name)); - } - } - } - } else { - // Nope. This is an Enum. We cannot handle these! - panic!("#[derive(HelloWorld)] is only defined for structs, not for enums!"); - } -} -``` - -If a user now tries to derive `HelloWorld` from an enum they will be greeted with following, hopefully helpful, error: - -```bash -error: custom derive attribute panicked - --> src/main.rs - | - | #[derive(HelloWorld)] - | ^^^^^^^^^^ - | - = help: message: #[derive(HelloWorld)] is only defined for structs, not for enums! -``` +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). diff --git a/first-edition/src/raw-pointers.md b/first-edition/src/raw-pointers.md index 77024275b1..c149da8681 100644 --- a/first-edition/src/raw-pointers.md +++ b/first-edition/src/raw-pointers.md @@ -1,121 +1,10 @@ # Raw Pointers -Rust has a number of different smart pointer types in its standard library, but -there are two types that are extra-special. Much of Rust’s safety comes from -compile-time checks, but raw pointers don’t have such guarantees, and are -[unsafe][unsafe] to use. +The first edition of the book is no longer distributed with Rust's documentation. -`*const T` and `*mut T` are called ‘raw pointers’ in Rust. Sometimes, when -writing certain kinds of libraries, you’ll need to get around Rust’s safety -guarantees for some reason. In this case, you can use raw pointers to implement -your library, while exposing a safe interface for your users. For example, `*` -pointers are allowed to alias, allowing them to be used to write -shared-ownership types, and even thread-safe shared memory types (the `Rc` -and `Arc` types are both implemented entirely in Rust). +If you came here via a link or web search, you may want to check out [the current +version of the book](../ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer) instead. -Here are some things to remember about raw pointers that are different than -other pointer types. They: - -- are not guaranteed to point to valid memory and are not even - guaranteed to be non-NULL (unlike both `Box` and `&`); -- do not have any automatic clean-up, unlike `Box`, and so require - manual resource management; -- are plain-old-data, that is, they don't move ownership, again unlike - `Box`, hence the Rust compiler cannot protect against bugs like - use-after-free; -- lack any form of lifetimes, unlike `&`, and so the compiler cannot - reason about dangling pointers; and -- have no guarantees about aliasing or mutability other than mutation - not being allowed directly through a `*const T`. - -# Basics - -Creating a raw pointer is perfectly safe: - -```rust -let x = 5; -let raw = &x as *const i32; - -let mut y = 10; -let raw_mut = &mut y as *mut i32; -``` - -However, dereferencing one is not. This won’t work: - -```rust,ignore -let x = 5; -let raw = &x as *const i32; - -println!("raw points at {}", *raw); -``` - -It gives this error: - -```text -error: dereference of raw pointer requires unsafe function or block [E0133] - println!("raw points at {}", *raw); - ^~~~ -``` - -When you dereference a raw pointer, you’re taking responsibility that it’s not -pointing somewhere that would be incorrect. As such, you need `unsafe`: - -```rust -let x = 5; -let raw = &x as *const i32; - -let points_at = unsafe { *raw }; - -println!("raw points at {}", points_at); -``` - -For more operations on raw pointers, see [their API documentation][rawapi]. - -[unsafe]: unsafe.html -[rawapi]: ../../std/primitive.pointer.html - -# FFI - -Raw pointers are useful for FFI: Rust’s `*const T` and `*mut T` are similar to -C’s `const T*` and `T*`, respectively. For more about this use, consult the -[FFI chapter][ffi]. - -[ffi]: ffi.html - -# References and raw pointers - -At runtime, a raw pointer `*` and a reference pointing to the same piece of -data have an identical representation. In fact, an `&T` reference will -implicitly coerce to an `*const T` raw pointer in safe code and similarly for -the `mut` variants (both coercions can be performed explicitly with, -respectively, `value as *const T` and `value as *mut T`). - -Going the opposite direction, from `*const` to a reference `&`, is not safe. A -`&T` is always valid, and so, at a minimum, the raw pointer `*const T` has to -point to a valid instance of type `T`. Furthermore, the resulting pointer must -satisfy the aliasing and mutability laws of references. The compiler assumes -these properties are true for any references, no matter how they are created, -and so any conversion from raw pointers is asserting that they hold. The -programmer *must* guarantee this. - -The recommended method for the conversion is: - -```rust -// Explicit cast: -let i: u32 = 1; -let p_imm: *const u32 = &i as *const u32; - -// Implicit coercion: -let mut m: u32 = 2; -let p_mut: *mut u32 = &mut m; - -unsafe { - let ref_imm: &u32 = &*p_imm; - let ref_mut: &mut u32 = &mut *p_mut; -} -``` - -The `&*x` dereferencing style is preferred to using a `transmute`. The latter -is far more powerful than necessary, and the more restricted operation is -harder to use incorrectly; for example, it requires that `x` is a pointer -(unlike `transmute`). +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). diff --git a/first-edition/src/references-and-borrowing.md b/first-edition/src/references-and-borrowing.md index 1daaaef3f1..1d8c75e2d8 100644 --- a/first-edition/src/references-and-borrowing.md +++ b/first-edition/src/references-and-borrowing.md @@ -1,411 +1,10 @@ # References and Borrowing -This is the second of three sections presenting Rust’s ownership system. This is one of -Rust’s most distinct and compelling features, with which Rust developers should -become quite acquainted. Ownership is how Rust achieves its largest goal, -memory safety. There are a few distinct concepts, each with its own -chapter: +The first edition of the book is no longer distributed with Rust's documentation. -* [ownership][ownership], the key concept -* borrowing, which you’re reading now -* [lifetimes][lifetimes], an advanced concept of borrowing +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. -These three chapters are related, and in order. You’ll need all three to fully -understand the ownership system. - -[ownership]: ownership.html -[lifetimes]: lifetimes.html - -# Meta - -Before we get to the details, two important notes about the ownership system. - -Rust has a focus on safety and speed. It accomplishes these goals through many -‘zero-cost abstractions’, which means that in Rust, abstractions cost as little -as possible in order to make them work. The ownership system is a prime example -of a zero-cost abstraction. All of the analysis we’ll talk about in this guide -is _done at compile time_. You do not pay any run-time cost for any of these -features. - -However, this system does have a certain cost: learning curve. Many new users -to Rust experience something we like to call ‘fighting with the borrow -checker’, where the Rust compiler refuses to compile a program that the author -thinks is valid. This often happens because the programmer’s mental model of -how ownership should work doesn’t match the actual rules that Rust implements. -You probably will experience similar things at first. There is good news, -however: more experienced Rust developers report that once they work with the -rules of the ownership system for a period of time, they fight the borrow -checker less and less. - -With that in mind, let’s learn about borrowing. - -# Borrowing - -At the end of the [ownership][ownership] section, we had a nasty function that looked -like this: - -```rust -fn foo(v1: Vec, v2: Vec) -> (Vec, Vec, i32) { - // Do stuff with `v1` and `v2`. - - // Hand back ownership, and the result of our function. - (v1, v2, 42) -} - -let v1 = vec![1, 2, 3]; -let v2 = vec![1, 2, 3]; - -let (v1, v2, answer) = foo(v1, v2); -``` - -This is not idiomatic Rust, however, as it doesn’t take advantage of borrowing. Here’s -the first step: - -```rust -fn foo(v1: &Vec, v2: &Vec) -> i32 { - // Do stuff with `v1` and `v2`. - - // Return the answer. - 42 -} - -let v1 = vec![1, 2, 3]; -let v2 = vec![1, 2, 3]; - -let answer = foo(&v1, &v2); - -// We can use `v1` and `v2` here! -``` - -A more concrete example: - -```rust -fn main() { - // Don't worry if you don't understand how `fold` works, the point here is that an immutable reference is borrowed. - fn sum_vec(v: &Vec) -> i32 { - v.iter().fold(0, |a, &b| a + b) - } - // Borrow two vectors and sum them. - // This kind of borrowing does not allow mutation through the borrowed reference. - fn foo(v1: &Vec, v2: &Vec) -> i32 { - // Do stuff with `v1` and `v2`. - let s1 = sum_vec(v1); - let s2 = sum_vec(v2); - // Return the answer. - s1 + s2 - } - - let v1 = vec![1, 2, 3]; - let v2 = vec![4, 5, 6]; - - let answer = foo(&v1, &v2); - println!("{}", answer); -} -``` - -Instead of taking `Vec`s as our arguments, we take a reference: -`&Vec`. And instead of passing `v1` and `v2` directly, we pass `&v1` and -`&v2`. We call the `&T` type a ‘reference’, and rather than owning the resource, -it borrows ownership. A binding that borrows something does not deallocate the -resource when it goes out of scope. This means that after the call to `foo()`, -we can use our original bindings again. - -References are immutable, like bindings. This means that inside of `foo()`, -the vectors can’t be changed at all: - -```rust,ignore -fn foo(v: &Vec) { - v.push(5); -} - -let v = vec![]; - -foo(&v); -``` - -will give us this error: - -```text -error: cannot borrow immutable borrowed content `*v` as mutable -v.push(5); -^ -``` - -Pushing a value mutates the vector, and so we aren’t allowed to do it. - -# &mut references - -There’s a second kind of reference: `&mut T`. A ‘mutable reference’ allows you -to mutate the resource you’re borrowing. For example: - -```rust -let mut x = 5; -{ - let y = &mut x; - *y += 1; -} -println!("{}", x); -``` - -This will print `6`. We make `y` a mutable reference to `x`, then add one to -the thing `y` points at. You’ll notice that `x` had to be marked `mut` as well. -If it wasn’t, we couldn’t take a mutable borrow to an immutable value. - -You'll also notice we added an asterisk (`*`) in front of `y`, making it `*y`, -this is because `y` is a `&mut` reference. You'll need to use asterisks to -access the contents of a reference as well. - -Otherwise, `&mut` references are like references. There _is_ a large -difference between the two, and how they interact, though. You can tell -something is fishy in the above example, because we need that extra scope, with -the `{` and `}`. If we remove them, we get an error: - -```text -error: cannot borrow `x` as immutable because it is also borrowed as mutable - println!("{}", x); - ^ -note: previous borrow of `x` occurs here; the mutable borrow prevents -subsequent moves, borrows, or modification of `x` until the borrow ends - let y = &mut x; - ^ -note: previous borrow ends here -fn main() { - -} -^ -``` - -As it turns out, there are rules. - -# The Rules - -Here are the rules for borrowing in Rust: - -First, any borrow must last for a scope no greater than that of the owner. -Second, you may have one or the other of these two kinds of borrows, but not -both at the same time: - -* one or more references (`&T`) to a resource, -* exactly one mutable reference (`&mut T`). - - -You may notice that this is very similar to, though not exactly the same as, -the definition of a data race: - -> There is a ‘data race’ when two or more pointers access the same memory -> location at the same time, where at least one of them is writing, and the -> operations are not synchronized. - -With references, you may have as many as you’d like, since none of them are -writing. However, as we can only have one `&mut` at a time, it is impossible to -have a data race. This is how Rust prevents data races at compile time: we’ll -get errors if we break the rules. - -With this in mind, let’s consider our example again. - -## Thinking in scopes - -Here’s the code: - -```rust,ignore -fn main() { - let mut x = 5; - let y = &mut x; - - *y += 1; - - println!("{}", x); -} -``` - -This code gives us this error: - -```text -error: cannot borrow `x` as immutable because it is also borrowed as mutable - println!("{}", x); - ^ -``` - -This is because we’ve violated the rules: we have a `&mut T` pointing to `x`, -and so we aren’t allowed to create any `&T`s. It's one or the other. The note -hints at how to think about this problem: - -```text -note: previous borrow ends here -fn main() { - -} -^ -``` - -In other words, the mutable borrow is held through the rest of our example. What -we want is for the mutable borrow by `y` to end so that the resource can be -returned to the owner, `x`. `x` can then provide an immutable borrow to `println!`. -In Rust, borrowing is tied to the scope that the borrow is valid for. And our -scopes look like this: - -```rust,ignore -fn main() { - let mut x = 5; - - let y = &mut x; // -+ &mut borrow of `x` starts here. - // | - *y += 1; // | - // | - println!("{}", x); // -+ - Try to borrow `x` here. -} // -+ &mut borrow of `x` ends here. - -``` - -The scopes conflict: we can’t make an `&x` while `y` is in scope. - -So when we add the curly braces: - -```rust -let mut x = 5; - -{ - let y = &mut x; // -+ &mut borrow starts here. - *y += 1; // | -} // -+ ... and ends here. - -println!("{}", x); // <- Try to borrow `x` here. -``` - -There’s no problem. Our mutable borrow goes out of scope before we create an -immutable one. So scope is the key to seeing how long a borrow lasts for. - -## Issues borrowing prevents - -Why have these restrictive rules? Well, as we noted, these rules prevent data -races. What kinds of issues do data races cause? Here are a few. - -### Iterator invalidation - -One example is ‘iterator invalidation’, which happens when you try to mutate a -collection that you’re iterating over. Rust’s borrow checker prevents this from -happening: - -```rust -let mut v = vec![1, 2, 3]; - -for i in &v { - println!("{}", i); -} -``` - -This prints out one through three. As we iterate through the vector, we’re -only given references to the elements. And `v` is itself borrowed as immutable, -which means we can’t change it while we’re iterating: - -```rust,ignore -let mut v = vec![1, 2, 3]; - -for i in &v { - println!("{}", i); - v.push(34); -} -``` - -Here’s the error: - -```text -error: cannot borrow `v` as mutable because it is also borrowed as immutable - v.push(34); - ^ -note: previous borrow of `v` occurs here; the immutable borrow prevents -subsequent moves or mutable borrows of `v` until the borrow ends -for i in &v { - ^ -note: previous borrow ends here -for i in &v { - println!(“{}”, i); - v.push(34); -} -^ -``` - -We can’t modify `v` because it’s borrowed by the loop. - -### Use after free - -References must not live longer than the resource they refer to. Rust will -check the scopes of your references to ensure that this is true. - -If Rust didn’t check this property, we could accidentally use a reference -which was invalid. For example: - -```rust,ignore -let y: &i32; -{ - let x = 5; - y = &x; -} - -println!("{}", y); -``` - -We get this error: - -```text -error: `x` does not live long enough - y = &x; - ^ -note: reference must be valid for the block suffix following statement 0 at -2:16... -let y: &i32; -{ - let x = 5; - y = &x; -} - -note: ...but borrowed value is only valid for the block suffix following -statement 0 at 4:18 - let x = 5; - y = &x; -} -``` - -In other words, `y` is only valid for the scope where `x` exists. As soon as -`x` goes away, it becomes invalid to refer to it. As such, the error says that -the borrow ‘doesn’t live long enough’ because it’s not valid for the right -amount of time. - -The same problem occurs when the reference is declared _before_ the variable it -refers to. This is because resources within the same scope are freed in the -opposite order they were declared: - -```rust,ignore -let y: &i32; -let x = 5; -y = &x; - -println!("{}", y); -``` - -We get this error: - -```text -error: `x` does not live long enough -y = &x; - ^ -note: reference must be valid for the block suffix following statement 0 at -2:16... - let y: &i32; - let x = 5; - y = &x; - - println!("{}", y); -} - -note: ...but borrowed value is only valid for the block suffix following -statement 1 at 3:14 - let x = 5; - y = &x; - - println!("{}", y); -} -``` - -In the above example, `y` is declared before `x`, meaning that `y` lives longer -than `x`, which is not allowed. +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). diff --git a/first-edition/src/release-channels.md b/first-edition/src/release-channels.md index f8c0e567a1..f0a643f270 100644 --- a/first-edition/src/release-channels.md +++ b/first-edition/src/release-channels.md @@ -1,68 +1,10 @@ # Release Channels -The Rust project uses a concept called ‘release channels’ to manage releases. -It’s important to understand this process to choose which version of Rust -your project should use. +The first edition of the book is no longer distributed with Rust's documentation. -# Overview +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. -There are three channels for Rust releases: - -* Nightly -* Beta -* Stable - -New nightly releases are created once a day. Every six weeks, the latest -nightly release is promoted to ‘Beta’. At that point, it will only receive -patches to fix serious errors. Six weeks later, the beta is promoted to -‘Stable’, and becomes the next release of `1.x`. - -This process happens in parallel. So every six weeks, on the same day, -nightly goes to beta, beta goes to stable. When `1.x` is released, at -the same time, `1.(x + 1)-beta` is released, and the nightly becomes the -first version of `1.(x + 2)-nightly`. - -# Choosing a version - -Generally speaking, unless you have a specific reason, you should be using the -stable release channel. These releases are intended for a general audience. - -However, depending on your interest in Rust, you may choose to use nightly -instead. The basic trade-off is this: in the nightly channel, you can use -unstable, new Rust features. However, unstable features are subject to change, -and so any new nightly release may break your code. If you use the stable -release, you cannot use experimental features, but the next release of Rust -will not cause significant issues through breaking changes. - -# Helping the ecosystem through CI - -What about beta? We encourage all Rust users who use the stable release channel -to also test against the beta channel in their continuous integration systems. -This will help alert the team in case there’s an accidental regression. - -Additionally, testing against nightly can catch regressions even sooner, and so -if you don’t mind a third build, we’d appreciate testing against all channels. - -As an example, many Rust programmers use [Travis](https://travis-ci.org/) to -test their crates, which is free for open source projects. Travis [supports -Rust directly][travis], and you can use a `.travis.yml` file like this to -test on all channels: - -```yaml -language: rust -rust: - - nightly - - beta - - stable - -matrix: - allow_failures: - - rust: nightly -``` - -[travis]: http://docs.travis-ci.com/user/languages/rust/ - -With this configuration, Travis will test all three channels, but if something -breaks on nightly, it won’t fail your build. A similar configuration is -recommended for any CI system, check the documentation of the one you’re -using for more details. +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). \ No newline at end of file diff --git a/first-edition/src/strings.md b/first-edition/src/strings.md index 537e5f94a8..f7648cde51 100644 --- a/first-edition/src/strings.md +++ b/first-edition/src/strings.md @@ -1,195 +1,10 @@ # Strings -Strings are an important concept for any programmer to master. Rust’s string -handling system is a bit different from other languages, due to its systems -focus. Any time you have a data structure of variable size, things can get -tricky, and strings are a re-sizable data structure. That being said, Rust’s -strings also work differently than in some other systems languages, such as C. +The first edition of the book is no longer distributed with Rust's documentation. -Let’s dig into the details. A ‘string’ is a sequence of Unicode scalar values -encoded as a stream of UTF-8 bytes. All strings are guaranteed to be a valid -encoding of UTF-8 sequences. Additionally, unlike some systems languages, -strings are not NUL-terminated and can contain NUL bytes. +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. -Rust has two main types of strings: `&str` and `String`. Let’s talk about -`&str` first. These are called ‘string slices’. A string slice has a fixed -size, and cannot be mutated. It is a reference to a sequence of UTF-8 bytes. - -```rust -let greeting = "Hello there."; // greeting: &'static str -``` - -`"Hello there."` is a string literal and its type is `&'static str`. A string -literal is a string slice that is statically allocated, meaning that it’s saved -inside our compiled program, and exists for the entire duration it runs. The -`greeting` binding is a reference to this statically allocated string. Any -function expecting a string slice will also accept a string literal. - -String literals can span multiple lines. There are two forms. The first will -include the newline and the leading spaces: - -```rust -let s = "foo - bar"; - -assert_eq!("foo\n bar", s); -``` - -The second, with a `\`, trims the spaces and the newline: - -```rust -let s = "foo\ - bar"; - -assert_eq!("foobar", s); -``` - -Note that you normally cannot access a `str` directly, but only through a `&str` -reference. This is because `str` is an unsized type which requires additional -runtime information to be usable. For more information see the chapter on -[unsized types][ut]. - -Rust has more than only `&str`s though. A `String` is a heap-allocated string. -This string is growable, and is also guaranteed to be UTF-8. `String`s are -commonly created by converting from a string slice using the `to_string` -method. - -```rust -let mut s = "Hello".to_string(); // mut s: String -println!("{}", s); - -s.push_str(", world."); -println!("{}", s); -``` - -`String`s will coerce into `&str` with an `&`: - -```rust -fn takes_slice(slice: &str) { - println!("Got: {}", slice); -} - -fn main() { - let s = "Hello".to_string(); - takes_slice(&s); -} -``` - -This coercion does not happen for functions that accept one of `&str`’s traits -instead of `&str`. For example, [`TcpStream::connect`][connect] has a parameter -of type `ToSocketAddrs`. A `&str` is okay but a `String` must be explicitly -converted using `&*`. - -```rust,no_run -use std::net::TcpStream; - -TcpStream::connect("192.168.0.1:3000"); // Parameter is of type &str. - -let addr_string = "192.168.0.1:3000".to_string(); -TcpStream::connect(&*addr_string); // Convert `addr_string` to &str. -``` - -Viewing a `String` as a `&str` is cheap, but converting the `&str` to a -`String` involves allocating memory. No reason to do that unless you have to! - -## Indexing - -Because strings are valid UTF-8, they do not support indexing: - -```rust,ignore -let s = "hello"; - -println!("The first letter of s is {}", s[0]); // ERROR!!! -``` - -Usually, access to a vector with `[]` is very fast. But, because each character -in a UTF-8 encoded string can be multiple bytes, you have to walk over the -string to find the nᵗʰ letter of a string. This is a significantly more -expensive operation, and we don’t want to be misleading. Furthermore, ‘letter’ -isn’t something defined in Unicode, exactly. We can choose to look at a string as -individual bytes, or as codepoints: - -```rust -let hachiko = "忠犬ハチ公"; - -for b in hachiko.as_bytes() { - print!("{}, ", b); -} - -println!(""); - -for c in hachiko.chars() { - print!("{}, ", c); -} - -println!(""); -``` - -This prints: - -```text -229, 191, 160, 231, 138, 172, 227, 131, 143, 227, 131, 129, 229, 133, 172, -忠, 犬, ハ, チ, 公, -``` - -As you can see, there are more bytes than `char`s. - -You can get something similar to an index like this: - -```rust -# let hachiko = "忠犬ハチ公"; -let dog = hachiko.chars().nth(1); // Kinda like `hachiko[1]`. -``` - -This emphasizes that we have to walk from the beginning of the list of `chars`. - -## Slicing - -You can get a slice of a string with the slicing syntax: - -```rust -let dog = "hachiko"; -let hachi = &dog[0..5]; -``` - -But note that these are _byte_ offsets, not _character_ offsets. So -this will fail at runtime: - -```rust,should_panic -let dog = "忠犬ハチ公"; -let hachi = &dog[0..2]; -``` - -with this error: - -```text -thread 'main' panicked at 'byte index 2 is not a char boundary; it is inside '忠' -(bytes 0..3) of `忠犬ハチ公`' -``` - -## Concatenation - -If you have a `String`, you can concatenate a `&str` to the end of it: - -```rust -let hello = "Hello ".to_string(); -let world = "world!"; - -let hello_world = hello + world; -``` - -But if you have two `String`s, you need an `&`: - -```rust -let hello = "Hello ".to_string(); -let world = "world!".to_string(); - -let hello_world = hello + &world; -``` - -This is because `&String` can automatically coerce to a `&str`. This is a -feature called ‘[`Deref` coercions][dc]’. - -[ut]: unsized-types.html -[dc]: deref-coercions.html -[connect]: ../../std/net/struct.TcpStream.html#method.connect +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). diff --git a/first-edition/src/structs.md b/first-edition/src/structs.md index f11c1610db..acfcdaf515 100644 --- a/first-edition/src/structs.md +++ b/first-edition/src/structs.md @@ -1,279 +1,10 @@ # Structs -`struct`s are a way of creating more complex data types. For example, if we were -doing calculations involving coordinates in 2D space, we would need both an `x` -and a `y` value: +The first edition of the book is no longer distributed with Rust's documentation. -```rust -let origin_x = 0; -let origin_y = 0; -``` +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. -A `struct` lets us combine these two into a single, unified datatype with `x` -and `y` as field labels: - -```rust -struct Point { - x: i32, - y: i32, -} - -fn main() { - let origin = Point { x: 0, y: 0 }; // origin: Point - - println!("The origin is at ({}, {})", origin.x, origin.y); -} -``` - -There’s a lot going on here, so let’s break it down. We declare a `struct` with -the `struct` keyword, and then with a name. By convention, `struct`s begin with -a capital letter and are camel cased: `PointInSpace`, not `Point_In_Space`. - -We can create an instance of our `struct` via `let`, as usual, but we use a `key: -value` style syntax to set each field. The order doesn’t need to be the same as -in the original declaration. - -Finally, because fields have names, we can access them through dot -notation: `origin.x`. - -The values in `struct`s are immutable by default, like other bindings in Rust. -Use `mut` to make them mutable: - -```rust -struct Point { - x: i32, - y: i32, -} - -fn main() { - let mut point = Point { x: 0, y: 0 }; - - point.x = 5; - - println!("The point is at ({}, {})", point.x, point.y); -} -``` - -This will print `The point is at (5, 0)`. - -Rust does not support field mutability at the language level, so you cannot -write something like this: - -```rust,ignore -struct Point { - mut x: i32, // This causes an error. - y: i32, -} -``` - -Mutability is a property of the binding, not of the structure itself. If you’re -used to field-level mutability, this may seem strange at first, but it -significantly simplifies things. It even lets you make things mutable on a temporary -basis: - -```rust,ignore -struct Point { - x: i32, - y: i32, -} - -fn main() { - let mut point = Point { x: 0, y: 0 }; - - point.x = 5; - - let point = point; // `point` is now immutable. - - point.y = 6; // This causes an error. -} -``` - -Your structure can still contain `&mut` references, which will let -you do some kinds of mutation: - -```rust -struct Point { - x: i32, - y: i32, -} - -struct PointRef<'a> { - x: &'a mut i32, - y: &'a mut i32, -} - -fn main() { - let mut point = Point { x: 0, y: 0 }; - - { - let r = PointRef { x: &mut point.x, y: &mut point.y }; - - *r.x = 5; - *r.y = 6; - } - - assert_eq!(5, point.x); - assert_eq!(6, point.y); -} -``` - -Initialization of a data structure (struct, enum, union) can be simplified when -fields of the data structure are initialized with variables of the same -names as the fields. - -```rust -#[derive(Debug)] -struct Person<'a> { - name: &'a str, - age: u8 -} - -fn main() { - // Create struct with field init shorthand - let name = "Peter"; - let age = 27; - let peter = Person { name, age }; - - // Debug-print struct - println!("{:?}", peter); -} -``` - -# Update syntax - -A `struct` can include `..` to indicate that you want to use a copy of some -other `struct` for some of the values. For example: - -```rust -struct Point3d { - x: i32, - y: i32, - z: i32, -} - -let mut point = Point3d { x: 0, y: 0, z: 0 }; -point = Point3d { y: 1, .. point }; -``` - -This gives `point` a new `y`, but keeps the old `x` and `z` values. It doesn’t -have to be the same `struct` either, you can use this syntax when making new -ones, and it will copy the values you don’t specify: - -```rust -# struct Point3d { -# x: i32, -# y: i32, -# z: i32, -# } -let origin = Point3d { x: 0, y: 0, z: 0 }; -let point = Point3d { z: 1, x: 2, .. origin }; -``` - -# Tuple structs - -Rust has another data type that’s like a hybrid between a [tuple][tuple] and a -`struct`, called a ‘tuple struct’. Tuple structs have a name, but their fields -don't. They are declared with the `struct` keyword, and then with a name -followed by a tuple: - -[tuple]: primitive-types.html#tuples - -```rust -struct Color(i32, i32, i32); -struct Point(i32, i32, i32); - -let black = Color(0, 0, 0); -let origin = Point(0, 0, 0); -``` - -Here, `black` and `origin` are not the same type, even though they contain the -same values. - -The members of a tuple struct may be accessed by dot notation or destructuring -`let`, just like regular tuples: - -```rust -# struct Color(i32, i32, i32); -# struct Point(i32, i32, i32); -# let black = Color(0, 0, 0); -# let origin = Point(0, 0, 0); -let black_r = black.0; -let Point(_, origin_y, origin_z) = origin; -``` - -Patterns like `Point(_, origin_y, origin_z)` are also used in -[match expressions][match]. - -One case when a tuple struct is very useful is when it has only one element. -We call this the ‘newtype’ pattern, because it allows you to create a new type -that is distinct from its contained value and also expresses its own semantic -meaning: - -```rust -struct Inches(i32); - -let length = Inches(10); - -let Inches(integer_length) = length; -println!("length is {} inches", integer_length); -``` - -As above, you can extract the inner integer type through a destructuring `let`. -In this case, the `let Inches(integer_length)` assigns `10` to `integer_length`. -We could have used dot notation to do the same thing: - -```rust -# struct Inches(i32); -# let length = Inches(10); -let integer_length = length.0; -``` - -It's always possible to use a `struct` instead of a tuple struct, and can be -clearer. We could write `Color` and `Point` like this instead: - -```rust -struct Color { - red: i32, - blue: i32, - green: i32, -} - -struct Point { - x: i32, - y: i32, - z: i32, -} -``` - -Good names are important, and while values in a tuple struct can be -referenced with dot notation as well, a `struct` gives us actual names, -rather than positions. - -[match]: match.html - -# Unit-like structs - -You can define a `struct` with no members at all: - -```rust,ignore -struct Electron {} // Use empty braces... -struct Proton; // ...or just a semicolon. - -// Use the same notation when creating an instance. -let x = Electron {}; -let y = Proton; -let z = Electron; // Error -``` - -Such a `struct` is called ‘unit-like’ because it resembles the empty -tuple, `()`, sometimes called ‘unit’. Like a tuple struct, it defines a -new type. - -This is rarely useful on its own (although sometimes it can serve as a -marker type), but in combination with other features, it can become -useful. For instance, a library may ask you to create a structure that -implements a certain [trait][trait] to handle events. If you don’t have -any data you need to store in the structure, you can create a -unit-like `struct`. - -[trait]: traits.html +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). diff --git a/first-edition/src/syntax-and-semantics.md b/first-edition/src/syntax-and-semantics.md index aa4c125102..62740385c8 100644 --- a/first-edition/src/syntax-and-semantics.md +++ b/first-edition/src/syntax-and-semantics.md @@ -1,10 +1,10 @@ # Syntax and Semantics -This chapter breaks Rust down into small chunks, one for each concept. +The first edition of the book is no longer distributed with Rust's documentation. -If you’d like to learn Rust from the bottom up, reading this in order is a -great way to do that. +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. -These sections also form a reference for each concept, so if you’re reading -another tutorial and find something confusing, you can find it explained -somewhere in here. +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). diff --git a/first-edition/src/syntax-index.md b/first-edition/src/syntax-index.md index b9a1868c26..a2ab62caca 100644 --- a/first-edition/src/syntax-index.md +++ b/first-edition/src/syntax-index.md @@ -1,253 +1,10 @@ # Syntax Index -## Keywords +The first edition of the book is no longer distributed with Rust's documentation. -* `as`: primitive casting, or disambiguating the specific trait containing an item. See [Casting Between Types (`as`)], [Universal Function Call Syntax (Angle-bracket Form)], [Associated Types]. -* `break`: break out of loop. See [Loops (Ending Iteration Early)]. -* `const`: constant items and constant raw pointers. See [`const` and `static`], [Raw Pointers]. -* `continue`: continue to next loop iteration. See [Loops (Ending Iteration Early)]. -* `crate`: external crate linkage. See [Crates and Modules (Importing External Crates)]. -* `else`: fallback for `if` and `if let` constructs. See [`if`], [`if let`]. -* `enum`: defining enumeration. See [Enums]. -* `extern`: external crate, function, and variable linkage. See [Crates and Modules (Importing External Crates)], [Foreign Function Interface]. -* `false`: boolean false literal. See [Primitive Types (Booleans)]. -* `fn`: function definition and function pointer types. See [Functions]. -* `for`: iterator loop, part of trait `impl` syntax, and higher-ranked lifetime syntax. See [Loops (`for`)], [Method Syntax]. -* `if`: conditional branching. See [`if`], [`if let`]. -* `impl`: inherent and trait implementation blocks. See [Method Syntax]. -* `in`: part of `for` loop syntax. See [Loops (`for`)]. -* `let`: variable binding. See [Variable Bindings]. -* `loop`: unconditional, infinite loop. See [Loops (`loop`)]. -* `match`: pattern matching. See [Match]. -* `mod`: module declaration. See [Crates and Modules (Defining Modules)]. -* `move`: part of closure syntax. See [Closures (`move` closures)]. -* `mut`: denotes mutability in pointer types and pattern bindings. See [Mutability]. -* `pub`: denotes public visibility in `struct` fields, `impl` blocks, and modules. See [Crates and Modules (Exporting a Public Interface)]. -* `ref`: by-reference binding. See [Patterns (`ref` and `ref mut`)]. -* `return`: return from function. See [Functions (Early Returns)]. -* `Self`: implementor type alias. See [Traits]. -* `self`: method subject. See [Method Syntax (Method Calls)]. -* `static`: global variable. See [`const` and `static` (`static`)]. -* `struct`: structure definition. See [Structs]. -* `trait`: trait definition. See [Traits]. -* `true`: boolean true literal. See [Primitive Types (Booleans)]. -* `type`: type alias, and associated type definition. See [`type` Aliases], [Associated Types]. -* `unsafe`: denotes unsafe code, functions, traits, and implementations. See [Unsafe]. -* `use`: import symbols into scope. See [Crates and Modules (Importing Modules with `use`)]. -* `where`: type constraint clauses. See [Traits (`where` clause)]. -* `while`: conditional loop. See [Loops (`while`)]. +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. -## Operators and Symbols - -* `!` (`ident!(…)`, `ident!{…}`, `ident![…]`): denotes macro expansion. See [Macros]. -* `!` (`!expr`): bitwise or logical complement. Overloadable (`Not`). -* `!=` (`var != expr`): nonequality comparison. Overloadable (`PartialEq`). -* `%` (`expr % expr`): arithmetic remainder. Overloadable (`Rem`). -* `%=` (`var %= expr`): arithmetic remainder & assignment. Overloadable (`RemAssign`). -* `&` (`expr & expr`): bitwise and. Overloadable (`BitAnd`). -* `&` (`&expr`, `&mut expr`): borrow. See [References and Borrowing]. -* `&` (`&type`, `&mut type`, `&'a type`, `&'a mut type`): borrowed pointer type. See [References and Borrowing]. -* `&=` (`var &= expr`): bitwise and & assignment. Overloadable (`BitAndAssign`). -* `&&` (`expr && expr`): logical and. -* `*` (`expr * expr`): arithmetic multiplication. Overloadable (`Mul`). -* `*` (`*expr`): dereference. -* `*` (`*const type`, `*mut type`): raw pointer. See [Raw Pointers]. -* `*=` (`var *= expr`): arithmetic multiplication & assignment. Overloadable (`MulAssign`). -* `+` (`expr + expr`): arithmetic addition. Overloadable (`Add`). -* `+` (`trait + trait`, `'a + trait`): compound type constraint. See [Traits (Multiple Trait Bounds)]. -* `+=` (`var += expr`): arithmetic addition & assignment. Overloadable (`AddAssign`). -* `,`: argument and element separator. See [Attributes], [Functions], [Structs], [Generics], [Match], [Closures], [Crates and Modules (Importing Modules with `use`)]. -* `-` (`expr - expr`): arithmetic subtraction. Overloadable (`Sub`). -* `-` (`- expr`): arithmetic negation. Overloadable (`Neg`). -* `-=` (`var -= expr`): arithmetic subtraction & assignment. Overloadable (`SubAssign`). -* `->` (`fn(…) -> type`, `|…| -> type`): function and closure return type. See [Functions], [Closures]. -* `.` (`expr.ident`): member access. See [Structs], [Method Syntax]. -* `..` (`..`, `expr..`, `..expr`, `expr..expr`): right-exclusive range literal. -* `..` (`..expr`): struct literal update syntax. See [Structs (Update syntax)]. -* `..` (`variant(x, ..)`, `struct_type { x, .. }`): "and the rest" pattern binding. See [Patterns (Ignoring bindings)]. -* `...` (`...expr`, `expr...expr`) *in an expression*: inclusive range expression. See [Iterators]. -* `...` (`expr...expr`) *in a pattern*: inclusive range pattern. See [Patterns (Ranges)]. -* `/` (`expr / expr`): arithmetic division. Overloadable (`Div`). -* `/=` (`var /= expr`): arithmetic division & assignment. Overloadable (`DivAssign`). -* `:` (`pat: type`, `ident: type`): constraints. See [Variable Bindings], [Functions], [Structs], [Traits]. -* `:` (`ident: expr`): struct field initializer. See [Structs]. -* `:` (`'a: loop {…}`): loop label. See [Loops (Loops Labels)]. -* `;`: statement and item terminator. -* `;` (`[…; len]`): part of fixed-size array syntax. See [Primitive Types (Arrays)]. -* `<<` (`expr << expr`): left-shift. Overloadable (`Shl`). -* `<<=` (`var <<= expr`): left-shift & assignment. Overloadable (`ShlAssign`). -* `<` (`expr < expr`): less-than comparison. Overloadable (`PartialOrd`). -* `<=` (`var <= expr`): less-than or equal-to comparison. Overloadable (`PartialOrd`). -* `=` (`var = expr`, `ident = type`): assignment/equivalence. See [Variable Bindings], [`type` Aliases], generic parameter defaults. -* `==` (`var == expr`): equality comparison. Overloadable (`PartialEq`). -* `=>` (`pat => expr`): part of match arm syntax. See [Match]. -* `>` (`expr > expr`): greater-than comparison. Overloadable (`PartialOrd`). -* `>=` (`var >= expr`): greater-than or equal-to comparison. Overloadable (`PartialOrd`). -* `>>` (`expr >> expr`): right-shift. Overloadable (`Shr`). -* `>>=` (`var >>= expr`): right-shift & assignment. Overloadable (`ShrAssign`). -* `@` (`ident @ pat`): pattern binding. See [Patterns (Bindings)]. -* `^` (`expr ^ expr`): bitwise exclusive or. Overloadable (`BitXor`). -* `^=` (`var ^= expr`): bitwise exclusive or & assignment. Overloadable (`BitXorAssign`). -* `|` (`expr | expr`): bitwise or. Overloadable (`BitOr`). -* `|` (`pat | pat`): pattern alternatives. See [Patterns (Multiple patterns)]. -* `|` (`|…| expr`): closures. See [Closures]. -* `|=` (`var |= expr`): bitwise or & assignment. Overloadable (`BitOrAssign`). -* `||` (`expr || expr`): logical or. -* `_`: "ignored" pattern binding (see [Patterns (Ignoring bindings)]). Also used to make integer-literals readable (see [Reference (Integer literals)]). -* `?` (`expr?`): Error propagation. Returns early when `Err(_)` is encountered, unwraps otherwise. Similar to the [`try!` macro]. - -## Other Syntax - - - -* `'ident`: named lifetime or loop label. See [Lifetimes], [Loops (Loops Labels)]. -* `…u8`, `…i32`, `…f64`, `…usize`, …: numeric literal of specific type. -* `"…"`: string literal. See [Strings]. -* `r"…"`, `r#"…"#`, `r##"…"##`, …: raw string literal, escape characters are not processed. See [Reference (Raw String Literals)]. -* `b"…"`: byte string literal, constructs a `[u8]` instead of a string. See [Reference (Byte String Literals)]. -* `br"…"`, `br#"…"#`, `br##"…"##`, …: raw byte string literal, combination of raw and byte string literal. See [Reference (Raw Byte String Literals)]. -* `'…'`: character literal. See [Primitive Types (`char`)]. -* `b'…'`: ASCII byte literal. -* `|…| expr`: closure. See [Closures]. - - - -* `ident::ident`: path. See [Crates and Modules (Defining Modules)]. -* `::path`: path relative to the crate root (*i.e.* an explicitly absolute path). See [Crates and Modules (Re-exporting with `pub use`)]. -* `self::path`: path relative to the current module (*i.e.* an explicitly relative path). See [Crates and Modules (Re-exporting with `pub use`)]. -* `super::path`: path relative to the parent of the current module. See [Crates and Modules (Re-exporting with `pub use`)]. -* `type::ident`, `::ident`: associated constants, functions, and types. See [Associated Types]. -* `::…`: associated item for a type which cannot be directly named (*e.g.* `<&T>::…`, `<[T]>::…`, *etc.*). See [Associated Types]. -* `trait::method(…)`: disambiguating a method call by naming the trait which defines it. See [Universal Function Call Syntax]. -* `type::method(…)`: disambiguating a method call by naming the type for which it's defined. See [Universal Function Call Syntax]. -* `::method(…)`: disambiguating a method call by naming the trait _and_ type. See [Universal Function Call Syntax (Angle-bracket Form)]. - - - -* `path<…>` (*e.g.* `Vec`): specifies parameters to generic type *in a type*. See [Generics]. -* `path::<…>`, `method::<…>` (*e.g.* `"42".parse::()`): specifies parameters to generic type, function, or method *in an expression*. See [Generics § Resolving ambiguities](generics.html#resolving-ambiguities). -* `fn ident<…> …`: define generic function. See [Generics]. -* `struct ident<…> …`: define generic structure. See [Generics]. -* `enum ident<…> …`: define generic enumeration. See [Generics]. -* `impl<…> …`: define generic implementation. -* `for<…> type`: higher-ranked lifetime bounds. -* `type` (*e.g.* `Iterator`): a generic type where one or more associated types have specific assignments. See [Associated Types]. - - - -* `T: U`: generic parameter `T` constrained to types that implement `U`. See [Traits]. -* `T: 'a`: generic type `T` must outlive lifetime `'a`. When we say that a type 'outlives' the lifetime, we mean that it cannot transitively contain any references with lifetimes shorter than `'a`. -* `T : 'static`: The generic type `T` contains no borrowed references other than `'static` ones. -* `'b: 'a`: generic lifetime `'b` must outlive lifetime `'a`. -* `T: ?Sized`: allow generic type parameter to be a dynamically-sized type. See [Unsized Types (`?Sized`)]. -* `'a + trait`, `trait + trait`: compound type constraint. See [Traits (Multiple Trait Bounds)]. - - - -* `#[meta]`: outer attribute. See [Attributes]. -* `#![meta]`: inner attribute. See [Attributes]. -* `$ident`: macro substitution. See [Macros]. -* `$ident:kind`: macro capture. See [Macros]. -* `$(…)…`: macro repetition. See [Macros]. - - - -* `//`: line comment. See [Comments]. -* `//!`: inner line doc comment. See [Comments]. -* `///`: outer line doc comment. See [Comments]. -* `/*…*/`: block comment. See [Comments]. -* `/*!…*/`: inner block doc comment. See [Comments]. -* `/**…*/`: outer block doc comment. See [Comments]. - - - -* `!`: always empty Never type. See [Diverging Functions]. - - - -* `()`: empty tuple (*a.k.a.* unit), both literal and type. -* `(expr)`: parenthesized expression. -* `(expr,)`: single-element tuple expression. See [Primitive Types (Tuples)]. -* `(type,)`: single-element tuple type. See [Primitive Types (Tuples)]. -* `(expr, …)`: tuple expression. See [Primitive Types (Tuples)]. -* `(type, …)`: tuple type. See [Primitive Types (Tuples)]. -* `expr(expr, …)`: function call expression. Also used to initialize tuple `struct`s and tuple `enum` variants. See [Functions]. -* `ident!(…)`, `ident!{…}`, `ident![…]`: macro invocation. See [Macros]. -* `expr.0`, `expr.1`, …: tuple indexing. See [Primitive Types (Tuple Indexing)]. - - - -* `{…}`: block expression. -* `Type {…}`: `struct` literal. See [Structs]. - - - -* `[…]`: array literal. See [Primitive Types (Arrays)]. -* `[expr; len]`: array literal containing `len` copies of `expr`. See [Primitive Types (Arrays)]. -* `[type; len]`: array type containing `len` instances of `type`. See [Primitive Types (Arrays)]. -* `expr[expr]`: collection indexing. Overloadable (`Index`, `IndexMut`). -* `expr[..]`, `expr[a..]`, `expr[..b]`, `expr[a..b]`: collection indexing pretending to be collection slicing, using `Range`, `RangeFrom`, `RangeTo`, `RangeFull` as the "index". - -[`const` and `static` (`static`)]: const-and-static.html#static -[`const` and `static`]: const-and-static.html -[`if let`]: if-let.html -[`if`]: if.html -[`type` Aliases]: type-aliases.html -[Associated Types]: associated-types.html -[Attributes]: attributes.html -[Casting Between Types (`as`)]: casting-between-types.html#as -[Closures (`move` closures)]: closures.html#move-closures -[Closures]: closures.html -[Comments]: comments.html -[Crates and Modules (Defining Modules)]: crates-and-modules.html#defining-modules -[Crates and Modules (Exporting a Public Interface)]: crates-and-modules.html#exporting-a-public-interface -[Crates and Modules (Importing External Crates)]: crates-and-modules.html#importing-external-crates -[Crates and Modules (Importing Modules with `use`)]: crates-and-modules.html#importing-modules-with-use -[Crates and Modules (Re-exporting with `pub use`)]: crates-and-modules.html#re-exporting-with-pub-use -[Diverging Functions]: functions.html#diverging-functions -[Enums]: enums.html -[Foreign Function Interface]: ffi.html -[Functions (Early Returns)]: functions.html#early-returns -[Functions]: functions.html -[Generics]: generics.html -[Iterators]: iterators.html -[`try!` macro]: error-handling.html#the-try-macro -[Lifetimes]: lifetimes.html -[Loops (`for`)]: loops.html#for -[Loops (`loop`)]: loops.html#loop -[Loops (`while`)]: loops.html#while -[Loops (Ending Iteration Early)]: loops.html#ending-iteration-early -[Loops (Loops Labels)]: loops.html#loop-labels -[Macros]: macros.html -[Match]: match.html -[Method Syntax (Method Calls)]: method-syntax.html#method-calls -[Method Syntax]: method-syntax.html -[Mutability]: mutability.html -[Operators and Overloading]: operators-and-overloading.html -[Patterns (`ref` and `ref mut`)]: patterns.html#ref-and-ref-mut -[Patterns (Bindings)]: patterns.html#bindings -[Patterns (Ignoring bindings)]: patterns.html#ignoring-bindings -[Patterns (Multiple patterns)]: patterns.html#multiple-patterns -[Patterns (Ranges)]: patterns.html#ranges -[Primitive Types (`char`)]: primitive-types.html#char -[Primitive Types (Arrays)]: primitive-types.html#arrays -[Primitive Types (Booleans)]: primitive-types.html#booleans -[Primitive Types (Tuple Indexing)]: primitive-types.html#tuple-indexing -[Primitive Types (Tuples)]: primitive-types.html#tuples -[Raw Pointers]: raw-pointers.html -[Reference (Byte String Literals)]: ../../reference/tokens.html#byte-and-byte-string-literals -[Reference (Integer literals)]: ../../reference/tokens.html#integer-literals -[Reference (Raw Byte String Literals)]: ../../reference/tokens.html#raw-byte-string-literals -[Reference (Raw String Literals)]: ../../reference/tokens.html#raw-string-literals -[References and Borrowing]: references-and-borrowing.html -[Strings]: strings.html -[Structs (Update syntax)]: structs.html#update-syntax -[Structs]: structs.html -[Traits (`where` clause)]: traits.html#where-clause -[Traits (Multiple Trait Bounds)]: traits.html#multiple-trait-bounds -[Traits]: traits.html -[Universal Function Call Syntax]: ufcs.html -[Universal Function Call Syntax (Angle-bracket Form)]: ufcs.html#angle-bracket-form -[Unsafe]: unsafe.html -[Unsized Types (`?Sized`)]: unsized-types.html#sized -[Variable Bindings]: variable-bindings.html +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). \ No newline at end of file diff --git a/first-edition/src/testing.md b/first-edition/src/testing.md index b4f580fcdf..d594189791 100644 --- a/first-edition/src/testing.md +++ b/first-edition/src/testing.md @@ -1,633 +1,10 @@ # Testing -> Program testing can be a very effective way to show the presence of bugs, but -> it is hopelessly inadequate for showing their absence. -> -> Edsger W. Dijkstra, "The Humble Programmer" (1972) +The first edition of the book is no longer distributed with Rust's documentation. -Let's talk about how to test Rust code. What we will not be talking about is -the right way to test Rust code. There are many schools of thought regarding -the right and wrong way to write tests. All of these approaches use the same -basic tools, and so we'll show you the syntax for using them. +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. -# The `test` attribute - -At its simplest, a test in Rust is a function that's annotated with the `test` -attribute. Let's make a new project with Cargo called `adder`: - -```bash -$ cargo new adder -$ cd adder -``` - -Cargo will automatically generate a simple test when you make a new project. -Here's the contents of `src/lib.rs`: - -```rust,ignore -# // The next line exists to trick play.rust-lang.org into running our code as a -# // test: -# // fn main -# -#[cfg(test)] -mod tests { - #[test] - fn it_works() { - } -} -``` - -For now, let's remove the `mod` bit, and focus on just the function: - -```rust,ignore -# // The next line exists to trick play.rust-lang.org into running our code as a -# // test: -# // fn main -# -#[test] -fn it_works() { -} -``` - -Note the `#[test]`. This attribute indicates that this is a test function. It -currently has no body. That's good enough to pass! We can run the tests with -`cargo test`: - -```bash -$ cargo test - Compiling adder v0.1.0 (file:///home/you/projects/adder) - Finished debug [unoptimized + debuginfo] target(s) in 0.15 secs - Running target/debug/deps/adder-941f01916ca4a642 - -running 1 test -test it_works ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Doc-tests adder - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured -``` - -Cargo compiled and ran our tests. There are two sets of output here: one -for the test we wrote, and another for documentation tests. We'll talk about -those later. For now, see this line: - -```text -test it_works ... ok -``` - -Note the `it_works`. This comes from the name of our function: - -```rust -# fn main() { -fn it_works() { -} -# } -``` - -We also get a summary line: - -```text -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured -``` - -So why does our do-nothing test pass? Any test which doesn't `panic!` passes, -and any test that does `panic!` fails. Let's make our test fail: - -```rust,ignore -# // The next line exists to trick play.rust-lang.org into running our code as a -# // test: -# // fn main -# -#[test] -fn it_works() { - assert!(false); -} -``` - -`assert!` is a macro provided by Rust which takes one argument: if the argument -is `true`, nothing happens. If the argument is `false`, it will `panic!`. Let's -run our tests again: - -```bash -$ cargo test - Compiling adder v0.1.0 (file:///home/you/projects/adder) - Finished debug [unoptimized + debuginfo] target(s) in 0.17 secs - Running target/debug/deps/adder-941f01916ca4a642 - -running 1 test -test it_works ... FAILED - -failures: - ----- it_works stdout ---- - thread 'it_works' panicked at 'assertion failed: false', src/lib.rs:5 -note: Run with `RUST_BACKTRACE=1` for a backtrace. - - -failures: - it_works - -test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured - -error: test failed -``` - -Rust indicates that our test failed: - -```text -test it_works ... FAILED -``` - -And that's reflected in the summary line: - -```text -test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured -``` - -We also get a non-zero status code. We can use `$?` on macOS and Linux: - -```bash -$ echo $? -101 -``` - -On Windows, if you’re using `cmd`: - -```bash -> echo %ERRORLEVEL% -``` - -And if you’re using PowerShell: - -```bash -> echo $LASTEXITCODE # the code itself -> echo $? # a boolean, fail or succeed -``` - -This is useful if you want to integrate `cargo test` into other tooling. - -We can invert our test's failure with another attribute: `should_panic`: - -```rust,ignore -# // The next line exists to trick play.rust-lang.org into running our code as a -# // test: -# // fn main -# -#[test] -#[should_panic] -fn it_works() { - assert!(false); -} -``` - -This test will now succeed if we `panic!` and fail if we complete. Let's try it: - -```bash -$ cargo test - Compiling adder v0.1.0 (file:///home/you/projects/adder) - Finished debug [unoptimized + debuginfo] target(s) in 0.17 secs - Running target/debug/deps/adder-941f01916ca4a642 - -running 1 test -test it_works ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Doc-tests adder - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured -``` - -Rust provides another macro, `assert_eq!`, that compares two arguments for -equality: - -```rust,ignore -# // The next line exists to trick play.rust-lang.org into running our code as a -# // test: -# // fn main -# -#[test] -#[should_panic] -fn it_works() { - assert_eq!("Hello", "world"); -} -``` - -Does this test pass or fail? Because of the `should_panic` attribute, it -passes: - -```bash -$ cargo test - Compiling adder v0.1.0 (file:///home/you/projects/adder) - Finished debug [unoptimized + debuginfo] target(s) in 0.21 secs - Running target/debug/deps/adder-941f01916ca4a642 - -running 1 test -test it_works ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Doc-tests adder - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured -``` - -`should_panic` tests can be fragile, as it's hard to guarantee that the test -didn't fail for an unexpected reason. To help with this, an optional `expected` -parameter can be added to the `should_panic` attribute. The test harness will -make sure that the failure message contains the provided text. A safer version -of the example above would be: - -```rust,ignore -# // The next line exists to trick play.rust-lang.org into running our code as a -# // test: -# // fn main -# -#[test] -#[should_panic(expected = "assertion failed")] -fn it_works() { - assert_eq!("Hello", "world"); -} -``` - -That's all there is to the basics! Let's write one 'real' test: - -```rust,ignore -# // The next line exists to trick play.rust-lang.org into running our code as a -# // test: -# // fn main -# -pub fn add_two(a: i32) -> i32 { - a + 2 -} - -#[test] -fn it_works() { - assert_eq!(4, add_two(2)); -} -``` - -This is a very common use of `assert_eq!`: call some function with -some known arguments and compare it to the expected output. - -# The `ignore` attribute - -Sometimes a few specific tests can be very time-consuming to execute. These -can be disabled by default by using the `ignore` attribute: - -```rust,ignore -# // The next line exists to trick play.rust-lang.org into running our code as a -# // test: -# // fn main -# -pub fn add_two(a: i32) -> i32 { - a + 2 -} - -#[test] -fn it_works() { - assert_eq!(4, add_two(2)); -} - -#[test] -#[ignore] -fn expensive_test() { - // Code that takes an hour to run... -} -``` - -Now we run our tests and see that `it_works` is run, but `expensive_test` is -not: - -```bash -$ cargo test - Compiling adder v0.1.0 (file:///home/you/projects/adder) - Finished debug [unoptimized + debuginfo] target(s) in 0.20 secs - Running target/debug/deps/adder-941f01916ca4a642 - -running 2 tests -test expensive_test ... ignored -test it_works ... ok - -test result: ok. 1 passed; 0 failed; 1 ignored; 0 measured - - Doc-tests adder - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured -``` - -The expensive tests can be run explicitly using `cargo test -- --ignored`: - -```bash -$ cargo test -- --ignored - Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs - Running target/debug/deps/adder-941f01916ca4a642 - -running 1 test -test expensive_test ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Doc-tests adder - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured -``` - -The `--ignored` argument is an argument to the test binary, and not to Cargo, -which is why the command is `cargo test -- --ignored`. - -# The `tests` module - -There is one way in which our existing example is not idiomatic: it's -missing the `tests` module. You might have noticed this test module was -present in the code that was initially generated with `cargo new` but -was missing from our last example. Let's explain what this does. - -The idiomatic way of writing our example looks like this: - -```rust,ignore -# // The next line exists to trick play.rust-lang.org into running our code as a -# // test: -# // fn main -# -pub fn add_two(a: i32) -> i32 { - a + 2 -} - -#[cfg(test)] -mod tests { - use super::add_two; - - #[test] - fn it_works() { - assert_eq!(4, add_two(2)); - } -} -``` - -There's a few changes here. The first is the introduction of a `mod tests` with -a `cfg` attribute. The module allows us to group all of our tests together, and -to also define helper functions if needed, that don't become a part of the rest -of our crate. The `cfg` attribute only compiles our test code if we're -currently trying to run the tests. This can save compile time, and also ensures -that our tests are entirely left out of a normal build. - -The second change is the `use` declaration. Because we're in an inner module, -we need to bring the tested function into scope. This can be annoying if you have -a large module, and so this is a common use of globs. Let's change our -`src/lib.rs` to make use of it: - -```rust,ignore -# // The next line exists to trick play.rust-lang.org into running our code as a -# // test: -# // fn main -# -pub fn add_two(a: i32) -> i32 { - a + 2 -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn it_works() { - assert_eq!(4, add_two(2)); - } -} -``` - -Note the different `use` line. Now we run our tests: - -```bash -$ cargo test - Updating registry `https://github.com/rust-lang/crates.io-index` - Compiling adder v0.1.0 (file:///home/you/projects/adder) - Running target/debug/deps/adder-91b3e234d4ed382a - -running 1 test -test tests::it_works ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Doc-tests adder - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured -``` - -It works! - -The current convention is to use the `tests` module to hold your "unit-style" -tests. Anything that tests one small bit of functionality makes sense to -go here. But what about "integration-style" tests instead? For that, we have -the `tests` directory. - -# The `tests` directory - -Each file in `tests/*.rs` directory is treated as an individual crate. -To write an integration test, let's make a `tests` directory and -put a `tests/integration_test.rs` file inside with this as its contents: - -```rust,ignore -# // The next line exists to trick play.rust-lang.org into running our code as a -# // test: -# // fn main -# -# // Sadly, this code will not work in play.rust-lang.org, because we have no -# // crate adder to import. You'll need to try this part on your own machine. -extern crate adder; - -#[test] -fn it_works() { - assert_eq!(4, adder::add_two(2)); -} -``` - -This looks similar to our previous tests, but slightly different. We now have -an `extern crate adder` at the top. This is because each test in the `tests` -directory is an entirely separate crate, and so we need to import our library. -This is also why `tests` is a suitable place to write integration-style tests: -they use the library like any other consumer of it would. - -Let's run them: - -```bash -$ cargo test - Compiling adder v0.1.0 (file:///home/you/projects/adder) - Running target/debug/deps/adder-91b3e234d4ed382a - -running 1 test -test tests::it_works ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Running target/debug/integration_test-68064b69521c828a - -running 1 test -test it_works ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Doc-tests adder - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured -``` - -Now we have three sections: our previous test is also run, as well as our new -one. - -Cargo will ignore files in subdirectories of the `tests/` directory. -Therefore shared modules in integrations tests are possible. -For example `tests/common/mod.rs` is not separately compiled by cargo but can -be imported in every test with `mod common;` - -That's all there is to the `tests` directory. The `tests` module isn't needed -here, since the whole thing is focused on tests. - -Note, when building integration tests, cargo will not pass the `test` attribute -to the compiler. It means that all parts in `cfg(test)` won't be included in -the build used in your integration tests. - -Let's finally check out that third section: documentation tests. - -# Documentation tests - -Nothing is better than documentation with examples. Nothing is worse than -examples that don't actually work, because the code has changed since the -documentation has been written. To this end, Rust supports automatically -running examples in your documentation (**note:** this only works in library -crates, not binary crates). Here's a fleshed-out `src/lib.rs` with examples: - -```rust,ignore -# // The next line exists to trick play.rust-lang.org into running our code as a -# // test: -# // fn main -# -//! The `adder` crate provides functions that add numbers to other numbers. -//! -//! # Examples -//! -//! ``` -//! assert_eq!(4, adder::add_two(2)); -//! ``` - -/// This function adds two to its argument. -/// -/// # Examples -/// -/// ``` -/// use adder::add_two; -/// -/// assert_eq!(4, add_two(2)); -/// ``` -pub fn add_two(a: i32) -> i32 { - a + 2 -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn it_works() { - assert_eq!(4, add_two(2)); - } -} -``` - -Note the module-level documentation with `//!` and the function-level -documentation with `///`. Rust's documentation supports Markdown in comments, -and so triple graves mark code blocks. It is conventional to include the -`# Examples` section, exactly like that, with examples following. - -Let's run the tests again: - -```bash -$ cargo test - Compiling adder v0.1.0. (file:///home/you/projects/adder) - Running target/debug/deps/adder-91b3e234d4ed382a - -running 1 test -test tests::it_works ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Running target/debug/integration_test-68064b69521c828a - -running 1 test -test it_works ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Doc-tests adder - -running 2 tests -test add_two_0 ... ok -test _0 ... ok - -test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured -``` - -Now we have all three kinds of tests running! Note the names of the -documentation tests: the `_0` is generated for the module test, and `add_two_0` -for the function test. These will auto increment with names like `add_two_1` as -you add more examples. - -We haven’t covered all of the details with writing documentation tests. For more, -please see the [Documentation chapter](documentation.html). - -# Testing and concurrency - -It is important to note that tests are run concurrently using threads. For this -reason, care should be taken to ensure your tests do not depend on each-other, -or on any shared state. "Shared state" can also include the environment, such -as the current working directory, or environment variables. - -If this is an issue it is possible to control this concurrency, either by -setting the environment variable `RUST_TEST_THREADS`, or by passing the argument -`--test-threads` to the tests: - -```bash -$ RUST_TEST_THREADS=1 cargo test # Run tests with no concurrency -... -$ cargo test -- --test-threads=1 # Same as above -... -``` - -# Test output - -By default Rust's test library captures and discards output to standard -out/error, e.g. output from `println!()`. This too can be controlled using the -environment or a switch: - - -```bash -$ RUST_TEST_NOCAPTURE=1 cargo test # Preserve stdout/stderr -... -$ cargo test -- --nocapture # Same as above -... -``` - -However a better method avoiding capture is to use logging rather than raw -output. Rust has a [standard logging API][log], which provides a frontend to -multiple logging implementations. This can be used in conjunction with the -default [env_logger] to output any debugging information in a manner that can be -controlled at runtime. - -[log]: https://crates.io/crates/log -[env_logger]: https://crates.io/crates/env_logger +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). diff --git a/first-edition/src/the-stack-and-the-heap.md b/first-edition/src/the-stack-and-the-heap.md index 7d7c76ef45..5c53af3563 100644 --- a/first-edition/src/the-stack-and-the-heap.md +++ b/first-edition/src/the-stack-and-the-heap.md @@ -1,585 +1,10 @@ # The Stack and the Heap -As a systems language, Rust operates at a low level. If you’re coming from a -high-level language, there are some aspects of systems programming that you may -not be familiar with. The most important one is how memory works, with a stack -and a heap. If you’re familiar with how C-like languages use stack allocation, -this chapter will be a refresher. If you’re not, you’ll learn about this more -general concept, but with a Rust-y focus. +The first edition of the book is no longer distributed with Rust's documentation. -As with most things, when learning about them, we’ll use a simplified model to -start. This lets you get a handle on the basics, without getting bogged down -with details which are, for now, irrelevant. The examples we’ll use aren’t 100% -accurate, but are representative for the level we’re trying to learn at right -now. Once you have the basics down, learning more about how allocators are -implemented, virtual memory, and other advanced topics will reveal the leaks in -this particular abstraction. +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. -# Memory management - -These two terms are about memory management. The stack and the heap are -abstractions that help you determine when to allocate and deallocate memory. - -Here’s a high-level comparison: - -The stack is very fast, and is where memory is allocated in Rust by default. -But the allocation is local to a function call, and is limited in size. The -heap, on the other hand, is slower, and is explicitly allocated by your -program. But it’s effectively unlimited in size, and is globally accessible. -Note this meaning of heap, which allocates arbitrary-sized blocks of memory in arbitrary -order, is quite different from the heap data structure. - -# The Stack - -Let’s talk about this Rust program: - -```rust -fn main() { - let x = 42; -} -``` - -This program has one variable binding, `x`. This memory needs to be allocated -from somewhere. Rust ‘stack allocates’ by default, which means that basic -values ‘go on the stack’. What does that mean? - -Well, when a function gets called, some memory gets allocated for all of its -local variables and some other information. This is called a ‘stack frame’, and -for the purpose of this tutorial, we’re going to ignore the extra information -and only consider the local variables we’re allocating. So in this case, when -`main()` is run, we’ll allocate a single 32-bit integer for our stack frame. -This is automatically handled for you, as you can see; we didn’t have to write -any special Rust code or anything. - -When the function exits, its stack frame gets deallocated. This happens -automatically as well. - -That’s all there is for this simple program. The key thing to understand here -is that stack allocation is very, very fast. Since we know all the local -variables we have ahead of time, we can grab the memory all at once. And since -we’ll throw them all away at the same time as well, we can get rid of it very -fast too. - -The downside is that we can’t keep values around if we need them for longer -than a single function. We also haven’t talked about what the word, ‘stack’, -means. To do that, we need a slightly more complicated example: - -```rust -fn foo() { - let y = 5; - let z = 100; -} - -fn main() { - let x = 42; - - foo(); -} -``` - -This program has three variables total: two in `foo()`, one in `main()`. Just -as before, when `main()` is called, a single integer is allocated for its stack -frame. But before we can show what happens when `foo()` is called, we need to -visualize what’s going on with memory. Your operating system presents a view of -memory to your program that’s pretty simple: a huge list of addresses, from 0 -to a large number, representing how much RAM your computer has. For example, if -you have a gigabyte of RAM, your addresses go from `0` to `1,073,741,823`. That -number comes from 230, the number of bytes in a gigabyte. [^gigabyte] - -[^gigabyte]: ‘Gigabyte’ can mean two things: 109, or 230. The IEC standard resolved this by stating that ‘gigabyte’ is 109, and ‘gibibyte’ is 230. However, very few people use this terminology, and rely on context to differentiate. We follow in that tradition here. - -This memory is kind of like a giant array: addresses start at zero and go -up to the final number. So here’s a diagram of our first stack frame: - -| Address | Name | Value | -|---------|------|-------| -| 0 | x | 42 | - -We’ve got `x` located at address `0`, with the value `42`. - -When `foo()` is called, a new stack frame is allocated: - -| Address | Name | Value | -|---------|------|-------| -| 2 | z | 100 | -| 1 | y | 5 | -| 0 | x | 42 | - -Because `0` was taken by the first frame, `1` and `2` are used for `foo()`’s -stack frame. It grows upward, the more functions we call. Notice that we are **not** -taking into account the size of each variable (for example, a 32 bit variable would -use the memory addresses from 0 to 3, or 4 bytes). - - -There are some important things we have to take note of here. The numbers 0, 1, -and 2 are all solely for illustrative purposes, and bear no relationship to the -address values the computer will use in reality. In particular, the series of -addresses are in reality going to be separated by some number of bytes that -separate each address, and that separation may even exceed the size of the -value being stored. - -After `foo()` is over, its frame is deallocated: - -| Address | Name | Value | -|---------|------|-------| -| 0 | x | 42 | - -And then, after `main()`, even this last value goes away. Easy! - -It’s called a ‘stack’ because it works like a stack of dinner plates: the first -plate you put down is the last plate to pick back up. Stacks are sometimes -called ‘last in, first out queues’ for this reason, as the last value you put -on the stack is the first one you retrieve from it. - -Let’s try a three-deep example: - -```rust -fn italic() { - let i = 6; -} - -fn bold() { - let a = 5; - let b = 100; - let c = 1; - - italic(); -} - -fn main() { - let x = 42; - - bold(); -} -``` - -We have some kooky function names to make the diagrams clearer. - -Okay, first, we call `main()`: - -| Address | Name | Value | -|---------|------|-------| -| 0 | x | 42 | - -Next up, `main()` calls `bold()`: - -| Address | Name | Value | -|---------|------|-------| -| **3** | **c**|**1** | -| **2** | **b**|**100**| -| **1** | **a**| **5** | -| 0 | x | 42 | - -And then `bold()` calls `italic()`: - -| Address | Name | Value | -|---------|------|-------| -| *4* | *i* | *6* | -| **3** | **c**|**1** | -| **2** | **b**|**100**| -| **1** | **a**| **5** | -| 0 | x | 42 | - -Whew! Our stack is growing tall. - -After `italic()` is over, its frame is deallocated, leaving only `bold()` and -`main()`: - -| Address | Name | Value | -|---------|------|-------| -| **3** | **c**|**1** | -| **2** | **b**|**100**| -| **1** | **a**| **5** | -| 0 | x | 42 | - -And then `bold()` ends, leaving only `main()`: - -| Address | Name | Value | -|---------|------|-------| -| 0 | x | 42 | - -And then we’re done. Getting the hang of it? It’s like piling up dishes: you -add to the top, you take away from the top. - -# The Heap - -Now, this works pretty well, but not everything can work like this. Sometimes, -you need to pass some memory between different functions, or keep it alive for -longer than a single function’s execution. For this, we can use the heap. - -In Rust, you can allocate memory on the heap with the [`Box` type][box]. -Here’s an example: - -```rust -fn main() { - let x = Box::new(5); - let y = 42; -} -``` - -[box]: ../../std/boxed/index.html - -Here’s what happens in memory when `main()` is called: - -| Address | Name | Value | -|---------|------|--------| -| 1 | y | 42 | -| 0 | x | ?????? | - -We allocate space for two variables on the stack. `y` is `42`, as it always has -been, but what about `x`? Well, `x` is a `Box`, and boxes allocate memory -on the heap. The actual value of the box is a structure which has a pointer to -‘the heap’. When we start executing the function, and `Box::new()` is called, -it allocates some memory for the heap, and puts `5` there. The memory now looks -like this: - -| Address | Name | Value | -|----------------------|------|------------------------| -| (230) - 1 | | 5 | -| ... | ... | ... | -| 1 | y | 42 | -| 0 | x | → (230) - 1 | - -We have (230) addresses in our hypothetical computer with 1GiB of RAM. And since -our stack grows from zero, the easiest place to allocate memory is from the -other end. So our first value is at the highest place in memory. And the value -of the struct at `x` has a [raw pointer][rawpointer] to the place we’ve -allocated on the heap, so the value of `x` is (230) - 1, the memory -location we’ve asked for. - -[rawpointer]: raw-pointers.html - -We haven’t really talked too much about what it actually means to allocate and -deallocate memory in these contexts. Getting into very deep detail is out of -the scope of this tutorial, but what’s important to point out here is that -the heap isn’t a stack that grows from the opposite end. We’ll have an -example of this later in the book, but because the heap can be allocated and -freed in any order, it can end up with ‘holes’. Here’s a diagram of the memory -layout of a program which has been running for a while now: - - -| Address | Name | Value | -|----------------------|------|------------------------| -| (230) - 1 | | 5 | -| (230) - 2 | | | -| (230) - 3 | | | -| (230) - 4 | | 42 | -| ... | ... | ... | -| 2 | z | → (230) - 4 | -| 1 | y | 42 | -| 0 | x | → (230) - 1 | - -In this case, we’ve allocated four things on the heap, but deallocated two of -them. There’s a gap between (230) - 1 and (230) - 4 which isn’t -currently being used. The specific details of how and why this happens depends -on what kind of strategy you use to manage the heap. Different programs can use -different ‘memory allocators’, which are libraries that manage this for you. -Rust programs use [jemalloc][jemalloc] for this purpose. - -[jemalloc]: http://www.canonware.com/jemalloc/ - -Anyway, back to our example. Since this memory is on the heap, it can stay -alive longer than the function which allocates the box. In this case, however, -it doesn’t.[^moving] When the function is over, we need to free the stack frame -for `main()`. `Box`, though, has a trick up its sleeve: [Drop][drop]. The -implementation of `Drop` for `Box` deallocates the memory that was allocated -when it was created. Great! So when `x` goes away, it first frees the memory -allocated on the heap: - -| Address | Name | Value | -|---------|------|--------| -| 1 | y | 42 | -| 0 | x | ?????? | - -[drop]: drop.html -[^moving]: We can make the memory live longer by transferring ownership, - sometimes called ‘moving out of the box’. More complex examples will - be covered later. - - -And then the stack frame goes away, freeing all of our memory. - -# Arguments and borrowing - -We’ve got some basic examples with the stack and the heap going, but what about -function arguments and borrowing? Here’s a small Rust program: - -```rust -fn foo(i: &i32) { - let z = 42; -} - -fn main() { - let x = 5; - let y = &x; - - foo(y); -} -``` - -When we enter `main()`, memory looks like this: - -| Address | Name | Value | -|---------|------|--------| -| 1 | y | → 0 | -| 0 | x | 5 | - -`x` is a plain old `5`, and `y` is a reference to `x`. So its value is the -memory location that `x` lives at, which in this case is `0`. - -What about when we call `foo()`, passing `y` as an argument? - -| Address | Name | Value | -|---------|------|--------| -| 3 | z | 42 | -| 2 | i | → 0 | -| 1 | y | → 0 | -| 0 | x | 5 | - -Stack frames aren’t only for local bindings, they’re for arguments too. So in -this case, we need to have both `i`, our argument, and `z`, our local variable -binding. `i` is a copy of the argument, `y`. Since `y`’s value is `0`, so is -`i`’s. - -This is one reason why borrowing a variable doesn’t deallocate any memory: the -value of a reference is a pointer to a memory location. If we got rid of -the underlying memory, things wouldn’t work very well. - -# A complex example - -Okay, let’s go through this complex program step-by-step: - -```rust -fn foo(x: &i32) { - let y = 10; - let z = &y; - - baz(z); - bar(x, z); -} - -fn bar(a: &i32, b: &i32) { - let c = 5; - let d = Box::new(5); - let e = &d; - - baz(e); -} - -fn baz(f: &i32) { - let g = 100; -} - -fn main() { - let h = 3; - let i = Box::new(20); - let j = &h; - - foo(j); -} -``` - -First, we call `main()`: - -| Address | Name | Value | -|----------------------|------|------------------------| -| (230) - 1 | | 20 | -| ... | ... | ... | -| 2 | j | → 0 | -| 1 | i | → (230) - 1 | -| 0 | h | 3 | - -We allocate memory for `j`, `i`, and `h`. `i` is on the heap, and so has a -value pointing there. - -Next, at the end of `main()`, `foo()` gets called: - -| Address | Name | Value | -|----------------------|------|------------------------| -| (230) - 1 | | 20 | -| ... | ... | ... | -| 5 | z | → 4 | -| 4 | y | 10 | -| 3 | x | → 0 | -| 2 | j | → 0 | -| 1 | i | → (230) - 1 | -| 0 | h | 3 | - -Space gets allocated for `x`, `y`, and `z`. The argument `x` has the same value -as `j`, since that’s what we passed it in. It’s a pointer to the `0` address, -since `j` points at `h`. - -Next, `foo()` calls `baz()`, passing `z`: - -| Address | Name | Value | -|----------------------|------|------------------------| -| (230) - 1 | | 20 | -| ... | ... | ... | -| 7 | g | 100 | -| 6 | f | → 4 | -| 5 | z | → 4 | -| 4 | y | 10 | -| 3 | x | → 0 | -| 2 | j | → 0 | -| 1 | i | → (230) - 1 | -| 0 | h | 3 | - -We’ve allocated memory for `f` and `g`. `baz()` is very short, so when it’s -over, we get rid of its stack frame: - -| Address | Name | Value | -|----------------------|------|------------------------| -| (230) - 1 | | 20 | -| ... | ... | ... | -| 5 | z | → 4 | -| 4 | y | 10 | -| 3 | x | → 0 | -| 2 | j | → 0 | -| 1 | i | → (230) - 1 | -| 0 | h | 3 | - -Next, `foo()` calls `bar()` with `x` and `z`: - -| Address | Name | Value | -|----------------------|------|------------------------| -| (230) - 1 | | 20 | -| (230) - 2 | | 5 | -| ... | ... | ... | -| 10 | e | → 9 | -| 9 | d | → (230) - 2 | -| 8 | c | 5 | -| 7 | b | → 4 | -| 6 | a | → 0 | -| 5 | z | → 4 | -| 4 | y | 10 | -| 3 | x | → 0 | -| 2 | j | → 0 | -| 1 | i | → (230) - 1 | -| 0 | h | 3 | - -We end up allocating another value on the heap, and so we have to subtract one -from (230) - 1. It’s easier to write that than `1,073,741,822`. In any -case, we set up the variables as usual. - -At the end of `bar()`, it calls `baz()`: - -| Address | Name | Value | -|----------------------|------|------------------------| -| (230) - 1 | | 20 | -| (230) - 2 | | 5 | -| ... | ... | ... | -| 12 | g | 100 | -| 11 | f | → (230) - 2 | -| 10 | e | → 9 | -| 9 | d | → (230) - 2 | -| 8 | c | 5 | -| 7 | b | → 4 | -| 6 | a | → 0 | -| 5 | z | → 4 | -| 4 | y | 10 | -| 3 | x | → 0 | -| 2 | j | → 0 | -| 1 | i | → (230) - 1 | -| 0 | h | 3 | - -With this, we’re at our deepest point! Whew! Congrats for following along this -far. - -After `baz()` is over, we get rid of `f` and `g`: - -| Address | Name | Value | -|----------------------|------|------------------------| -| (230) - 1 | | 20 | -| (230) - 2 | | 5 | -| ... | ... | ... | -| 10 | e | → 9 | -| 9 | d | → (230) - 2 | -| 8 | c | 5 | -| 7 | b | → 4 | -| 6 | a | → 0 | -| 5 | z | → 4 | -| 4 | y | 10 | -| 3 | x | → 0 | -| 2 | j | → 0 | -| 1 | i | → (230) - 1 | -| 0 | h | 3 | - -Next, we return from `bar()`. `d` in this case is a `Box`, so it also frees -what it points to: (230) - 2. - -| Address | Name | Value | -|----------------------|------|------------------------| -| (230) - 1 | | 20 | -| ... | ... | ... | -| 5 | z | → 4 | -| 4 | y | 10 | -| 3 | x | → 0 | -| 2 | j | → 0 | -| 1 | i | → (230) - 1 | -| 0 | h | 3 | - -And after that, `foo()` returns: - -| Address | Name | Value | -|----------------------|------|------------------------| -| (230) - 1 | | 20 | -| ... | ... | ... | -| 2 | j | → 0 | -| 1 | i | → (230) - 1 | -| 0 | h | 3 | - -And then, finally, `main()`, which cleans the rest up. When `i` is `Drop`ped, -it will clean up the last of the heap too. - -# What do other languages do? - -Most languages with a garbage collector heap-allocate by default. This means -that every value is boxed. There are a number of reasons why this is done, but -they’re out of scope for this tutorial. There are some possible optimizations -that don’t make it true 100% of the time, too. Rather than relying on the stack -and `Drop` to clean up memory, the garbage collector deals with the heap -instead. - -# Which to use? - -So if the stack is faster and easier to manage, why do we need the heap? A big -reason is that Stack-allocation alone means you only have 'Last In First Out (LIFO)' semantics for -reclaiming storage. Heap-allocation is strictly more general, allowing storage -to be taken from and returned to the pool in arbitrary order, but at a -complexity cost. - -Generally, you should prefer stack allocation, and so, Rust stack-allocates by -default. The LIFO model of the stack is simpler, at a fundamental level. This -has two big impacts: runtime efficiency and semantic impact. - -## Runtime Efficiency - -Managing the memory for the stack is trivial: The machine -increments or decrements a single value, the so-called “stack pointer”. -Managing memory for the heap is non-trivial: heap-allocated memory is freed at -arbitrary points, and each block of heap-allocated memory can be of arbitrary -size, so the memory manager must generally work much harder to -identify memory for reuse. - -If you’d like to dive into this topic in greater detail, [this paper][wilson] -is a great introduction. - -[wilson]: http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.143.4688 - -## Semantic impact - -Stack-allocation impacts the Rust language itself, and thus the developer’s -mental model. The LIFO semantics is what drives how the Rust language handles -automatic memory management. Even the deallocation of a uniquely-owned -heap-allocated box can be driven by the stack-based LIFO semantics, as -discussed throughout this chapter. The flexibility (i.e. expressiveness) of non -LIFO-semantics means that in general the compiler cannot automatically infer at -compile-time where memory should be freed; it has to rely on dynamic protocols, -potentially from outside the language itself, to drive deallocation (reference -counting, as used by `Rc` and `Arc`, is one example of this). - -When taken to the extreme, the increased expressive power of heap allocation -comes at the cost of either significant runtime support (e.g. in the form of a -garbage collector) or significant programmer effort (in the form of explicit -memory management calls that require verification not provided by the Rust -compiler). +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). diff --git a/first-edition/src/theme/index.hbs b/first-edition/src/theme/index.hbs new file mode 100644 index 0000000000..f3f1b52fa8 --- /dev/null +++ b/first-edition/src/theme/index.hbs @@ -0,0 +1,37 @@ + + + + + + Outdated link: {{ title }} + + + + + + + + + + + + + + + {{#each additional_css}} + + {{/each}} + + +
+
+ {{> header}} +
+
+ {{{ content }}} +
+
+
+
+ + diff --git a/first-edition/src/trait-objects.md b/first-edition/src/trait-objects.md index 4a4b2cb8e6..871bad6140 100644 --- a/first-edition/src/trait-objects.md +++ b/first-edition/src/trait-objects.md @@ -1,335 +1,10 @@ # Trait Objects -When code involves polymorphism, there needs to be a mechanism to determine -which specific version is actually run. This is called ‘dispatch’. There are -two major forms of dispatch: static dispatch and dynamic dispatch. While Rust -favors static dispatch, it also supports dynamic dispatch through a mechanism -called ‘trait objects’. +The first edition of the book is no longer distributed with Rust's documentation. -## Background +If you came here via a link or web search, you may want to check out [the current +version of the book](../ch17-02-trait-objects.html) instead. -For the rest of this chapter, we’ll need a trait and some implementations. -Let’s make a simple one, `Foo`. It has one method that is expected to return a -`String`. - -```rust -trait Foo { - fn method(&self) -> String; -} -``` - -We’ll also implement this trait for `u8` and `String`: - -```rust -# trait Foo { fn method(&self) -> String; } -impl Foo for u8 { - fn method(&self) -> String { format!("u8: {}", *self) } -} - -impl Foo for String { - fn method(&self) -> String { format!("string: {}", *self) } -} -``` - - -## Static dispatch - -We can use this trait to perform static dispatch with trait bounds: - -```rust -# trait Foo { fn method(&self) -> String; } -# impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } } -# impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } } -fn do_something(x: T) { - x.method(); -} - -fn main() { - let x = 5u8; - let y = "Hello".to_string(); - - do_something(x); - do_something(y); -} -``` - -Rust uses ‘monomorphization’ to perform static dispatch here. This means that -Rust will create a special version of `do_something()` for both `u8` and -`String`, and then replace the call sites with calls to these specialized -functions. In other words, Rust generates something like this: - -```rust -# trait Foo { fn method(&self) -> String; } -# impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } } -# impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } } -fn do_something_u8(x: u8) { - x.method(); -} - -fn do_something_string(x: String) { - x.method(); -} - -fn main() { - let x = 5u8; - let y = "Hello".to_string(); - - do_something_u8(x); - do_something_string(y); -} -``` - -This has a great upside: static dispatch allows function calls to be -inlined because the callee is known at compile time, and inlining is -the key to good optimization. Static dispatch is fast, but it comes at -a tradeoff: ‘code bloat’, due to many copies of the same function -existing in the binary, one for each type. - -Furthermore, compilers aren’t perfect and may “optimize” code to become slower. -For example, functions inlined too eagerly will bloat the instruction cache -(cache rules everything around us). This is part of the reason that `#[inline]` -and `#[inline(always)]` should be used carefully, and one reason why using a -dynamic dispatch is sometimes more efficient. - -However, the common case is that it is more efficient to use static dispatch, -and one can always have a thin statically-dispatched wrapper function that does -a dynamic dispatch, but not vice versa, meaning static calls are more flexible. -The standard library tries to be statically dispatched where possible for this -reason. - -## Dynamic dispatch - -Rust provides dynamic dispatch through a feature called ‘trait objects’. Trait -objects, like `&Foo` or `Box`, are normal values that store a value of -*any* type that implements the given trait, where the precise type can only be -known at runtime. - -A trait object can be obtained from a pointer to a concrete type that -implements the trait by *casting* it (e.g. `&x as &Foo`) or *coercing* it -(e.g. using `&x` as an argument to a function that takes `&Foo`). - -These trait object coercions and casts also work for pointers like `&mut T` to -`&mut Foo` and `Box` to `Box`, but that’s all at the moment. Coercions -and casts are identical. - -This operation can be seen as ‘erasing’ the compiler’s knowledge about the -specific type of the pointer, and hence trait objects are sometimes referred to -as ‘type erasure’. - -Coming back to the example above, we can use the same trait to perform dynamic -dispatch with trait objects by casting: - -```rust -# trait Foo { fn method(&self) -> String; } -# impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } } -# impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } } -fn do_something(x: &Foo) { - x.method(); -} - -fn main() { - let x = 5u8; - do_something(&x as &Foo); -} -``` - -or by coercing: - -```rust -# trait Foo { fn method(&self) -> String; } -# impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } } -# impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } } -fn do_something(x: &Foo) { - x.method(); -} - -fn main() { - let x = "Hello".to_string(); - do_something(&x); -} -``` - -A function that takes a trait object is not specialized to each of the types -that implements `Foo`: only one copy is generated, often (but not always) -resulting in less code bloat. However, this comes at the cost of requiring -slower virtual function calls, and effectively inhibiting any chance of -inlining and related optimizations from occurring. - -### Why pointers? - -Rust does not put things behind a pointer by default, unlike many managed -languages, so types can have different sizes. Knowing the size of the value at -compile time is important for things like passing it as an argument to a -function, moving it about on the stack and allocating (and deallocating) space -on the heap to store it. - -For `Foo`, we would need to have a value that could be at least either a -`String` (24 bytes) or a `u8` (1 byte), as well as any other type for which -dependent crates may implement `Foo` (any number of bytes at all). There’s no -way to guarantee that this last point can work if the values are stored without -a pointer, because those other types can be arbitrarily large. - -Putting the value behind a pointer means the size of the value is not relevant -when we are tossing a trait object around, only the size of the pointer itself. - -### Representation - -The methods of the trait can be called on a trait object via a special record -of function pointers traditionally called a ‘vtable’ (created and managed by -the compiler). - -Trait objects are both simple and complicated: their core representation and -layout is quite straight-forward, but there are some curly error messages and -surprising behaviors to discover. - -Let’s start simple, with the runtime representation of a trait object. The -`std::raw` module contains structs with layouts that are the same as the -complicated built-in types, [including trait objects][stdraw]: - -```rust -# mod foo { -pub struct TraitObject { - pub data: *mut (), - pub vtable: *mut (), -} -# } -``` - -[stdraw]: ../../std/raw/struct.TraitObject.html - -That is, a trait object like `&Foo` consists of a ‘data’ pointer and a ‘vtable’ -pointer. - -The data pointer addresses the data (of some unknown type `T`) that the trait -object is storing, and the vtable pointer points to the vtable (‘virtual method -table’) corresponding to the implementation of `Foo` for `T`. - - -A vtable is essentially a struct of function pointers, pointing to the concrete -piece of machine code for each method in the implementation. A method call like -`trait_object.method()` will retrieve the correct pointer out of the vtable and -then do a dynamic call of it. For example: - -```rust,ignore -struct FooVtable { - destructor: fn(*mut ()), - size: usize, - align: usize, - method: fn(*const ()) -> String, -} - -// u8: - -fn call_method_on_u8(x: *const ()) -> String { - // The compiler guarantees that this function is only called - // with `x` pointing to a u8. - let byte: &u8 = unsafe { &*(x as *const u8) }; - - byte.method() -} - -static Foo_for_u8_vtable: FooVtable = FooVtable { - destructor: /* compiler magic */, - size: 1, - align: 1, - - // Cast to a function pointer: - method: call_method_on_u8 as fn(*const ()) -> String, -}; - - -// String: - -fn call_method_on_String(x: *const ()) -> String { - // The compiler guarantees that this function is only called - // with `x` pointing to a String. - let string: &String = unsafe { &*(x as *const String) }; - - string.method() -} - -static Foo_for_String_vtable: FooVtable = FooVtable { - destructor: /* compiler magic */, - // Values for a 64-bit computer, halve them for 32-bit ones. - size: 24, - align: 8, - - method: call_method_on_String as fn(*const ()) -> String, -}; -``` - -The `destructor` field in each vtable points to a function that will clean up -any resources of the vtable’s type: for `u8` it is trivial, but for `String` it -will free the memory. This is necessary for owning trait objects like -`Box`, which need to clean-up both the `Box` allocation as well as the -internal type when they go out of scope. The `size` and `align` fields store -the size of the erased type, and its alignment requirements. - -Suppose we’ve got some values that implement `Foo`. The explicit form of -construction and use of `Foo` trait objects might look a bit like (ignoring the -type mismatches: they’re all pointers anyway): - -```rust,ignore -let a: String = "foo".to_string(); -let x: u8 = 1; - -// let b: &Foo = &a; -let b = TraitObject { - // Store the data: - data: &a, - // Store the methods: - vtable: &Foo_for_String_vtable -}; - -// let y: &Foo = x; -let y = TraitObject { - // Store the data: - data: &x, - // Store the methods: - vtable: &Foo_for_u8_vtable -}; - -// b.method(); -(b.vtable.method)(b.data); - -// y.method(); -(y.vtable.method)(y.data); -``` - -## Object Safety - -Not every trait can be used to make a trait object. For example, vectors implement -`Clone`, but if we try to make a trait object: - -```rust,ignore -let v = vec![1, 2, 3]; -let o = &v as &Clone; -``` - -We get an error: - -```text -error: cannot convert to a trait object because trait `core::clone::Clone` is not object-safe [E0038] -let o = &v as &Clone; - ^~ -note: the trait cannot require that `Self : Sized` -let o = &v as &Clone; - ^~ -``` - -The error says that `Clone` is not ‘object-safe’. Only traits that are -object-safe can be made into trait objects. A trait is object-safe if both of -these are true: - -* the trait does not require that `Self: Sized` -* all of its methods are object-safe - -So what makes a method object-safe? Each method must require that `Self: Sized` -or all of the following: - -* must not have any type parameters -* must not use `Self` - -Whew! As we can see, almost all of these rules talk about `Self`. A good intuition -is “except in special circumstances, if your trait’s method uses `Self`, it is not -object-safe.” +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). diff --git a/first-edition/src/traits.md b/first-edition/src/traits.md index 91a4bbbf56..955776a74b 100644 --- a/first-edition/src/traits.md +++ b/first-edition/src/traits.md @@ -1,551 +1,10 @@ # Traits -A trait is a language feature that tells the Rust compiler about -functionality a type must provide. +The first edition of the book is no longer distributed with Rust's documentation. -Recall the `impl` keyword, used to call a function with [method -syntax][methodsyntax]: +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. -```rust -struct Circle { - x: f64, - y: f64, - radius: f64, -} - -impl Circle { - fn area(&self) -> f64 { - std::f64::consts::PI * (self.radius * self.radius) - } -} -``` - -[methodsyntax]: method-syntax.html - -Traits are similar, except that we first define a trait with a method -signature, then implement the trait for a type. In this example, we implement the trait `HasArea` for `Circle`: - -```rust -struct Circle { - x: f64, - y: f64, - radius: f64, -} - -trait HasArea { - fn area(&self) -> f64; -} - -impl HasArea for Circle { - fn area(&self) -> f64 { - std::f64::consts::PI * (self.radius * self.radius) - } -} -``` - -As you can see, the `trait` block looks very similar to the `impl` block, -but we don’t define a body, only a type signature. When we `impl` a trait, -we use `impl Trait for Item`, rather than only `impl Item`. - -`Self` may be used in a type annotation to refer to an instance of the type -implementing this trait passed as a parameter. `Self`, `&Self` or `&mut Self` -may be used depending on the level of ownership required. - -```rust -struct Circle { - x: f64, - y: f64, - radius: f64, -} - -trait HasArea { - fn area(&self) -> f64; - - fn is_larger(&self, &Self) -> bool; -} - -impl HasArea for Circle { - fn area(&self) -> f64 { - std::f64::consts::PI * (self.radius * self.radius) - } - - fn is_larger(&self, other: &Self) -> bool { - self.area() > other.area() - } -} -``` - -## Trait bounds on generic functions - -Traits are useful because they allow a type to make certain promises about its -behavior. Generic functions can exploit this to constrain, or [bound][bounds], the types they -accept. Consider this function, which does not compile: - -[bounds]: glossary.html#bounds - -```rust,ignore -fn print_area(shape: T) { - println!("This shape has an area of {}", shape.area()); -} -``` - -Rust complains: - -```text -error: no method named `area` found for type `T` in the current scope -``` - -Because `T` can be any type, we can’t be sure that it implements the `area` -method. But we can add a trait bound to our generic `T`, ensuring -that it does: - -```rust -# trait HasArea { -# fn area(&self) -> f64; -# } -fn print_area(shape: T) { - println!("This shape has an area of {}", shape.area()); -} -``` - -The syntax `` means “any type that implements the `HasArea` trait.” -Because traits define function type signatures, we can be sure that any type -which implements `HasArea` will have an `.area()` method. - -Here’s an extended example of how this works: - -```rust -trait HasArea { - fn area(&self) -> f64; -} - -struct Circle { - x: f64, - y: f64, - radius: f64, -} - -impl HasArea for Circle { - fn area(&self) -> f64 { - std::f64::consts::PI * (self.radius * self.radius) - } -} - -struct Square { - x: f64, - y: f64, - side: f64, -} - -impl HasArea for Square { - fn area(&self) -> f64 { - self.side * self.side - } -} - -fn print_area(shape: T) { - println!("This shape has an area of {}", shape.area()); -} - -fn main() { - let c = Circle { - x: 0.0f64, - y: 0.0f64, - radius: 1.0f64, - }; - - let s = Square { - x: 0.0f64, - y: 0.0f64, - side: 1.0f64, - }; - - print_area(c); - print_area(s); -} -``` - -This program outputs: - -```text -This shape has an area of 3.141593 -This shape has an area of 1 -``` - -As you can see, `print_area` is now generic, but also ensures that we have -passed in the correct types. If we pass in an incorrect type: - -```rust,ignore -print_area(5); -``` - -We get a compile-time error: - -```text -error: the trait bound `_ : HasArea` is not satisfied [E0277] -``` - -## Trait bounds on generic structs - -Your generic structs can also benefit from trait bounds. All you need to -do is append the bound when you declare type parameters. Here is a new -type `Rectangle` and its operation `is_square()`: - -```rust -struct Rectangle { - x: T, - y: T, - width: T, - height: T, -} - -impl Rectangle { - fn is_square(&self) -> bool { - self.width == self.height - } -} - -fn main() { - let mut r = Rectangle { - x: 0, - y: 0, - width: 47, - height: 47, - }; - - assert!(r.is_square()); - - r.height = 42; - assert!(!r.is_square()); -} -``` - -`is_square()` needs to check that the sides are equal, so the sides must be of -a type that implements the [`core::cmp::PartialEq`][PartialEq] trait: - -```rust,ignore -impl Rectangle { ... } -``` - -Now, a rectangle can be defined in terms of any type that can be compared for -equality. - -[PartialEq]: ../../core/cmp/trait.PartialEq.html - -Here we defined a new struct `Rectangle` that accepts numbers of any -precision—really, objects of pretty much any type—as long as they can be -compared for equality. Could we do the same for our `HasArea` structs, `Square` -and `Circle`? Yes, but they need multiplication, and to work with that we need -to know more about [operator traits][operators-and-overloading]. - -[operators-and-overloading]: operators-and-overloading.html - -# Rules for implementing traits - -So far, we’ve only added trait implementations to structs, but you can -implement a trait for any type such as `f32`: - -```rust -trait ApproxEqual { - fn approx_equal(&self, other: &Self) -> bool; -} -impl ApproxEqual for f32 { - fn approx_equal(&self, other: &Self) -> bool { - // Appropriate for `self` and `other` being close to 1.0. - (self - other).abs() <= ::std::f32::EPSILON - } -} - -println!("{}", 1.0.approx_equal(&1.00000001)); -``` - -This may seem like the Wild West, but there are two restrictions around -implementing traits that prevent this from getting out of hand. The first is -that if the trait isn’t defined in your scope, it doesn’t apply. Here’s an -example: the standard library provides a [`Write`][write] trait which adds -extra functionality to `File`s, for doing file I/O. By default, a `File` -won’t have its methods: - -[write]: ../../std/io/trait.Write.html - -```rust,ignore -let mut f = std::fs::File::create("foo.txt").expect("Couldn’t create foo.txt"); -let buf = b"whatever"; // buf: &[u8; 8], a byte string literal. -let result = f.write(buf); -# result.unwrap(); // Ignore the error. -``` - -Here’s the error: - -```text -error: type `std::fs::File` does not implement any method in scope named `write` -let result = f.write(buf); - ^~~~~~~~~~ -``` - -We need to `use` the `Write` trait first: - -```rust,no_run -use std::io::Write; - -let mut f = std::fs::File::create("foo.txt").expect("Couldn’t create foo.txt"); -let buf = b"whatever"; -let result = f.write(buf); -# result.unwrap(); // Ignore the error. -``` - -This will compile without error. - -This means that even if someone does something bad like add methods to `i32`, -it won’t affect you, unless you `use` that trait. - -There’s one more restriction on implementing traits: either the trait -or the type you’re implementing it for must be defined by you. Or more -precisely, one of them must be defined in the same crate as the `impl` -you're writing. For more on Rust's module and package system, see the -chapter on [crates and modules][cm]. - -So, we could implement the `HasArea` type for `i32`, because we defined -`HasArea` in our code. But if we tried to implement `ToString`, a trait -provided by Rust, for `i32`, we could not, because neither the trait nor -the type are defined in our crate. - -One last thing about traits: generic functions with a trait bound use -‘monomorphization’ (mono: one, morph: form), so they are statically dispatched. -What’s that mean? Check out the chapter on [trait objects][to] for more details. - -[cm]: crates-and-modules.html -[to]: trait-objects.html - -# Multiple trait bounds - -You’ve seen that you can bound a generic type parameter with a trait: - -```rust -fn foo(x: T) { - x.clone(); -} -``` - -If you need more than one bound, you can use `+`: - -```rust -use std::fmt::Debug; - -fn foo(x: T) { - x.clone(); - println!("{:?}", x); -} -``` - -`T` now needs to be both `Clone` as well as `Debug`. - -# Where clause - -Writing functions with only a few generic types and a small number of trait -bounds isn’t too bad, but as the number increases, the syntax gets increasingly -awkward: - -```rust -use std::fmt::Debug; - -fn foo(x: T, y: K) { - x.clone(); - y.clone(); - println!("{:?}", y); -} -``` - -The name of the function is on the far left, and the parameter list is on the -far right. The bounds are getting in the way. - -Rust has a solution, and it’s called a ‘`where` clause’: - -```rust -use std::fmt::Debug; - -fn foo(x: T, y: K) { - x.clone(); - y.clone(); - println!("{:?}", y); -} - -fn bar(x: T, y: K) where T: Clone, K: Clone + Debug { - x.clone(); - y.clone(); - println!("{:?}", y); -} - -fn main() { - foo("Hello", "world"); - bar("Hello", "world"); -} -``` - -`foo()` uses the syntax we showed earlier, and `bar()` uses a `where` clause. -All you need to do is leave off the bounds when defining your type parameters, -and then add `where` after the parameter list. For longer lists, whitespace can -be added: - -```rust -use std::fmt::Debug; - -fn bar(x: T, y: K) - where T: Clone, - K: Clone + Debug { - - x.clone(); - y.clone(); - println!("{:?}", y); -} -``` - -This flexibility can add clarity in complex situations. - -`where` is also more powerful than the simpler syntax. For example: - -```rust -trait ConvertTo { - fn convert(&self) -> Output; -} - -impl ConvertTo for i32 { - fn convert(&self) -> i64 { *self as i64 } -} - -// Can be called with T == i32. -fn convert_t_to_i64>(x: T) -> i64 { - x.convert() -} - -// Can be called with T == i64. -fn convert_i32_to_t(x: i32) -> T - // This is using ConvertTo as if it were "ConvertTo". - where i32: ConvertTo { - x.convert() -} -``` - -This shows off the additional feature of `where` clauses: they allow bounds -on the left-hand side not only of type parameters `T`, but also of types (`i32` in this case). In this example, `i32` must implement -`ConvertTo`. Rather than defining what `i32` is (since that's obvious), the -`where` clause here constrains `T`. - -# Default methods - -A default method can be added to a trait definition if it is already known how a typical implementor will define a method. For example, `is_invalid()` is defined as the opposite of `is_valid()`: - -```rust -trait Foo { - fn is_valid(&self) -> bool; - - fn is_invalid(&self) -> bool { !self.is_valid() } -} -``` - -Implementors of the `Foo` trait need to implement `is_valid()` but not `is_invalid()` due to the added default behavior. This default behavior can still be overridden as in: - -```rust -# trait Foo { -# fn is_valid(&self) -> bool; -# -# fn is_invalid(&self) -> bool { !self.is_valid() } -# } -struct UseDefault; - -impl Foo for UseDefault { - fn is_valid(&self) -> bool { - println!("Called UseDefault.is_valid."); - true - } -} - -struct OverrideDefault; - -impl Foo for OverrideDefault { - fn is_valid(&self) -> bool { - println!("Called OverrideDefault.is_valid."); - true - } - - fn is_invalid(&self) -> bool { - println!("Called OverrideDefault.is_invalid!"); - true // Overrides the expected value of `is_invalid()`. - } -} - -let default = UseDefault; -assert!(!default.is_invalid()); // Prints "Called UseDefault.is_valid." - -let over = OverrideDefault; -assert!(over.is_invalid()); // Prints "Called OverrideDefault.is_invalid!" -``` - -# Inheritance - -Sometimes, implementing a trait requires implementing another trait: - -```rust -trait Foo { - fn foo(&self); -} - -trait FooBar : Foo { - fn foobar(&self); -} -``` - -Implementors of `FooBar` must also implement `Foo`, like this: - -```rust -# trait Foo { -# fn foo(&self); -# } -# trait FooBar : Foo { -# fn foobar(&self); -# } -struct Baz; - -impl Foo for Baz { - fn foo(&self) { println!("foo"); } -} - -impl FooBar for Baz { - fn foobar(&self) { println!("foobar"); } -} -``` - -If we forget to implement `Foo`, Rust will tell us: - -```text -error: the trait bound `main::Baz : main::Foo` is not satisfied [E0277] -``` - -# Deriving - -Implementing traits like `Debug` and `Default` repeatedly can become -quite tedious. For that reason, Rust provides an [attribute][attributes] that -allows you to let Rust automatically implement traits for you: - -```rust -#[derive(Debug)] -struct Foo; - -fn main() { - println!("{:?}", Foo); -} -``` - -[attributes]: attributes.html - -However, deriving is limited to a certain set of traits: - -- [`Clone`](../../core/clone/trait.Clone.html) -- [`Copy`](../../core/marker/trait.Copy.html) -- [`Debug`](../../core/fmt/trait.Debug.html) -- [`Default`](../../core/default/trait.Default.html) -- [`Eq`](../../core/cmp/trait.Eq.html) -- [`Hash`](../../core/hash/trait.Hash.html) -- [`Ord`](../../core/cmp/trait.Ord.html) -- [`PartialEq`](../../core/cmp/trait.PartialEq.html) -- [`PartialOrd`](../../core/cmp/trait.PartialOrd.html) +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). diff --git a/first-edition/src/type-aliases.md b/first-edition/src/type-aliases.md index f70e7a3176..7ac51ff191 100644 --- a/first-edition/src/type-aliases.md +++ b/first-edition/src/type-aliases.md @@ -1,78 +1,10 @@ # Type Aliases -The `type` keyword lets you declare an alias of another type: +The first edition of the book is no longer distributed with Rust's documentation. -```rust -type Name = String; -``` +If you came here via a link or web search, you may want to check out [the current +version of the book](../ch19-04-advanced-types.html#creating-type-synonyms-with-type-aliases) instead. -You can then use this type as if it were a real type: - -```rust -type Name = String; - -let x: Name = "Hello".to_string(); -``` - -Note, however, that this is an _alias_, not a new type entirely. In other -words, because Rust is strongly typed, you’d expect a comparison between two -different types to fail: - -```rust,ignore -let x: i32 = 5; -let y: i64 = 5; - -if x == y { - // ... -} -``` - -this gives - -```text -error: mismatched types: - expected `i32`, - found `i64` -(expected i32, - found i64) [E0308] - if x == y { - ^ -``` - -But, if we had an alias: - -```rust -type Num = i32; - -let x: i32 = 5; -let y: Num = 5; - -if x == y { - // ... -} -``` - -This compiles without error. Values of a `Num` type are the same as a value of -type `i32`, in every way. You can use [tuple struct] to really get a new type. - -[tuple struct]: structs.html#tuple-structs - -You can also use type aliases with generics: - -```rust -use std::result; - -enum ConcreteError { - Foo, - Bar, -} - -type Result = result::Result; -``` - -This creates a specialized version of the `Result` type, which always has a -`ConcreteError` for the `E` part of `Result`. This is commonly used -in the standard library to create custom errors for each subsection. For -example, [io::Result][ioresult]. - -[ioresult]: ../../std/io/type.Result.html +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). diff --git a/first-edition/src/ufcs.md b/first-edition/src/ufcs.md index 016ecc7097..dad121ab30 100644 --- a/first-edition/src/ufcs.md +++ b/first-edition/src/ufcs.md @@ -1,136 +1,10 @@ # Universal Function Call Syntax -Sometimes, functions can have the same names. Consider this code: +The first edition of the book is no longer distributed with Rust's documentation. -```rust -trait Foo { - fn f(&self); -} +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. -trait Bar { - fn f(&self); -} - -struct Baz; - -impl Foo for Baz { - fn f(&self) { println!("Baz’s impl of Foo"); } -} - -impl Bar for Baz { - fn f(&self) { println!("Baz’s impl of Bar"); } -} - -let b = Baz; -``` - -If we were to try to call `b.f()`, we’d get an error: - -```text -error: multiple applicable methods in scope [E0034] -b.f(); - ^~~ -note: candidate #1 is defined in an impl of the trait `main::Foo` for the type -`main::Baz` - fn f(&self) { println!("Baz’s impl of Foo"); } - ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -note: candidate #2 is defined in an impl of the trait `main::Bar` for the type -`main::Baz` - fn f(&self) { println!("Baz’s impl of Bar"); } - ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -``` - -We need a way to disambiguate which method we need. This feature is called -‘universal function call syntax’, and it looks like this: - -```rust -# trait Foo { -# fn f(&self); -# } -# trait Bar { -# fn f(&self); -# } -# struct Baz; -# impl Foo for Baz { -# fn f(&self) { println!("Baz’s impl of Foo"); } -# } -# impl Bar for Baz { -# fn f(&self) { println!("Baz’s impl of Bar"); } -# } -# let b = Baz; -Foo::f(&b); -Bar::f(&b); -``` - -Let’s break it down. - -```rust,ignore -Foo:: -Bar:: -``` - -These halves of the invocation are the types of the two traits: `Foo` and -`Bar`. This is what ends up actually doing the disambiguation between the two: -Rust calls the one from the trait name you use. - -```rust,ignore -f(&b) -``` - -When we call a method like `b.f()` using [method syntax][methodsyntax], Rust -will automatically borrow `b` if `f()` takes `&self`. In this case, Rust will -not, and so we need to pass an explicit `&b`. - -[methodsyntax]: method-syntax.html - -# Angle-bracket Form - -The form of UFCS we just talked about: - -```rust,ignore -Trait::method(args); -``` - -Is a short-hand. There’s an expanded form of this that’s needed in some -situations: - -```rust,ignore -::method(args); -``` - -The `<>::` syntax is a means of providing a type hint. The type goes inside -the `<>`s. In this case, the type is `Type as Trait`, indicating that we want -`Trait`’s version of `method` to be called here. The `as Trait` part is -optional if it’s not ambiguous. Same with the angle brackets, hence the -shorter form. - -Here’s an example of using the longer form. - -```rust -trait Foo { - fn foo() -> i32; -} - -struct Bar; - -impl Bar { - fn foo() -> i32 { - 20 - } -} - -impl Foo for Bar { - fn foo() -> i32 { - 10 - } -} - -fn main() { - assert_eq!(10, ::foo()); - assert_eq!(20, Bar::foo()); -} -``` - -Using the angle bracket syntax lets you call the trait method instead of the -inherent one. +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). \ No newline at end of file diff --git a/first-edition/src/unsafe.md b/first-edition/src/unsafe.md index 0331c9530b..be816dfd3d 100644 --- a/first-edition/src/unsafe.md +++ b/first-edition/src/unsafe.md @@ -1,142 +1,10 @@ # Unsafe -Rust’s main draw is its powerful static guarantees about behavior. But safety -checks are conservative by nature: there are some programs that are actually -safe, but the compiler is not able to verify this is true. To write these kinds -of programs, we need to tell the compiler to relax its restrictions a bit. For -this, Rust has a keyword, `unsafe`. Code using `unsafe` has fewer restrictions -than normal code does. +The first edition of the book is no longer distributed with Rust's documentation. -Let’s go over the syntax, and then we’ll talk semantics. `unsafe` is used in -four contexts. The first one is to mark a function as unsafe: +If you came here via a link or web search, you may want to check out [the current +version of the book](../ch19-01-unsafe-rust.html) instead. -```rust -unsafe fn danger_will_robinson() { - // Scary stuff... -} -``` - -All functions called from [FFI][ffi] must be marked as `unsafe`, for example. -The second use of `unsafe` is an unsafe block: - -[ffi]: ffi.html - -```rust -unsafe { - // Scary stuff... -} -``` - -The third is for unsafe traits: - -```rust -unsafe trait Scary { } -``` - -And the fourth is for `impl`ementing one of those traits: - -```rust -# unsafe trait Scary { } -unsafe impl Scary for i32 {} -``` - -It’s important to be able to explicitly delineate code that may have bugs that -cause big problems. If a Rust program segfaults, you can be sure the cause is -related to something marked `unsafe`. - -# What does ‘safe’ mean? - -Safe, in the context of Rust, means ‘doesn’t do anything unsafe’. It’s also -important to know that there are certain behaviors that are probably not -desirable in your code, but are expressly _not_ unsafe: - -* Deadlocks -* Leaks of memory or other resources -* Exiting without calling destructors -* Integer overflow - -Rust cannot prevent all kinds of software problems. Buggy code can and will be -written in Rust. These things aren’t great, but they don’t qualify as `unsafe` -specifically. - -In addition, the following are all undefined behaviors in Rust, and must be -avoided, even when writing `unsafe` code: - -* Data races -* Dereferencing a NULL/dangling raw pointer -* Reads of [undef][undef] (uninitialized) memory -* Breaking the [pointer aliasing rules][aliasing] with raw pointers. -* `&mut T` and `&T` follow LLVM’s scoped [noalias][noalias] model, except if - the `&T` contains an `UnsafeCell`. Unsafe code must not violate these - aliasing guarantees. -* Mutating an immutable value/reference without `UnsafeCell` -* Invoking undefined behavior via compiler intrinsics: - * Indexing outside of the bounds of an object with `std::ptr::offset` - (`offset` intrinsic), with - the exception of one byte past the end which is permitted. - * Using `std::ptr::copy_nonoverlapping_memory` (`memcpy32`/`memcpy64` - intrinsics) on overlapping buffers -* Invalid values in primitive types, even in private fields/locals: - * NULL/dangling references or boxes - * A value other than `false` (0) or `true` (1) in a `bool` - * A discriminant in an `enum` not included in its type definition - * A value in a `char` which is a surrogate or above `char::MAX` - * Non-UTF-8 byte sequences in a `str` -* Unwinding into Rust from foreign code or unwinding from Rust into foreign - code. - -[noalias]: http://llvm.org/docs/LangRef.html#noalias -[undef]: http://llvm.org/docs/LangRef.html#undefined-values -[aliasing]: http://llvm.org/docs/LangRef.html#pointer-aliasing-rules - -# Unsafe Superpowers - -In both unsafe functions and unsafe blocks, Rust will let you do three things -that you normally can not do. Just three. Here they are: - -1. Access or update a [static mutable variable][static]. -2. Dereference a raw pointer. -3. Call unsafe functions. This is the most powerful ability. - -That’s it. It’s important that `unsafe` does not, for example, ‘turn off the -borrow checker’. Adding `unsafe` to some random Rust code doesn’t change its -semantics, it won’t start accepting anything. But it will let you write -things that _do_ break some of the rules. - -You will also encounter the `unsafe` keyword when writing bindings to foreign -(non-Rust) interfaces. You're encouraged to write a safe, native Rust interface -around the methods provided by the library. - -Let’s go over the basic three abilities listed, in order. - -## Access or update a `static mut` - -Rust has a feature called ‘`static mut`’ which allows for mutable global state. -Doing so can cause a data race, and as such is inherently not safe. For more -details, see the [static][static] section of the book. - -[static]: const-and-static.html#static - -## Dereference a raw pointer - -Raw pointers let you do arbitrary pointer arithmetic, and can cause a number of -different memory safety and security issues. In some senses, the ability to -dereference an arbitrary pointer is one of the most dangerous things you can -do. For more on raw pointers, see [their section of the book][rawpointers]. - -[rawpointers]: raw-pointers.html - -## Call unsafe functions - -This last ability works with both aspects of `unsafe`: you can only call -functions marked `unsafe` from inside an unsafe block. - -This ability is powerful and varied. Rust exposes some [compiler -intrinsics][intrinsics] as unsafe functions, and some unsafe functions bypass -safety checks, trading safety for speed. - -I’ll repeat again: even though you _can_ do arbitrary things in unsafe blocks -and functions doesn’t mean you should. The compiler will act as though you’re -upholding its invariants, so be careful! - -[intrinsics]: ../../unstable-book/language-features/intrinsics.html +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). diff --git a/first-edition/src/unsized-types.md b/first-edition/src/unsized-types.md index 2d090925d5..4ec43ecadf 100644 --- a/first-edition/src/unsized-types.md +++ b/first-edition/src/unsized-types.md @@ -1,61 +1,10 @@ # Unsized Types -Most types have a particular size, in bytes, that is knowable at compile time. -For example, an `i32` is thirty-two bits big, or four bytes. However, there are -some types which are useful to express, but do not have a defined size. These are -called ‘unsized’ or ‘dynamically sized’ types. One example is `[T]`. This type -represents a certain number of `T` in sequence. But we don’t know how many -there are, so the size is not known. +The first edition of the book is no longer distributed with Rust's documentation. -Rust understands a few of these types, but they have some restrictions. There -are three: +If you came here via a link or web search, you may want to check out [the current +version of the book](../ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait) instead. -1. We can only manipulate an instance of an unsized type via a pointer. An - `&[T]` works fine, but a `[T]` does not. -2. Variables and arguments cannot have dynamically sized types. -3. Only the last field in a `struct` may have a dynamically sized type; the - other fields must not. Enum variants must not have dynamically sized types as - data. - -So why bother? Well, because `[T]` can only be used behind a pointer, if we -didn’t have language support for unsized types, it would be impossible to write -this: - -```rust,ignore -impl Foo for str { -``` - -or - -```rust,ignore -impl Foo for [T] { -``` - -Instead, you would have to write: - -```rust,ignore -impl Foo for &str { -``` - -Meaning, this implementation would only work for [references][ref], and not -other types of pointers. With the `impl for str`, all pointers, including (at -some point, there are some bugs to fix first) user-defined custom smart -pointers, can use this `impl`. - -[ref]: references-and-borrowing.html - -# ?Sized - -If you want to write a function that accepts a dynamically sized type, you -can use the special bound syntax, `?Sized`: - -```rust -struct Foo { - f: T, -} -``` - -This `?Sized`, read as “T may or may not be `Sized`”, which allows us to match -both sized and unsized types. All generic type parameters implicitly -have the `Sized` bound, so the `?Sized` can be used to opt-out of the implicit -bound. +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). diff --git a/first-edition/src/using-rust-without-the-standard-library.md b/first-edition/src/using-rust-without-the-standard-library.md index c1dcfea149..28e4e763b3 100644 --- a/first-edition/src/using-rust-without-the-standard-library.md +++ b/first-edition/src/using-rust-without-the-standard-library.md @@ -1,44 +1,10 @@ # Using Rust Without the Standard Library -Rust’s standard library provides a lot of useful functionality, but assumes -support for various features of its host system: threads, networking, heap -allocation, and others. There are systems that do not have these features, -however, and Rust can work with those too! To do so, we tell Rust that we -don’t want to use the standard library via an attribute: `#![no_std]`. +The first edition of the book is no longer distributed with Rust's documentation. -> Note: This feature is technically stable, but there are some caveats. For -> one, you can build a `#![no_std]` _library_ on stable, but not a _binary_. -> For details on binaries without the standard library, see [the nightly -> chapter on 'lang items'][unstable book lang items] +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. -To use `#![no_std]`, add it to your crate root: - -```rust,ignore -#![no_std] - -fn plus_one(x: i32) -> i32 { - x + 1 -} -``` - -Much of the functionality that’s exposed in the standard library is also -available via the [`core` crate](../../core/index.html). When we’re using the -standard library, Rust automatically brings `std` into scope, allowing you to -use its features without an explicit import. By the same token, when using -`#![no_std]`, Rust will bring `core` into scope for you, as well as [its -prelude](../../core/prelude/v1/index.html). This means that a lot of code will Just -Work: - -```rust,ignore -#![no_std] - -fn may_fail(failure: bool) -> Result<(), &'static str> { - if failure { - Err("this didn’t work!") - } else { - Ok(()) - } -} -``` - -[unstable book lang items]: ../../unstable-book/language-features/lang-items.html#using-libc +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). \ No newline at end of file diff --git a/first-edition/src/variable-bindings.md b/first-edition/src/variable-bindings.md index 65e172e9b2..d11c926fde 100644 --- a/first-edition/src/variable-bindings.md +++ b/first-edition/src/variable-bindings.md @@ -1,256 +1,10 @@ # Variable Bindings -Virtually every non-'Hello World’ Rust program uses *variable bindings*. They -bind some value to a name, so it can be used later. `let` is -used to introduce a binding, like this: +The first edition of the book is no longer distributed with Rust's documentation. -```rust -fn main() { - let x = 5; -} -``` +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. -Putting `fn main() {` in each example is a bit tedious, so we’ll leave that out -in the future. If you’re following along, make sure to edit your `main()` -function, rather than leaving it off. Otherwise, you’ll get an error. - -# Patterns - -In many languages, a variable binding would be called a *variable*, but Rust’s -variable bindings have a few tricks up their sleeves. For example the -left-hand side of a `let` statement is a ‘[pattern][pattern]’, not a -variable name. This means we can do things like: - -```rust -let (x, y) = (1, 2); -``` - -After this statement is evaluated, `x` will be one, and `y` will be two. -Patterns are really powerful, and have [their own section][pattern] in the -book. We don’t need those features for now, so we’ll keep this in the back -of our minds as we go forward. - -[pattern]: patterns.html - -# Type annotations - -Rust is a statically typed language, which means that we specify our types up -front, and they’re checked at compile time. So why does our first example -compile? Well, Rust has this thing called ‘type inference’. If it can figure -out what the type of something is, Rust doesn’t require you to explicitly type -it out. - -We can add the type if we want to, though. Types come after a colon (`:`): - -```rust -let x: i32 = 5; -``` - -If I asked you to read this out loud to the rest of the class, you’d say “`x` -is a binding with the type `i32` and the value `5`.” - -In this case we chose to represent `x` as a 32-bit signed integer. Rust has -many different primitive integer types. They begin with `i` for signed integers -and `u` for unsigned integers. The possible integer sizes are 8, 16, 32, and 64 -bits. - -In future examples, we may annotate the type in a comment. The examples will -look like this: - -```rust -fn main() { - let x = 5; // x: i32 -} -``` - -Note the similarities between this annotation and the syntax you use with -`let`. Including these kinds of comments is not idiomatic Rust, but we'll -occasionally include them to help you understand what the types that Rust -infers are. - -# Mutability - -By default, bindings are *immutable*. This code will not compile: - -```rust,ignore -let x = 5; -x = 10; -``` - -It will give you this error: - -```text -error: re-assignment of immutable variable `x` - x = 10; - ^~~~~~~ -``` - -If you want a binding to be mutable, you can use `mut`: - -```rust -let mut x = 5; // mut x: i32 -x = 10; -``` - -There is no single reason that bindings are immutable by default, but we can -think about it through one of Rust’s primary focuses: safety. If you forget to -say `mut`, the compiler will catch it, and let you know that you have mutated -something you may not have intended to mutate. If bindings were mutable by -default, the compiler would not be able to tell you this. If you _did_ intend -mutation, then the solution is quite easy: add `mut`. - -There are other good reasons to avoid mutable state when possible, but they’re -out of the scope of this guide. In general, you can often avoid explicit -mutation, and so it is preferable in Rust. That said, sometimes, mutation is -what you need, so it’s not forbidden. - -# Initializing bindings - -Rust variable bindings have one more aspect that differs from other languages: -bindings are required to be initialized with a value before you're allowed to -use them. - -Let’s try it out. Change your `src/main.rs` file to look like this: - -```rust -fn main() { - let x: i32; - - println!("Hello world!"); -} -``` - -You can use `cargo build` on the command line to build it. You’ll get a -warning, but it will still print "Hello, world!": - -```text - Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world) -src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variables)] - on by default -src/main.rs:2 let x: i32; - ^ -``` - -Rust warns us that we never use the variable binding, but since we never use -it, no harm, no foul. Things change if we try to actually use this `x`, -however. Let’s do that. Change your program to look like this: - -```rust,ignore -fn main() { - let x: i32; - - println!("The value of x is: {}", x); -} -``` - -And try to build it. You’ll get an error: - -```bash -$ cargo build - Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world) -src/main.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x` -src/main.rs:4 println!("The value of x is: {}", x); - ^ -note: in expansion of format_args! -:2:23: 2:77 note: expansion site -:1:1: 3:2 note: in expansion of println! -src/main.rs:4:5: 4:42 note: expansion site -error: aborting due to previous error -Could not compile `hello_world`. -``` - -Rust will not let us use a value that has not been initialized. - -Let us take a minute to talk about this stuff we've added to `println!`. - -If you include two curly braces (`{}`, some call them moustaches...) in your -string to print, Rust will interpret this as a request to interpolate some sort -of value. *String interpolation* is a computer science term that means "stick -in the middle of a string." We add a comma, and then `x`, to indicate that we -want `x` to be the value we’re interpolating. The comma is used to separate -arguments we pass to functions and macros, if you’re passing more than one. - -When you use the curly braces, Rust will attempt to display the value in a -meaningful way by checking out its type. If you want to specify the format in a -more detailed manner, there are a [wide number of options available][format]. -For now, we'll stick to the default: integers aren't very complicated to -print. - -[format]: ../../std/fmt/index.html - -# Scope and shadowing - -Let’s get back to bindings. Variable bindings have a scope - they are -constrained to live in the block they were defined in. A block is a collection -of statements enclosed by `{` and `}`. Function definitions are also blocks! -In the following example we define two variable bindings, `x` and `y`, which -live in different blocks. `x` can be accessed from inside the `fn main() {}` -block, while `y` can be accessed only from inside the inner block: - -```rust,ignore -fn main() { - let x: i32 = 17; - { - let y: i32 = 3; - println!("The value of x is {} and value of y is {}", x, y); - } - println!("The value of x is {} and value of y is {}", x, y); // This won't work. -} -``` - -The first `println!` would print "The value of x is 17 and the value of y is -3", but this example cannot be compiled successfully, because the second -`println!` cannot access the value of `y`, since it is not in scope anymore. -Instead we get this error: - -```bash -$ cargo build - Compiling hello v0.1.0 (file:///home/you/projects/hello_world) -main.rs:7:62: 7:63 error: unresolved name `y`. Did you mean `x`? [E0425] -main.rs:7 println!("The value of x is {} and value of y is {}", x, y); // This won't work. - ^ -note: in expansion of format_args! -:2:25: 2:56 note: expansion site -:1:1: 2:62 note: in expansion of print! -:3:1: 3:54 note: expansion site -:1:1: 3:58 note: in expansion of println! -main.rs:7:5: 7:65 note: expansion site -main.rs:7:62: 7:63 help: run `rustc --explain E0425` to see a detailed explanation -error: aborting due to previous error -Could not compile `hello`. - -To learn more, run the command again with --verbose. -``` - -Additionally, variable bindings can be shadowed. This means that a later -variable binding with the same name as another binding that is currently in -scope will override the previous binding. - -```rust -let x: i32 = 8; -{ - println!("{}", x); // Prints "8". - let x = 12; - println!("{}", x); // Prints "12". -} -println!("{}", x); // Prints "8". -let x = 42; -println!("{}", x); // Prints "42". -``` - -Shadowing and mutable bindings may appear as two sides of the same coin, but -they are two distinct concepts that can't always be used interchangeably. For -one, shadowing enables us to rebind a name to a value of a different type. It -is also possible to change the mutability of a binding. Note that shadowing a -name does not alter or destroy the value it was bound to, and the value will -continue to exist until it goes out of scope, even if it is no longer accessible -by any means. - -```rust -let mut x: i32 = 1; -x = 7; -let x = x; // `x` is now immutable and is bound to `7`. - -let y = 4; -let y = "I can also be bound to text!"; // `y` is now of a different type. -``` +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). \ No newline at end of file diff --git a/first-edition/src/vectors.md b/first-edition/src/vectors.md index 138a15273c..14f83b7f78 100644 --- a/first-edition/src/vectors.md +++ b/first-edition/src/vectors.md @@ -1,156 +1,10 @@ # Vectors -A ‘vector’ is a dynamic or ‘growable’ array, implemented as the standard -library type [`Vec`][vec]. The `T` means that we can have vectors -of any type (see the chapter on [generics][generic] for more). -Vectors always allocate their data on the heap. -You can create them with the `vec!` macro: +The first edition of the book is no longer distributed with Rust's documentation. -```rust -let v = vec![1, 2, 3, 4, 5]; // v: Vec -``` +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. -(Notice that unlike the `println!` macro we’ve used in the past, we use square -brackets `[]` with `vec!` macro. Rust allows you to use either in either -situation, this is just convention.) - -There’s an alternate form of `vec!` for repeating an initial value: - -```rust -let v = vec![0; 10]; // A vector of ten zeroes. -``` - -Vectors store their contents as contiguous arrays of `T` on the heap. This means -that they must be able to know the size of `T` at compile time (that is, how -many bytes are needed to store a `T`?). The size of some things can't be known -at compile time. For these you'll have to store a pointer to that thing: -thankfully, the [`Box`][box] type works perfectly for this. - -## Accessing elements - -To get the value at a particular index in the vector, we use `[]`s: - -```rust -let v = vec![1, 2, 3, 4, 5]; - -println!("The third element of v is {}", v[2]); -``` - -The indices count from `0`, so the third element is `v[2]`. - -It’s also important to note that you must index with the `usize` type: - -```rust,ignore -let v = vec![1, 2, 3, 4, 5]; - -let i: usize = 0; -let j: i32 = 0; - -// Works: -v[i]; - -// Doesn’t: -v[j]; -``` - -Indexing with a non-`usize` type gives an error that looks like this: - -```text -error: the trait bound `collections::vec::Vec<_> : core::ops::Index` -is not satisfied [E0277] -v[j]; -^~~~ -note: the type `collections::vec::Vec<_>` cannot be indexed by `i32` -error: aborting due to previous error -``` - -There’s a lot of punctuation in that message, but the core of it makes sense: -you cannot index with an `i32`. - -## Out-of-bounds Access - -If you try to access an index that doesn’t exist: - -```rust,ignore -let v = vec![1, 2, 3]; -println!("Item 7 is {}", v[7]); -``` - -then the current thread will [panic] with a message like this: - -```text -thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 7' -``` - -If you want to handle out-of-bounds errors without panicking, you can use -methods like [`get`][get] or [`get_mut`][get_mut] that return `None` when -given an invalid index: - -```rust -let v = vec![1, 2, 3]; -match v.get(7) { - Some(x) => println!("Item 7 is {}", x), - None => println!("Sorry, this vector is too short.") -} -``` - -## Iterating - -Once you have a vector, you can iterate through its elements with `for`. There -are three versions: - -```rust -let mut v = vec![1, 2, 3, 4, 5]; - -for i in &v { - println!("A reference to {}", i); -} - -for i in &mut v { - println!("A mutable reference to {}", i); -} - -for i in v { - println!("Take ownership of the vector and its element {}", i); -} -``` - -Note: You cannot use the vector again once you have iterated by taking ownership of the vector. -You can iterate the vector multiple times by taking a reference to the vector whilst iterating. -For example, the following code does not compile. - -```rust,ignore -let v = vec![1, 2, 3, 4, 5]; - -for i in v { - println!("Take ownership of the vector and its element {}", i); -} - -for i in v { - println!("Take ownership of the vector and its element {}", i); -} -``` - -Whereas the following works perfectly, - -```rust -let v = vec![1, 2, 3, 4, 5]; - -for i in &v { - println!("This is a reference to {}", i); -} - -for i in &v { - println!("This is a reference to {}", i); -} -``` - -Vectors have many more useful methods, which you can read about in [their -API documentation][vec]. - -[vec]: ../../std/vec/index.html -[box]: ../../std/boxed/index.html -[generic]: generics.html -[panic]: concurrency.html#panics -[get]: ../../std/vec/struct.Vec.html#method.get -[get_mut]: ../../std/vec/struct.Vec.html#method.get_mut +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). diff --git a/index.md b/index.md deleted file mode 100644 index 359267d84b..0000000000 --- a/index.md +++ /dev/null @@ -1,25 +0,0 @@ -# The Rust Programming Language - -The current edition of "The Rust Programming Language" is the second -edition, which you can [read here](second-edition/index.html). - -The source for all editions lives [on GitHub](https://github.com/rust-lang/book). -Please open issues with any questions, concerns, or tweaks. - -## Notes - -The second edition is still receiving some minor edits, but is effectively -complete. It will be [available in dead-tree form through NoStarch -Press](https://nostarch.com/Rust) once these final edits are complete. - -The second edition is a complete re-write of TRPL, from the ground up, -and is therefore very different from the first edition. - -## Other editions - -We keep older editions of TRPL online for history's sake. - -### First Edition - -You can [read the first edition of "The Rust Programming Language" -here](first-edition/index.html). diff --git a/listings/ch02-guessing-game-tutorial/listing-02-01/Cargo.lock b/listings/ch02-guessing-game-tutorial/listing-02-01/Cargo.lock new file mode 100644 index 0000000000..5802b7dc9a --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/listing-02-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "guessing_game" +version = "0.1.0" + diff --git a/listings/ch02-guessing-game-tutorial/listing-02-01/Cargo.toml b/listings/ch02-guessing-game-tutorial/listing-02-01/Cargo.toml new file mode 100644 index 0000000000..e3091e7da8 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/listing-02-01/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs b/listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs new file mode 100644 index 0000000000..b822b89ff3 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs @@ -0,0 +1,31 @@ +// 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 diff --git a/listings/ch02-guessing-game-tutorial/listing-02-02/Cargo.lock b/listings/ch02-guessing-game-tutorial/listing-02-02/Cargo.lock new file mode 100644 index 0000000000..26af308db4 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/listing-02-02/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.66" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)" = "d515b1f41455adea1313a4a2ac8a8a477634fbae63cc6100e3aebb207ce61558" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" +"checksum winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/listings/ch02-guessing-game-tutorial/listing-02-02/Cargo.toml b/listings/ch02-guessing-game-tutorial/listing-02-02/Cargo.toml new file mode 100644 index 0000000000..10932024b4 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/listing-02-02/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.5.5" diff --git a/listings/ch02-guessing-game-tutorial/listing-02-02/src/main.rs b/listings/ch02-guessing-game-tutorial/listing-02-02/src/main.rs new file mode 100644 index 0000000000..60fb2a8e5f --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/listing-02-02/src/main.rs @@ -0,0 +1,15 @@ +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); +} diff --git a/listings/ch02-guessing-game-tutorial/listing-02-03/Cargo.lock b/listings/ch02-guessing-game-tutorial/listing-02-03/Cargo.lock new file mode 100644 index 0000000000..2b3d41ad67 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/listing-02-03/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.51" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8a606a02debe2813760609f57a64a2ffd27d9fdf5b2f133eaca0b248dd92cdd2" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)" = "bedcc7a809076656486ffe045abeeac163da1b558e963a31e29fbfbeba916917" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/listings/ch02-guessing-game-tutorial/listing-02-03/Cargo.toml b/listings/ch02-guessing-game-tutorial/listing-02-03/Cargo.toml new file mode 100644 index 0000000000..10932024b4 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/listing-02-03/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.5.5" diff --git a/listings/ch02-guessing-game-tutorial/listing-02-03/src/main.rs b/listings/ch02-guessing-game-tutorial/listing-02-03/src/main.rs new file mode 100644 index 0000000000..d5e3df7f61 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/listing-02-03/src/main.rs @@ -0,0 +1,28 @@ +// 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, 101); + // 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 diff --git a/listings/ch02-guessing-game-tutorial/listing-02-04/Cargo.lock b/listings/ch02-guessing-game-tutorial/listing-02-04/Cargo.lock new file mode 100644 index 0000000000..2b3d41ad67 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/listing-02-04/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.51" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8a606a02debe2813760609f57a64a2ffd27d9fdf5b2f133eaca0b248dd92cdd2" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)" = "bedcc7a809076656486ffe045abeeac163da1b558e963a31e29fbfbeba916917" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/listings/ch02-guessing-game-tutorial/listing-02-04/Cargo.toml b/listings/ch02-guessing-game-tutorial/listing-02-04/Cargo.toml new file mode 100644 index 0000000000..10932024b4 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/listing-02-04/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.5.5" diff --git a/listings/ch02-guessing-game-tutorial/listing-02-04/output.txt b/listings/ch02-guessing-game-tutorial/listing-02-04/output.txt new file mode 100644 index 0000000000..06ab080e47 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/listing-02-04/output.txt @@ -0,0 +1,21 @@ +$ cargo build + Compiling libc v0.2.51 + Compiling rand_core v0.4.0 + Compiling rand_core v0.3.1 + Compiling rand v0.5.6 + Compiling guessing_game v0.1.0 (file:///projects/guessing_game) +error[E0308]: mismatched types + --> src/main.rs:22:21 + | +22 | match guess.cmp(&secret_number) { + | ^^^^^^^^^^^^^^ expected struct `std::string::String`, found integer + | + = note: expected type `&std::string::String` + found type `&{integer}` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. +error: could not compile `guessing_game`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch02-guessing-game-tutorial/listing-02-04/src/main.rs b/listings/ch02-guessing-game-tutorial/listing-02-04/src/main.rs new file mode 100644 index 0000000000..ac432df3d0 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/listing-02-04/src/main.rs @@ -0,0 +1,32 @@ +// ANCHOR: here +use rand::Rng; +use std::cmp::Ordering; +use std::io; + +fn main() { + // --snip-- + // ANCHOR_END: here + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1, 101); + + 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 diff --git a/listings/ch02-guessing-game-tutorial/listing-02-05/Cargo.lock b/listings/ch02-guessing-game-tutorial/listing-02-05/Cargo.lock new file mode 100644 index 0000000000..2b3d41ad67 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/listing-02-05/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.51" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8a606a02debe2813760609f57a64a2ffd27d9fdf5b2f133eaca0b248dd92cdd2" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)" = "bedcc7a809076656486ffe045abeeac163da1b558e963a31e29fbfbeba916917" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/listings/ch02-guessing-game-tutorial/listing-02-05/Cargo.toml b/listings/ch02-guessing-game-tutorial/listing-02-05/Cargo.toml new file mode 100644 index 0000000000..10932024b4 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/listing-02-05/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.5.5" diff --git a/listings/ch02-guessing-game-tutorial/listing-02-05/src/main.rs b/listings/ch02-guessing-game-tutorial/listing-02-05/src/main.rs new file mode 100644 index 0000000000..e4f4f87d98 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/listing-02-05/src/main.rs @@ -0,0 +1,45 @@ +use rand::Rng; +use std::cmp::Ordering; +use std::io; + +fn main() { + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1, 101); + + 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; + } + } + } +} diff --git a/listings/ch02-guessing-game-tutorial/listing-02-06/Cargo.lock b/listings/ch02-guessing-game-tutorial/listing-02-06/Cargo.lock new file mode 100644 index 0000000000..890a658000 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/listing-02-06/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.53" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.53 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8a606a02debe2813760609f57a64a2ffd27d9fdf5b2f133eaca0b248dd92cdd2" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.53 (registry+https://github.com/rust-lang/crates.io-index)" = "ec350a9417dfd244dc9a6c4a71e13895a4db6b92f0b106f07ebbc3f3bc580cee" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/listings/ch02-guessing-game-tutorial/listing-02-06/Cargo.toml b/listings/ch02-guessing-game-tutorial/listing-02-06/Cargo.toml new file mode 100644 index 0000000000..10932024b4 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/listing-02-06/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.5.5" diff --git a/listings/ch02-guessing-game-tutorial/listing-02-06/src/main.rs b/listings/ch02-guessing-game-tutorial/listing-02-06/src/main.rs new file mode 100644 index 0000000000..0d4006e946 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/listing-02-06/src/main.rs @@ -0,0 +1,35 @@ +use rand::Rng; +use std::cmp::Ordering; +use std::io; + +fn main() { + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1, 101); + + 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; + } + } + } +} diff --git a/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/Cargo.lock b/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/Cargo.lock new file mode 100644 index 0000000000..5802b7dc9a --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "guessing_game" +version = "0.1.0" + diff --git a/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/Cargo.toml b/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/Cargo.toml new file mode 100644 index 0000000000..e3091e7da8 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/output.txt b/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/output.txt new file mode 100644 index 0000000000..2724c145d3 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling guessing_game v0.1.0 (file:///projects/guessing_game) + Finished dev [unoptimized + debuginfo] target(s) in 1.50s + Running `target/debug/guessing_game` +Hello, world! diff --git a/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/src/main.rs b/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/src/main.rs new file mode 100644 index 0000000000..e7a11a969c --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} diff --git a/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/Cargo.lock b/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/Cargo.lock new file mode 100644 index 0000000000..5802b7dc9a --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "guessing_game" +version = "0.1.0" + diff --git a/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/Cargo.toml b/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/Cargo.toml new file mode 100644 index 0000000000..e3091e7da8 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/output.txt b/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/output.txt new file mode 100644 index 0000000000..56fb75b382 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/output.txt @@ -0,0 +1,12 @@ +$ cargo build + Compiling guessing_game v0.1.0 (file:///projects/guessing_game) +warning: unused `std::result::Result` that must be used + --> src/main.rs:10:5 + | +10 | io::stdin().read_line(&mut guess); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: `#[warn(unused_must_use)]` on by default + = note: this `Result` may be an `Err` variant, which should be handled + + Finished dev [unoptimized + debuginfo] target(s) in 0.59s diff --git a/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/src/main.rs b/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/src/main.rs new file mode 100644 index 0000000000..aaf90bd659 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/src/main.rs @@ -0,0 +1,13 @@ +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); +} diff --git a/listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/Cargo.lock b/listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/Cargo.lock new file mode 100644 index 0000000000..2b3d41ad67 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.51" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8a606a02debe2813760609f57a64a2ffd27d9fdf5b2f133eaca0b248dd92cdd2" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)" = "bedcc7a809076656486ffe045abeeac163da1b558e963a31e29fbfbeba916917" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/Cargo.toml b/listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/Cargo.toml new file mode 100644 index 0000000000..10932024b4 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.5.5" diff --git a/listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/src/main.rs b/listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/src/main.rs new file mode 100644 index 0000000000..44d8db6b88 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/src/main.rs @@ -0,0 +1,33 @@ +use rand::Rng; +use std::cmp::Ordering; +use std::io; + +fn main() { + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1, 101); + + 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 diff --git a/listings/ch02-guessing-game-tutorial/no-listing-04-looping/Cargo.lock b/listings/ch02-guessing-game-tutorial/no-listing-04-looping/Cargo.lock new file mode 100644 index 0000000000..2b3d41ad67 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/no-listing-04-looping/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.51" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8a606a02debe2813760609f57a64a2ffd27d9fdf5b2f133eaca0b248dd92cdd2" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)" = "bedcc7a809076656486ffe045abeeac163da1b558e963a31e29fbfbeba916917" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/listings/ch02-guessing-game-tutorial/no-listing-04-looping/Cargo.toml b/listings/ch02-guessing-game-tutorial/no-listing-04-looping/Cargo.toml new file mode 100644 index 0000000000..10932024b4 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/no-listing-04-looping/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.5.5" diff --git a/listings/ch02-guessing-game-tutorial/no-listing-04-looping/src/main.rs b/listings/ch02-guessing-game-tutorial/no-listing-04-looping/src/main.rs new file mode 100644 index 0000000000..5b42f65578 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/no-listing-04-looping/src/main.rs @@ -0,0 +1,40 @@ +use rand::Rng; +use std::cmp::Ordering; +use std::io; + +fn main() { + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1, 101); + + // 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 diff --git a/listings/ch02-guessing-game-tutorial/no-listing-05-quitting/Cargo.lock b/listings/ch02-guessing-game-tutorial/no-listing-05-quitting/Cargo.lock new file mode 100644 index 0000000000..2b3d41ad67 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/no-listing-05-quitting/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.51" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8a606a02debe2813760609f57a64a2ffd27d9fdf5b2f133eaca0b248dd92cdd2" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)" = "bedcc7a809076656486ffe045abeeac163da1b558e963a31e29fbfbeba916917" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/listings/ch02-guessing-game-tutorial/no-listing-05-quitting/Cargo.toml b/listings/ch02-guessing-game-tutorial/no-listing-05-quitting/Cargo.toml new file mode 100644 index 0000000000..10932024b4 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/no-listing-05-quitting/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.5.5" diff --git a/listings/ch02-guessing-game-tutorial/no-listing-05-quitting/src/main.rs b/listings/ch02-guessing-game-tutorial/no-listing-05-quitting/src/main.rs new file mode 100644 index 0000000000..b32fadbb12 --- /dev/null +++ b/listings/ch02-guessing-game-tutorial/no-listing-05-quitting/src/main.rs @@ -0,0 +1,38 @@ +use rand::Rng; +use std::cmp::Ordering; +use std::io; + +fn main() { + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1, 101); + + 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 diff --git a/listings/ch03-common-programming-concepts/listing-03-01/Cargo.lock b/listings/ch03-common-programming-concepts/listing-03-01/Cargo.lock new file mode 100644 index 0000000000..88287d1363 --- /dev/null +++ b/listings/ch03-common-programming-concepts/listing-03-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/listing-03-01/Cargo.toml b/listings/ch03-common-programming-concepts/listing-03-01/Cargo.toml new file mode 100644 index 0000000000..291680cf8f --- /dev/null +++ b/listings/ch03-common-programming-concepts/listing-03-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/listing-03-01/src/main.rs b/listings/ch03-common-programming-concepts/listing-03-01/src/main.rs new file mode 100644 index 0000000000..b492d384f0 --- /dev/null +++ b/listings/ch03-common-programming-concepts/listing-03-01/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + let y = 6; +} diff --git a/listings/ch03-common-programming-concepts/listing-03-02/Cargo.lock b/listings/ch03-common-programming-concepts/listing-03-02/Cargo.lock new file mode 100644 index 0000000000..4ca0c2dbdb --- /dev/null +++ b/listings/ch03-common-programming-concepts/listing-03-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "branches" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/listing-03-02/Cargo.toml b/listings/ch03-common-programming-concepts/listing-03-02/Cargo.toml new file mode 100644 index 0000000000..8ddf691495 --- /dev/null +++ b/listings/ch03-common-programming-concepts/listing-03-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "branches" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/listing-03-02/output.txt b/listings/ch03-common-programming-concepts/listing-03-02/output.txt new file mode 100644 index 0000000000..3eb8d102a5 --- /dev/null +++ b/listings/ch03-common-programming-concepts/listing-03-02/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling branches v0.1.0 (file:///projects/branches) + Finished dev [unoptimized + debuginfo] target(s) in 0.30s + Running `target/debug/branches` +The value of number is: 5 diff --git a/listings/ch03-common-programming-concepts/listing-03-02/src/main.rs b/listings/ch03-common-programming-concepts/listing-03-02/src/main.rs new file mode 100644 index 0000000000..0b8ee95fd0 --- /dev/null +++ b/listings/ch03-common-programming-concepts/listing-03-02/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + let condition = true; + let number = if condition { 5 } else { 6 }; + + println!("The value of number is: {}", number); +} diff --git a/listings/ch03-common-programming-concepts/listing-03-03/Cargo.lock b/listings/ch03-common-programming-concepts/listing-03-03/Cargo.lock new file mode 100644 index 0000000000..9942b362ac --- /dev/null +++ b/listings/ch03-common-programming-concepts/listing-03-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "loops" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/listing-03-03/Cargo.toml b/listings/ch03-common-programming-concepts/listing-03-03/Cargo.toml new file mode 100644 index 0000000000..b5ed848ab4 --- /dev/null +++ b/listings/ch03-common-programming-concepts/listing-03-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "loops" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/listing-03-03/src/main.rs b/listings/ch03-common-programming-concepts/listing-03-03/src/main.rs new file mode 100644 index 0000000000..651ed68c8e --- /dev/null +++ b/listings/ch03-common-programming-concepts/listing-03-03/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + let mut number = 3; + + while number != 0 { + println!("{}!", number); + + number -= 1; + } + + println!("LIFTOFF!!!"); +} diff --git a/listings/ch03-common-programming-concepts/listing-03-04/Cargo.lock b/listings/ch03-common-programming-concepts/listing-03-04/Cargo.lock new file mode 100644 index 0000000000..9942b362ac --- /dev/null +++ b/listings/ch03-common-programming-concepts/listing-03-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "loops" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/listing-03-04/Cargo.toml b/listings/ch03-common-programming-concepts/listing-03-04/Cargo.toml new file mode 100644 index 0000000000..b5ed848ab4 --- /dev/null +++ b/listings/ch03-common-programming-concepts/listing-03-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "loops" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/listing-03-04/output.txt b/listings/ch03-common-programming-concepts/listing-03-04/output.txt new file mode 100644 index 0000000000..35c0f804a7 --- /dev/null +++ b/listings/ch03-common-programming-concepts/listing-03-04/output.txt @@ -0,0 +1,9 @@ +$ cargo run + Compiling loops v0.1.0 (file:///projects/loops) + Finished dev [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 diff --git a/listings/ch03-common-programming-concepts/listing-03-04/src/main.rs b/listings/ch03-common-programming-concepts/listing-03-04/src/main.rs new file mode 100644 index 0000000000..38fd301e64 --- /dev/null +++ b/listings/ch03-common-programming-concepts/listing-03-04/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + let a = [10, 20, 30, 40, 50]; + let mut index = 0; + + while index < 5 { + println!("the value is: {}", a[index]); + + index += 1; + } +} diff --git a/listings/ch03-common-programming-concepts/listing-03-05/Cargo.lock b/listings/ch03-common-programming-concepts/listing-03-05/Cargo.lock new file mode 100644 index 0000000000..9942b362ac --- /dev/null +++ b/listings/ch03-common-programming-concepts/listing-03-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "loops" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/listing-03-05/Cargo.toml b/listings/ch03-common-programming-concepts/listing-03-05/Cargo.toml new file mode 100644 index 0000000000..b5ed848ab4 --- /dev/null +++ b/listings/ch03-common-programming-concepts/listing-03-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "loops" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/listing-03-05/src/main.rs b/listings/ch03-common-programming-concepts/listing-03-05/src/main.rs new file mode 100644 index 0000000000..6e3cca66ea --- /dev/null +++ b/listings/ch03-common-programming-concepts/listing-03-05/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + let a = [10, 20, 30, 40, 50]; + + for element in a.iter() { + println!("the value is: {}", element); + } +} diff --git a/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/Cargo.lock new file mode 100644 index 0000000000..2d62cbe7af --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "variables" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/Cargo.toml new file mode 100644 index 0000000000..7915d397e2 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "variables" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/output.txt b/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/output.txt new file mode 100644 index 0000000000..4693ca9da4 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/output.txt @@ -0,0 +1,20 @@ +$ 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` + | help: make this binding mutable: `mut x` +3 | println!("The value of x is: {}", x); +4 | x = 6; + | ^^^^^ cannot assign twice to immutable variable + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0384`. +error: could not compile `variables`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/src/main.rs new file mode 100644 index 0000000000..a6c7ac071f --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + let x = 5; + println!("The value of x is: {}", x); + x = 6; + println!("The value of x is: {}", x); +} diff --git a/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/Cargo.lock new file mode 100644 index 0000000000..2d62cbe7af --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "variables" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/Cargo.toml new file mode 100644 index 0000000000..7915d397e2 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "variables" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/output.txt b/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/output.txt new file mode 100644 index 0000000000..8ed6598ff1 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/output.txt @@ -0,0 +1,6 @@ +$ cargo run + Compiling variables v0.1.0 (file:///projects/variables) + Finished dev [unoptimized + debuginfo] target(s) in 0.30s + Running `target/debug/variables` +The value of x is: 5 +The value of x is: 6 diff --git a/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/src/main.rs new file mode 100644 index 0000000000..c4e4a1953d --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + let mut x = 5; + println!("The value of x is: {}", x); + x = 6; + println!("The value of x is: {}", x); +} diff --git a/listings/ch03-common-programming-concepts/no-listing-03-shadowing/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-03-shadowing/Cargo.lock new file mode 100644 index 0000000000..2d62cbe7af --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-03-shadowing/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "variables" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-03-shadowing/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-03-shadowing/Cargo.toml new file mode 100644 index 0000000000..7915d397e2 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-03-shadowing/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "variables" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-03-shadowing/output.txt b/listings/ch03-common-programming-concepts/no-listing-03-shadowing/output.txt new file mode 100644 index 0000000000..64ac2bf51d --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-03-shadowing/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling variables v0.1.0 (file:///projects/variables) + Finished dev [unoptimized + debuginfo] target(s) in 0.31s + Running `target/debug/variables` +The value of x is: 12 diff --git a/listings/ch03-common-programming-concepts/no-listing-03-shadowing/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-03-shadowing/src/main.rs new file mode 100644 index 0000000000..d32518011e --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-03-shadowing/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let x = 5; + + let x = x + 1; + + let x = x * 2; + + println!("The value of x is: {}", x); +} diff --git a/listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/Cargo.lock new file mode 100644 index 0000000000..2d62cbe7af --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "variables" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/Cargo.toml new file mode 100644 index 0000000000..7915d397e2 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "variables" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/src/main.rs new file mode 100644 index 0000000000..42589f5489 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + // ANCHOR: here + let spaces = " "; + let spaces = spaces.len(); + // ANCHOR_END: here +} diff --git a/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/Cargo.lock new file mode 100644 index 0000000000..2d62cbe7af --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "variables" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/Cargo.toml new file mode 100644 index 0000000000..7915d397e2 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "variables" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/output.txt b/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/output.txt new file mode 100644 index 0000000000..a8b628a1c5 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/output.txt @@ -0,0 +1,17 @@ +$ cargo run + Compiling variables v0.1.0 (file:///projects/variables) +error[E0308]: mismatched types + --> src/main.rs:3:14 + | +3 | spaces = spaces.len(); + | ^^^^^^^^^^^^ expected &str, found usize + | + = note: expected type `&str` + found type `usize` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. +error: could not compile `variables`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/src/main.rs new file mode 100644 index 0000000000..f52635d0b2 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + // ANCHOR: here + let mut spaces = " "; + spaces = spaces.len(); + // ANCHOR_END: here +} diff --git a/listings/ch03-common-programming-concepts/no-listing-06-floating-point/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-06-floating-point/Cargo.lock new file mode 100644 index 0000000000..3b40559a79 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-06-floating-point/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "floating-point" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-06-floating-point/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-06-floating-point/Cargo.toml new file mode 100644 index 0000000000..81e80c2964 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-06-floating-point/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "floating-point" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-06-floating-point/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-06-floating-point/src/main.rs new file mode 100644 index 0000000000..6f4f0fe872 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-06-floating-point/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + let x = 2.0; // f64 + + let y: f32 = 3.0; // f32 +} diff --git a/listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/Cargo.lock new file mode 100644 index 0000000000..94a12b2553 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "numeric-operations" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/Cargo.toml new file mode 100644 index 0000000000..00601dde45 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "numeric-operations" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/src/main.rs new file mode 100644 index 0000000000..0a784bbc21 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/src/main.rs @@ -0,0 +1,16 @@ +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; + + // remainder + let remainder = 43 % 5; +} diff --git a/listings/ch03-common-programming-concepts/no-listing-08-boolean/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-08-boolean/Cargo.lock new file mode 100644 index 0000000000..5d5728ebd9 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-08-boolean/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "boolean" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-08-boolean/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-08-boolean/Cargo.toml new file mode 100644 index 0000000000..783df3ddf3 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-08-boolean/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "boolean" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-08-boolean/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-08-boolean/src/main.rs new file mode 100644 index 0000000000..2c56e62f94 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-08-boolean/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + let t = true; + + let f: bool = false; // with explicit type annotation +} diff --git a/listings/ch03-common-programming-concepts/no-listing-09-char/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-09-char/Cargo.lock new file mode 100644 index 0000000000..bb58446cc7 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-09-char/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "char" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-09-char/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-09-char/Cargo.toml new file mode 100644 index 0000000000..cfde83b8c6 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-09-char/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "char" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-09-char/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-09-char/src/main.rs new file mode 100644 index 0000000000..4b8d9d930b --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-09-char/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + let c = 'z'; + let z = 'ℤ'; + let heart_eyed_cat = '😻'; +} diff --git a/listings/ch03-common-programming-concepts/no-listing-10-tuples/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-10-tuples/Cargo.lock new file mode 100644 index 0000000000..f57f0767c9 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-10-tuples/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "tuples" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-10-tuples/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-10-tuples/Cargo.toml new file mode 100644 index 0000000000..8d6c2d577d --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-10-tuples/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "tuples" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-10-tuples/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-10-tuples/src/main.rs new file mode 100644 index 0000000000..b7b51fb2f9 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-10-tuples/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + let tup: (i32, f64, u8) = (500, 6.4, 1); +} diff --git a/listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/Cargo.lock new file mode 100644 index 0000000000..f57f0767c9 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "tuples" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/Cargo.toml new file mode 100644 index 0000000000..8d6c2d577d --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "tuples" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/src/main.rs new file mode 100644 index 0000000000..35dcb442ea --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + let tup = (500, 6.4, 1); + + let (x, y, z) = tup; + + println!("The value of y is: {}", y); +} diff --git a/listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/Cargo.lock new file mode 100644 index 0000000000..f57f0767c9 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "tuples" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/Cargo.toml new file mode 100644 index 0000000000..8d6c2d577d --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "tuples" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/src/main.rs new file mode 100644 index 0000000000..1b1e646fd6 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/src/main.rs @@ -0,0 +1,9 @@ +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; +} diff --git a/listings/ch03-common-programming-concepts/no-listing-13-arrays/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-13-arrays/Cargo.lock new file mode 100644 index 0000000000..68e3c59678 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-13-arrays/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "arrays" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-13-arrays/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-13-arrays/Cargo.toml new file mode 100644 index 0000000000..ec97b7d5e7 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-13-arrays/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "arrays" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-13-arrays/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-13-arrays/src/main.rs new file mode 100644 index 0000000000..d475901ce6 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-13-arrays/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + let a = [1, 2, 3, 4, 5]; +} diff --git a/listings/ch03-common-programming-concepts/no-listing-14-array-indexing/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-14-array-indexing/Cargo.lock new file mode 100644 index 0000000000..68e3c59678 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-14-array-indexing/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "arrays" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-14-array-indexing/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-14-array-indexing/Cargo.toml new file mode 100644 index 0000000000..ec97b7d5e7 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-14-array-indexing/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "arrays" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-14-array-indexing/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-14-array-indexing/src/main.rs new file mode 100644 index 0000000000..d33e3174f6 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-14-array-indexing/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + let a = [1, 2, 3, 4, 5]; + + let first = a[0]; + let second = a[1]; +} diff --git a/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/Cargo.lock new file mode 100644 index 0000000000..68e3c59678 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "arrays" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/Cargo.toml new file mode 100644 index 0000000000..ec97b7d5e7 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "arrays" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/output.txt b/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/output.txt new file mode 100644 index 0000000000..be3ef310f8 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/output.txt @@ -0,0 +1,6 @@ +$ cargo run + Compiling arrays v0.1.0 (file:///projects/arrays) + Finished dev [unoptimized + debuginfo] target(s) in 0.31s + Running `target/debug/arrays` +thread 'main' panicked at 'index out of bounds: the len is 5 but the index is 10', src/main.rs:5:19 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. diff --git a/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/src/main.rs new file mode 100644 index 0000000000..5ce0ed4a5b --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + let a = [1, 2, 3, 4, 5]; + let index = 10; + + let element = a[index]; + + println!("The value of element is: {}", element); +} diff --git a/listings/ch03-common-programming-concepts/no-listing-16-functions/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-16-functions/Cargo.lock new file mode 100644 index 0000000000..88287d1363 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-16-functions/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-16-functions/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-16-functions/Cargo.toml new file mode 100644 index 0000000000..291680cf8f --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-16-functions/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-16-functions/output.txt b/listings/ch03-common-programming-concepts/no-listing-16-functions/output.txt new file mode 100644 index 0000000000..723fad32ad --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-16-functions/output.txt @@ -0,0 +1,6 @@ +$ cargo run + Compiling functions v0.1.0 (file:///projects/functions) + Finished dev [unoptimized + debuginfo] target(s) in 0.28s + Running `target/debug/functions` +Hello, world! +Another function. diff --git a/listings/ch03-common-programming-concepts/no-listing-16-functions/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-16-functions/src/main.rs new file mode 100644 index 0000000000..38be8565bf --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-16-functions/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + println!("Hello, world!"); + + another_function(); +} + +fn another_function() { + println!("Another function."); +} diff --git a/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/Cargo.lock new file mode 100644 index 0000000000..88287d1363 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/Cargo.toml new file mode 100644 index 0000000000..291680cf8f --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/output.txt b/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/output.txt new file mode 100644 index 0000000000..546bbc0473 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling functions v0.1.0 (file:///projects/functions) + Finished dev [unoptimized + debuginfo] target(s) in 1.21s + Running `target/debug/functions` +The value of x is: 5 diff --git a/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/src/main.rs new file mode 100644 index 0000000000..029446c044 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + another_function(5); +} + +fn another_function(x: i32) { + println!("The value of x is: {}", x); +} diff --git a/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/Cargo.lock new file mode 100644 index 0000000000..88287d1363 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/Cargo.toml new file mode 100644 index 0000000000..291680cf8f --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/output.txt b/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/output.txt new file mode 100644 index 0000000000..d651191cd4 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/output.txt @@ -0,0 +1,6 @@ +$ cargo run + Compiling functions v0.1.0 (file:///projects/functions) + Finished dev [unoptimized + debuginfo] target(s) in 0.31s + Running `target/debug/functions` +The value of x is: 5 +The value of y is: 6 diff --git a/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/src/main.rs new file mode 100644 index 0000000000..fe476db0a8 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + another_function(5, 6); +} + +fn another_function(x: i32, y: i32) { + println!("The value of x is: {}", x); + println!("The value of y is: {}", y); +} diff --git a/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/Cargo.lock new file mode 100644 index 0000000000..89a654d696 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "functions" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/Cargo.toml new file mode 100644 index 0000000000..291680cf8f --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/rustfmt-ignore b/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/rustfmt-ignore new file mode 100644 index 0000000000..06a976dd46 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/rustfmt-ignore @@ -0,0 +1 @@ +This listing deliberately doesn't parse so rustfmt fails. diff --git a/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/src/main.rs new file mode 100644 index 0000000000..988f9653ed --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + let x = (let y = 6); +} diff --git a/listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/Cargo.lock new file mode 100644 index 0000000000..88287d1363 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/Cargo.toml new file mode 100644 index 0000000000..291680cf8f --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/src/main.rs new file mode 100644 index 0000000000..baa853e187 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + let x = 5; + + let y = { + let x = 3; + x + 1 + }; + + println!("The value of y is: {}", y); +} diff --git a/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/Cargo.lock new file mode 100644 index 0000000000..88287d1363 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/Cargo.toml new file mode 100644 index 0000000000..291680cf8f --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/output.txt b/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/output.txt new file mode 100644 index 0000000000..a457e33996 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling functions v0.1.0 (file:///projects/functions) + Finished dev [unoptimized + debuginfo] target(s) in 0.30s + Running `target/debug/functions` +The value of x is: 5 diff --git a/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/src/main.rs new file mode 100644 index 0000000000..5303b10827 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/src/main.rs @@ -0,0 +1,9 @@ +fn five() -> i32 { + 5 +} + +fn main() { + let x = five(); + + println!("The value of x is: {}", x); +} diff --git a/listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/Cargo.lock new file mode 100644 index 0000000000..88287d1363 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/Cargo.toml new file mode 100644 index 0000000000..291680cf8f --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/src/main.rs new file mode 100644 index 0000000000..b4c84437a9 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let x = plus_one(5); + + println!("The value of x is: {}", x); +} + +fn plus_one(x: i32) -> i32 { + x + 1 +} diff --git a/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/Cargo.lock new file mode 100644 index 0000000000..88287d1363 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/Cargo.toml new file mode 100644 index 0000000000..291680cf8f --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/output.txt b/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/output.txt new file mode 100644 index 0000000000..3104740410 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/output.txt @@ -0,0 +1,21 @@ +$ 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: consider removing this semicolon + | + = note: expected type `i32` + found type `()` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. +error: could not compile `functions`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/src/main.rs new file mode 100644 index 0000000000..c9c4edc190 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let x = plus_one(5); + + println!("The value of x is: {}", x); +} + +fn plus_one(x: i32) -> i32 { + x + 1; +} diff --git a/listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/Cargo.lock new file mode 100644 index 0000000000..a289136a62 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "comments" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/Cargo.toml new file mode 100644 index 0000000000..c53d87571f --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "comments" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/src/main.rs new file mode 100644 index 0000000000..535f4b993b --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + let lucky_number = 7; // I’m feeling lucky today +} diff --git a/listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/Cargo.lock new file mode 100644 index 0000000000..a289136a62 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "comments" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/Cargo.toml new file mode 100644 index 0000000000..c53d87571f --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "comments" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/src/main.rs new file mode 100644 index 0000000000..81cd935591 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/src/main.rs @@ -0,0 +1,4 @@ +fn main() { + // I’m feeling lucky today + let lucky_number = 7; +} diff --git a/listings/ch03-common-programming-concepts/no-listing-26-if-true/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-26-if-true/Cargo.lock new file mode 100644 index 0000000000..4ca0c2dbdb --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-26-if-true/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "branches" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-26-if-true/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-26-if-true/Cargo.toml new file mode 100644 index 0000000000..8ddf691495 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-26-if-true/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "branches" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-26-if-true/output.txt b/listings/ch03-common-programming-concepts/no-listing-26-if-true/output.txt new file mode 100644 index 0000000000..3d8c7dc333 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-26-if-true/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling branches v0.1.0 (file:///projects/branches) + Finished dev [unoptimized + debuginfo] target(s) in 0.31s + Running `target/debug/branches` +condition was true diff --git a/listings/ch03-common-programming-concepts/no-listing-26-if-true/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-26-if-true/src/main.rs new file mode 100644 index 0000000000..e64a42adf7 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-26-if-true/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let number = 3; + + if number < 5 { + println!("condition was true"); + } else { + println!("condition was false"); + } +} diff --git a/listings/ch03-common-programming-concepts/no-listing-27-if-false/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-27-if-false/Cargo.lock new file mode 100644 index 0000000000..4ca0c2dbdb --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-27-if-false/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "branches" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-27-if-false/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-27-if-false/Cargo.toml new file mode 100644 index 0000000000..8ddf691495 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-27-if-false/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "branches" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-27-if-false/output.txt b/listings/ch03-common-programming-concepts/no-listing-27-if-false/output.txt new file mode 100644 index 0000000000..e40da961c9 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-27-if-false/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling branches v0.1.0 (file:///projects/branches) + Finished dev [unoptimized + debuginfo] target(s) in 0.31s + Running `target/debug/branches` +condition was false diff --git a/listings/ch03-common-programming-concepts/no-listing-27-if-false/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-27-if-false/src/main.rs new file mode 100644 index 0000000000..f7d76cf558 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-27-if-false/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let number = 7; + // ANCHOR_END: here + + if number < 5 { + println!("condition was true"); + } else { + println!("condition was false"); + } +} diff --git a/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/Cargo.lock new file mode 100644 index 0000000000..4ca0c2dbdb --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "branches" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/Cargo.toml new file mode 100644 index 0000000000..8ddf691495 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "branches" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/output.txt b/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/output.txt new file mode 100644 index 0000000000..304f3140a8 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/output.txt @@ -0,0 +1,17 @@ +$ 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 + | + = note: expected type `bool` + found type `{integer}` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. +error: could not compile `branches`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/src/main.rs new file mode 100644 index 0000000000..bc4af767b1 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + let number = 3; + + if number { + println!("number was three"); + } +} diff --git a/listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/Cargo.lock new file mode 100644 index 0000000000..4ca0c2dbdb --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "branches" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/Cargo.toml new file mode 100644 index 0000000000..8ddf691495 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "branches" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/src/main.rs new file mode 100644 index 0000000000..704650f467 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + let number = 3; + + if number != 0 { + println!("number was something other than zero"); + } +} diff --git a/listings/ch03-common-programming-concepts/no-listing-30-else-if/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-30-else-if/Cargo.lock new file mode 100644 index 0000000000..4ca0c2dbdb --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-30-else-if/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "branches" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-30-else-if/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-30-else-if/Cargo.toml new file mode 100644 index 0000000000..8ddf691495 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-30-else-if/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "branches" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-30-else-if/output.txt b/listings/ch03-common-programming-concepts/no-listing-30-else-if/output.txt new file mode 100644 index 0000000000..b218941ad0 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-30-else-if/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling branches v0.1.0 (file:///projects/branches) + Finished dev [unoptimized + debuginfo] target(s) in 0.31s + Running `target/debug/branches` +number is divisible by 3 diff --git a/listings/ch03-common-programming-concepts/no-listing-30-else-if/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-30-else-if/src/main.rs new file mode 100644 index 0000000000..d0ef9b2c15 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-30-else-if/src/main.rs @@ -0,0 +1,13 @@ +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"); + } +} diff --git a/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/Cargo.lock new file mode 100644 index 0000000000..4ca0c2dbdb --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "branches" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/Cargo.toml new file mode 100644 index 0000000000..8ddf691495 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "branches" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/output.txt b/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/output.txt new file mode 100644 index 0000000000..db77c62744 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/output.txt @@ -0,0 +1,19 @@ +$ 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 + | + = note: expected type `{integer}` + found type `&str` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. +error: could not compile `branches`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/src/main.rs new file mode 100644 index 0000000000..440b286f5e --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + let condition = true; + + let number = if condition { 5 } else { "six" }; + + println!("The value of number is: {}", number); +} diff --git a/listings/ch03-common-programming-concepts/no-listing-32-loop/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-32-loop/Cargo.lock new file mode 100644 index 0000000000..9942b362ac --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-32-loop/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "loops" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-32-loop/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-32-loop/Cargo.toml new file mode 100644 index 0000000000..b5ed848ab4 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-32-loop/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "loops" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-32-loop/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-32-loop/src/main.rs new file mode 100644 index 0000000000..f1692e4625 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-32-loop/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + loop { + println!("again!"); + } +} diff --git a/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/Cargo.lock new file mode 100644 index 0000000000..9942b362ac --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "loops" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/Cargo.toml new file mode 100644 index 0000000000..b5ed848ab4 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "loops" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/src/main.rs new file mode 100644 index 0000000000..6ffdab5a4b --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + let mut counter = 0; + + let result = loop { + counter += 1; + + if counter == 10 { + break counter * 2; + } + }; + + println!("The result is {}", result); +} diff --git a/listings/ch03-common-programming-concepts/no-listing-34-for-range/Cargo.lock b/listings/ch03-common-programming-concepts/no-listing-34-for-range/Cargo.lock new file mode 100644 index 0000000000..9942b362ac --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-34-for-range/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "loops" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/no-listing-34-for-range/Cargo.toml b/listings/ch03-common-programming-concepts/no-listing-34-for-range/Cargo.toml new file mode 100644 index 0000000000..b5ed848ab4 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-34-for-range/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "loops" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/no-listing-34-for-range/src/main.rs b/listings/ch03-common-programming-concepts/no-listing-34-for-range/src/main.rs new file mode 100644 index 0000000000..e7286a84e4 --- /dev/null +++ b/listings/ch03-common-programming-concepts/no-listing-34-for-range/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + for number in (1..4).rev() { + println!("{}!", number); + } + println!("LIFTOFF!!!"); +} diff --git a/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/Cargo.lock b/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/Cargo.lock new file mode 100644 index 0000000000..b5664bc336 --- /dev/null +++ b/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "no_type_annotations" +version = "0.1.0" + diff --git a/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/Cargo.toml b/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/Cargo.toml new file mode 100644 index 0000000000..964f9e8e23 --- /dev/null +++ b/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "no_type_annotations" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/output.txt b/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/output.txt new file mode 100644 index 0000000000..5b00236206 --- /dev/null +++ b/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/output.txt @@ -0,0 +1,14 @@ +$ cargo build + Compiling no_type_annotations v0.1.0 (file:///projects/no_type_annotations) +error[E0282]: type annotations needed + --> src/main.rs:2:9 + | +2 | let guess = "42".parse().expect("Not a number!"); + | ^^^^^ consider giving `guess` a type + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0282`. +error: could not compile `no_type_annotations`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/src/main.rs b/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/src/main.rs new file mode 100644 index 0000000000..f41c55805f --- /dev/null +++ b/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + let guess = "42".parse().expect("Not a number!"); +} diff --git a/listings/ch04-understanding-ownership/listing-04-01/Cargo.lock b/listings/ch04-understanding-ownership/listing-04-01/Cargo.lock new file mode 100644 index 0000000000..9e4e62ddf5 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-01/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/listing-04-01/Cargo.toml b/listings/ch04-understanding-ownership/listing-04-01/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/listing-04-01/rustfmt-ignore b/listings/ch04-understanding-ownership/listing-04-01/rustfmt-ignore new file mode 100644 index 0000000000..9a53c718a8 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-01/rustfmt-ignore @@ -0,0 +1,3 @@ +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 diff --git a/listings/ch04-understanding-ownership/listing-04-01/src/main.rs b/listings/ch04-understanding-ownership/listing-04-01/src/main.rs new file mode 100644 index 0000000000..148ad84c97 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-01/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + // ANCHOR: here + { // s is not valid here, 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 +} \ No newline at end of file diff --git a/listings/ch04-understanding-ownership/listing-04-02/Cargo.lock b/listings/ch04-understanding-ownership/listing-04-02/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/listing-04-02/Cargo.toml b/listings/ch04-understanding-ownership/listing-04-02/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/listing-04-02/src/main.rs b/listings/ch04-understanding-ownership/listing-04-02/src/main.rs new file mode 100644 index 0000000000..de0f1b3251 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-02/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + // ANCHOR: here + let x = 5; + let y = x; + // ANCHOR_END: here +} diff --git a/listings/ch04-understanding-ownership/listing-04-03/Cargo.lock b/listings/ch04-understanding-ownership/listing-04-03/Cargo.lock new file mode 100644 index 0000000000..9e4e62ddf5 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-03/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/listing-04-03/Cargo.toml b/listings/ch04-understanding-ownership/listing-04-03/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/listing-04-03/rustfmt-ignore b/listings/ch04-understanding-ownership/listing-04-03/rustfmt-ignore new file mode 100644 index 0000000000..9a53c718a8 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-03/rustfmt-ignore @@ -0,0 +1,3 @@ +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 diff --git a/listings/ch04-understanding-ownership/listing-04-03/src/main.rs b/listings/ch04-understanding-ownership/listing-04-03/src/main.rs new file mode 100644 index 0000000000..23906b4306 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-03/src/main.rs @@ -0,0 +1,23 @@ +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); // x would move into the function, + // but i32 is Copy, so it’s okay to still + // use x afterward + +} // Here, x goes out of scope, then s. But 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. diff --git a/listings/ch04-understanding-ownership/listing-04-04/Cargo.lock b/listings/ch04-understanding-ownership/listing-04-04/Cargo.lock new file mode 100644 index 0000000000..9e4e62ddf5 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-04/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/listing-04-04/Cargo.toml b/listings/ch04-understanding-ownership/listing-04-04/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/listing-04-04/rustfmt-ignore b/listings/ch04-understanding-ownership/listing-04-04/rustfmt-ignore new file mode 100644 index 0000000000..9a53c718a8 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-04/rustfmt-ignore @@ -0,0 +1,3 @@ +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 diff --git a/listings/ch04-understanding-ownership/listing-04-04/src/main.rs b/listings/ch04-understanding-ownership/listing-04-04/src/main.rs new file mode 100644 index 0000000000..e3e54a8181 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-04/src/main.rs @@ -0,0 +1,29 @@ +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 goes out of scope but 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("hello"); // some_string comes into scope + + some_string // some_string is returned and + // moves out to the calling + // function +} + +// takes_and_gives_back will take a String and return one +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 +} diff --git a/listings/ch04-understanding-ownership/listing-04-05/Cargo.lock b/listings/ch04-understanding-ownership/listing-04-05/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/listing-04-05/Cargo.toml b/listings/ch04-understanding-ownership/listing-04-05/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/listing-04-05/src/main.rs b/listings/ch04-understanding-ownership/listing-04-05/src/main.rs new file mode 100644 index 0000000000..22aee1419e --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-05/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + let s1 = String::from("hello"); + + let (s2, len) = calculate_length(s1); + + println!("The length of '{}' is {}.", s2, len); +} + +fn calculate_length(s: String) -> (String, usize) { + let length = s.len(); // len() returns the length of a String + + (s, length) +} diff --git a/listings/ch04-understanding-ownership/listing-04-06/Cargo.lock b/listings/ch04-understanding-ownership/listing-04-06/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/listing-04-06/Cargo.toml b/listings/ch04-understanding-ownership/listing-04-06/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/listing-04-06/output.txt b/listings/ch04-understanding-ownership/listing-04-06/output.txt new file mode 100644 index 0000000000..98f438f614 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-06/output.txt @@ -0,0 +1,16 @@ +$ 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 + | +7 | fn change(some_string: &String) { + | ------- help: consider changing this to be a mutable reference: `&mut std::string::String` +8 | some_string.push_str(", world"); + | ^^^^^^^^^^^ `some_string` is a `&` reference, so the data it refers to cannot be borrowed as mutable + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0596`. +error: could not compile `ownership`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch04-understanding-ownership/listing-04-06/src/main.rs b/listings/ch04-understanding-ownership/listing-04-06/src/main.rs new file mode 100644 index 0000000000..330ffa68ab --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-06/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let s = String::from("hello"); + + change(&s); +} + +fn change(some_string: &String) { + some_string.push_str(", world"); +} diff --git a/listings/ch04-understanding-ownership/listing-04-07/Cargo.lock b/listings/ch04-understanding-ownership/listing-04-07/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/listing-04-07/Cargo.toml b/listings/ch04-understanding-ownership/listing-04-07/Cargo.toml new file mode 100644 index 0000000000..dddcb5a141 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Carol (Nichols || Goulding) "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/listing-04-07/src/main.rs b/listings/ch04-understanding-ownership/listing-04-07/src/main.rs new file mode 100644 index 0000000000..3bb3c8580d --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-07/src/main.rs @@ -0,0 +1,21 @@ +// 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() {} diff --git a/listings/ch04-understanding-ownership/listing-04-08/Cargo.lock b/listings/ch04-understanding-ownership/listing-04-08/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/listing-04-08/Cargo.toml b/listings/ch04-understanding-ownership/listing-04-08/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/listing-04-08/src/main.rs b/listings/ch04-understanding-ownership/listing-04-08/src/main.rs new file mode 100644 index 0000000000..b6182fe2b7 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-08/src/main.rs @@ -0,0 +1,24 @@ +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 there's no more string that + // we could meaningfully use the value 5 with. word is now totally invalid! +} +// ANCHOR_END: here diff --git a/listings/ch04-understanding-ownership/listing-04-09/Cargo.lock b/listings/ch04-understanding-ownership/listing-04-09/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/listing-04-09/Cargo.toml b/listings/ch04-understanding-ownership/listing-04-09/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/listing-04-09/src/main.rs b/listings/ch04-understanding-ownership/listing-04-09/src/main.rs new file mode 100644 index 0000000000..19a9cc74b6 --- /dev/null +++ b/listings/ch04-understanding-ownership/listing-04-09/src/main.rs @@ -0,0 +1,31 @@ +// 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 + let word = first_word(&my_string[..]); + + let my_string_literal = "hello world"; + + // first_word works on slices of string literals + 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 diff --git a/listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/Cargo.lock b/listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/Cargo.toml b/listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/src/main.rs b/listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/src/main.rs new file mode 100644 index 0000000000..b68f0f1e78 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/src/main.rs @@ -0,0 +1,9 @@ +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 +} diff --git a/listings/ch04-understanding-ownership/no-listing-02-string-scope/Cargo.lock b/listings/ch04-understanding-ownership/no-listing-02-string-scope/Cargo.lock new file mode 100644 index 0000000000..9e4e62ddf5 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-02-string-scope/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/no-listing-02-string-scope/Cargo.toml b/listings/ch04-understanding-ownership/no-listing-02-string-scope/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-02-string-scope/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/no-listing-02-string-scope/rustfmt-ignore b/listings/ch04-understanding-ownership/no-listing-02-string-scope/rustfmt-ignore new file mode 100644 index 0000000000..9a53c718a8 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-02-string-scope/rustfmt-ignore @@ -0,0 +1,3 @@ +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 diff --git a/listings/ch04-understanding-ownership/no-listing-02-string-scope/src/main.rs b/listings/ch04-understanding-ownership/no-listing-02-string-scope/src/main.rs new file mode 100644 index 0000000000..7e6d46f836 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-02-string-scope/src/main.rs @@ -0,0 +1,10 @@ +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 +} diff --git a/listings/ch04-understanding-ownership/no-listing-03-string-move/Cargo.lock b/listings/ch04-understanding-ownership/no-listing-03-string-move/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-03-string-move/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/no-listing-03-string-move/Cargo.toml b/listings/ch04-understanding-ownership/no-listing-03-string-move/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-03-string-move/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/no-listing-03-string-move/src/main.rs b/listings/ch04-understanding-ownership/no-listing-03-string-move/src/main.rs new file mode 100644 index 0000000000..a5817e714b --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-03-string-move/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + // ANCHOR: here + let s1 = String::from("hello"); + let s2 = s1; + // ANCHOR_END: here +} diff --git a/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/Cargo.lock b/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/Cargo.toml b/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/output.txt b/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/output.txt new file mode 100644 index 0000000000..910332ac13 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/output.txt @@ -0,0 +1,19 @@ +$ cargo run + Compiling ownership v0.1.0 (file:///projects/ownership) +error[E0382]: borrow of moved value: `s1` + --> src/main.rs:5:28 + | +2 | let s1 = String::from("hello"); + | -- move occurs because `s1` has type `std::string::String`, which does not implement the `Copy` trait +3 | let s2 = s1; + | -- value moved here +4 | +5 | println!("{}, world!", s1); + | ^^ value borrowed here after move + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0382`. +error: could not compile `ownership`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/src/main.rs b/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/src/main.rs new file mode 100644 index 0000000000..d0b9f18795 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let s1 = String::from("hello"); + let s2 = s1; + + println!("{}, world!", s1); + // ANCHOR_END: here +} diff --git a/listings/ch04-understanding-ownership/no-listing-05-clone/Cargo.lock b/listings/ch04-understanding-ownership/no-listing-05-clone/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-05-clone/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/no-listing-05-clone/Cargo.toml b/listings/ch04-understanding-ownership/no-listing-05-clone/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-05-clone/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/no-listing-05-clone/src/main.rs b/listings/ch04-understanding-ownership/no-listing-05-clone/src/main.rs new file mode 100644 index 0000000000..4e61cc1a16 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-05-clone/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let s1 = String::from("hello"); + let s2 = s1.clone(); + + println!("s1 = {}, s2 = {}", s1, s2); + // ANCHOR_END: here +} diff --git a/listings/ch04-understanding-ownership/no-listing-06-copy/Cargo.lock b/listings/ch04-understanding-ownership/no-listing-06-copy/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-06-copy/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/no-listing-06-copy/Cargo.toml b/listings/ch04-understanding-ownership/no-listing-06-copy/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-06-copy/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/no-listing-06-copy/src/main.rs b/listings/ch04-understanding-ownership/no-listing-06-copy/src/main.rs new file mode 100644 index 0000000000..63a1fae248 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-06-copy/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let x = 5; + let y = x; + + println!("x = {}, y = {}", x, y); + // ANCHOR_END: here +} diff --git a/listings/ch04-understanding-ownership/no-listing-07-reference/Cargo.lock b/listings/ch04-understanding-ownership/no-listing-07-reference/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-07-reference/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/no-listing-07-reference/Cargo.toml b/listings/ch04-understanding-ownership/no-listing-07-reference/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-07-reference/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/no-listing-07-reference/src/main.rs b/listings/ch04-understanding-ownership/no-listing-07-reference/src/main.rs new file mode 100644 index 0000000000..fd32a5fc95 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-07-reference/src/main.rs @@ -0,0 +1,15 @@ +// ANCHOR: all +fn main() { + // ANCHOR: here + let s1 = String::from("hello"); + + let len = calculate_length(&s1); + // ANCHOR_END: here + + println!("The length of '{}' is {}.", s1, len); +} + +fn calculate_length(s: &String) -> usize { + s.len() +} +// ANCHOR_END: all diff --git a/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/Cargo.lock b/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/Cargo.lock new file mode 100644 index 0000000000..9e4e62ddf5 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/Cargo.toml b/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/rustfmt-ignore b/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/rustfmt-ignore new file mode 100644 index 0000000000..9a53c718a8 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/rustfmt-ignore @@ -0,0 +1,3 @@ +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 diff --git a/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/src/main.rs b/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/src/main.rs new file mode 100644 index 0000000000..6e40b8c300 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/src/main.rs @@ -0,0 +1,14 @@ +fn main() { + let s1 = String::from("hello"); + + let len = calculate_length(&s1); + + println!("The length of '{}' is {}.", s1, 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 it does not have ownership of what + // it refers to, nothing happens. +// ANCHOR_END: here diff --git a/listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/Cargo.lock b/listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/Cargo.toml b/listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/src/main.rs b/listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/src/main.rs new file mode 100644 index 0000000000..fdf7f0a6f4 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let mut s = String::from("hello"); + + change(&mut s); +} + +fn change(some_string: &mut String) { + some_string.push_str(", world"); +} diff --git a/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/Cargo.lock b/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/Cargo.toml b/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/output.txt b/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/output.txt new file mode 100644 index 0000000000..cb69a714b3 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/output.txt @@ -0,0 +1,19 @@ +$ 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 + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0499`. +error: could not compile `ownership`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/src/main.rs b/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/src/main.rs new file mode 100644 index 0000000000..ddbf8120f9 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + // ANCHOR: here + let mut s = String::from("hello"); + + let r1 = &mut s; + let r2 = &mut s; + + println!("{}, {}", r1, r2); + // ANCHOR_END: here +} diff --git a/listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/Cargo.lock b/listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/Cargo.toml b/listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/src/main.rs b/listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/src/main.rs new file mode 100644 index 0000000000..4b1a5a383d --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/src/main.rs @@ -0,0 +1,11 @@ +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 +} diff --git a/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/Cargo.lock b/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/Cargo.toml b/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/output.txt b/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/output.txt new file mode 100644 index 0000000000..cd4168f8ce --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/output.txt @@ -0,0 +1,20 @@ +$ 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!("{}, {}, and {}", r1, r2, r3); + | -- immutable borrow later used here + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0502`. +error: could not compile `ownership`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/src/main.rs b/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/src/main.rs new file mode 100644 index 0000000000..0da04c010e --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/src/main.rs @@ -0,0 +1,11 @@ +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!("{}, {}, and {}", r1, r2, r3); + // ANCHOR_END: here +} diff --git a/listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/Cargo.lock b/listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/Cargo.toml b/listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/src/main.rs b/listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/src/main.rs new file mode 100644 index 0000000000..3b0a7da659 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + // ANCHOR: here + let mut s = String::from("hello"); + + let r1 = &s; // no problem + let r2 = &s; // no problem + println!("{} and {}", r1, r2); + // r1 and r2 are no longer used after this point + + let r3 = &mut s; // no problem + println!("{}", r3); + // ANCHOR_END: here +} diff --git a/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/Cargo.lock b/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/Cargo.toml b/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/output.txt b/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/output.txt new file mode 100644 index 0000000000..6381d2a305 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/output.txt @@ -0,0 +1,16 @@ +$ cargo run + Compiling ownership v0.1.0 (file:///projects/ownership) +error[E0106]: missing lifetime specifier + --> src/main.rs:5:16 + | +5 | fn dangle() -> &String { + | ^ help: consider giving it a 'static lifetime: `&'static` + | + = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0106`. +error: could not compile `ownership`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/src/main.rs b/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/src/main.rs new file mode 100644 index 0000000000..b102697812 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let reference_to_nothing = dangle(); +} + +fn dangle() -> &String { + let s = String::from("hello"); + + &s +} diff --git a/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/Cargo.lock b/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/Cargo.lock new file mode 100644 index 0000000000..9e4e62ddf5 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/Cargo.toml b/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/rustfmt-ignore b/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/rustfmt-ignore new file mode 100644 index 0000000000..9a53c718a8 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/rustfmt-ignore @@ -0,0 +1,3 @@ +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 diff --git a/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/src/main.rs b/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/src/main.rs new file mode 100644 index 0000000000..9fbb372a05 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/src/main.rs @@ -0,0 +1,13 @@ +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. Its memory goes away. + // Danger! +// ANCHOR_END: here diff --git a/listings/ch04-understanding-ownership/no-listing-16-no-dangle/Cargo.lock b/listings/ch04-understanding-ownership/no-listing-16-no-dangle/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-16-no-dangle/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/no-listing-16-no-dangle/Cargo.toml b/listings/ch04-understanding-ownership/no-listing-16-no-dangle/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-16-no-dangle/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/no-listing-16-no-dangle/src/main.rs b/listings/ch04-understanding-ownership/no-listing-16-no-dangle/src/main.rs new file mode 100644 index 0000000000..9c20a3b2d6 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-16-no-dangle/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + let string = no_dangle(); +} + +// ANCHOR: here +fn no_dangle() -> String { + let s = String::from("hello"); + + s +} +// ANCHOR_END: here diff --git a/listings/ch04-understanding-ownership/no-listing-17-slice/Cargo.lock b/listings/ch04-understanding-ownership/no-listing-17-slice/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-17-slice/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/no-listing-17-slice/Cargo.toml b/listings/ch04-understanding-ownership/no-listing-17-slice/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-17-slice/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/no-listing-17-slice/src/main.rs b/listings/ch04-understanding-ownership/no-listing-17-slice/src/main.rs new file mode 100644 index 0000000000..44163af990 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-17-slice/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let s = String::from("hello world"); + + let hello = &s[0..5]; + let world = &s[6..11]; + // ANCHOR_END: here +} diff --git a/listings/ch04-understanding-ownership/no-listing-18-first-word-slice/Cargo.lock b/listings/ch04-understanding-ownership/no-listing-18-first-word-slice/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-18-first-word-slice/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/no-listing-18-first-word-slice/Cargo.toml b/listings/ch04-understanding-ownership/no-listing-18-first-word-slice/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-18-first-word-slice/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/no-listing-18-first-word-slice/src/main.rs b/listings/ch04-understanding-ownership/no-listing-18-first-word-slice/src/main.rs new file mode 100644 index 0000000000..f44a970daa --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-18-first-word-slice/src/main.rs @@ -0,0 +1,15 @@ +// 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() {} diff --git a/listings/ch04-understanding-ownership/no-listing-19-slice-error/Cargo.lock b/listings/ch04-understanding-ownership/no-listing-19-slice-error/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-19-slice-error/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch04-understanding-ownership/no-listing-19-slice-error/Cargo.toml b/listings/ch04-understanding-ownership/no-listing-19-slice-error/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-19-slice-error/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch04-understanding-ownership/no-listing-19-slice-error/output.txt b/listings/ch04-understanding-ownership/no-listing-19-slice-error/output.txt new file mode 100644 index 0000000000..0e95bb8cd6 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-19-slice-error/output.txt @@ -0,0 +1,20 @@ +$ 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 + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0502`. +error: could not compile `ownership`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch04-understanding-ownership/no-listing-19-slice-error/src/main.rs b/listings/ch04-understanding-ownership/no-listing-19-slice-error/src/main.rs new file mode 100644 index 0000000000..99e04018d2 --- /dev/null +++ b/listings/ch04-understanding-ownership/no-listing-19-slice-error/src/main.rs @@ -0,0 +1,23 @@ +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 diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-01/Cargo.lock b/listings/ch05-using-structs-to-structure-related-data/listing-05-01/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-01/Cargo.toml b/listings/ch05-using-structs-to-structure-related-data/listing-05-01/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-01/src/main.rs b/listings/ch05-using-structs-to-structure-related-data/listing-05-01/src/main.rs new file mode 100644 index 0000000000..a7cff6ec21 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-01/src/main.rs @@ -0,0 +1,10 @@ +// ANCHOR: here +struct User { + username: String, + email: String, + sign_in_count: u64, + active: bool, +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-02/Cargo.lock b/listings/ch05-using-structs-to-structure-related-data/listing-05-02/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-02/Cargo.toml b/listings/ch05-using-structs-to-structure-related-data/listing-05-02/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-02/src/main.rs b/listings/ch05-using-structs-to-structure-related-data/listing-05-02/src/main.rs new file mode 100644 index 0000000000..390c8ff19d --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-02/src/main.rs @@ -0,0 +1,17 @@ +struct User { + username: String, + email: String, + sign_in_count: u64, + active: bool, +} + +fn main() { + // ANCHOR: here + let user1 = User { + email: String::from("someone@example.com"), + username: String::from("someusername123"), + active: true, + sign_in_count: 1, + }; + // ANCHOR_END: here +} diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-03/Cargo.lock b/listings/ch05-using-structs-to-structure-related-data/listing-05-03/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-03/Cargo.toml b/listings/ch05-using-structs-to-structure-related-data/listing-05-03/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-03/src/main.rs b/listings/ch05-using-structs-to-structure-related-data/listing-05-03/src/main.rs new file mode 100644 index 0000000000..c599c9d602 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-03/src/main.rs @@ -0,0 +1,19 @@ +struct User { + username: String, + email: String, + sign_in_count: u64, + active: bool, +} + +fn main() { + // ANCHOR: here + let mut user1 = User { + email: String::from("someone@example.com"), + username: String::from("someusername123"), + active: true, + sign_in_count: 1, + }; + + user1.email = String::from("anotheremail@example.com"); + // ANCHOR_END: here +} diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-04/Cargo.lock b/listings/ch05-using-structs-to-structure-related-data/listing-05-04/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-04/Cargo.toml b/listings/ch05-using-structs-to-structure-related-data/listing-05-04/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-04/src/main.rs b/listings/ch05-using-structs-to-structure-related-data/listing-05-04/src/main.rs new file mode 100644 index 0000000000..f934d4c000 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-04/src/main.rs @@ -0,0 +1,24 @@ +struct User { + username: String, + email: String, + sign_in_count: u64, + active: bool, +} + +// ANCHOR: here +fn build_user(email: String, username: String) -> User { + User { + email: email, + username: username, + active: true, + sign_in_count: 1, + } +} +// ANCHOR_END: here + +fn main() { + let user1 = build_user( + String::from("someone@example.com"), + String::from("someusername123"), + ); +} diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-05/Cargo.lock b/listings/ch05-using-structs-to-structure-related-data/listing-05-05/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-05/Cargo.toml b/listings/ch05-using-structs-to-structure-related-data/listing-05-05/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-05/src/main.rs b/listings/ch05-using-structs-to-structure-related-data/listing-05-05/src/main.rs new file mode 100644 index 0000000000..1833aa8e4d --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-05/src/main.rs @@ -0,0 +1,24 @@ +struct User { + username: String, + email: String, + sign_in_count: u64, + active: bool, +} + +// ANCHOR: here +fn build_user(email: String, username: String) -> User { + User { + email, + username, + active: true, + sign_in_count: 1, + } +} +// ANCHOR_END: here + +fn main() { + let user1 = build_user( + String::from("someone@example.com"), + String::from("someusername123"), + ); +} diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-06/Cargo.lock b/listings/ch05-using-structs-to-structure-related-data/listing-05-06/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-06/Cargo.toml b/listings/ch05-using-structs-to-structure-related-data/listing-05-06/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-06/src/main.rs b/listings/ch05-using-structs-to-structure-related-data/listing-05-06/src/main.rs new file mode 100644 index 0000000000..6c6d83d9be --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-06/src/main.rs @@ -0,0 +1,24 @@ +struct User { + username: String, + email: String, + sign_in_count: u64, + active: bool, +} + +fn main() { + 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"), + username: String::from("anotherusername567"), + active: user1.active, + sign_in_count: user1.sign_in_count, + }; + // ANCHOR_END: here +} diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-07/Cargo.lock b/listings/ch05-using-structs-to-structure-related-data/listing-05-07/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-07/Cargo.toml b/listings/ch05-using-structs-to-structure-related-data/listing-05-07/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-07/src/main.rs b/listings/ch05-using-structs-to-structure-related-data/listing-05-07/src/main.rs new file mode 100644 index 0000000000..17cef457bd --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-07/src/main.rs @@ -0,0 +1,23 @@ +struct User { + username: String, + email: String, + sign_in_count: u64, + active: bool, +} + +fn main() { + 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"), + username: String::from("anotherusername567"), + ..user1 + }; + // ANCHOR_END: here +} diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-08/Cargo.lock b/listings/ch05-using-structs-to-structure-related-data/listing-05-08/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-08/Cargo.toml b/listings/ch05-using-structs-to-structure-related-data/listing-05-08/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-08/output.txt b/listings/ch05-using-structs-to-structure-related-data/listing-05-08/output.txt new file mode 100644 index 0000000000..88e10d320a --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-08/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling structs v0.1.0 (file:///projects/structs) + Finished dev [unoptimized + debuginfo] target(s) in 0.42s + Running `target/debug/structs` +The area of the rectangle is 1500 square pixels. diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-08/src/main.rs b/listings/ch05-using-structs-to-structure-related-data/listing-05-08/src/main.rs new file mode 100644 index 0000000000..f324529fdc --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-08/src/main.rs @@ -0,0 +1,17 @@ +// 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 diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-09/Cargo.lock b/listings/ch05-using-structs-to-structure-related-data/listing-05-09/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-09/Cargo.toml b/listings/ch05-using-structs-to-structure-related-data/listing-05-09/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-09/src/main.rs b/listings/ch05-using-structs-to-structure-related-data/listing-05-09/src/main.rs new file mode 100644 index 0000000000..d4b77ba7ad --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-09/src/main.rs @@ -0,0 +1,12 @@ +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 +} diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-10/Cargo.lock b/listings/ch05-using-structs-to-structure-related-data/listing-05-10/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-10/Cargo.toml b/listings/ch05-using-structs-to-structure-related-data/listing-05-10/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-10/src/main.rs b/listings/ch05-using-structs-to-structure-related-data/listing-05-10/src/main.rs new file mode 100644 index 0000000000..62ef9acd82 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-10/src/main.rs @@ -0,0 +1,20 @@ +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 +} diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-11/Cargo.lock b/listings/ch05-using-structs-to-structure-related-data/listing-05-11/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-11/Cargo.toml b/listings/ch05-using-structs-to-structure-related-data/listing-05-11/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-11/output.txt b/listings/ch05-using-structs-to-structure-related-data/listing-05-11/output.txt new file mode 100644 index 0000000000..1e03d06259 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-11/output.txt @@ -0,0 +1,18 @@ +$ cargo run + Compiling structs v0.1.0 (file:///projects/structs) +error[E0277]: `Rectangle` doesn't implement `std::fmt::Display` + --> src/main.rs:12:29 + | +12 | println!("rect1 is {}", rect1); + | ^^^^^ `Rectangle` cannot be formatted with the default formatter + | + = 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: required by `std::fmt::Display::fmt` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. +error: could not compile `structs`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-11/src/main.rs b/listings/ch05-using-structs-to-structure-related-data/listing-05-11/src/main.rs new file mode 100644 index 0000000000..0ff8dcc8cc --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-11/src/main.rs @@ -0,0 +1,13 @@ +struct Rectangle { + width: u32, + height: u32, +} + +fn main() { + let rect1 = Rectangle { + width: 30, + height: 50, + }; + + println!("rect1 is {}", rect1); +} diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-12/Cargo.lock b/listings/ch05-using-structs-to-structure-related-data/listing-05-12/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-12/Cargo.toml b/listings/ch05-using-structs-to-structure-related-data/listing-05-12/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-12/output.txt b/listings/ch05-using-structs-to-structure-related-data/listing-05-12/output.txt new file mode 100644 index 0000000000..3abfb42574 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-12/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling structs v0.1.0 (file:///projects/structs) + Finished dev [unoptimized + debuginfo] target(s) in 0.48s + Running `target/debug/structs` +rect1 is Rectangle { width: 30, height: 50 } diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-12/src/main.rs b/listings/ch05-using-structs-to-structure-related-data/listing-05-12/src/main.rs new file mode 100644 index 0000000000..2ffc4b8e7b --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-12/src/main.rs @@ -0,0 +1,14 @@ +#[derive(Debug)] +struct Rectangle { + width: u32, + height: u32, +} + +fn main() { + let rect1 = Rectangle { + width: 30, + height: 50, + }; + + println!("rect1 is {:?}", rect1); +} diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-13/Cargo.lock b/listings/ch05-using-structs-to-structure-related-data/listing-05-13/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-13/Cargo.toml b/listings/ch05-using-structs-to-structure-related-data/listing-05-13/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-13/src/main.rs b/listings/ch05-using-structs-to-structure-related-data/listing-05-13/src/main.rs new file mode 100644 index 0000000000..e4f45e868c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-13/src/main.rs @@ -0,0 +1,23 @@ +#[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() + ); +} diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-14/Cargo.lock b/listings/ch05-using-structs-to-structure-related-data/listing-05-14/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-14/Cargo.toml b/listings/ch05-using-structs-to-structure-related-data/listing-05-14/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-14/src/main.rs b/listings/ch05-using-structs-to-structure-related-data/listing-05-14/src/main.rs new file mode 100644 index 0000000000..843dab4815 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-14/src/main.rs @@ -0,0 +1,17 @@ +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)); +} diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-15/Cargo.lock b/listings/ch05-using-structs-to-structure-related-data/listing-05-15/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-15/Cargo.toml b/listings/ch05-using-structs-to-structure-related-data/listing-05-15/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-15/src/main.rs b/listings/ch05-using-structs-to-structure-related-data/listing-05-15/src/main.rs new file mode 100644 index 0000000000..e6a32723f1 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-15/src/main.rs @@ -0,0 +1,35 @@ +#[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)); +} diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-16/Cargo.lock b/listings/ch05-using-structs-to-structure-related-data/listing-05-16/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-16/Cargo.toml b/listings/ch05-using-structs-to-structure-related-data/listing-05-16/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch05-using-structs-to-structure-related-data/listing-05-16/src/main.rs b/listings/ch05-using-structs-to-structure-related-data/listing-05-16/src/main.rs new file mode 100644 index 0000000000..a5d3f772a8 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/listing-05-16/src/main.rs @@ -0,0 +1,37 @@ +#[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)); +} diff --git a/listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/Cargo.lock b/listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/Cargo.toml b/listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/src/main.rs b/listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/src/main.rs new file mode 100644 index 0000000000..4c92c5d778 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + // ANCHOR: here + struct Color(i32, i32, i32); + struct Point(i32, i32, i32); + + let black = Color(0, 0, 0); + let origin = Point(0, 0, 0); + // ANCHOR_END: here +} diff --git a/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/Cargo.lock b/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/Cargo.toml b/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/Cargo.toml new file mode 100644 index 0000000000..dec1c4bd58 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/output.txt b/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/output.txt new file mode 100644 index 0000000000..9a75534c3b --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/output.txt @@ -0,0 +1,20 @@ +$ cargo run + Compiling structs v0.1.0 (file:///projects/structs) +error[E0106]: missing lifetime specifier + --> src/main.rs:2:15 + | +2 | username: &str, + | ^ expected lifetime parameter + +error[E0106]: missing lifetime specifier + --> src/main.rs:3:12 + | +3 | email: &str, + | ^ expected lifetime parameter + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0106`. +error: could not compile `structs`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/src/main.rs b/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/src/main.rs new file mode 100644 index 0000000000..3cf6ffa4fc --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/src/main.rs @@ -0,0 +1,15 @@ +struct User { + username: &str, + email: &str, + sign_in_count: u64, + active: bool, +} + +fn main() { + let user1 = User { + email: "someone@example.com", + username: "someusername123", + active: true, + sign_in_count: 1, + }; +} diff --git a/listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/Cargo.lock b/listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/Cargo.toml b/listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/src/main.rs b/listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/src/main.rs new file mode 100644 index 0000000000..d5b1692a4f --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/src/main.rs @@ -0,0 +1,20 @@ +#[derive(Debug)] +struct Rectangle { + width: u32, + height: u32, +} + +// ANCHOR: here +impl Rectangle { + fn square(size: u32) -> Rectangle { + Rectangle { + width: size, + height: size, + } + } +} +// ANCHOR_END: here + +fn main() { + let sq = Rectangle::square(3); +} diff --git a/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/Cargo.lock b/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/Cargo.toml b/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/output.txt b/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/output.txt new file mode 100644 index 0000000000..c891d9342b --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/output.txt @@ -0,0 +1,18 @@ +$ cargo run + Compiling structs v0.1.0 (file:///projects/structs) +error[E0277]: `Rectangle` doesn't implement `std::fmt::Debug` + --> src/main.rs:12:31 + | +12 | println!("rect1 is {:?}", rect1); + | ^^^^^ `Rectangle` cannot be formatted using `{:?}` + | + = help: the trait `std::fmt::Debug` is not implemented for `Rectangle` + = note: add `#[derive(Debug)]` or manually implement `std::fmt::Debug` + = note: required by `std::fmt::Debug::fmt` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. +error: could not compile `structs`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/src/main.rs b/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/src/main.rs new file mode 100644 index 0000000000..019a357ab9 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/src/main.rs @@ -0,0 +1,13 @@ +struct Rectangle { + width: u32, + height: u32, +} + +fn main() { + let rect1 = Rectangle { + width: 30, + height: 50, + }; + + println!("rect1 is {:?}", rect1); +} diff --git a/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/Cargo.lock b/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/Cargo.toml b/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/output.txt b/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/output.txt new file mode 100644 index 0000000000..099ef9eac4 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/output.txt @@ -0,0 +1,8 @@ +$ cargo run + Compiling structs v0.1.0 (file:///projects/structs) + Finished dev [unoptimized + debuginfo] target(s) in 0.48s + Running `target/debug/structs` +rect1 is Rectangle { + width: 30, + height: 50, +} diff --git a/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/src/main.rs b/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/src/main.rs new file mode 100644 index 0000000000..84e32aee49 --- /dev/null +++ b/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/src/main.rs @@ -0,0 +1,14 @@ +#[derive(Debug)] +struct Rectangle { + width: u32, + height: u32, +} + +fn main() { + let rect1 = Rectangle { + width: 30, + height: 50, + }; + + println!("rect1 is {:#?}", rect1); +} diff --git a/listings/ch06-enums-and-pattern-matching/listing-06-01/Cargo.lock b/listings/ch06-enums-and-pattern-matching/listing-06-01/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/listing-06-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/listings/ch06-enums-and-pattern-matching/listing-06-01/Cargo.toml b/listings/ch06-enums-and-pattern-matching/listing-06-01/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/listing-06-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch06-enums-and-pattern-matching/listing-06-01/src/main.rs b/listings/ch06-enums-and-pattern-matching/listing-06-01/src/main.rs new file mode 100644 index 0000000000..5b688e0f21 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/listing-06-01/src/main.rs @@ -0,0 +1,23 @@ +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 +} diff --git a/listings/ch06-enums-and-pattern-matching/listing-06-02/Cargo.lock b/listings/ch06-enums-and-pattern-matching/listing-06-02/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/listing-06-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/listings/ch06-enums-and-pattern-matching/listing-06-02/Cargo.toml b/listings/ch06-enums-and-pattern-matching/listing-06-02/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/listing-06-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch06-enums-and-pattern-matching/listing-06-02/src/main.rs b/listings/ch06-enums-and-pattern-matching/listing-06-02/src/main.rs new file mode 100644 index 0000000000..3ba749788a --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/listing-06-02/src/main.rs @@ -0,0 +1,10 @@ +// ANCHOR: here +enum Message { + Quit, + Move { x: i32, y: i32 }, + Write(String), + ChangeColor(i32, i32, i32), +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch06-enums-and-pattern-matching/listing-06-03/Cargo.lock b/listings/ch06-enums-and-pattern-matching/listing-06-03/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/listing-06-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/listings/ch06-enums-and-pattern-matching/listing-06-03/Cargo.toml b/listings/ch06-enums-and-pattern-matching/listing-06-03/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/listing-06-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch06-enums-and-pattern-matching/listing-06-03/src/main.rs b/listings/ch06-enums-and-pattern-matching/listing-06-03/src/main.rs new file mode 100644 index 0000000000..93dce48cb4 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/listing-06-03/src/main.rs @@ -0,0 +1,19 @@ +// 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() {} diff --git a/listings/ch06-enums-and-pattern-matching/listing-06-04/Cargo.lock b/listings/ch06-enums-and-pattern-matching/listing-06-04/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/listing-06-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/listings/ch06-enums-and-pattern-matching/listing-06-04/Cargo.toml b/listings/ch06-enums-and-pattern-matching/listing-06-04/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/listing-06-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch06-enums-and-pattern-matching/listing-06-04/src/main.rs b/listings/ch06-enums-and-pattern-matching/listing-06-04/src/main.rs new file mode 100644 index 0000000000..3ba384fbaa --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/listing-06-04/src/main.rs @@ -0,0 +1,17 @@ +// 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() {} diff --git a/listings/ch06-enums-and-pattern-matching/listing-06-05/Cargo.lock b/listings/ch06-enums-and-pattern-matching/listing-06-05/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/listing-06-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/listings/ch06-enums-and-pattern-matching/listing-06-05/Cargo.toml b/listings/ch06-enums-and-pattern-matching/listing-06-05/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/listing-06-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch06-enums-and-pattern-matching/listing-06-05/src/main.rs b/listings/ch06-enums-and-pattern-matching/listing-06-05/src/main.rs new file mode 100644 index 0000000000..c86190aa7f --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/listing-06-05/src/main.rs @@ -0,0 +1,18 @@ +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 +} diff --git a/listings/ch06-enums-and-pattern-matching/listing-06-06/Cargo.lock b/listings/ch06-enums-and-pattern-matching/listing-06-06/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/listing-06-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/listings/ch06-enums-and-pattern-matching/listing-06-06/Cargo.toml b/listings/ch06-enums-and-pattern-matching/listing-06-06/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/listing-06-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch06-enums-and-pattern-matching/listing-06-06/src/main.rs b/listings/ch06-enums-and-pattern-matching/listing-06-06/src/main.rs new file mode 100644 index 0000000000..222d54552c --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/listing-06-06/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + // ANCHOR: here + let some_u8_value = Some(0u8); + match some_u8_value { + Some(3) => println!("three"), + _ => (), + } + // ANCHOR_END: here +} diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/Cargo.lock b/listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/Cargo.toml b/listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/src/main.rs b/listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/src/main.rs new file mode 100644 index 0000000000..c631e56baf --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/src/main.rs @@ -0,0 +1,22 @@ +// 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 diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/Cargo.lock b/listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/Cargo.toml b/listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/src/main.rs b/listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/src/main.rs new file mode 100644 index 0000000000..7d59b811ff --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/src/main.rs @@ -0,0 +1,12 @@ +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 +} diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/Cargo.lock b/listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/Cargo.toml b/listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/src/main.rs b/listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/src/main.rs new file mode 100644 index 0000000000..844a14041c --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/src/main.rs @@ -0,0 +1,12 @@ +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 +} diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/Cargo.lock b/listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/Cargo.toml b/listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/src/main.rs b/listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/src/main.rs new file mode 100644 index 0000000000..df451be8b6 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/src/main.rs @@ -0,0 +1,11 @@ +// 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() {} diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/Cargo.lock b/listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/Cargo.toml b/listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/src/main.rs b/listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/src/main.rs new file mode 100644 index 0000000000..66e0b6da11 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/src/main.rs @@ -0,0 +1,19 @@ +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 +} diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/Cargo.lock b/listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/Cargo.toml b/listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/src/main.rs b/listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/src/main.rs new file mode 100644 index 0000000000..9de5791b41 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let some_number = Some(5); + let some_string = Some("a string"); + + let absent_number: Option = None; + // ANCHOR_END: here +} diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/Cargo.lock b/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/Cargo.toml b/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/output.txt b/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/output.txt new file mode 100644 index 0000000000..d3092d9fb3 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/output.txt @@ -0,0 +1,16 @@ +$ cargo run + Compiling enums v0.1.0 (file:///projects/enums) +error[E0277]: cannot add `std::option::Option` to `i8` + --> src/main.rs:5:17 + | +5 | let sum = x + y; + | ^ no implementation for `i8 + std::option::Option` + | + = help: the trait `std::ops::Add>` is not implemented for `i8` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. +error: could not compile `enums`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/src/main.rs b/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/src/main.rs new file mode 100644 index 0000000000..ec65565d42 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let x: i8 = 5; + let y: Option = Some(5); + + let sum = x + y; + // ANCHOR_END: here +} diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/Cargo.lock b/listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/Cargo.toml b/listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/src/main.rs b/listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/src/main.rs new file mode 100644 index 0000000000..3f909dcaf7 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/src/main.rs @@ -0,0 +1,22 @@ +enum Coin { + Penny, + Nickel, + Dime, + Quarter, +} + +// ANCHOR: here +fn value_in_cents(coin: Coin) -> u8 { + match coin { + Coin::Penny => { + println!("Lucky penny!"); + 1 + } + Coin::Nickel => 5, + Coin::Dime => 10, + Coin::Quarter => 25, + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/Cargo.lock b/listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/Cargo.toml b/listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/src/main.rs b/listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/src/main.rs new file mode 100644 index 0000000000..a4d500c11c --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/src/main.rs @@ -0,0 +1,31 @@ +#[derive(Debug)] +enum UsState { + Alabama, + Alaska, + // --snip-- +} + +enum Coin { + Penny, + Nickel, + Dime, + Quarter(UsState), +} + +// ANCHOR: here +fn value_in_cents(coin: Coin) -> u8 { + match coin { + Coin::Penny => 1, + Coin::Nickel => 5, + Coin::Dime => 10, + Coin::Quarter(state) => { + println!("State quarter from {:?}!", state); + 25 + } + } +} +// ANCHOR_END: here + +fn main() { + value_in_cents(Coin::Quarter(UsState::Alaska)); +} diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/Cargo.lock b/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/Cargo.toml b/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/output.txt b/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/output.txt new file mode 100644 index 0000000000..da9e9d9bfe --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/output.txt @@ -0,0 +1,16 @@ +$ cargo run + Compiling enums v0.1.0 (file:///projects/enums) +error[E0004]: non-exhaustive patterns: `None` not covered + --> src/main.rs:3:15 + | +3 | match x { + | ^ pattern `None` not covered + | + = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0004`. +error: could not compile `enums`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/src/main.rs b/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/src/main.rs new file mode 100644 index 0000000000..f1963d0c9d --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + // ANCHOR: here + fn plus_one(x: Option) -> Option { + match x { + Some(i) => Some(i + 1), + } + } + // ANCHOR_END: here + + let five = Some(5); + let six = plus_one(five); + let none = plus_one(None); +} diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/Cargo.lock b/listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/Cargo.toml b/listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/src/main.rs b/listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/src/main.rs new file mode 100644 index 0000000000..6fc8ab058b --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + // ANCHOR: here + let some_u8_value = 0u8; + match some_u8_value { + 1 => println!("one"), + 3 => println!("three"), + 5 => println!("five"), + 7 => println!("seven"), + _ => (), + } + // ANCHOR_END: here +} diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/Cargo.lock b/listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/Cargo.toml b/listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/src/main.rs b/listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/src/main.rs new file mode 100644 index 0000000000..fb6578cf64 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + let some_u8_value = Some(0u8); + // ANCHOR: here + if let Some(3) = some_u8_value { + println!("three"); + } + // ANCHOR_END: here +} diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/Cargo.lock b/listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/Cargo.toml b/listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/src/main.rs b/listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/src/main.rs new file mode 100644 index 0000000000..12c4c0fec1 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/src/main.rs @@ -0,0 +1,24 @@ +#[derive(Debug)] +enum UsState { + Alabama, + Alaska, + // --snip-- +} + +enum Coin { + Penny, + Nickel, + Dime, + Quarter(UsState), +} + +fn main() { + let coin = Coin::Penny; + // ANCHOR: here + let mut count = 0; + match coin { + Coin::Quarter(state) => println!("State quarter from {:?}!", state), + _ => count += 1, + } + // ANCHOR_END: here +} diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/Cargo.lock b/listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/Cargo.toml b/listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/src/main.rs b/listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/src/main.rs new file mode 100644 index 0000000000..ba7eda27b4 --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/src/main.rs @@ -0,0 +1,25 @@ +#[derive(Debug)] +enum UsState { + Alabama, + Alaska, + // --snip-- +} + +enum Coin { + Penny, + Nickel, + Dime, + Quarter(UsState), +} + +fn main() { + let coin = Coin::Penny; + // ANCHOR: here + let mut count = 0; + if let Coin::Quarter(state) = coin { + println!("State quarter from {:?}!", state); + } else { + count += 1; + } + // ANCHOR_END: here +} diff --git a/listings/ch07-managing-growing-projects/listing-07-01/Cargo.lock b/listings/ch07-managing-growing-projects/listing-07-01/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/listings/ch07-managing-growing-projects/listing-07-01/Cargo.toml b/listings/ch07-managing-growing-projects/listing-07-01/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch07-managing-growing-projects/listing-07-01/src/lib.rs b/listings/ch07-managing-growing-projects/listing-07-01/src/lib.rs new file mode 100644 index 0000000000..0e40be70d9 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-01/src/lib.rs @@ -0,0 +1,19 @@ +// ANCHOR: here +mod front_of_house { + mod hosting { + fn add_to_waitlist() {} + + fn seat_at_table() {} + } + + mod serving { + fn take_order() {} + + fn serve_order() {} + + fn take_payment() {} + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch07-managing-growing-projects/listing-07-03/Cargo.lock b/listings/ch07-managing-growing-projects/listing-07-03/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/listings/ch07-managing-growing-projects/listing-07-03/Cargo.toml b/listings/ch07-managing-growing-projects/listing-07-03/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch07-managing-growing-projects/listing-07-03/output.txt b/listings/ch07-managing-growing-projects/listing-07-03/output.txt new file mode 100644 index 0000000000..2a494c29ea --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-03/output.txt @@ -0,0 +1,20 @@ +$ cargo build + Compiling restaurant v0.1.0 (file:///projects/restaurant) +error[E0603]: module `hosting` is private + --> src/lib.rs:9:28 + | +9 | crate::front_of_house::hosting::add_to_waitlist(); + | ^^^^^^^ + +error[E0603]: module `hosting` is private + --> src/lib.rs:12:21 + | +12 | front_of_house::hosting::add_to_waitlist(); + | ^^^^^^^ + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0603`. +error: could not compile `restaurant`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch07-managing-growing-projects/listing-07-03/src/lib.rs b/listings/ch07-managing-growing-projects/listing-07-03/src/lib.rs new file mode 100644 index 0000000000..0b8a43c6b3 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-03/src/lib.rs @@ -0,0 +1,13 @@ +mod front_of_house { + mod hosting { + fn add_to_waitlist() {} + } +} + +pub fn eat_at_restaurant() { + // Absolute path + crate::front_of_house::hosting::add_to_waitlist(); + + // Relative path + front_of_house::hosting::add_to_waitlist(); +} diff --git a/listings/ch07-managing-growing-projects/listing-07-05/Cargo.lock b/listings/ch07-managing-growing-projects/listing-07-05/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/listings/ch07-managing-growing-projects/listing-07-05/Cargo.toml b/listings/ch07-managing-growing-projects/listing-07-05/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch07-managing-growing-projects/listing-07-05/output.txt b/listings/ch07-managing-growing-projects/listing-07-05/output.txt new file mode 100644 index 0000000000..664c6a4800 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-05/output.txt @@ -0,0 +1,20 @@ +$ cargo build + Compiling restaurant v0.1.0 (file:///projects/restaurant) +error[E0603]: function `add_to_waitlist` is private + --> src/lib.rs:9:37 + | +9 | crate::front_of_house::hosting::add_to_waitlist(); + | ^^^^^^^^^^^^^^^ + +error[E0603]: function `add_to_waitlist` is private + --> src/lib.rs:12:30 + | +12 | front_of_house::hosting::add_to_waitlist(); + | ^^^^^^^^^^^^^^^ + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0603`. +error: could not compile `restaurant`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch07-managing-growing-projects/listing-07-05/src/lib.rs b/listings/ch07-managing-growing-projects/listing-07-05/src/lib.rs new file mode 100644 index 0000000000..05372dbe5e --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-05/src/lib.rs @@ -0,0 +1,13 @@ +mod front_of_house { + pub mod hosting { + fn add_to_waitlist() {} + } +} + +pub fn eat_at_restaurant() { + // Absolute path + crate::front_of_house::hosting::add_to_waitlist(); + + // Relative path + front_of_house::hosting::add_to_waitlist(); +} diff --git a/listings/ch07-managing-growing-projects/listing-07-07/Cargo.lock b/listings/ch07-managing-growing-projects/listing-07-07/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/listings/ch07-managing-growing-projects/listing-07-07/Cargo.toml b/listings/ch07-managing-growing-projects/listing-07-07/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch07-managing-growing-projects/listing-07-07/src/lib.rs b/listings/ch07-managing-growing-projects/listing-07-07/src/lib.rs new file mode 100644 index 0000000000..5a6edf9832 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-07/src/lib.rs @@ -0,0 +1,17 @@ +// ANCHOR: here +mod front_of_house { + pub mod hosting { + pub fn add_to_waitlist() {} + } +} + +pub fn eat_at_restaurant() { + // Absolute path + crate::front_of_house::hosting::add_to_waitlist(); + + // Relative path + front_of_house::hosting::add_to_waitlist(); +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch07-managing-growing-projects/listing-07-08/Cargo.lock b/listings/ch07-managing-growing-projects/listing-07-08/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/listings/ch07-managing-growing-projects/listing-07-08/Cargo.toml b/listings/ch07-managing-growing-projects/listing-07-08/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch07-managing-growing-projects/listing-07-08/src/lib.rs b/listings/ch07-managing-growing-projects/listing-07-08/src/lib.rs new file mode 100644 index 0000000000..a789379ae2 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-08/src/lib.rs @@ -0,0 +1,14 @@ +// ANCHOR: here +fn serve_order() {} + +mod back_of_house { + fn fix_incorrect_order() { + cook_order(); + super::serve_order(); + } + + fn cook_order() {} +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch07-managing-growing-projects/listing-07-09/Cargo.lock b/listings/ch07-managing-growing-projects/listing-07-09/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/listings/ch07-managing-growing-projects/listing-07-09/Cargo.toml b/listings/ch07-managing-growing-projects/listing-07-09/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch07-managing-growing-projects/listing-07-09/src/lib.rs b/listings/ch07-managing-growing-projects/listing-07-09/src/lib.rs new file mode 100644 index 0000000000..92c4695d50 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-09/src/lib.rs @@ -0,0 +1,27 @@ +mod back_of_house { + pub struct Breakfast { + pub toast: String, + seasonal_fruit: String, + } + + impl Breakfast { + pub fn summer(toast: &str) -> Breakfast { + Breakfast { + toast: String::from(toast), + seasonal_fruit: String::from("peaches"), + } + } + } +} + +pub fn eat_at_restaurant() { + // Order a breakfast in the summer with Rye toast + let mut meal = back_of_house::Breakfast::summer("Rye"); + // Change our mind about what bread we'd like + meal.toast = String::from("Wheat"); + println!("I'd like {} toast please", meal.toast); + + // The next line won't compile if we uncomment it; we're not allowed + // to see or modify the seasonal fruit that comes with the meal + // meal.seasonal_fruit = String::from("blueberries"); +} diff --git a/listings/ch07-managing-growing-projects/listing-07-10/Cargo.lock b/listings/ch07-managing-growing-projects/listing-07-10/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/listings/ch07-managing-growing-projects/listing-07-10/Cargo.toml b/listings/ch07-managing-growing-projects/listing-07-10/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch07-managing-growing-projects/listing-07-10/src/lib.rs b/listings/ch07-managing-growing-projects/listing-07-10/src/lib.rs new file mode 100644 index 0000000000..908f1dfb71 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-10/src/lib.rs @@ -0,0 +1,11 @@ +mod back_of_house { + pub enum Appetizer { + Soup, + Salad, + } +} + +pub fn eat_at_restaurant() { + let order1 = back_of_house::Appetizer::Soup; + let order2 = back_of_house::Appetizer::Salad; +} diff --git a/listings/ch07-managing-growing-projects/listing-07-11/Cargo.lock b/listings/ch07-managing-growing-projects/listing-07-11/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/listings/ch07-managing-growing-projects/listing-07-11/Cargo.toml b/listings/ch07-managing-growing-projects/listing-07-11/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch07-managing-growing-projects/listing-07-11/src/lib.rs b/listings/ch07-managing-growing-projects/listing-07-11/src/lib.rs new file mode 100644 index 0000000000..3a75683757 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-11/src/lib.rs @@ -0,0 +1,17 @@ +// ANCHOR: here +mod front_of_house { + pub mod hosting { + pub fn add_to_waitlist() {} + } +} + +use crate::front_of_house::hosting; + +pub fn eat_at_restaurant() { + hosting::add_to_waitlist(); + hosting::add_to_waitlist(); + hosting::add_to_waitlist(); +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch07-managing-growing-projects/listing-07-12/Cargo.lock b/listings/ch07-managing-growing-projects/listing-07-12/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/listings/ch07-managing-growing-projects/listing-07-12/Cargo.toml b/listings/ch07-managing-growing-projects/listing-07-12/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch07-managing-growing-projects/listing-07-12/src/lib.rs b/listings/ch07-managing-growing-projects/listing-07-12/src/lib.rs new file mode 100644 index 0000000000..6b0101b7d1 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-12/src/lib.rs @@ -0,0 +1,17 @@ +// ANCHOR: here +mod front_of_house { + pub mod hosting { + pub fn add_to_waitlist() {} + } +} + +use self::front_of_house::hosting; + +pub fn eat_at_restaurant() { + hosting::add_to_waitlist(); + hosting::add_to_waitlist(); + hosting::add_to_waitlist(); +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch07-managing-growing-projects/listing-07-13/Cargo.lock b/listings/ch07-managing-growing-projects/listing-07-13/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/listings/ch07-managing-growing-projects/listing-07-13/Cargo.toml b/listings/ch07-managing-growing-projects/listing-07-13/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch07-managing-growing-projects/listing-07-13/src/lib.rs b/listings/ch07-managing-growing-projects/listing-07-13/src/lib.rs new file mode 100644 index 0000000000..98414aac91 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-13/src/lib.rs @@ -0,0 +1,17 @@ +// ANCHOR: here +mod front_of_house { + pub mod hosting { + pub fn add_to_waitlist() {} + } +} + +use crate::front_of_house::hosting::add_to_waitlist; + +pub fn eat_at_restaurant() { + add_to_waitlist(); + add_to_waitlist(); + add_to_waitlist(); +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch07-managing-growing-projects/listing-07-14/Cargo.lock b/listings/ch07-managing-growing-projects/listing-07-14/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/listings/ch07-managing-growing-projects/listing-07-14/Cargo.toml b/listings/ch07-managing-growing-projects/listing-07-14/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch07-managing-growing-projects/listing-07-14/src/main.rs b/listings/ch07-managing-growing-projects/listing-07-14/src/main.rs new file mode 100644 index 0000000000..4379e7c791 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-14/src/main.rs @@ -0,0 +1,6 @@ +use std::collections::HashMap; + +fn main() { + let mut map = HashMap::new(); + map.insert(1, 2); +} diff --git a/listings/ch07-managing-growing-projects/listing-07-15/Cargo.lock b/listings/ch07-managing-growing-projects/listing-07-15/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/listings/ch07-managing-growing-projects/listing-07-15/Cargo.toml b/listings/ch07-managing-growing-projects/listing-07-15/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch07-managing-growing-projects/listing-07-15/src/lib.rs b/listings/ch07-managing-growing-projects/listing-07-15/src/lib.rs new file mode 100644 index 0000000000..bfac3a07ac --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-15/src/lib.rs @@ -0,0 +1,18 @@ +// ANCHOR: here +use std::fmt; +use std::io; + +fn function1() -> fmt::Result { + // --snip-- + // ANCHOR_END: here + Ok(()) + // ANCHOR: here +} + +fn function2() -> io::Result<()> { + // --snip-- + // ANCHOR_END: here + Ok(()) + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/listings/ch07-managing-growing-projects/listing-07-16/Cargo.lock b/listings/ch07-managing-growing-projects/listing-07-16/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/listings/ch07-managing-growing-projects/listing-07-16/Cargo.toml b/listings/ch07-managing-growing-projects/listing-07-16/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch07-managing-growing-projects/listing-07-16/src/lib.rs b/listings/ch07-managing-growing-projects/listing-07-16/src/lib.rs new file mode 100644 index 0000000000..843490b4d0 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-16/src/lib.rs @@ -0,0 +1,18 @@ +// ANCHOR: here +use std::fmt::Result; +use std::io::Result as IoResult; + +fn function1() -> Result { + // --snip-- + // ANCHOR_END: here + Ok(()) + // ANCHOR: here +} + +fn function2() -> IoResult<()> { + // --snip-- + // ANCHOR_END: here + Ok(()) + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/listings/ch07-managing-growing-projects/listing-07-17/Cargo.lock b/listings/ch07-managing-growing-projects/listing-07-17/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-17/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/listings/ch07-managing-growing-projects/listing-07-17/Cargo.toml b/listings/ch07-managing-growing-projects/listing-07-17/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-17/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch07-managing-growing-projects/listing-07-17/src/lib.rs b/listings/ch07-managing-growing-projects/listing-07-17/src/lib.rs new file mode 100644 index 0000000000..e948d7c38e --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-17/src/lib.rs @@ -0,0 +1,17 @@ +// ANCHOR: here +mod front_of_house { + pub mod hosting { + pub fn add_to_waitlist() {} + } +} + +pub use crate::front_of_house::hosting; + +pub fn eat_at_restaurant() { + hosting::add_to_waitlist(); + hosting::add_to_waitlist(); + hosting::add_to_waitlist(); +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch07-managing-growing-projects/listing-07-18/Cargo.lock b/listings/ch07-managing-growing-projects/listing-07-18/Cargo.lock new file mode 100644 index 0000000000..c346748e55 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-18/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.53" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.53 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.53 (registry+https://github.com/rust-lang/crates.io-index)" = "ec350a9417dfd244dc9a6c4a71e13895a4db6b92f0b106f07ebbc3f3bc580cee" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/listings/ch07-managing-growing-projects/listing-07-18/Cargo.toml b/listings/ch07-managing-growing-projects/listing-07-18/Cargo.toml new file mode 100644 index 0000000000..ad5ca696d5 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-18/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] +rand = "0.5.5" diff --git a/listings/ch07-managing-growing-projects/listing-07-18/src/main.rs b/listings/ch07-managing-growing-projects/listing-07-18/src/main.rs new file mode 100644 index 0000000000..61a2023fff --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-18/src/main.rs @@ -0,0 +1,32 @@ +use rand::Rng; +// ANCHOR: here +// --snip-- +use std::{cmp::Ordering, io}; +// --snip-- +// ANCHOR_END: here + +fn main() { + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1, 101); + + 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"); + + 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!"), + } +} diff --git a/listings/ch07-managing-growing-projects/listing-07-19/Cargo.lock b/listings/ch07-managing-growing-projects/listing-07-19/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-19/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/listings/ch07-managing-growing-projects/listing-07-19/Cargo.toml b/listings/ch07-managing-growing-projects/listing-07-19/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-19/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch07-managing-growing-projects/listing-07-19/src/lib.rs b/listings/ch07-managing-growing-projects/listing-07-19/src/lib.rs new file mode 100644 index 0000000000..3fee46c443 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-19/src/lib.rs @@ -0,0 +1,2 @@ +use std::io; +use std::io::Write; diff --git a/listings/ch07-managing-growing-projects/listing-07-20/Cargo.lock b/listings/ch07-managing-growing-projects/listing-07-20/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-20/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/listings/ch07-managing-growing-projects/listing-07-20/Cargo.toml b/listings/ch07-managing-growing-projects/listing-07-20/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-20/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch07-managing-growing-projects/listing-07-20/src/lib.rs b/listings/ch07-managing-growing-projects/listing-07-20/src/lib.rs new file mode 100644 index 0000000000..341f40a472 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-20/src/lib.rs @@ -0,0 +1 @@ +use std::io::{self, Write}; diff --git a/listings/ch07-managing-growing-projects/listing-07-21-and-22/Cargo.lock b/listings/ch07-managing-growing-projects/listing-07-21-and-22/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-21-and-22/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/listings/ch07-managing-growing-projects/listing-07-21-and-22/Cargo.toml b/listings/ch07-managing-growing-projects/listing-07-21-and-22/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-21-and-22/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch07-managing-growing-projects/listing-07-21-and-22/src/front_of_house.rs b/listings/ch07-managing-growing-projects/listing-07-21-and-22/src/front_of_house.rs new file mode 100644 index 0000000000..6875dfdb63 --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-21-and-22/src/front_of_house.rs @@ -0,0 +1,3 @@ +pub mod hosting { + pub fn add_to_waitlist() {} +} diff --git a/listings/ch07-managing-growing-projects/listing-07-21-and-22/src/lib.rs b/listings/ch07-managing-growing-projects/listing-07-21-and-22/src/lib.rs new file mode 100644 index 0000000000..065b1b804c --- /dev/null +++ b/listings/ch07-managing-growing-projects/listing-07-21-and-22/src/lib.rs @@ -0,0 +1,9 @@ +mod front_of_house; + +pub use crate::front_of_house::hosting; + +pub fn eat_at_restaurant() { + hosting::add_to_waitlist(); + hosting::add_to_waitlist(); + hosting::add_to_waitlist(); +} diff --git a/listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/Cargo.lock b/listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/Cargo.lock new file mode 100644 index 0000000000..2b3d41ad67 --- /dev/null +++ b/listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.51" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8a606a02debe2813760609f57a64a2ffd27d9fdf5b2f133eaca0b248dd92cdd2" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)" = "bedcc7a809076656486ffe045abeeac163da1b558e963a31e29fbfbeba916917" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/Cargo.toml b/listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/Cargo.toml new file mode 100644 index 0000000000..10932024b4 --- /dev/null +++ b/listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.5.5" diff --git a/listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/src/main.rs b/listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/src/main.rs new file mode 100644 index 0000000000..c25b0a52a8 --- /dev/null +++ b/listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/src/main.rs @@ -0,0 +1,31 @@ +use rand::Rng; +// ANCHOR: here +// --snip-- +use std::cmp::Ordering; +use std::io; +// --snip-- +// ANCHOR_END: here + +fn main() { + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1, 101); + + 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); + + match guess.cmp(&secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => println!("You win!"), + } +} diff --git a/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/Cargo.lock b/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/Cargo.toml b/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/front_of_house.rs b/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/front_of_house.rs new file mode 100644 index 0000000000..d0a8154eaf --- /dev/null +++ b/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/front_of_house.rs @@ -0,0 +1 @@ +pub mod hosting; diff --git a/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/front_of_house/hosting.rs b/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/front_of_house/hosting.rs new file mode 100644 index 0000000000..d65f3afd13 --- /dev/null +++ b/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/front_of_house/hosting.rs @@ -0,0 +1 @@ +pub fn add_to_waitlist() {} diff --git a/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/lib.rs b/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/lib.rs new file mode 100644 index 0000000000..065b1b804c --- /dev/null +++ b/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/lib.rs @@ -0,0 +1,9 @@ +mod front_of_house; + +pub use crate::front_of_house::hosting; + +pub fn eat_at_restaurant() { + hosting::add_to_waitlist(); + hosting::add_to_waitlist(); + hosting::add_to_waitlist(); +} diff --git a/listings/ch08-common-collections/listing-08-01/Cargo.lock b/listings/ch08-common-collections/listing-08-01/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-01/Cargo.toml b/listings/ch08-common-collections/listing-08-01/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-01/src/main.rs b/listings/ch08-common-collections/listing-08-01/src/main.rs new file mode 100644 index 0000000000..45e45581e2 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-01/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + // ANCHOR: here + let v: Vec = Vec::new(); + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-02/Cargo.lock b/listings/ch08-common-collections/listing-08-02/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-02/Cargo.toml b/listings/ch08-common-collections/listing-08-02/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-02/src/main.rs b/listings/ch08-common-collections/listing-08-02/src/main.rs new file mode 100644 index 0000000000..3b10a53e88 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-02/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + // ANCHOR: here + let v = vec![1, 2, 3]; + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-03/Cargo.lock b/listings/ch08-common-collections/listing-08-03/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-03/Cargo.toml b/listings/ch08-common-collections/listing-08-03/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-03/src/main.rs b/listings/ch08-common-collections/listing-08-03/src/main.rs new file mode 100644 index 0000000000..147223f9ae --- /dev/null +++ b/listings/ch08-common-collections/listing-08-03/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + // ANCHOR: here + let mut v = Vec::new(); + + v.push(5); + v.push(6); + v.push(7); + v.push(8); + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-04/Cargo.lock b/listings/ch08-common-collections/listing-08-04/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-04/Cargo.toml b/listings/ch08-common-collections/listing-08-04/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-04/src/main.rs b/listings/ch08-common-collections/listing-08-04/src/main.rs new file mode 100644 index 0000000000..abda2db660 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-04/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + // ANCHOR: here + { + let v = vec![1, 2, 3, 4]; + + // do stuff with v + } // <- v goes out of scope and is freed here + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-05/Cargo.lock b/listings/ch08-common-collections/listing-08-05/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-05/Cargo.toml b/listings/ch08-common-collections/listing-08-05/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-05/src/main.rs b/listings/ch08-common-collections/listing-08-05/src/main.rs new file mode 100644 index 0000000000..9bfa37a4c2 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-05/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + // ANCHOR: here + let v = vec![1, 2, 3, 4, 5]; + + let third: &i32 = &v[2]; + println!("The third element is {}", third); + + match v.get(2) { + Some(third) => println!("The third element is {}", third), + None => println!("There is no third element."), + } + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-06/Cargo.lock b/listings/ch08-common-collections/listing-08-06/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-06/Cargo.toml b/listings/ch08-common-collections/listing-08-06/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-06/src/main.rs b/listings/ch08-common-collections/listing-08-06/src/main.rs new file mode 100644 index 0000000000..783d9b110f --- /dev/null +++ b/listings/ch08-common-collections/listing-08-06/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let v = vec![1, 2, 3, 4, 5]; + + let does_not_exist = &v[100]; + let does_not_exist = v.get(100); + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-07/Cargo.lock b/listings/ch08-common-collections/listing-08-07/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-07/Cargo.toml b/listings/ch08-common-collections/listing-08-07/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-07/output.txt b/listings/ch08-common-collections/listing-08-07/output.txt new file mode 100644 index 0000000000..b50110bdba --- /dev/null +++ b/listings/ch08-common-collections/listing-08-07/output.txt @@ -0,0 +1,20 @@ +$ cargo run + Compiling collections v0.1.0 (file:///projects/collections) +error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable + --> src/main.rs:6:5 + | +4 | let first = &v[0]; + | - immutable borrow occurs here +5 | +6 | v.push(6); + | ^^^^^^^^^ mutable borrow occurs here +7 | +8 | println!("The first element is: {}", first); + | ----- immutable borrow later used here + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0502`. +error: could not compile `collections`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch08-common-collections/listing-08-07/src/main.rs b/listings/ch08-common-collections/listing-08-07/src/main.rs new file mode 100644 index 0000000000..1b42274a6d --- /dev/null +++ b/listings/ch08-common-collections/listing-08-07/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let mut v = vec![1, 2, 3, 4, 5]; + + let first = &v[0]; + + v.push(6); + + println!("The first element is: {}", first); + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-08/Cargo.lock b/listings/ch08-common-collections/listing-08-08/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-08/Cargo.toml b/listings/ch08-common-collections/listing-08-08/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-08/src/main.rs b/listings/ch08-common-collections/listing-08-08/src/main.rs new file mode 100644 index 0000000000..38b97784be --- /dev/null +++ b/listings/ch08-common-collections/listing-08-08/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let v = vec![100, 32, 57]; + for i in &v { + println!("{}", i); + } + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-09/Cargo.lock b/listings/ch08-common-collections/listing-08-09/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-09/Cargo.toml b/listings/ch08-common-collections/listing-08-09/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-09/src/main.rs b/listings/ch08-common-collections/listing-08-09/src/main.rs new file mode 100644 index 0000000000..c62ba21b4f --- /dev/null +++ b/listings/ch08-common-collections/listing-08-09/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let mut v = vec![100, 32, 57]; + for i in &mut v { + *i += 50; + } + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-10/Cargo.lock b/listings/ch08-common-collections/listing-08-10/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-10/Cargo.toml b/listings/ch08-common-collections/listing-08-10/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-10/src/main.rs b/listings/ch08-common-collections/listing-08-10/src/main.rs new file mode 100644 index 0000000000..c2198883b2 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-10/src/main.rs @@ -0,0 +1,15 @@ +fn main() { + // ANCHOR: here + enum SpreadsheetCell { + Int(i32), + Float(f64), + Text(String), + } + + let row = vec![ + SpreadsheetCell::Int(3), + SpreadsheetCell::Text(String::from("blue")), + SpreadsheetCell::Float(10.12), + ]; + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-11/Cargo.lock b/listings/ch08-common-collections/listing-08-11/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-11/Cargo.toml b/listings/ch08-common-collections/listing-08-11/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-11/src/main.rs b/listings/ch08-common-collections/listing-08-11/src/main.rs new file mode 100644 index 0000000000..4cf4c81c26 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-11/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + // ANCHOR: here + let mut s = String::new(); + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-12/Cargo.lock b/listings/ch08-common-collections/listing-08-12/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-12/Cargo.toml b/listings/ch08-common-collections/listing-08-12/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-12/src/main.rs b/listings/ch08-common-collections/listing-08-12/src/main.rs new file mode 100644 index 0000000000..d9e5e768ab --- /dev/null +++ b/listings/ch08-common-collections/listing-08-12/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + // ANCHOR: here + let data = "initial contents"; + + let s = data.to_string(); + + // the method also works on a literal directly: + let s = "initial contents".to_string(); + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-13/Cargo.lock b/listings/ch08-common-collections/listing-08-13/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-13/Cargo.toml b/listings/ch08-common-collections/listing-08-13/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-13/src/main.rs b/listings/ch08-common-collections/listing-08-13/src/main.rs new file mode 100644 index 0000000000..b81e374536 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-13/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + // ANCHOR: here + let s = String::from("initial contents"); + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-14/Cargo.lock b/listings/ch08-common-collections/listing-08-14/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-14/Cargo.toml b/listings/ch08-common-collections/listing-08-14/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-14/src/main.rs b/listings/ch08-common-collections/listing-08-14/src/main.rs new file mode 100644 index 0000000000..f701fd578b --- /dev/null +++ b/listings/ch08-common-collections/listing-08-14/src/main.rs @@ -0,0 +1,19 @@ +fn main() { + // ANCHOR: here + let hello = String::from("السلام عليكم"); + let hello = String::from("Dobrý den"); + let hello = String::from("Hello"); + let hello = String::from("שָׁלוֹם"); + let hello = String::from("नमस्ते"); + let hello = String::from("こんにちは"); + let hello = String::from("안녕하세요"); + let hello = String::from("你好"); + let hello = String::from("Olá"); + // ANCHOR: russian + let hello = String::from("Здравствуйте"); + // ANCHOR_END: russian + // ANCHOR: spanish + let hello = String::from("Hola"); + // ANCHOR_END: spanish + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-15/Cargo.lock b/listings/ch08-common-collections/listing-08-15/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-15/Cargo.toml b/listings/ch08-common-collections/listing-08-15/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-15/src/main.rs b/listings/ch08-common-collections/listing-08-15/src/main.rs new file mode 100644 index 0000000000..7dec657d92 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-15/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + // ANCHOR: here + let mut s = String::from("foo"); + s.push_str("bar"); + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-16/Cargo.lock b/listings/ch08-common-collections/listing-08-16/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-16/Cargo.toml b/listings/ch08-common-collections/listing-08-16/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-16/src/main.rs b/listings/ch08-common-collections/listing-08-16/src/main.rs new file mode 100644 index 0000000000..8938dc143b --- /dev/null +++ b/listings/ch08-common-collections/listing-08-16/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let mut s1 = String::from("foo"); + let s2 = "bar"; + s1.push_str(s2); + println!("s2 is {}", s2); + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-17/Cargo.lock b/listings/ch08-common-collections/listing-08-17/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-17/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-17/Cargo.toml b/listings/ch08-common-collections/listing-08-17/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-17/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-17/src/main.rs b/listings/ch08-common-collections/listing-08-17/src/main.rs new file mode 100644 index 0000000000..0a9e8cc0a8 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-17/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + // ANCHOR: here + let mut s = String::from("lo"); + s.push('l'); + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-18/Cargo.lock b/listings/ch08-common-collections/listing-08-18/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-18/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-18/Cargo.toml b/listings/ch08-common-collections/listing-08-18/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-18/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-18/src/main.rs b/listings/ch08-common-collections/listing-08-18/src/main.rs new file mode 100644 index 0000000000..93939a69fb --- /dev/null +++ b/listings/ch08-common-collections/listing-08-18/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + // ANCHOR: here + let s1 = String::from("Hello, "); + let s2 = String::from("world!"); + let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-19/Cargo.lock b/listings/ch08-common-collections/listing-08-19/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-19/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-19/Cargo.toml b/listings/ch08-common-collections/listing-08-19/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-19/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-19/output.txt b/listings/ch08-common-collections/listing-08-19/output.txt new file mode 100644 index 0000000000..c239f71896 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-19/output.txt @@ -0,0 +1,16 @@ +$ cargo run + Compiling collections v0.1.0 (file:///projects/collections) +error[E0277]: the type `std::string::String` cannot be indexed by `{integer}` + --> src/main.rs:3:13 + | +3 | let h = s1[0]; + | ^^^^^ `std::string::String` cannot be indexed by `{integer}` + | + = help: the trait `std::ops::Index<{integer}>` is not implemented for `std::string::String` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. +error: could not compile `collections`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch08-common-collections/listing-08-19/src/main.rs b/listings/ch08-common-collections/listing-08-19/src/main.rs new file mode 100644 index 0000000000..fc08e9ceaa --- /dev/null +++ b/listings/ch08-common-collections/listing-08-19/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + // ANCHOR: here + let s1 = String::from("hello"); + let h = s1[0]; + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-20/Cargo.lock b/listings/ch08-common-collections/listing-08-20/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-20/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-20/Cargo.toml b/listings/ch08-common-collections/listing-08-20/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-20/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-20/src/main.rs b/listings/ch08-common-collections/listing-08-20/src/main.rs new file mode 100644 index 0000000000..54c2010911 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-20/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + // ANCHOR: here + use std::collections::HashMap; + + let mut scores = HashMap::new(); + + scores.insert(String::from("Blue"), 10); + scores.insert(String::from("Yellow"), 50); + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-21/Cargo.lock b/listings/ch08-common-collections/listing-08-21/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-21/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-21/Cargo.toml b/listings/ch08-common-collections/listing-08-21/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-21/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-21/src/main.rs b/listings/ch08-common-collections/listing-08-21/src/main.rs new file mode 100644 index 0000000000..b21e0dee55 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-21/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + use std::collections::HashMap; + + let teams = vec![String::from("Blue"), String::from("Yellow")]; + let initial_scores = vec![10, 50]; + + let scores: HashMap<_, _> = + teams.iter().zip(initial_scores.iter()).collect(); + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-22/Cargo.lock b/listings/ch08-common-collections/listing-08-22/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-22/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-22/Cargo.toml b/listings/ch08-common-collections/listing-08-22/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-22/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-22/src/main.rs b/listings/ch08-common-collections/listing-08-22/src/main.rs new file mode 100644 index 0000000000..2b2a73f94a --- /dev/null +++ b/listings/ch08-common-collections/listing-08-22/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + // ANCHOR: here + use std::collections::HashMap; + + let field_name = String::from("Favorite color"); + let field_value = String::from("Blue"); + + let mut map = HashMap::new(); + map.insert(field_name, field_value); + // field_name and field_value are invalid at this point, try using them and + // see what compiler error you get! + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-23/Cargo.lock b/listings/ch08-common-collections/listing-08-23/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-23/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-23/Cargo.toml b/listings/ch08-common-collections/listing-08-23/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-23/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-23/src/main.rs b/listings/ch08-common-collections/listing-08-23/src/main.rs new file mode 100644 index 0000000000..508e33cbbf --- /dev/null +++ b/listings/ch08-common-collections/listing-08-23/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + // ANCHOR: here + use std::collections::HashMap; + + let mut scores = HashMap::new(); + + scores.insert(String::from("Blue"), 10); + scores.insert(String::from("Yellow"), 50); + + let team_name = String::from("Blue"); + let score = scores.get(&team_name); + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-24/Cargo.lock b/listings/ch08-common-collections/listing-08-24/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-24/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-24/Cargo.toml b/listings/ch08-common-collections/listing-08-24/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-24/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-24/src/main.rs b/listings/ch08-common-collections/listing-08-24/src/main.rs new file mode 100644 index 0000000000..e8684cf2b6 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-24/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + // ANCHOR: here + use std::collections::HashMap; + + let mut scores = HashMap::new(); + + scores.insert(String::from("Blue"), 10); + scores.insert(String::from("Blue"), 25); + + println!("{:?}", scores); + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-25/Cargo.lock b/listings/ch08-common-collections/listing-08-25/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-25/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-25/Cargo.toml b/listings/ch08-common-collections/listing-08-25/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-25/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-25/src/main.rs b/listings/ch08-common-collections/listing-08-25/src/main.rs new file mode 100644 index 0000000000..3ad97b57af --- /dev/null +++ b/listings/ch08-common-collections/listing-08-25/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + // ANCHOR: here + use std::collections::HashMap; + + let mut scores = HashMap::new(); + scores.insert(String::from("Blue"), 10); + + scores.entry(String::from("Yellow")).or_insert(50); + scores.entry(String::from("Blue")).or_insert(50); + + println!("{:?}", scores); + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/listing-08-26/Cargo.lock b/listings/ch08-common-collections/listing-08-26/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/listing-08-26/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/listing-08-26/Cargo.toml b/listings/ch08-common-collections/listing-08-26/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/listing-08-26/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/listing-08-26/src/main.rs b/listings/ch08-common-collections/listing-08-26/src/main.rs new file mode 100644 index 0000000000..f3f6aa166d --- /dev/null +++ b/listings/ch08-common-collections/listing-08-26/src/main.rs @@ -0,0 +1,16 @@ +fn main() { + // ANCHOR: here + use std::collections::HashMap; + + let text = "hello world wonderful world"; + + let mut map = HashMap::new(); + + for word in text.split_whitespace() { + let count = map.entry(word).or_insert(0); + *count += 1; + } + + println!("{:?}", map); + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/no-listing-01-concat-multiple-strings/Cargo.lock b/listings/ch08-common-collections/no-listing-01-concat-multiple-strings/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/no-listing-01-concat-multiple-strings/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/no-listing-01-concat-multiple-strings/Cargo.toml b/listings/ch08-common-collections/no-listing-01-concat-multiple-strings/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/no-listing-01-concat-multiple-strings/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/no-listing-01-concat-multiple-strings/src/main.rs b/listings/ch08-common-collections/no-listing-01-concat-multiple-strings/src/main.rs new file mode 100644 index 0000000000..4995650d19 --- /dev/null +++ b/listings/ch08-common-collections/no-listing-01-concat-multiple-strings/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + // ANCHOR: here + let s1 = String::from("tic"); + let s2 = String::from("tac"); + let s3 = String::from("toe"); + + let s = s1 + "-" + &s2 + "-" + &s3; + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/no-listing-02-format/Cargo.lock b/listings/ch08-common-collections/no-listing-02-format/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/no-listing-02-format/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/no-listing-02-format/Cargo.toml b/listings/ch08-common-collections/no-listing-02-format/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/no-listing-02-format/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/no-listing-02-format/src/main.rs b/listings/ch08-common-collections/no-listing-02-format/src/main.rs new file mode 100644 index 0000000000..4a38e63d23 --- /dev/null +++ b/listings/ch08-common-collections/no-listing-02-format/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + // ANCHOR: here + let s1 = String::from("tic"); + let s2 = String::from("tac"); + let s3 = String::from("toe"); + + let s = format!("{}-{}-{}", s1, s2, s3); + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/Cargo.lock b/listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/Cargo.toml b/listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/src/main.rs b/listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/src/main.rs new file mode 100644 index 0000000000..2e7dc02e60 --- /dev/null +++ b/listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/src/main.rs @@ -0,0 +1,14 @@ +fn main() { + // ANCHOR: here + use std::collections::HashMap; + + let mut scores = HashMap::new(); + + scores.insert(String::from("Blue"), 10); + scores.insert(String::from("Yellow"), 50); + + for (key, value) in &scores { + println!("{}: {}", key, value); + } + // ANCHOR_END: here +} diff --git a/listings/ch08-common-collections/output-only-01-not-char-boundary/Cargo.lock b/listings/ch08-common-collections/output-only-01-not-char-boundary/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/listings/ch08-common-collections/output-only-01-not-char-boundary/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/listings/ch08-common-collections/output-only-01-not-char-boundary/Cargo.toml b/listings/ch08-common-collections/output-only-01-not-char-boundary/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/listings/ch08-common-collections/output-only-01-not-char-boundary/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch08-common-collections/output-only-01-not-char-boundary/output.txt b/listings/ch08-common-collections/output-only-01-not-char-boundary/output.txt new file mode 100644 index 0000000000..1c9c2b110d --- /dev/null +++ b/listings/ch08-common-collections/output-only-01-not-char-boundary/output.txt @@ -0,0 +1,6 @@ +$ cargo run + Compiling collections v0.1.0 (file:///projects/collections) + Finished dev [unoptimized + debuginfo] target(s) in 0.43s + Running `target/debug/collections` +thread 'main' panicked at 'byte index 1 is not a char boundary; it is inside 'З' (bytes 0..2) of `Здравствуйте`', src/libcore/str/mod.rs:2068:5 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. diff --git a/listings/ch08-common-collections/output-only-01-not-char-boundary/src/main.rs b/listings/ch08-common-collections/output-only-01-not-char-boundary/src/main.rs new file mode 100644 index 0000000000..9283ff5bde --- /dev/null +++ b/listings/ch08-common-collections/output-only-01-not-char-boundary/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + let hello = "Здравствуйте"; + + let s = &hello[0..1]; +} diff --git a/listings/ch09-error-handling/listing-09-01/Cargo.lock b/listings/ch09-error-handling/listing-09-01/Cargo.lock new file mode 100644 index 0000000000..4fe030fabf --- /dev/null +++ b/listings/ch09-error-handling/listing-09-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "panic" +version = "0.1.0" + diff --git a/listings/ch09-error-handling/listing-09-01/Cargo.toml b/listings/ch09-error-handling/listing-09-01/Cargo.toml new file mode 100644 index 0000000000..310342cd33 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "panic" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch09-error-handling/listing-09-01/output.txt b/listings/ch09-error-handling/listing-09-01/output.txt new file mode 100644 index 0000000000..b1e324eced --- /dev/null +++ b/listings/ch09-error-handling/listing-09-01/output.txt @@ -0,0 +1,6 @@ +$ cargo run + Compiling panic v0.1.0 (file:///projects/panic) + Finished dev [unoptimized + debuginfo] target(s) in 0.27s + Running `target/debug/panic` +thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 99', /rustc/73528e339aae0f17a15ffa49a8ac608f50c6cf14/src/libcore/slice/mod.rs:2796:10 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. diff --git a/listings/ch09-error-handling/listing-09-01/src/main.rs b/listings/ch09-error-handling/listing-09-01/src/main.rs new file mode 100644 index 0000000000..70194abd79 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-01/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + let v = vec![1, 2, 3]; + + v[99]; +} diff --git a/listings/ch09-error-handling/listing-09-03/Cargo.lock b/listings/ch09-error-handling/listing-09-03/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/listings/ch09-error-handling/listing-09-03/Cargo.toml b/listings/ch09-error-handling/listing-09-03/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch09-error-handling/listing-09-03/src/main.rs b/listings/ch09-error-handling/listing-09-03/src/main.rs new file mode 100644 index 0000000000..0dfd10b5e5 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-03/src/main.rs @@ -0,0 +1,5 @@ +use std::fs::File; + +fn main() { + let f = File::open("hello.txt"); +} diff --git a/listings/ch09-error-handling/listing-09-04/Cargo.lock b/listings/ch09-error-handling/listing-09-04/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/listings/ch09-error-handling/listing-09-04/Cargo.toml b/listings/ch09-error-handling/listing-09-04/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch09-error-handling/listing-09-04/output.txt b/listings/ch09-error-handling/listing-09-04/output.txt new file mode 100644 index 0000000000..acc4f0c741 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-04/output.txt @@ -0,0 +1,6 @@ +$ cargo run + Compiling error-handling v0.1.0 (file:///projects/error-handling) + Finished dev [unoptimized + debuginfo] target(s) in 0.73s + Running `target/debug/error-handling` +thread 'main' panicked at 'Problem opening the file: Os { code: 2, kind: NotFound, message: "No such file or directory" }', src/main.rs:8:23 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. diff --git a/listings/ch09-error-handling/listing-09-04/src/main.rs b/listings/ch09-error-handling/listing-09-04/src/main.rs new file mode 100644 index 0000000000..070fc33809 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-04/src/main.rs @@ -0,0 +1,10 @@ +use std::fs::File; + +fn main() { + let f = File::open("hello.txt"); + + let f = match f { + Ok(file) => file, + Err(error) => panic!("Problem opening the file: {:?}", error), + }; +} diff --git a/listings/ch09-error-handling/listing-09-05/Cargo.lock b/listings/ch09-error-handling/listing-09-05/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/listings/ch09-error-handling/listing-09-05/Cargo.toml b/listings/ch09-error-handling/listing-09-05/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch09-error-handling/listing-09-05/src/main.rs b/listings/ch09-error-handling/listing-09-05/src/main.rs new file mode 100644 index 0000000000..8c4f773b9e --- /dev/null +++ b/listings/ch09-error-handling/listing-09-05/src/main.rs @@ -0,0 +1,19 @@ +use std::fs::File; +use std::io::ErrorKind; + +fn main() { + let f = File::open("hello.txt"); + + let f = match f { + Ok(file) => file, + Err(error) => match error.kind() { + ErrorKind::NotFound => match File::create("hello.txt") { + Ok(fc) => fc, + Err(e) => panic!("Problem creating the file: {:?}", e), + }, + other_error => { + panic!("Problem opening the file: {:?}", other_error) + } + }, + }; +} diff --git a/listings/ch09-error-handling/listing-09-06/Cargo.lock b/listings/ch09-error-handling/listing-09-06/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/listings/ch09-error-handling/listing-09-06/Cargo.toml b/listings/ch09-error-handling/listing-09-06/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch09-error-handling/listing-09-06/src/main.rs b/listings/ch09-error-handling/listing-09-06/src/main.rs new file mode 100644 index 0000000000..437d858f44 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-06/src/main.rs @@ -0,0 +1,25 @@ +// ANCHOR: here +use std::fs::File; +use std::io; +use std::io::Read; + +fn read_username_from_file() -> Result { + let f = File::open("hello.txt"); + + let mut f = match f { + Ok(file) => file, + Err(e) => return Err(e), + }; + + let mut s = String::new(); + + match f.read_to_string(&mut s) { + Ok(_) => Ok(s), + Err(e) => Err(e), + } +} +// ANCHOR_END: here + +fn main() { + let username = read_username_from_file().expect("Unable to get username"); +} diff --git a/listings/ch09-error-handling/listing-09-07/Cargo.lock b/listings/ch09-error-handling/listing-09-07/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/listings/ch09-error-handling/listing-09-07/Cargo.toml b/listings/ch09-error-handling/listing-09-07/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch09-error-handling/listing-09-07/src/main.rs b/listings/ch09-error-handling/listing-09-07/src/main.rs new file mode 100644 index 0000000000..b9f6172cb2 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-07/src/main.rs @@ -0,0 +1,16 @@ +// ANCHOR: here +use std::fs::File; +use std::io; +use std::io::Read; + +fn read_username_from_file() -> Result { + let mut f = File::open("hello.txt")?; + let mut s = String::new(); + f.read_to_string(&mut s)?; + Ok(s) +} +// ANCHOR_END: here + +fn main() { + let username = read_username_from_file().expect("Unable to get username"); +} diff --git a/listings/ch09-error-handling/listing-09-08/Cargo.lock b/listings/ch09-error-handling/listing-09-08/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/listings/ch09-error-handling/listing-09-08/Cargo.toml b/listings/ch09-error-handling/listing-09-08/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch09-error-handling/listing-09-08/src/main.rs b/listings/ch09-error-handling/listing-09-08/src/main.rs new file mode 100644 index 0000000000..f36e4d0219 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-08/src/main.rs @@ -0,0 +1,17 @@ +// ANCHOR: here +use std::fs::File; +use std::io; +use std::io::Read; + +fn read_username_from_file() -> Result { + let mut s = String::new(); + + File::open("hello.txt")?.read_to_string(&mut s)?; + + Ok(s) +} +// ANCHOR_END: here + +fn main() { + let username = read_username_from_file().expect("Unable to get username"); +} diff --git a/listings/ch09-error-handling/listing-09-09/Cargo.lock b/listings/ch09-error-handling/listing-09-09/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/listings/ch09-error-handling/listing-09-09/Cargo.toml b/listings/ch09-error-handling/listing-09-09/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch09-error-handling/listing-09-09/src/main.rs b/listings/ch09-error-handling/listing-09-09/src/main.rs new file mode 100644 index 0000000000..4597dc2eea --- /dev/null +++ b/listings/ch09-error-handling/listing-09-09/src/main.rs @@ -0,0 +1,12 @@ +// ANCHOR: here +use std::fs; +use std::io; + +fn read_username_from_file() -> Result { + fs::read_to_string("hello.txt") +} +// ANCHOR_END: here + +fn main() { + let username = read_username_from_file().expect("Unable to get username"); +} diff --git a/listings/ch09-error-handling/listing-09-10/Cargo.lock b/listings/ch09-error-handling/listing-09-10/Cargo.lock new file mode 100644 index 0000000000..c346748e55 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-10/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.53" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.53 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.53 (registry+https://github.com/rust-lang/crates.io-index)" = "ec350a9417dfd244dc9a6c4a71e13895a4db6b92f0b106f07ebbc3f3bc580cee" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/listings/ch09-error-handling/listing-09-10/Cargo.toml b/listings/ch09-error-handling/listing-09-10/Cargo.toml new file mode 100644 index 0000000000..ad5ca696d5 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-10/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] +rand = "0.5.5" diff --git a/listings/ch09-error-handling/listing-09-10/src/main.rs b/listings/ch09-error-handling/listing-09-10/src/main.rs new file mode 100644 index 0000000000..7448979a06 --- /dev/null +++ b/listings/ch09-error-handling/listing-09-10/src/main.rs @@ -0,0 +1,55 @@ +use rand::Rng; +use std::cmp::Ordering; +use std::io; + +// ANCHOR: here +pub struct Guess { + value: i32, +} + +impl Guess { + pub fn new(value: i32) -> Guess { + if value < 1 || value > 100 { + panic!("Guess value must be between 1 and 100, got {}.", value); + } + + Guess { value } + } + + pub fn value(&self) -> i32 { + self.value + } +} +// ANCHOR_END: here + +fn main() { + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1, 101); + + loop { + println!("Please input your guess."); + + let mut guess = String::new(); + + io::stdin() + .read_line(&mut guess) + .expect("Failed to read line"); + + let guess: i32 = match guess.trim().parse() { + Ok(num) => num, + Err(_) => continue, + }; + + let guess = Guess::new(guess); + + match guess.value().cmp(&secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => { + println!("You win!"); + break; + } + } + } +} diff --git a/listings/ch09-error-handling/no-listing-01-panic/Cargo.lock b/listings/ch09-error-handling/no-listing-01-panic/Cargo.lock new file mode 100644 index 0000000000..4fe030fabf --- /dev/null +++ b/listings/ch09-error-handling/no-listing-01-panic/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "panic" +version = "0.1.0" + diff --git a/listings/ch09-error-handling/no-listing-01-panic/Cargo.toml b/listings/ch09-error-handling/no-listing-01-panic/Cargo.toml new file mode 100644 index 0000000000..310342cd33 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-01-panic/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "panic" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch09-error-handling/no-listing-01-panic/output.txt b/listings/ch09-error-handling/no-listing-01-panic/output.txt new file mode 100644 index 0000000000..1bc3dc729a --- /dev/null +++ b/listings/ch09-error-handling/no-listing-01-panic/output.txt @@ -0,0 +1,6 @@ +$ cargo run + Compiling panic v0.1.0 (file:///projects/panic) + Finished dev [unoptimized + debuginfo] target(s) in 0.25s + Running `target/debug/panic` +thread 'main' panicked at 'crash and burn', src/main.rs:2:5 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. diff --git a/listings/ch09-error-handling/no-listing-01-panic/src/main.rs b/listings/ch09-error-handling/no-listing-01-panic/src/main.rs new file mode 100644 index 0000000000..32a4c243da --- /dev/null +++ b/listings/ch09-error-handling/no-listing-01-panic/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + panic!("crash and burn"); +} diff --git a/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/Cargo.lock b/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/Cargo.toml b/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/output.txt b/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/output.txt new file mode 100644 index 0000000000..812eac2e23 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/output.txt @@ -0,0 +1,17 @@ +$ cargo run + Compiling error-handling v0.1.0 (file:///projects/error-handling) +error[E0308]: mismatched types + --> src/main.rs:4:18 + | +4 | let f: u32 = File::open("hello.txt"); + | ^^^^^^^^^^^^^^^^^^^^^^^ expected u32, found enum `std::result::Result` + | + = note: expected type `u32` + found type `std::result::Result` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. +error: could not compile `error-handling`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/src/main.rs b/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/src/main.rs new file mode 100644 index 0000000000..a637f5f957 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/src/main.rs @@ -0,0 +1,7 @@ +use std::fs::File; + +fn main() { + // ANCHOR: here + let f: u32 = File::open("hello.txt"); + // ANCHOR_END: here +} diff --git a/listings/ch09-error-handling/no-listing-03-closures/Cargo.lock b/listings/ch09-error-handling/no-listing-03-closures/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-03-closures/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/listings/ch09-error-handling/no-listing-03-closures/Cargo.toml b/listings/ch09-error-handling/no-listing-03-closures/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-03-closures/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch09-error-handling/no-listing-03-closures/src/main.rs b/listings/ch09-error-handling/no-listing-03-closures/src/main.rs new file mode 100644 index 0000000000..c6682cd233 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-03-closures/src/main.rs @@ -0,0 +1,14 @@ +use std::fs::File; +use std::io::ErrorKind; + +fn main() { + let f = File::open("hello.txt").unwrap_or_else(|error| { + if error.kind() == ErrorKind::NotFound { + File::create("hello.txt").unwrap_or_else(|error| { + panic!("Problem creating the file: {:?}", error); + }) + } else { + panic!("Problem opening the file: {:?}", error); + } + }); +} diff --git a/listings/ch09-error-handling/no-listing-04-unwrap/Cargo.lock b/listings/ch09-error-handling/no-listing-04-unwrap/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-04-unwrap/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/listings/ch09-error-handling/no-listing-04-unwrap/Cargo.toml b/listings/ch09-error-handling/no-listing-04-unwrap/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-04-unwrap/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch09-error-handling/no-listing-04-unwrap/src/main.rs b/listings/ch09-error-handling/no-listing-04-unwrap/src/main.rs new file mode 100644 index 0000000000..7b6b13ae76 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-04-unwrap/src/main.rs @@ -0,0 +1,5 @@ +use std::fs::File; + +fn main() { + let f = File::open("hello.txt").unwrap(); +} diff --git a/listings/ch09-error-handling/no-listing-05-expect/Cargo.lock b/listings/ch09-error-handling/no-listing-05-expect/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-05-expect/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/listings/ch09-error-handling/no-listing-05-expect/Cargo.toml b/listings/ch09-error-handling/no-listing-05-expect/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-05-expect/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch09-error-handling/no-listing-05-expect/src/main.rs b/listings/ch09-error-handling/no-listing-05-expect/src/main.rs new file mode 100644 index 0000000000..cab643bc5c --- /dev/null +++ b/listings/ch09-error-handling/no-listing-05-expect/src/main.rs @@ -0,0 +1,5 @@ +use std::fs::File; + +fn main() { + let f = File::open("hello.txt").expect("Failed to open hello.txt"); +} diff --git a/listings/ch09-error-handling/no-listing-06-question-mark-in-main/Cargo.lock b/listings/ch09-error-handling/no-listing-06-question-mark-in-main/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-06-question-mark-in-main/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/listings/ch09-error-handling/no-listing-06-question-mark-in-main/Cargo.toml b/listings/ch09-error-handling/no-listing-06-question-mark-in-main/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-06-question-mark-in-main/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch09-error-handling/no-listing-06-question-mark-in-main/output.txt b/listings/ch09-error-handling/no-listing-06-question-mark-in-main/output.txt new file mode 100644 index 0000000000..f8688192ae --- /dev/null +++ b/listings/ch09-error-handling/no-listing-06-question-mark-in-main/output.txt @@ -0,0 +1,17 @@ +$ cargo run + Compiling error-handling v0.1.0 (file:///projects/error-handling) +error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`) + --> src/main.rs:4:13 + | +4 | let f = File::open("hello.txt")?; + | ^^^^^^^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()` + | + = help: the trait `std::ops::Try` is not implemented for `()` + = note: required by `std::ops::Try::from_error` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. +error: could not compile `error-handling`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch09-error-handling/no-listing-06-question-mark-in-main/src/main.rs b/listings/ch09-error-handling/no-listing-06-question-mark-in-main/src/main.rs new file mode 100644 index 0000000000..8608dc13ff --- /dev/null +++ b/listings/ch09-error-handling/no-listing-06-question-mark-in-main/src/main.rs @@ -0,0 +1,5 @@ +use std::fs::File; + +fn main() { + let f = File::open("hello.txt")?; +} diff --git a/listings/ch09-error-handling/no-listing-07-main-returning-result/Cargo.lock b/listings/ch09-error-handling/no-listing-07-main-returning-result/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-07-main-returning-result/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/listings/ch09-error-handling/no-listing-07-main-returning-result/Cargo.toml b/listings/ch09-error-handling/no-listing-07-main-returning-result/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-07-main-returning-result/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch09-error-handling/no-listing-07-main-returning-result/src/main.rs b/listings/ch09-error-handling/no-listing-07-main-returning-result/src/main.rs new file mode 100644 index 0000000000..7f16b8e995 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-07-main-returning-result/src/main.rs @@ -0,0 +1,8 @@ +use std::error::Error; +use std::fs::File; + +fn main() -> Result<(), Box> { + let f = File::open("hello.txt")?; + + Ok(()) +} diff --git a/listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/Cargo.lock b/listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/Cargo.toml b/listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/src/main.rs b/listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/src/main.rs new file mode 100644 index 0000000000..e829724c57 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + // ANCHOR: here + use std::net::IpAddr; + + let home: IpAddr = "127.0.0.1".parse().unwrap(); + // ANCHOR_END: here +} diff --git a/listings/ch09-error-handling/no-listing-09-guess-out-of-range/Cargo.lock b/listings/ch09-error-handling/no-listing-09-guess-out-of-range/Cargo.lock new file mode 100644 index 0000000000..c346748e55 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-09-guess-out-of-range/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.53" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.53 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.53 (registry+https://github.com/rust-lang/crates.io-index)" = "ec350a9417dfd244dc9a6c4a71e13895a4db6b92f0b106f07ebbc3f3bc580cee" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/listings/ch09-error-handling/no-listing-09-guess-out-of-range/Cargo.toml b/listings/ch09-error-handling/no-listing-09-guess-out-of-range/Cargo.toml new file mode 100644 index 0000000000..ad5ca696d5 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-09-guess-out-of-range/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] +rand = "0.5.5" diff --git a/listings/ch09-error-handling/no-listing-09-guess-out-of-range/src/main.rs b/listings/ch09-error-handling/no-listing-09-guess-out-of-range/src/main.rs new file mode 100644 index 0000000000..d89d719aa0 --- /dev/null +++ b/listings/ch09-error-handling/no-listing-09-guess-out-of-range/src/main.rs @@ -0,0 +1,47 @@ +use rand::Rng; +use std::cmp::Ordering; +use std::io; + +fn main() { + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1, 101); + + // ANCHOR: here + loop { + // --snip-- + + // ANCHOR_END: here + println!("Please input your guess."); + + let mut guess = String::new(); + + io::stdin() + .read_line(&mut guess) + .expect("Failed to read line"); + + // ANCHOR: here + let guess: i32 = match guess.trim().parse() { + Ok(num) => num, + Err(_) => continue, + }; + + if guess < 1 || guess > 100 { + println!("The secret number will be between 1 and 100."); + continue; + } + + match guess.cmp(&secret_number) { + // --snip-- + // ANCHOR_END: here + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => { + println!("You win!"); + break; + } + } + // ANCHOR: here + } + // ANCHOR_END: here +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/src/main.rs new file mode 100644 index 0000000000..d2ba23b4a7 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/src/main.rs @@ -0,0 +1,18 @@ +// ANCHOR: here +fn main() { + let number_list = vec![34, 50, 25, 100, 65]; + + let mut largest = number_list[0]; + + for number in number_list { + if number > largest { + largest = number; + } + } + + println!("The largest number is {}", largest); + // ANCHOR_END: here + assert_eq!(largest, 100); + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/src/main.rs new file mode 100644 index 0000000000..9138dfcb44 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/src/main.rs @@ -0,0 +1,25 @@ +fn main() { + let number_list = vec![34, 50, 25, 100, 65]; + + let mut largest = number_list[0]; + + for number in number_list { + if number > largest { + largest = number; + } + } + + println!("The largest number is {}", largest); + + let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8]; + + let mut largest = number_list[0]; + + for number in number_list { + if number > largest { + largest = number; + } + } + + println!("The largest number is {}", largest); +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/src/main.rs new file mode 100644 index 0000000000..7704ff3382 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/src/main.rs @@ -0,0 +1,31 @@ +// ANCHOR: here +fn largest(list: &[i32]) -> i32 { + let mut largest = list[0]; + + for &item in list { + if item > largest { + largest = item; + } + } + + largest +} + +fn main() { + let number_list = vec![34, 50, 25, 100, 65]; + + let result = largest(&number_list); + println!("The largest number is {}", result); + // ANCHOR_END: here + assert_eq!(result, 100); + // ANCHOR: here + + let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8]; + + let result = largest(&number_list); + println!("The largest number is {}", result); + // ANCHOR_END: here + assert_eq!(result, 6000); + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/src/main.rs new file mode 100644 index 0000000000..6b483ec976 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/src/main.rs @@ -0,0 +1,43 @@ +// ANCHOR: here +fn largest_i32(list: &[i32]) -> i32 { + let mut largest = list[0]; + + for &item in list { + if item > largest { + largest = item; + } + } + + largest +} + +fn largest_char(list: &[char]) -> char { + let mut largest = list[0]; + + for &item in list { + if item > largest { + largest = item; + } + } + + largest +} + +fn main() { + let number_list = vec![34, 50, 25, 100, 65]; + + let result = largest_i32(&number_list); + println!("The largest number is {}", result); + // ANCHOR_END: here + assert_eq!(result, 100); + // ANCHOR: here + + let char_list = vec!['y', 'm', 'a', 'q']; + + let result = largest_char(&char_list); + println!("The largest char is {}", result); + // ANCHOR_END: here + assert_eq!(result, 'y'); + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/output.txt b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/output.txt new file mode 100644 index 0000000000..65498128db --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/output.txt @@ -0,0 +1,18 @@ +$ cargo run + Compiling chapter10 v0.1.0 (file:///projects/chapter10) +error[E0369]: binary operation `>` cannot be applied to type `T` + --> src/main.rs:5:17 + | +5 | if item > largest { + | ---- ^ ------- T + | | + | T + | + = note: `T` might need a bound for `std::cmp::PartialOrd` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0369`. +error: could not compile `chapter10`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/src/main.rs new file mode 100644 index 0000000000..e731157060 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/src/main.rs @@ -0,0 +1,23 @@ +fn largest(list: &[T]) -> T { + let mut largest = list[0]; + + for &item in list { + if item > largest { + largest = item; + } + } + + largest +} + +fn main() { + let number_list = vec![34, 50, 25, 100, 65]; + + let result = largest(&number_list); + println!("The largest number is {}", result); + + let char_list = vec!['y', 'm', 'a', 'q']; + + let result = largest(&char_list); + println!("The largest char is {}", result); +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/src/main.rs new file mode 100644 index 0000000000..4252593df9 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/src/main.rs @@ -0,0 +1,9 @@ +struct Point { + x: T, + y: T, +} + +fn main() { + let integer = Point { x: 5, y: 10 }; + let float = Point { x: 1.0, y: 4.0 }; +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/output.txt b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/output.txt new file mode 100644 index 0000000000..dce3be8c50 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/output.txt @@ -0,0 +1,17 @@ +$ cargo run + Compiling chapter10 v0.1.0 (file:///projects/chapter10) +error[E0308]: mismatched types + --> src/main.rs:7:38 + | +7 | let wont_work = Point { x: 5, y: 4.0 }; + | ^^^ expected integer, found floating-point number + | + = note: expected type `{integer}` + found type `{float}` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. +error: could not compile `chapter10`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/src/main.rs new file mode 100644 index 0000000000..7883db1a6f --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/src/main.rs @@ -0,0 +1,8 @@ +struct Point { + x: T, + y: T, +} + +fn main() { + let wont_work = Point { x: 5, y: 4.0 }; +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/src/main.rs new file mode 100644 index 0000000000..615b78cfd7 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/src/main.rs @@ -0,0 +1,10 @@ +struct Point { + x: T, + y: U, +} + +fn main() { + let both_integer = Point { x: 5, y: 10 }; + let both_float = Point { x: 1.0, y: 4.0 }; + let integer_and_float = Point { x: 5, y: 4.0 }; +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/src/main.rs new file mode 100644 index 0000000000..288b64eac5 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/src/main.rs @@ -0,0 +1,16 @@ +struct Point { + x: T, + y: T, +} + +impl Point { + fn x(&self) -> &T { + &self.x + } +} + +fn main() { + let p = Point { x: 5, y: 10 }; + + println!("p.x = {}", p.x()); +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/src/main.rs new file mode 100644 index 0000000000..4c5b01bdcd --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/src/main.rs @@ -0,0 +1,24 @@ +struct Point { + x: T, + y: T, +} + +impl Point { + fn x(&self) -> &T { + &self.x + } +} + +// ANCHOR: here +impl Point { + fn distance_from_origin(&self) -> f32 { + (self.x.powi(2) + self.y.powi(2)).sqrt() + } +} +// ANCHOR_END: here + +fn main() { + let p = Point { x: 5, y: 10 }; + + println!("p.x = {}", p.x()); +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/src/main.rs new file mode 100644 index 0000000000..4a08d1a8d6 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/src/main.rs @@ -0,0 +1,22 @@ +struct Point { + x: T, + y: U, +} + +impl Point { + fn mixup(self, other: Point) -> Point { + Point { + x: self.x, + y: other.y, + } + } +} + +fn main() { + let p1 = Point { x: 5, y: 10.4 }; + let p2 = Point { x: "Hello", y: 'c' }; + + let p3 = p1.mixup(p2); + + println!("p3.x = {}, p3.y = {}", p3.x, p3.y); +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/src/lib.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/src/lib.rs new file mode 100644 index 0000000000..cfaedb02f4 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/src/lib.rs @@ -0,0 +1,3 @@ +pub trait Summary { + fn summarize(&self) -> String; +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/src/lib.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/src/lib.rs new file mode 100644 index 0000000000..c4c83329ef --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/src/lib.rs @@ -0,0 +1,31 @@ +pub trait Summary { + fn summarize(&self) -> String; +} + +// ANCHOR: here +pub struct NewsArticle { + pub headline: String, + pub location: String, + pub author: String, + pub content: String, +} + +impl Summary for NewsArticle { + fn summarize(&self) -> String { + format!("{}, by {} ({})", self.headline, self.author, self.location) + } +} + +pub struct Tweet { + pub username: String, + pub content: String, + pub reply: bool, + pub retweet: bool, +} + +impl Summary for Tweet { + fn summarize(&self) -> String { + format!("{}: {}", self.username, self.content) + } +} +// ANCHOR_END: here diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/src/lib.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/src/lib.rs new file mode 100644 index 0000000000..fb59b84fb1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/src/lib.rs @@ -0,0 +1,29 @@ +// ANCHOR: here +pub trait Summary { + fn summarize(&self) -> String { + String::from("(Read more...)") + } +} +// ANCHOR_END: here + +pub struct NewsArticle { + pub headline: String, + pub location: String, + pub author: String, + pub content: String, +} + +impl Summary for NewsArticle {} + +pub struct Tweet { + pub username: String, + pub content: String, + pub reply: bool, + pub retweet: bool, +} + +impl Summary for Tweet { + fn summarize(&self) -> String { + format!("{}: {}", self.username, self.content) + } +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/src/main.rs new file mode 100644 index 0000000000..7aa6a3bd22 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/src/main.rs @@ -0,0 +1,23 @@ +fn largest(list: &[T]) -> T { + let mut largest = list[0]; + + for &item in list { + if item > largest { + largest = item; + } + } + + largest +} + +fn main() { + let number_list = vec![34, 50, 25, 100, 65]; + + let result = largest(&number_list); + println!("The largest number is {}", result); + + let char_list = vec!['y', 'm', 'a', 'q']; + + let result = largest(&char_list); + println!("The largest char is {}", result); +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/src/lib.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/src/lib.rs new file mode 100644 index 0000000000..669cc5fdc2 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/src/lib.rs @@ -0,0 +1,22 @@ +use std::fmt::Display; + +struct Pair { + x: T, + y: T, +} + +impl Pair { + fn new(x: T, y: T) -> Self { + Self { x, y } + } +} + +impl Pair { + fn cmp_display(&self) { + if self.x >= self.y { + println!("The largest member is x = {}", self.x); + } else { + println!("The largest member is y = {}", self.y); + } + } +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/output.txt b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/output.txt new file mode 100644 index 0000000000..d6364c3c1c --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/output.txt @@ -0,0 +1,19 @@ +$ cargo run + Compiling chapter10 v0.1.0 (file:///projects/chapter10) +error[E0597]: `x` does not live long enough + --> src/main.rs:7:13 + | +7 | r = &x; + | ^^^^^^ borrowed value does not live long enough +8 | } + | - `x` dropped here while still borrowed +9 | +10 | println!("r: {}", r); + | - borrow later used here + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0597`. +error: could not compile `chapter10`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/src/main.rs new file mode 100644 index 0000000000..16adb6a0d6 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/src/main.rs @@ -0,0 +1,14 @@ +fn main() { + // ANCHOR: here + { + let r; + + { + let x = 5; + r = &x; + } + + println!("r: {}", r); + } + // ANCHOR_END: here +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/Cargo.lock new file mode 100644 index 0000000000..6388bb2b53 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/rustfmt-ignore b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/rustfmt-ignore new file mode 100644 index 0000000000..9a53c718a8 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/rustfmt-ignore @@ -0,0 +1,3 @@ +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 diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/src/main.rs new file mode 100644 index 0000000000..65dbf375a8 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/src/main.rs @@ -0,0 +1,14 @@ +fn main() { + // ANCHOR: here + { + let r; // ---------+-- 'a + // | + { // | + let x = 5; // -+-- 'b | + r = &x; // | | + } // -+ | + // | + println!("r: {}", r); // | + } // ---------+ + // ANCHOR_END: here +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/Cargo.lock new file mode 100644 index 0000000000..6388bb2b53 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/rustfmt-ignore b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/rustfmt-ignore new file mode 100644 index 0000000000..9a53c718a8 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/rustfmt-ignore @@ -0,0 +1,3 @@ +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 diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/src/main.rs new file mode 100644 index 0000000000..94e70f00f8 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + // ANCHOR: here + { + let x = 5; // ----------+-- 'b + // | + let r = &x; // --+-- 'a | + // | | + println!("r: {}", r); // | | + // --+ | + } // ----------+ + // ANCHOR_END: here +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/src/main.rs new file mode 100644 index 0000000000..0f076a71db --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + let string1 = String::from("abcd"); + let string2 = "xyz"; + + let result = longest(string1.as_str(), string2); + println!("The longest string is {}", result); +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/output.txt b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/output.txt new file mode 100644 index 0000000000..21fb936145 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/output.txt @@ -0,0 +1,16 @@ +$ cargo run + Compiling chapter10 v0.1.0 (file:///projects/chapter10) +error[E0106]: missing lifetime specifier + --> src/main.rs:9:33 + | +9 | fn longest(x: &str, y: &str) -> &str { + | ^ expected lifetime parameter + | + = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or `y` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0106`. +error: could not compile `chapter10`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/src/main.rs new file mode 100644 index 0000000000..6af8c9f0da --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/src/main.rs @@ -0,0 +1,17 @@ +fn main() { + let string1 = String::from("abcd"); + let string2 = "xyz"; + + let result = longest(string1.as_str(), string2); + println!("The longest string is {}", result); +} + +// ANCHOR: here +fn longest(x: &str, y: &str) -> &str { + if x.len() > y.len() { + x + } else { + y + } +} +// ANCHOR_END: here diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/src/main.rs new file mode 100644 index 0000000000..09c3a0daaa --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/src/main.rs @@ -0,0 +1,17 @@ +fn main() { + let string1 = String::from("abcd"); + let string2 = "xyz"; + + let result = longest(string1.as_str(), string2); + println!("The longest string is {}", result); +} + +// ANCHOR: here +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { + if x.len() > y.len() { + x + } else { + y + } +} +// ANCHOR_END: here diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/src/main.rs new file mode 100644 index 0000000000..836ec72959 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/src/main.rs @@ -0,0 +1,19 @@ +// ANCHOR: here +fn main() { + let string1 = String::from("long string is long"); + + { + let string2 = String::from("xyz"); + let result = longest(string1.as_str(), string2.as_str()); + println!("The longest string is {}", result); + } +} +// ANCHOR_END: here + +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { + if x.len() > y.len() { + x + } else { + y + } +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/output.txt b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/output.txt new file mode 100644 index 0000000000..bcedda0f49 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/output.txt @@ -0,0 +1,18 @@ +$ cargo run + Compiling chapter10 v0.1.0 (file:///projects/chapter10) +error[E0597]: `string2` does not live long enough + --> src/main.rs:6:44 + | +6 | result = longest(string1.as_str(), string2.as_str()); + | ^^^^^^^ borrowed value does not live long enough +7 | } + | - `string2` dropped here while still borrowed +8 | println!("The longest string is {}", result); + | ------ borrow later used here + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0597`. +error: could not compile `chapter10`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/src/main.rs new file mode 100644 index 0000000000..2a6fa5898f --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/src/main.rs @@ -0,0 +1,19 @@ +// ANCHOR: here +fn main() { + let string1 = String::from("long string is long"); + let result; + { + let string2 = String::from("xyz"); + result = longest(string1.as_str(), string2.as_str()); + } + println!("The longest string is {}", result); +} +// ANCHOR_END: here + +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { + if x.len() > y.len() { + x + } else { + y + } +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/src/main.rs new file mode 100644 index 0000000000..2937b194ca --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/src/main.rs @@ -0,0 +1,11 @@ +struct ImportantExcerpt<'a> { + part: &'a str, +} + +fn main() { + let novel = String::from("Call me Ishmael. Some years ago..."); + let first_sentence = novel.split('.').next().expect("Could not find a '.'"); + let i = ImportantExcerpt { + part: first_sentence, + }; +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/src/main.rs new file mode 100644 index 0000000000..431a261d2c --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/src/main.rs @@ -0,0 +1,29 @@ +// ANCHOR: here +fn first_word(s: &str) -> &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() { + let my_string = String::from("hello world"); + + // first_word works on slices of `String`s + let word = first_word(&my_string[..]); + + let my_string_literal = "hello world"; + + // first_word works on slices of string literals + 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); +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/src/lib.rs b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/src/lib.rs new file mode 100644 index 0000000000..fa644ca4fb --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/src/lib.rs @@ -0,0 +1,29 @@ +pub trait Summary { + fn summarize(&self) -> String; +} + +pub struct NewsArticle { + pub headline: String, + pub location: String, + pub author: String, + pub content: String, +} + +impl Summary for NewsArticle { + fn summarize(&self) -> String { + format!("{}, by {} ({})", self.headline, self.author, self.location) + } +} + +pub struct Tweet { + pub username: String, + pub content: String, + pub reply: bool, + pub retweet: bool, +} + +impl Summary for Tweet { + fn summarize(&self) -> String { + format!("{}: {}", self.username, self.content) + } +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/src/main.rs new file mode 100644 index 0000000000..466dc4d59a --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/src/main.rs @@ -0,0 +1,16 @@ +use chapter10::{self, Summary, Tweet}; + +fn main() { + // ANCHOR: here + let tweet = Tweet { + username: String::from("horse_ebooks"), + content: String::from( + "of course, as you probably already know, people", + ), + reply: false, + retweet: false, + }; + + println!("1 new tweet: {}", tweet.summarize()); + // ANCHOR_END: here +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/src/lib.rs b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/src/lib.rs new file mode 100644 index 0000000000..b6f93a68f7 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/src/lib.rs @@ -0,0 +1,27 @@ +pub trait Summary { + fn summarize(&self) -> String { + String::from("(Read more...)") + } +} + +pub struct NewsArticle { + pub headline: String, + pub location: String, + pub author: String, + pub content: String, +} + +impl Summary for NewsArticle {} + +pub struct Tweet { + pub username: String, + pub content: String, + pub reply: bool, + pub retweet: bool, +} + +impl Summary for Tweet { + fn summarize(&self) -> String { + format!("{}: {}", self.username, self.content) + } +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/src/main.rs new file mode 100644 index 0000000000..44c9c64ea1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/src/main.rs @@ -0,0 +1,17 @@ +use chapter10::{self, NewsArticle, Summary}; + +fn main() { + // ANCHOR: here + let article = NewsArticle { + headline: String::from("Penguins win the Stanley Cup Championship!"), + location: String::from("Pittsburgh, PA, USA"), + author: String::from("Iceburgh"), + content: String::from( + "The Pittsburgh Penguins once again are the best \ + hockey team in the NHL.", + ), + }; + + println!("New article available! {}", article.summarize()); + // ANCHOR_END: here +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/src/lib.rs b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/src/lib.rs new file mode 100644 index 0000000000..643906f691 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/src/lib.rs @@ -0,0 +1,24 @@ +// ANCHOR: here +pub trait Summary { + fn summarize_author(&self) -> String; + + fn summarize(&self) -> String { + format!("(Read more from {}...)", self.summarize_author()) + } +} +// ANCHOR_END: here + +pub struct Tweet { + pub username: String, + pub content: String, + pub reply: bool, + pub retweet: bool, +} + +// ANCHOR: impl +impl Summary for Tweet { + fn summarize_author(&self) -> String { + format!("@{}", self.username) + } +} +// ANCHOR_END: impl diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/src/main.rs new file mode 100644 index 0000000000..466dc4d59a --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/src/main.rs @@ -0,0 +1,16 @@ +use chapter10::{self, Summary, Tweet}; + +fn main() { + // ANCHOR: here + let tweet = Tweet { + username: String::from("horse_ebooks"), + content: String::from( + "of course, as you probably already know, people", + ), + reply: false, + retweet: false, + }; + + println!("1 new tweet: {}", tweet.summarize()); + // ANCHOR_END: here +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/src/lib.rs b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/src/lib.rs new file mode 100644 index 0000000000..95038433e8 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/src/lib.rs @@ -0,0 +1,35 @@ +pub trait Summary { + fn summarize(&self) -> String; +} + +pub struct NewsArticle { + pub headline: String, + pub location: String, + pub author: String, + pub content: String, +} + +impl Summary for NewsArticle { + fn summarize(&self) -> String { + format!("{}, by {} ({})", self.headline, self.author, self.location) + } +} + +pub struct Tweet { + pub username: String, + pub content: String, + pub reply: bool, + pub retweet: bool, +} + +impl Summary for Tweet { + fn summarize(&self) -> String { + format!("{}: {}", self.username, self.content) + } +} + +// ANCHOR: here +pub fn notify(item: impl Summary) { + println!("Breaking news! {}", item.summarize()); +} +// ANCHOR_END: here diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/src/lib.rs b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/src/lib.rs new file mode 100644 index 0000000000..a611fce38e --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/src/lib.rs @@ -0,0 +1,42 @@ +pub trait Summary { + fn summarize(&self) -> String; +} + +pub struct NewsArticle { + pub headline: String, + pub location: String, + pub author: String, + pub content: String, +} + +impl Summary for NewsArticle { + fn summarize(&self) -> String { + format!("{}, by {} ({})", self.headline, self.author, self.location) + } +} + +pub struct Tweet { + pub username: String, + pub content: String, + pub reply: bool, + pub retweet: bool, +} + +impl Summary for Tweet { + fn summarize(&self) -> String { + format!("{}: {}", self.username, self.content) + } +} + +// ANCHOR: here +fn returns_summarizable() -> impl Summary { + Tweet { + username: String::from("horse_ebooks"), + content: String::from( + "of course, as you probably already know, people", + ), + reply: false, + retweet: false, + } +} +// ANCHOR_END: here diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/src/lib.rs b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/src/lib.rs new file mode 100644 index 0000000000..7cd81d4c32 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/src/lib.rs @@ -0,0 +1,56 @@ +pub trait Summary { + fn summarize(&self) -> String; +} + +pub struct NewsArticle { + pub headline: String, + pub location: String, + pub author: String, + pub content: String, +} + +impl Summary for NewsArticle { + fn summarize(&self) -> String { + format!("{}, by {} ({})", self.headline, self.author, self.location) + } +} + +pub struct Tweet { + pub username: String, + pub content: String, + pub reply: bool, + pub retweet: bool, +} + +impl Summary for Tweet { + fn summarize(&self) -> String { + format!("{}: {}", self.username, self.content) + } +} + +// ANCHOR: here +fn returns_summarizable(switch: bool) -> impl Summary { + if switch { + NewsArticle { + headline: String::from( + "Penguins win the Stanley Cup Championship!", + ), + location: String::from("Pittsburgh, PA, USA"), + author: String::from("Iceburgh"), + content: String::from( + "The Pittsburgh Penguins once again are the best \ + hockey team in the NHL.", + ), + } + } else { + Tweet { + username: String::from("horse_ebooks"), + content: String::from( + "of course, as you probably already know, people", + ), + reply: false, + retweet: false, + } + } +} +// ANCHOR_END: here diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/output.txt b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/output.txt new file mode 100644 index 0000000000..ca7023f1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/output.txt @@ -0,0 +1,29 @@ +$ cargo run + Compiling chapter10 v0.1.0 (file:///projects/chapter10) +error[E0508]: cannot move out of type `[T]`, a non-copy slice + --> src/main.rs:2:23 + | +2 | let mut largest = list[0]; + | ^^^^^^^ + | | + | cannot move out of here + | move occurs because `list[_]` has type `T`, which does not implement the `Copy` trait + | help: consider borrowing here: `&list[0]` + +error[E0507]: cannot move out of a shared reference + --> src/main.rs:4:18 + | +4 | for &item in list { + | ----- ^^^^ + | || + | |data moved here + | |move occurs because `item` has type `T`, which does not implement the `Copy` trait + | help: consider removing the `&`: `item` + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0507, E0508. +For more information about an error, try `rustc --explain E0507`. +error: could not compile `chapter10`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/src/main.rs new file mode 100644 index 0000000000..525ce815a0 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/src/main.rs @@ -0,0 +1,25 @@ +// ANCHOR: here +fn largest(list: &[T]) -> T { + // ANCHOR_END: here + let mut largest = list[0]; + + for &item in list { + if item > largest { + largest = item; + } + } + + largest +} + +fn main() { + let number_list = vec![34, 50, 25, 100, 65]; + + let result = largest(&number_list); + println!("The largest number is {}", result); + + let char_list = vec!['y', 'm', 'a', 'q']; + + let result = largest(&char_list); + println!("The largest char is {}", result); +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/src/main.rs new file mode 100644 index 0000000000..d144305cb0 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + let string1 = String::from("abcd"); + let string2 = "efghijklmnopqrstuvwxyz"; + + let result = longest(string1.as_str(), string2); + println!("The longest string is {}", result); +} + +// ANCHOR: here +fn longest<'a>(x: &'a str, y: &str) -> &'a str { + x +} +// ANCHOR_END: here diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/output.txt b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/output.txt new file mode 100644 index 0000000000..cadd5fa32c --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/output.txt @@ -0,0 +1,17 @@ +$ cargo run + Compiling chapter10 v0.1.0 (file:///projects/chapter10) +error[E0515]: cannot return value referencing local variable `result` + --> src/main.rs:11:5 + | +11 | result.as_str() + | ------^^^^^^^^^ + | | + | returns a value referencing data owned by the current function + | `result` is borrowed here + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0515`. +error: could not compile `chapter10`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/src/main.rs new file mode 100644 index 0000000000..aca4be0a78 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/src/main.rs @@ -0,0 +1,14 @@ +fn main() { + let string1 = String::from("abcd"); + let string2 = "xyz"; + + let result = longest(string1.as_str(), string2); + println!("The longest string is {}", result); +} + +// ANCHOR: here +fn longest<'a>(x: &str, y: &str) -> &'a str { + let result = String::from("really long string"); + result.as_str() +} +// ANCHOR_END: here diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/src/main.rs new file mode 100644 index 0000000000..32ad530b51 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/src/main.rs @@ -0,0 +1,28 @@ +struct ImportantExcerpt<'a> { + part: &'a str, +} + +// ANCHOR: 1st +impl<'a> ImportantExcerpt<'a> { + fn level(&self) -> i32 { + 3 + } +} +// ANCHOR_END: 1st + +// ANCHOR: 3rd +impl<'a> ImportantExcerpt<'a> { + fn announce_and_return_part(&self, announcement: &str) -> &str { + println!("Attention please: {}", announcement); + self.part + } +} +// ANCHOR_END: 3rd + +fn main() { + let novel = String::from("Call me Ishmael. Some years ago..."); + let first_sentence = novel.split('.').next().expect("Could not find a '.'"); + let i = ImportantExcerpt { + part: first_sentence, + }; +} diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/Cargo.lock b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/Cargo.toml b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/src/main.rs b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/src/main.rs new file mode 100644 index 0000000000..cfafa9a6d3 --- /dev/null +++ b/listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/src/main.rs @@ -0,0 +1,31 @@ +fn main() { + let string1 = String::from("abcd"); + let string2 = "xyz"; + + let result = longest_with_an_announcement( + string1.as_str(), + string2, + "Today is someone's birthday!", + ); + println!("The longest string is {}", result); +} + +// ANCHOR: here +use std::fmt::Display; + +fn longest_with_an_announcement<'a, T>( + x: &'a str, + y: &'a str, + ann: T, +) -> &'a str +where + T: Display, +{ + println!("Announcement! {}", ann); + if x.len() > y.len() { + x + } else { + y + } +} +// ANCHOR_END: here diff --git a/listings/ch11-writing-automated-tests/listing-11-01/Cargo.lock b/listings/ch11-writing-automated-tests/listing-11-01/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/listing-11-01/Cargo.toml b/listings/ch11-writing-automated-tests/listing-11-01/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/listing-11-01/output.txt b/listings/ch11-writing-automated-tests/listing-11-01/output.txt new file mode 100644 index 0000000000..b56a40a1f4 --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-01/output.txt @@ -0,0 +1,16 @@ +$ cargo test + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.57s + Running target/debug/deps/adder-076f0528706a8604 + +running 1 test +test tests::it_works ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests adder + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/listings/ch11-writing-automated-tests/listing-11-01/src/lib.rs b/listings/ch11-writing-automated-tests/listing-11-01/src/lib.rs new file mode 100644 index 0000000000..8e678421e9 --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-01/src/lib.rs @@ -0,0 +1,11 @@ +// ANCHOR: here +#[cfg(test)] +mod tests { + #[test] + fn it_works() { + assert_eq!(2 + 2, 4); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch11-writing-automated-tests/listing-11-03/Cargo.lock b/listings/ch11-writing-automated-tests/listing-11-03/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/listing-11-03/Cargo.toml b/listings/ch11-writing-automated-tests/listing-11-03/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/listing-11-03/output.txt b/listings/ch11-writing-automated-tests/listing-11-03/output.txt new file mode 100644 index 0000000000..bc6a905b25 --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-03/output.txt @@ -0,0 +1,22 @@ +$ cargo test + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.72s + Running target/debug/deps/adder-076f0528706a8604 + +running 2 tests +test tests::another ... FAILED +test tests::exploration ... ok + +failures: + +---- tests::another stdout ---- +thread 'main' panicked at 'Make this test fail', src/lib.rs:10:9 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. + + +failures: + tests::another + +test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/listings/ch11-writing-automated-tests/listing-11-03/src/lib.rs b/listings/ch11-writing-automated-tests/listing-11-03/src/lib.rs new file mode 100644 index 0000000000..92f315ac85 --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-03/src/lib.rs @@ -0,0 +1,16 @@ +// ANCHOR: here +#[cfg(test)] +mod tests { + #[test] + fn exploration() { + assert_eq!(2 + 2, 4); + } + + #[test] + fn another() { + panic!("Make this test fail"); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch11-writing-automated-tests/listing-11-05/Cargo.lock b/listings/ch11-writing-automated-tests/listing-11-05/Cargo.lock new file mode 100644 index 0000000000..9dcd5439df --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "rectangle" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/listing-11-05/Cargo.toml b/listings/ch11-writing-automated-tests/listing-11-05/Cargo.toml new file mode 100644 index 0000000000..32efee50ad --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "rectangle" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/listing-11-05/src/lib.rs b/listings/ch11-writing-automated-tests/listing-11-05/src/lib.rs new file mode 100644 index 0000000000..aad33554b9 --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-05/src/lib.rs @@ -0,0 +1,15 @@ +// ANCHOR: here +#[derive(Debug)] +struct Rectangle { + width: u32, + height: u32, +} + +impl Rectangle { + fn can_hold(&self, other: &Rectangle) -> bool { + self.width > other.width && self.height > other.height + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch11-writing-automated-tests/listing-11-06/Cargo.lock b/listings/ch11-writing-automated-tests/listing-11-06/Cargo.lock new file mode 100644 index 0000000000..9dcd5439df --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "rectangle" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/listing-11-06/Cargo.toml b/listings/ch11-writing-automated-tests/listing-11-06/Cargo.toml new file mode 100644 index 0000000000..32efee50ad --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "rectangle" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/listing-11-06/output.txt b/listings/ch11-writing-automated-tests/listing-11-06/output.txt new file mode 100644 index 0000000000..337878eb22 --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-06/output.txt @@ -0,0 +1,16 @@ +$ cargo test + Compiling rectangle v0.1.0 (file:///projects/rectangle) + Finished test [unoptimized + debuginfo] target(s) in 0.66s + Running target/debug/deps/rectangle-6fe0c0eff9a70690 + +running 1 test +test tests::larger_can_hold_smaller ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests rectangle + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/listings/ch11-writing-automated-tests/listing-11-06/src/lib.rs b/listings/ch11-writing-automated-tests/listing-11-06/src/lib.rs new file mode 100644 index 0000000000..a02395313d --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-06/src/lib.rs @@ -0,0 +1,34 @@ +#[derive(Debug)] +struct Rectangle { + width: u32, + height: u32, +} + +impl Rectangle { + fn can_hold(&self, other: &Rectangle) -> bool { + self.width > other.width && self.height > other.height + } +} + +// ANCHOR: here +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn larger_can_hold_smaller() { + let larger = Rectangle { + width: 8, + height: 7, + }; + let smaller = Rectangle { + width: 5, + height: 1, + }; + + assert!(larger.can_hold(&smaller)); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch11-writing-automated-tests/listing-11-07/Cargo.lock b/listings/ch11-writing-automated-tests/listing-11-07/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/listing-11-07/Cargo.toml b/listings/ch11-writing-automated-tests/listing-11-07/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/listing-11-07/output.txt b/listings/ch11-writing-automated-tests/listing-11-07/output.txt new file mode 100644 index 0000000000..548ab756ba --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-07/output.txt @@ -0,0 +1,16 @@ +$ cargo test + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.58s + Running target/debug/deps/adder-076f0528706a8604 + +running 1 test +test tests::it_adds_two ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests adder + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/listings/ch11-writing-automated-tests/listing-11-07/src/lib.rs b/listings/ch11-writing-automated-tests/listing-11-07/src/lib.rs new file mode 100644 index 0000000000..534073276d --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-07/src/lib.rs @@ -0,0 +1,17 @@ +// ANCHOR: here +pub fn add_two(a: i32) -> i32 { + a + 2 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_adds_two() { + assert_eq!(4, add_two(2)); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch11-writing-automated-tests/listing-11-08/Cargo.lock b/listings/ch11-writing-automated-tests/listing-11-08/Cargo.lock new file mode 100644 index 0000000000..5802b7dc9a --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "guessing_game" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/listing-11-08/Cargo.toml b/listings/ch11-writing-automated-tests/listing-11-08/Cargo.toml new file mode 100644 index 0000000000..922762ab1f --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/listing-11-08/output.txt b/listings/ch11-writing-automated-tests/listing-11-08/output.txt new file mode 100644 index 0000000000..09c8d9e4bd --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-08/output.txt @@ -0,0 +1,16 @@ +$ cargo test + Compiling guessing_game v0.1.0 (file:///projects/guessing_game) + Finished test [unoptimized + debuginfo] target(s) in 0.58s + Running target/debug/deps/guessing_game-1bf5eca04a7d401d + +running 1 test +test tests::greater_than_100 ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests guessing_game + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/listings/ch11-writing-automated-tests/listing-11-08/src/lib.rs b/listings/ch11-writing-automated-tests/listing-11-08/src/lib.rs new file mode 100644 index 0000000000..b417302131 --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-08/src/lib.rs @@ -0,0 +1,28 @@ +// ANCHOR: here +pub struct Guess { + value: i32, +} + +impl Guess { + pub fn new(value: i32) -> Guess { + if value < 1 || value > 100 { + panic!("Guess value must be between 1 and 100, got {}.", value); + } + + Guess { value } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[should_panic] + fn greater_than_100() { + Guess::new(200); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch11-writing-automated-tests/listing-11-09/Cargo.lock b/listings/ch11-writing-automated-tests/listing-11-09/Cargo.lock new file mode 100644 index 0000000000..5802b7dc9a --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "guessing_game" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/listing-11-09/Cargo.toml b/listings/ch11-writing-automated-tests/listing-11-09/Cargo.toml new file mode 100644 index 0000000000..922762ab1f --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/listing-11-09/src/lib.rs b/listings/ch11-writing-automated-tests/listing-11-09/src/lib.rs new file mode 100644 index 0000000000..ffa543bfb6 --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-09/src/lib.rs @@ -0,0 +1,37 @@ +pub struct Guess { + value: i32, +} + +// ANCHOR: here +// --snip-- +impl Guess { + pub fn new(value: i32) -> Guess { + if value < 1 { + panic!( + "Guess value must be greater than or equal to 1, got {}.", + value + ); + } else if value > 100 { + panic!( + "Guess value must be less than or equal to 100, got {}.", + value + ); + } + + Guess { value } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[should_panic(expected = "Guess value must be less than or equal to 100")] + fn greater_than_100() { + Guess::new(200); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch11-writing-automated-tests/listing-11-10/Cargo.lock b/listings/ch11-writing-automated-tests/listing-11-10/Cargo.lock new file mode 100644 index 0000000000..a6d35e395a --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "silly-function" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/listing-11-10/Cargo.toml b/listings/ch11-writing-automated-tests/listing-11-10/Cargo.toml new file mode 100644 index 0000000000..4e0f185af4 --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "silly-function" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/listing-11-10/output.txt b/listings/ch11-writing-automated-tests/listing-11-10/output.txt new file mode 100644 index 0000000000..3f1af78bf9 --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-10/output.txt @@ -0,0 +1,25 @@ +$ cargo test + Compiling silly-function v0.1.0 (file:///projects/silly-function) + Finished test [unoptimized + debuginfo] target(s) in 0.58s + Running target/debug/deps/silly_function-b02a4796f0aeb021 + +running 2 tests +test tests::this_test_will_fail ... FAILED +test tests::this_test_will_pass ... ok + +failures: + +---- tests::this_test_will_fail stdout ---- +I got the value 8 +thread 'main' panicked at 'assertion failed: `(left == right)` + left: `5`, + right: `10`', src/lib.rs:19:9 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. + + +failures: + tests::this_test_will_fail + +test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/listings/ch11-writing-automated-tests/listing-11-10/src/lib.rs b/listings/ch11-writing-automated-tests/listing-11-10/src/lib.rs new file mode 100644 index 0000000000..6fd76ce006 --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-10/src/lib.rs @@ -0,0 +1,21 @@ +fn prints_and_returns_10(a: i32) -> i32 { + println!("I got the value {}", a); + 10 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn this_test_will_pass() { + let value = prints_and_returns_10(4); + assert_eq!(10, value); + } + + #[test] + fn this_test_will_fail() { + let value = prints_and_returns_10(8); + assert_eq!(5, value); + } +} diff --git a/listings/ch11-writing-automated-tests/listing-11-11/Cargo.lock b/listings/ch11-writing-automated-tests/listing-11-11/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/listing-11-11/Cargo.toml b/listings/ch11-writing-automated-tests/listing-11-11/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/listing-11-11/output.txt b/listings/ch11-writing-automated-tests/listing-11-11/output.txt new file mode 100644 index 0000000000..7e48f1c502 --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-11/output.txt @@ -0,0 +1,18 @@ +$ cargo test + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.62s + Running target/debug/deps/adder-076f0528706a8604 + +running 3 tests +test tests::add_three_and_two ... ok +test tests::add_two_and_two ... ok +test tests::one_hundred ... ok + +test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests adder + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/listings/ch11-writing-automated-tests/listing-11-11/src/lib.rs b/listings/ch11-writing-automated-tests/listing-11-11/src/lib.rs new file mode 100644 index 0000000000..f56715263e --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-11/src/lib.rs @@ -0,0 +1,23 @@ +pub fn add_two(a: i32) -> i32 { + a + 2 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn add_two_and_two() { + assert_eq!(4, add_two(2)); + } + + #[test] + fn add_three_and_two() { + assert_eq!(5, add_two(3)); + } + + #[test] + fn one_hundred() { + assert_eq!(102, add_two(100)); + } +} diff --git a/listings/ch11-writing-automated-tests/listing-11-12/Cargo.lock b/listings/ch11-writing-automated-tests/listing-11-12/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/listing-11-12/Cargo.toml b/listings/ch11-writing-automated-tests/listing-11-12/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/listing-11-12/src/lib.rs b/listings/ch11-writing-automated-tests/listing-11-12/src/lib.rs new file mode 100644 index 0000000000..800b84f53b --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-12/src/lib.rs @@ -0,0 +1,21 @@ +// ANCHOR: here +pub fn add_two(a: i32) -> i32 { + internal_adder(a, 2) +} + +fn internal_adder(a: i32, b: i32) -> i32 { + a + b +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn internal() { + assert_eq!(4, internal_adder(2, 2)); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch11-writing-automated-tests/listing-11-13/Cargo.lock b/listings/ch11-writing-automated-tests/listing-11-13/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/listing-11-13/Cargo.toml b/listings/ch11-writing-automated-tests/listing-11-13/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/listing-11-13/output.txt b/listings/ch11-writing-automated-tests/listing-11-13/output.txt new file mode 100644 index 0000000000..7648a5e039 --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-13/output.txt @@ -0,0 +1,23 @@ +$ cargo test + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.73s + Running target/debug/deps/adder-076f0528706a8604 + +running 1 test +test tests::internal ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Running target/debug/deps/integration_test-60fcbc66f73b2933 + +running 1 test +test it_adds_two ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests adder + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/listings/ch11-writing-automated-tests/listing-11-13/src/lib.rs b/listings/ch11-writing-automated-tests/listing-11-13/src/lib.rs new file mode 100644 index 0000000000..c3961b1f62 --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-13/src/lib.rs @@ -0,0 +1,17 @@ +pub fn add_two(a: i32) -> i32 { + internal_adder(a, 2) +} + +fn internal_adder(a: i32, b: i32) -> i32 { + a + b +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn internal() { + assert_eq!(4, internal_adder(2, 2)); + } +} diff --git a/listings/ch11-writing-automated-tests/listing-11-13/tests/integration_test.rs b/listings/ch11-writing-automated-tests/listing-11-13/tests/integration_test.rs new file mode 100644 index 0000000000..e26fa71096 --- /dev/null +++ b/listings/ch11-writing-automated-tests/listing-11-13/tests/integration_test.rs @@ -0,0 +1,6 @@ +use adder; + +#[test] +fn it_adds_two() { + assert_eq!(4, adder::add_two(2)); +} diff --git a/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/Cargo.lock b/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/Cargo.toml b/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/output.txt b/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/output.txt new file mode 100644 index 0000000000..bf2e1a8fe6 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/output.txt @@ -0,0 +1,16 @@ +$ cargo test + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.59s + Running target/debug/deps/adder-076f0528706a8604 + +running 1 test +test tests::exploration ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests adder + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/src/lib.rs b/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/src/lib.rs new file mode 100644 index 0000000000..2974d7273d --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/src/lib.rs @@ -0,0 +1,11 @@ +// ANCHOR: here +#[cfg(test)] +mod tests { + #[test] + fn exploration() { + assert_eq!(2 + 2, 4); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/Cargo.lock b/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/Cargo.lock new file mode 100644 index 0000000000..9dcd5439df --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "rectangle" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/Cargo.toml b/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/Cargo.toml new file mode 100644 index 0000000000..32efee50ad --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "rectangle" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/output.txt b/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/output.txt new file mode 100644 index 0000000000..222bd99e47 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/output.txt @@ -0,0 +1,17 @@ +$ cargo test + Compiling rectangle v0.1.0 (file:///projects/rectangle) + Finished test [unoptimized + debuginfo] target(s) in 0.66s + Running target/debug/deps/rectangle-6fe0c0eff9a70690 + +running 2 tests +test tests::larger_can_hold_smaller ... ok +test tests::smaller_cannot_hold_larger ... ok + +test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests rectangle + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/src/lib.rs b/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/src/lib.rs new file mode 100644 index 0000000000..338ad09364 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/src/lib.rs @@ -0,0 +1,51 @@ +#[derive(Debug)] +struct Rectangle { + width: u32, + height: u32, +} + +impl Rectangle { + fn can_hold(&self, other: &Rectangle) -> bool { + self.width > other.width && self.height > other.height + } +} + +// ANCHOR: here +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn larger_can_hold_smaller() { + // --snip-- + // ANCHOR_END: here + let larger = Rectangle { + width: 8, + height: 7, + }; + let smaller = Rectangle { + width: 5, + height: 1, + }; + + assert!(larger.can_hold(&smaller)); + // ANCHOR: here + } + + #[test] + fn smaller_cannot_hold_larger() { + let larger = Rectangle { + width: 8, + height: 7, + }; + let smaller = Rectangle { + width: 5, + height: 1, + }; + + assert!(!smaller.can_hold(&larger)); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/Cargo.lock b/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/Cargo.lock new file mode 100644 index 0000000000..9dcd5439df --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "rectangle" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/Cargo.toml b/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/Cargo.toml new file mode 100644 index 0000000000..32efee50ad --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "rectangle" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/output.txt b/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/output.txt new file mode 100644 index 0000000000..04913446b7 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/output.txt @@ -0,0 +1,22 @@ +$ cargo test + Compiling rectangle v0.1.0 (file:///projects/rectangle) + Finished test [unoptimized + debuginfo] target(s) in 0.66s + Running target/debug/deps/rectangle-6fe0c0eff9a70690 + +running 2 tests +test tests::larger_can_hold_smaller ... FAILED +test tests::smaller_cannot_hold_larger ... ok + +failures: + +---- tests::larger_can_hold_smaller stdout ---- +thread 'main' panicked at 'assertion failed: larger.can_hold(&smaller)', src/lib.rs:28:9 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. + + +failures: + tests::larger_can_hold_smaller + +test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/src/lib.rs b/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/src/lib.rs new file mode 100644 index 0000000000..33a2dd0ac1 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/src/lib.rs @@ -0,0 +1,49 @@ +#[derive(Debug)] +struct Rectangle { + width: u32, + height: u32, +} + +// ANCHOR: here +// --snip-- +impl Rectangle { + fn can_hold(&self, other: &Rectangle) -> bool { + self.width < other.width && self.height > other.height + } +} +// ANCHOR_END: here + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn larger_can_hold_smaller() { + let larger = Rectangle { + width: 8, + height: 7, + }; + let smaller = Rectangle { + width: 5, + height: 1, + }; + + assert!(larger.can_hold(&smaller)); + } + + #[test] + fn smaller_cannot_hold_larger() { + let larger = Rectangle { + width: 8, + height: 7, + }; + let smaller = Rectangle { + width: 5, + height: 1, + }; + + assert!(!smaller.can_hold(&larger)); + } +} + +fn main() {} diff --git a/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/Cargo.lock b/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/Cargo.toml b/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/output.txt b/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/output.txt new file mode 100644 index 0000000000..6b51b3980a --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/output.txt @@ -0,0 +1,23 @@ +$ cargo test + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.61s + Running target/debug/deps/adder-076f0528706a8604 + +running 1 test +test tests::it_adds_two ... FAILED + +failures: + +---- tests::it_adds_two stdout ---- +thread 'main' panicked at 'assertion failed: `(left == right)` + left: `4`, + right: `5`', src/lib.rs:11:9 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. + + +failures: + tests::it_adds_two + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/src/lib.rs b/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/src/lib.rs new file mode 100644 index 0000000000..8b4534b4aa --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/src/lib.rs @@ -0,0 +1,17 @@ +// ANCHOR: here +pub fn add_two(a: i32) -> i32 { + a + 3 +} +// ANCHOR_END: here + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_adds_two() { + assert_eq!(4, add_two(2)); + } +} + +fn main() {} diff --git a/listings/ch11-writing-automated-tests/no-listing-05-greeter/Cargo.lock b/listings/ch11-writing-automated-tests/no-listing-05-greeter/Cargo.lock new file mode 100644 index 0000000000..9a7ecdd9f2 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-05-greeter/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "greeter" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/no-listing-05-greeter/Cargo.toml b/listings/ch11-writing-automated-tests/no-listing-05-greeter/Cargo.toml new file mode 100644 index 0000000000..c289e837ab --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-05-greeter/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "greeter" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/no-listing-05-greeter/src/lib.rs b/listings/ch11-writing-automated-tests/no-listing-05-greeter/src/lib.rs new file mode 100644 index 0000000000..4fcdbbf279 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-05-greeter/src/lib.rs @@ -0,0 +1,18 @@ +// ANCHOR: here +pub fn greeting(name: &str) -> String { + format!("Hello {}!", name) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn greeting_contains_name() { + let result = greeting("Carol"); + assert!(result.contains("Carol")); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/Cargo.lock b/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/Cargo.lock new file mode 100644 index 0000000000..9a7ecdd9f2 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "greeter" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/Cargo.toml b/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/Cargo.toml new file mode 100644 index 0000000000..c289e837ab --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "greeter" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/output.txt b/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/output.txt new file mode 100644 index 0000000000..f7b6e9b4fa --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/output.txt @@ -0,0 +1,21 @@ +$ cargo test + Compiling greeter v0.1.0 (file:///projects/greeter) + Finished test [unoptimized + debuginfo] target(s) in 0.91s + Running target/debug/deps/greeter-01c2d86f487c60e6 + +running 1 test +test tests::greeting_contains_name ... FAILED + +failures: + +---- tests::greeting_contains_name stdout ---- +thread 'main' panicked at 'assertion failed: result.contains("Carol")', src/lib.rs:12:9 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. + + +failures: + tests::greeting_contains_name + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/src/lib.rs b/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/src/lib.rs new file mode 100644 index 0000000000..d516534e59 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/src/lib.rs @@ -0,0 +1,18 @@ +// ANCHOR: here +pub fn greeting(name: &str) -> String { + String::from("Hello!") +} +// ANCHOR_END: here + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn greeting_contains_name() { + let result = greeting("Carol"); + assert!(result.contains("Carol")); + } +} + +fn main() {} diff --git a/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/Cargo.lock b/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/Cargo.lock new file mode 100644 index 0000000000..9a7ecdd9f2 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "greeter" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/Cargo.toml b/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/Cargo.toml new file mode 100644 index 0000000000..c289e837ab --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "greeter" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/output.txt b/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/output.txt new file mode 100644 index 0000000000..a30b0cd77c --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/output.txt @@ -0,0 +1,21 @@ +$ cargo test + Compiling greeter v0.1.0 (file:///projects/greeter) + Finished test [unoptimized + debuginfo] target(s) in 0.93s + Running target/debug/deps/greeter-01c2d86f487c60e6 + +running 1 test +test tests::greeting_contains_name ... FAILED + +failures: + +---- tests::greeting_contains_name stdout ---- +thread 'main' panicked at 'Greeting did not contain name, value was `Hello!`', src/lib.rs:12:9 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. + + +failures: + tests::greeting_contains_name + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/src/lib.rs b/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/src/lib.rs new file mode 100644 index 0000000000..519c7a4c6f --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/src/lib.rs @@ -0,0 +1,20 @@ +pub fn greeting(name: &str) -> String { + String::from("Hello!") +} + +#[cfg(test)] +mod tests { + use super::*; + + // ANCHOR: here + #[test] + fn greeting_contains_name() { + let result = greeting("Carol"); + assert!( + result.contains("Carol"), + "Greeting did not contain name, value was `{}`", + result + ); + } + // ANCHOR_END: here +} diff --git a/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/Cargo.lock b/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/Cargo.lock new file mode 100644 index 0000000000..5802b7dc9a --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "guessing_game" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/Cargo.toml b/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/Cargo.toml new file mode 100644 index 0000000000..922762ab1f --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/output.txt b/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/output.txt new file mode 100644 index 0000000000..33a78e4936 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/output.txt @@ -0,0 +1,19 @@ +$ cargo test + Compiling guessing_game v0.1.0 (file:///projects/guessing_game) + Finished test [unoptimized + debuginfo] target(s) in 0.62s + Running target/debug/deps/guessing_game-1bf5eca04a7d401d + +running 1 test +test tests::greater_than_100 ... FAILED + +failures: + +---- tests::greater_than_100 stdout ---- +note: test did not panic as expected + +failures: + tests::greater_than_100 + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/src/lib.rs b/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/src/lib.rs new file mode 100644 index 0000000000..269c73cefa --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/src/lib.rs @@ -0,0 +1,29 @@ +pub struct Guess { + value: i32, +} + +// ANCHOR: here +// --snip-- +impl Guess { + pub fn new(value: i32) -> Guess { + if value < 1 { + panic!("Guess value must be between 1 and 100, got {}.", value); + } + + Guess { value } + } +} +// ANCHOR_END: here + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[should_panic] + fn greater_than_100() { + Guess::new(200); + } +} + +fn main() {} diff --git a/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/Cargo.lock b/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/Cargo.lock new file mode 100644 index 0000000000..5802b7dc9a --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "guessing_game" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/Cargo.toml b/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/Cargo.toml new file mode 100644 index 0000000000..922762ab1f --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/output.txt b/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/output.txt new file mode 100644 index 0000000000..3ffee55b33 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/output.txt @@ -0,0 +1,21 @@ +$ cargo test + Compiling guessing_game v0.1.0 (file:///projects/guessing_game) + Finished test [unoptimized + debuginfo] target(s) in 0.66s + Running target/debug/deps/guessing_game-1bf5eca04a7d401d + +running 1 test +test tests::greater_than_100 ... FAILED + +failures: + +---- tests::greater_than_100 stdout ---- +thread 'main' panicked at 'Guess value must be greater than or equal to 1, got 200.', src/lib.rs:13:13 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. +note: panic did not include expected string 'Guess value must be less than or equal to 100' + +failures: + tests::greater_than_100 + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/src/lib.rs b/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/src/lib.rs new file mode 100644 index 0000000000..21650040da --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/src/lib.rs @@ -0,0 +1,34 @@ +pub struct Guess { + value: i32, +} + +impl Guess { + pub fn new(value: i32) -> Guess { + // ANCHOR: here + if value < 1 { + panic!( + "Guess value must be less than or equal to 100, got {}.", + value + ); + } else if value > 100 { + panic!( + "Guess value must be greater than or equal to 1, got {}.", + value + ); + } + // ANCHOR_END: here + + Guess { value } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[should_panic(expected = "Guess value must be less than or equal to 100")] + fn greater_than_100() { + Guess::new(200); + } +} diff --git a/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/Cargo.lock b/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/Cargo.toml b/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/src/lib.rs b/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/src/lib.rs new file mode 100644 index 0000000000..6284f4f291 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/src/lib.rs @@ -0,0 +1,11 @@ +#[cfg(test)] +mod tests { + #[test] + fn it_works() -> Result<(), String> { + if 2 + 2 == 4 { + Ok(()) + } else { + Err(String::from("two plus two does not equal four")) + } + } +} diff --git a/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/Cargo.lock b/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/Cargo.toml b/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/output.txt b/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/output.txt new file mode 100644 index 0000000000..68c129b373 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/output.txt @@ -0,0 +1,17 @@ +$ cargo test + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.60s + Running target/debug/deps/adder-076f0528706a8604 + +running 2 tests +test expensive_test ... ignored +test it_works ... ok + +test result: ok. 1 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out + + Doc-tests adder + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/src/lib.rs b/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/src/lib.rs new file mode 100644 index 0000000000..9a75301e31 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/src/lib.rs @@ -0,0 +1,14 @@ +// ANCHOR: here +#[test] +fn it_works() { + assert_eq!(2 + 2, 4); +} + +#[test] +#[ignore] +fn expensive_test() { + // code that takes an hour to run +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/Cargo.lock b/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/Cargo.toml b/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/output.txt b/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/output.txt new file mode 100644 index 0000000000..a826703a95 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/output.txt @@ -0,0 +1,29 @@ +$ cargo test + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.89s + Running target/debug/deps/adder-076f0528706a8604 + +running 1 test +test tests::internal ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Running target/debug/deps/common-a282abfe78e5b141 + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Running target/debug/deps/integration_test-60fcbc66f73b2933 + +running 1 test +test it_adds_two ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests adder + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/src/lib.rs b/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/src/lib.rs new file mode 100644 index 0000000000..c3961b1f62 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/src/lib.rs @@ -0,0 +1,17 @@ +pub fn add_two(a: i32) -> i32 { + internal_adder(a, 2) +} + +fn internal_adder(a: i32, b: i32) -> i32 { + a + b +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn internal() { + assert_eq!(4, internal_adder(2, 2)); + } +} diff --git a/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/tests/common.rs b/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/tests/common.rs new file mode 100644 index 0000000000..5fb7a390a6 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/tests/common.rs @@ -0,0 +1,3 @@ +pub fn setup() { + // setup code specific to your library's tests would go here +} diff --git a/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/tests/integration_test.rs b/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/tests/integration_test.rs new file mode 100644 index 0000000000..e26fa71096 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/tests/integration_test.rs @@ -0,0 +1,6 @@ +use adder; + +#[test] +fn it_adds_two() { + assert_eq!(4, adder::add_two(2)); +} diff --git a/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/Cargo.lock b/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/Cargo.toml b/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/src/lib.rs b/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/src/lib.rs new file mode 100644 index 0000000000..c3961b1f62 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/src/lib.rs @@ -0,0 +1,17 @@ +pub fn add_two(a: i32) -> i32 { + internal_adder(a, 2) +} + +fn internal_adder(a: i32, b: i32) -> i32 { + a + b +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn internal() { + assert_eq!(4, internal_adder(2, 2)); + } +} diff --git a/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/tests/common/mod.rs b/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/tests/common/mod.rs new file mode 100644 index 0000000000..5fb7a390a6 --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/tests/common/mod.rs @@ -0,0 +1,3 @@ +pub fn setup() { + // setup code specific to your library's tests would go here +} diff --git a/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/tests/integration_test.rs b/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/tests/integration_test.rs new file mode 100644 index 0000000000..58b8b7b89b --- /dev/null +++ b/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/tests/integration_test.rs @@ -0,0 +1,9 @@ +use adder; + +mod common; + +#[test] +fn it_adds_two() { + common::setup(); + assert_eq!(4, adder::add_two(2)); +} diff --git a/listings/ch11-writing-automated-tests/output-only-01-show-output/Cargo.lock b/listings/ch11-writing-automated-tests/output-only-01-show-output/Cargo.lock new file mode 100644 index 0000000000..a6d35e395a --- /dev/null +++ b/listings/ch11-writing-automated-tests/output-only-01-show-output/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "silly-function" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/output-only-01-show-output/Cargo.toml b/listings/ch11-writing-automated-tests/output-only-01-show-output/Cargo.toml new file mode 100644 index 0000000000..4e0f185af4 --- /dev/null +++ b/listings/ch11-writing-automated-tests/output-only-01-show-output/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "silly-function" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/output-only-01-show-output/output.txt b/listings/ch11-writing-automated-tests/output-only-01-show-output/output.txt new file mode 100644 index 0000000000..c1df21359c --- /dev/null +++ b/listings/ch11-writing-automated-tests/output-only-01-show-output/output.txt @@ -0,0 +1,34 @@ +$ cargo test -- --show-output + Compiling silly-function v0.1.0 (file:///projects/silly-function) + Finished test [unoptimized + debuginfo] target(s) in 0.60s + Running target/debug/deps/silly_function-b02a4796f0aeb021 + +running 2 tests +test tests::this_test_will_fail ... FAILED +test tests::this_test_will_pass ... ok + +successes: + +---- tests::this_test_will_pass stdout ---- +I got the value 4 + + +successes: + tests::this_test_will_pass + +failures: + +---- tests::this_test_will_fail stdout ---- +I got the value 8 +thread 'main' panicked at 'assertion failed: `(left == right)` + left: `5`, + right: `10`', src/lib.rs:19:9 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. + + +failures: + tests::this_test_will_fail + +test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/listings/ch11-writing-automated-tests/output-only-01-show-output/src/lib.rs b/listings/ch11-writing-automated-tests/output-only-01-show-output/src/lib.rs new file mode 100644 index 0000000000..43c4c92f9a --- /dev/null +++ b/listings/ch11-writing-automated-tests/output-only-01-show-output/src/lib.rs @@ -0,0 +1,21 @@ +pub fn prints_and_returns_10(a: i32) -> i32 { + println!("I got the value {}", a); + 10 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn this_test_will_pass() { + let value = prints_and_returns_10(4); + assert_eq!(10, value); + } + + #[test] + fn this_test_will_fail() { + let value = prints_and_returns_10(8); + assert_eq!(5, value); + } +} diff --git a/listings/ch11-writing-automated-tests/output-only-02-single-test/Cargo.lock b/listings/ch11-writing-automated-tests/output-only-02-single-test/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/listings/ch11-writing-automated-tests/output-only-02-single-test/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/output-only-02-single-test/Cargo.toml b/listings/ch11-writing-automated-tests/output-only-02-single-test/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/listings/ch11-writing-automated-tests/output-only-02-single-test/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/output-only-02-single-test/output.txt b/listings/ch11-writing-automated-tests/output-only-02-single-test/output.txt new file mode 100644 index 0000000000..6e715ff85c --- /dev/null +++ b/listings/ch11-writing-automated-tests/output-only-02-single-test/output.txt @@ -0,0 +1,10 @@ +$ cargo test one_hundred + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.69s + Running target/debug/deps/adder-076f0528706a8604 + +running 1 test +test tests::one_hundred ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out + diff --git a/listings/ch11-writing-automated-tests/output-only-02-single-test/src/lib.rs b/listings/ch11-writing-automated-tests/output-only-02-single-test/src/lib.rs new file mode 100644 index 0000000000..f56715263e --- /dev/null +++ b/listings/ch11-writing-automated-tests/output-only-02-single-test/src/lib.rs @@ -0,0 +1,23 @@ +pub fn add_two(a: i32) -> i32 { + a + 2 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn add_two_and_two() { + assert_eq!(4, add_two(2)); + } + + #[test] + fn add_three_and_two() { + assert_eq!(5, add_two(3)); + } + + #[test] + fn one_hundred() { + assert_eq!(102, add_two(100)); + } +} diff --git a/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/Cargo.lock b/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/Cargo.toml b/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/output.txt b/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/output.txt new file mode 100644 index 0000000000..db56677605 --- /dev/null +++ b/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/output.txt @@ -0,0 +1,11 @@ +$ cargo test add + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.61s + Running target/debug/deps/adder-076f0528706a8604 + +running 2 tests +test tests::add_three_and_two ... ok +test tests::add_two_and_two ... ok + +test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out + diff --git a/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/src/lib.rs b/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/src/lib.rs new file mode 100644 index 0000000000..f56715263e --- /dev/null +++ b/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/src/lib.rs @@ -0,0 +1,23 @@ +pub fn add_two(a: i32) -> i32 { + a + 2 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn add_two_and_two() { + assert_eq!(4, add_two(2)); + } + + #[test] + fn add_three_and_two() { + assert_eq!(5, add_two(3)); + } + + #[test] + fn one_hundred() { + assert_eq!(102, add_two(100)); + } +} diff --git a/listings/ch11-writing-automated-tests/output-only-04-running-ignored/Cargo.lock b/listings/ch11-writing-automated-tests/output-only-04-running-ignored/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/listings/ch11-writing-automated-tests/output-only-04-running-ignored/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/output-only-04-running-ignored/Cargo.toml b/listings/ch11-writing-automated-tests/output-only-04-running-ignored/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/listings/ch11-writing-automated-tests/output-only-04-running-ignored/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/output-only-04-running-ignored/output.txt b/listings/ch11-writing-automated-tests/output-only-04-running-ignored/output.txt new file mode 100644 index 0000000000..3c30e01677 --- /dev/null +++ b/listings/ch11-writing-automated-tests/output-only-04-running-ignored/output.txt @@ -0,0 +1,16 @@ +$ cargo test -- --ignored + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.61s + Running target/debug/deps/adder-076f0528706a8604 + +running 1 test +test expensive_test ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out + + Doc-tests adder + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/listings/ch11-writing-automated-tests/output-only-04-running-ignored/src/lib.rs b/listings/ch11-writing-automated-tests/output-only-04-running-ignored/src/lib.rs new file mode 100644 index 0000000000..9a75301e31 --- /dev/null +++ b/listings/ch11-writing-automated-tests/output-only-04-running-ignored/src/lib.rs @@ -0,0 +1,14 @@ +// ANCHOR: here +#[test] +fn it_works() { + assert_eq!(2 + 2, 4); +} + +#[test] +#[ignore] +fn expensive_test() { + // code that takes an hour to run +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch11-writing-automated-tests/output-only-05-single-integration/Cargo.lock b/listings/ch11-writing-automated-tests/output-only-05-single-integration/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/listings/ch11-writing-automated-tests/output-only-05-single-integration/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/listings/ch11-writing-automated-tests/output-only-05-single-integration/Cargo.toml b/listings/ch11-writing-automated-tests/output-only-05-single-integration/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/listings/ch11-writing-automated-tests/output-only-05-single-integration/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch11-writing-automated-tests/output-only-05-single-integration/output.txt b/listings/ch11-writing-automated-tests/output-only-05-single-integration/output.txt new file mode 100644 index 0000000000..b95c2681d1 --- /dev/null +++ b/listings/ch11-writing-automated-tests/output-only-05-single-integration/output.txt @@ -0,0 +1,10 @@ +$ cargo test --test integration_test + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.64s + Running target/debug/deps/integration_test-60fcbc66f73b2933 + +running 1 test +test it_adds_two ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/listings/ch11-writing-automated-tests/output-only-05-single-integration/src/lib.rs b/listings/ch11-writing-automated-tests/output-only-05-single-integration/src/lib.rs new file mode 100644 index 0000000000..c3961b1f62 --- /dev/null +++ b/listings/ch11-writing-automated-tests/output-only-05-single-integration/src/lib.rs @@ -0,0 +1,17 @@ +pub fn add_two(a: i32) -> i32 { + internal_adder(a, 2) +} + +fn internal_adder(a: i32, b: i32) -> i32 { + a + b +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn internal() { + assert_eq!(4, internal_adder(2, 2)); + } +} diff --git a/listings/ch11-writing-automated-tests/output-only-05-single-integration/tests/integration_test.rs b/listings/ch11-writing-automated-tests/output-only-05-single-integration/tests/integration_test.rs new file mode 100644 index 0000000000..e26fa71096 --- /dev/null +++ b/listings/ch11-writing-automated-tests/output-only-05-single-integration/tests/integration_test.rs @@ -0,0 +1,6 @@ +use adder; + +#[test] +fn it_adds_two() { + assert_eq!(4, adder::add_two(2)); +} diff --git a/listings/ch12-an-io-project/listing-12-01/Cargo.lock b/listings/ch12-an-io-project/listing-12-01/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-01/Cargo.toml b/listings/ch12-an-io-project/listing-12-01/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-01/output.txt b/listings/ch12-an-io-project/listing-12-01/output.txt new file mode 100644 index 0000000000..d0ef998122 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-01/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 0.61s + Running `target/debug/minigrep` +["target/debug/minigrep"] diff --git a/listings/ch12-an-io-project/listing-12-01/src/main.rs b/listings/ch12-an-io-project/listing-12-01/src/main.rs new file mode 100644 index 0000000000..aa3056de60 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-01/src/main.rs @@ -0,0 +1,6 @@ +use std::env; + +fn main() { + let args: Vec = env::args().collect(); + println!("{:?}", args); +} diff --git a/listings/ch12-an-io-project/listing-12-02/Cargo.lock b/listings/ch12-an-io-project/listing-12-02/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-02/Cargo.toml b/listings/ch12-an-io-project/listing-12-02/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-02/output.txt b/listings/ch12-an-io-project/listing-12-02/output.txt new file mode 100644 index 0000000000..f759eea008 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-02/output.txt @@ -0,0 +1,6 @@ +$ cargo run test sample.txt + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 0.0s + Running `target/debug/minigrep test sample.txt` +Searching for test +In file sample.txt diff --git a/listings/ch12-an-io-project/listing-12-02/src/main.rs b/listings/ch12-an-io-project/listing-12-02/src/main.rs new file mode 100644 index 0000000000..8daf125c67 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-02/src/main.rs @@ -0,0 +1,11 @@ +use std::env; + +fn main() { + let args: Vec = env::args().collect(); + + let query = &args[1]; + let filename = &args[2]; + + println!("Searching for {}", query); + println!("In file {}", filename); +} diff --git a/listings/ch12-an-io-project/listing-12-03/Cargo.lock b/listings/ch12-an-io-project/listing-12-03/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-03/Cargo.toml b/listings/ch12-an-io-project/listing-12-03/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-03/poem.txt b/listings/ch12-an-io-project/listing-12-03/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-03/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-03/src/main.rs b/listings/ch12-an-io-project/listing-12-03/src/main.rs new file mode 100644 index 0000000000..8daf125c67 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-03/src/main.rs @@ -0,0 +1,11 @@ +use std::env; + +fn main() { + let args: Vec = env::args().collect(); + + let query = &args[1]; + let filename = &args[2]; + + println!("Searching for {}", query); + println!("In file {}", filename); +} diff --git a/listings/ch12-an-io-project/listing-12-04/Cargo.lock b/listings/ch12-an-io-project/listing-12-04/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-04/Cargo.toml b/listings/ch12-an-io-project/listing-12-04/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-04/output.txt b/listings/ch12-an-io-project/listing-12-04/output.txt new file mode 100644 index 0000000000..75e7863ef5 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-04/output.txt @@ -0,0 +1,17 @@ +$ cargo run the poem.txt + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 0.0s + Running `target/debug/minigrep the poem.txt` +Searching for the +In file poem.txt +With text: +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! + diff --git a/listings/ch12-an-io-project/listing-12-04/poem.txt b/listings/ch12-an-io-project/listing-12-04/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-04/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-04/src/main.rs b/listings/ch12-an-io-project/listing-12-04/src/main.rs new file mode 100644 index 0000000000..9a0eade562 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-04/src/main.rs @@ -0,0 +1,22 @@ +// ANCHOR: here +use std::env; +use std::fs; + +fn main() { + // --snip-- + // ANCHOR_END: here + let args: Vec = env::args().collect(); + + let query = &args[1]; + let filename = &args[2]; + + println!("Searching for {}", query); + // ANCHOR: here + println!("In file {}", filename); + + let contents = fs::read_to_string(filename) + .expect("Something went wrong reading the file"); + + println!("With text:\n{}", contents); +} +// ANCHOR_END: here diff --git a/listings/ch12-an-io-project/listing-12-05/Cargo.lock b/listings/ch12-an-io-project/listing-12-05/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-05/Cargo.toml b/listings/ch12-an-io-project/listing-12-05/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-05/poem.txt b/listings/ch12-an-io-project/listing-12-05/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-05/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-05/src/main.rs b/listings/ch12-an-io-project/listing-12-05/src/main.rs new file mode 100644 index 0000000000..fb8805687e --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-05/src/main.rs @@ -0,0 +1,29 @@ +use std::env; +use std::fs; + +// ANCHOR: here +fn main() { + let args: Vec = env::args().collect(); + + let (query, filename) = parse_config(&args); + + // --snip-- + // ANCHOR_END: here + + println!("Searching for {}", query); + println!("In file {}", filename); + + let contents = fs::read_to_string(filename) + .expect("Something went wrong reading the file"); + + println!("With text:\n{}", contents); + // ANCHOR: here +} + +fn parse_config(args: &[String]) -> (&str, &str) { + let query = &args[1]; + let filename = &args[2]; + + (query, filename) +} +// ANCHOR_END: here diff --git a/listings/ch12-an-io-project/listing-12-06/Cargo.lock b/listings/ch12-an-io-project/listing-12-06/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-06/Cargo.toml b/listings/ch12-an-io-project/listing-12-06/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-06/poem.txt b/listings/ch12-an-io-project/listing-12-06/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-06/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-06/src/main.rs b/listings/ch12-an-io-project/listing-12-06/src/main.rs new file mode 100644 index 0000000000..b5d89bc98f --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-06/src/main.rs @@ -0,0 +1,34 @@ +use std::env; +use std::fs; + +// ANCHOR: here +fn main() { + let args: Vec = env::args().collect(); + + let config = parse_config(&args); + + println!("Searching for {}", config.query); + println!("In file {}", config.filename); + + let contents = fs::read_to_string(config.filename) + .expect("Something went wrong reading the file"); + + // --snip-- + // ANCHOR_END: here + + println!("With text:\n{}", contents); + // ANCHOR: here +} + +struct Config { + query: String, + filename: String, +} + +fn parse_config(args: &[String]) -> Config { + let query = args[1].clone(); + let filename = args[2].clone(); + + Config { query, filename } +} +// ANCHOR_END: here diff --git a/listings/ch12-an-io-project/listing-12-07/Cargo.lock b/listings/ch12-an-io-project/listing-12-07/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-07/Cargo.toml b/listings/ch12-an-io-project/listing-12-07/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-07/output.txt b/listings/ch12-an-io-project/listing-12-07/output.txt new file mode 100644 index 0000000000..8c8d53aa8b --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-07/output.txt @@ -0,0 +1,6 @@ +$ cargo run + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 0.0s + Running `target/debug/minigrep` +thread 'main' panicked at 'index out of bounds: the len is 1 but the index is 1', src/main.rs:27:21 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. diff --git a/listings/ch12-an-io-project/listing-12-07/poem.txt b/listings/ch12-an-io-project/listing-12-07/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-07/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-07/src/main.rs b/listings/ch12-an-io-project/listing-12-07/src/main.rs new file mode 100644 index 0000000000..36d35ceafb --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-07/src/main.rs @@ -0,0 +1,40 @@ +use std::env; +use std::fs; + +// ANCHOR: here +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args); + // ANCHOR_END: here + + println!("Searching for {}", config.query); + println!("In file {}", config.filename); + + let contents = fs::read_to_string(config.filename) + .expect("Something went wrong reading the file"); + + println!("With text:\n{}", contents); + // ANCHOR: here + + // --snip-- +} + +// --snip-- + +// ANCHOR_END: here +struct Config { + query: String, + filename: String, +} + +// ANCHOR: here +impl Config { + fn new(args: &[String]) -> Config { + let query = args[1].clone(); + let filename = args[2].clone(); + + Config { query, filename } + } +} +// ANCHOR_END: here diff --git a/listings/ch12-an-io-project/listing-12-08/Cargo.lock b/listings/ch12-an-io-project/listing-12-08/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-08/Cargo.toml b/listings/ch12-an-io-project/listing-12-08/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-08/output.txt b/listings/ch12-an-io-project/listing-12-08/output.txt new file mode 100644 index 0000000000..fa5d235eb5 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-08/output.txt @@ -0,0 +1,6 @@ +$ cargo run + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 0.0s + Running `target/debug/minigrep` +thread 'main' panicked at 'not enough arguments', src/main.rs:26:13 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. diff --git a/listings/ch12-an-io-project/listing-12-08/poem.txt b/listings/ch12-an-io-project/listing-12-08/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-08/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-08/src/main.rs b/listings/ch12-an-io-project/listing-12-08/src/main.rs new file mode 100644 index 0000000000..dddf10bd44 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-08/src/main.rs @@ -0,0 +1,38 @@ +use std::env; +use std::fs; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args); + + println!("Searching for {}", config.query); + println!("In file {}", config.filename); + + let contents = fs::read_to_string(config.filename) + .expect("Something went wrong reading the file"); + + println!("With text:\n{}", contents); +} + +struct Config { + query: String, + filename: String, +} + +impl Config { + // ANCHOR: here + // --snip-- + fn new(args: &[String]) -> Config { + if args.len() < 3 { + panic!("not enough arguments"); + } + // --snip-- + // ANCHOR_END: here + + let query = args[1].clone(); + let filename = args[2].clone(); + + Config { query, filename } + } +} diff --git a/listings/ch12-an-io-project/listing-12-09/Cargo.lock b/listings/ch12-an-io-project/listing-12-09/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-09/Cargo.toml b/listings/ch12-an-io-project/listing-12-09/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-09/poem.txt b/listings/ch12-an-io-project/listing-12-09/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-09/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-09/src/main.rs b/listings/ch12-an-io-project/listing-12-09/src/main.rs new file mode 100644 index 0000000000..83f46ee37f --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-09/src/main.rs @@ -0,0 +1,36 @@ +use std::env; +use std::fs; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args); + + println!("Searching for {}", config.query); + println!("In file {}", config.filename); + + let contents = fs::read_to_string(config.filename) + .expect("Something went wrong reading the file"); + + println!("With text:\n{}", contents); +} + +struct Config { + query: String, + filename: String, +} + +// ANCHOR: here +impl Config { + fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} +// ANCHOR_END: here diff --git a/listings/ch12-an-io-project/listing-12-10/Cargo.lock b/listings/ch12-an-io-project/listing-12-10/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-10/Cargo.toml b/listings/ch12-an-io-project/listing-12-10/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-10/output.txt b/listings/ch12-an-io-project/listing-12-10/output.txt new file mode 100644 index 0000000000..7aad57f52d --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-10/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 0.48s + Running `target/debug/minigrep` +Problem parsing arguments: not enough arguments diff --git a/listings/ch12-an-io-project/listing-12-10/poem.txt b/listings/ch12-an-io-project/listing-12-10/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-10/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-10/src/main.rs b/listings/ch12-an-io-project/listing-12-10/src/main.rs new file mode 100644 index 0000000000..c8aeb1d37e --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-10/src/main.rs @@ -0,0 +1,42 @@ +use std::env; +use std::fs; +// ANCHOR: here +use std::process; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + // --snip-- + // ANCHOR_END: here + + println!("Searching for {}", config.query); + println!("In file {}", config.filename); + + let contents = fs::read_to_string(config.filename) + .expect("Something went wrong reading the file"); + + println!("With text:\n{}", contents); +} + +struct Config { + query: String, + filename: String, +} + +impl Config { + fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} diff --git a/listings/ch12-an-io-project/listing-12-11/Cargo.lock b/listings/ch12-an-io-project/listing-12-11/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-11/Cargo.toml b/listings/ch12-an-io-project/listing-12-11/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-11/poem.txt b/listings/ch12-an-io-project/listing-12-11/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-11/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-11/src/main.rs b/listings/ch12-an-io-project/listing-12-11/src/main.rs new file mode 100644 index 0000000000..974b503b72 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-11/src/main.rs @@ -0,0 +1,50 @@ +use std::env; +use std::fs; +use std::process; + +// ANCHOR: here +fn main() { + // --snip-- + + // ANCHOR_END: here + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + // ANCHOR: here + println!("Searching for {}", config.query); + println!("In file {}", config.filename); + + run(config); +} + +fn run(config: Config) { + let contents = fs::read_to_string(config.filename) + .expect("Something went wrong reading the file"); + + println!("With text:\n{}", contents); +} + +// --snip-- +// ANCHOR_END: here + +struct Config { + query: String, + filename: String, +} + +impl Config { + fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} diff --git a/listings/ch12-an-io-project/listing-12-12/Cargo.lock b/listings/ch12-an-io-project/listing-12-12/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-12/Cargo.toml b/listings/ch12-an-io-project/listing-12-12/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-12/output.txt b/listings/ch12-an-io-project/listing-12-12/output.txt new file mode 100644 index 0000000000..565479d0c8 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-12/output.txt @@ -0,0 +1,26 @@ +$ cargo run the poem.txt + Compiling minigrep v0.1.0 (file:///projects/minigrep) +warning: unused `std::result::Result` that must be used + --> src/main.rs:19:5 + | +19 | run(config); + | ^^^^^^^^^^^^ + | + = note: `#[warn(unused_must_use)]` on by default + = note: this `Result` may be an `Err` variant, which should be handled + + Finished dev [unoptimized + debuginfo] target(s) in 0.71s + Running `target/debug/minigrep the poem.txt` +Searching for the +In file poem.txt +With text: +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! + diff --git a/listings/ch12-an-io-project/listing-12-12/poem.txt b/listings/ch12-an-io-project/listing-12-12/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-12/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-12/src/main.rs b/listings/ch12-an-io-project/listing-12-12/src/main.rs new file mode 100644 index 0000000000..f2e0e6b9f3 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-12/src/main.rs @@ -0,0 +1,51 @@ +use std::env; +use std::fs; +use std::process; +// ANCHOR: here +use std::error::Error; + +// --snip-- + +// ANCHOR_END: here + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + println!("Searching for {}", config.query); + println!("In file {}", config.filename); + + run(config); +} + +// ANCHOR: here +fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + println!("With text:\n{}", contents); + + Ok(()) +} +// ANCHOR_END: here + +struct Config { + query: String, + filename: String, +} + +impl Config { + fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} diff --git a/listings/ch12-an-io-project/listing-12-13/Cargo.lock b/listings/ch12-an-io-project/listing-12-13/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-13/Cargo.toml b/listings/ch12-an-io-project/listing-12-13/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-13/poem.txt b/listings/ch12-an-io-project/listing-12-13/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-13/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-13/src/lib.rs b/listings/ch12-an-io-project/listing-12-13/src/lib.rs new file mode 100644 index 0000000000..5b2850a5df --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-13/src/lib.rs @@ -0,0 +1,36 @@ +// ANCHOR: here +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + // --snip-- + // ANCHOR_END: here + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + // ANCHOR: here + } +} + +pub fn run(config: Config) -> Result<(), Box> { + // --snip-- + // ANCHOR_END: here + let contents = fs::read_to_string(config.filename)?; + + println!("With text:\n{}", contents); + + Ok(()) + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/listings/ch12-an-io-project/listing-12-13/src/main.rs b/listings/ch12-an-io-project/listing-12-13/src/main.rs new file mode 100644 index 0000000000..b2447dce97 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-13/src/main.rs @@ -0,0 +1,20 @@ +use std::env; +use std::process; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + println!("Searching for {}", config.query); + println!("In file {}", config.filename); + + if let Err(e) = run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/listings/ch12-an-io-project/listing-12-14/Cargo.lock b/listings/ch12-an-io-project/listing-12-14/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-14/Cargo.toml b/listings/ch12-an-io-project/listing-12-14/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-14/poem.txt b/listings/ch12-an-io-project/listing-12-14/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-14/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-14/src/lib.rs b/listings/ch12-an-io-project/listing-12-14/src/lib.rs new file mode 100644 index 0000000000..2ba2fd1961 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-14/src/lib.rs @@ -0,0 +1,28 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + println!("With text:\n{}", contents); + + Ok(()) +} diff --git a/listings/ch12-an-io-project/listing-12-14/src/main.rs b/listings/ch12-an-io-project/listing-12-14/src/main.rs new file mode 100644 index 0000000000..5eb4024f5c --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-14/src/main.rs @@ -0,0 +1,30 @@ +// ANCHOR: here +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + // --snip-- + // ANCHOR_END: here + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + println!("Searching for {}", config.query); + println!("In file {}", config.filename); + + // ANCHOR: here + if let Err(e) = minigrep::run(config) { + // --snip-- + // ANCHOR_END: here + println!("Application error: {}", e); + + process::exit(1); + // ANCHOR: here + } +} +// ANCHOR_END: here diff --git a/listings/ch12-an-io-project/listing-12-15/Cargo.lock b/listings/ch12-an-io-project/listing-12-15/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-15/Cargo.toml b/listings/ch12-an-io-project/listing-12-15/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-15/poem.txt b/listings/ch12-an-io-project/listing-12-15/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-15/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-15/src/lib.rs b/listings/ch12-an-io-project/listing-12-15/src/lib.rs new file mode 100644 index 0000000000..22ec381783 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-15/src/lib.rs @@ -0,0 +1,46 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + Ok(()) +} + +// ANCHOR: here +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_result() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch12-an-io-project/listing-12-15/src/main.rs b/listings/ch12-an-io-project/listing-12-15/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-15/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/listings/ch12-an-io-project/listing-12-16/Cargo.lock b/listings/ch12-an-io-project/listing-12-16/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-16/Cargo.toml b/listings/ch12-an-io-project/listing-12-16/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-16/output.txt b/listings/ch12-an-io-project/listing-12-16/output.txt new file mode 100644 index 0000000000..bc28612298 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-16/output.txt @@ -0,0 +1,23 @@ +$ cargo test + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished test [unoptimized + debuginfo] target(s) in 0.97s + Running target/debug/deps/minigrep-7003bffd2dda3b01 + +running 1 test +test tests::one_result ... FAILED + +failures: + +---- tests::one_result stdout ---- +thread 'main' panicked at 'assertion failed: `(left == right)` + left: `["safe, fast, productive."]`, + right: `[]`', src/lib.rs:44:9 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. + + +failures: + tests::one_result + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/listings/ch12-an-io-project/listing-12-16/poem.txt b/listings/ch12-an-io-project/listing-12-16/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-16/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-16/src/lib.rs b/listings/ch12-an-io-project/listing-12-16/src/lib.rs new file mode 100644 index 0000000000..2fc5b4f722 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-16/src/lib.rs @@ -0,0 +1,50 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + Ok(()) +} + +// ANCHOR: here +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + vec![] +} +// ANCHOR_END: here + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_result() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } +} + +fn main() {} diff --git a/listings/ch12-an-io-project/listing-12-16/src/main.rs b/listings/ch12-an-io-project/listing-12-16/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-16/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/listings/ch12-an-io-project/listing-12-17/Cargo.lock b/listings/ch12-an-io-project/listing-12-17/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-17/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-17/Cargo.toml b/listings/ch12-an-io-project/listing-12-17/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-17/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-17/poem.txt b/listings/ch12-an-io-project/listing-12-17/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-17/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-17/src/lib.rs b/listings/ch12-an-io-project/listing-12-17/src/lib.rs new file mode 100644 index 0000000000..0b094ce28a --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-17/src/lib.rs @@ -0,0 +1,50 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + Ok(()) +} + +// ANCHOR: here +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + for line in contents.lines() { + // do something with line + } +} +// ANCHOR_END: here + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_result() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } +} diff --git a/listings/ch12-an-io-project/listing-12-17/src/main.rs b/listings/ch12-an-io-project/listing-12-17/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-17/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/listings/ch12-an-io-project/listing-12-18/Cargo.lock b/listings/ch12-an-io-project/listing-12-18/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-18/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-18/Cargo.toml b/listings/ch12-an-io-project/listing-12-18/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-18/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-18/poem.txt b/listings/ch12-an-io-project/listing-12-18/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-18/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-18/src/lib.rs b/listings/ch12-an-io-project/listing-12-18/src/lib.rs new file mode 100644 index 0000000000..c9d1f529da --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-18/src/lib.rs @@ -0,0 +1,52 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + Ok(()) +} + +// ANCHOR: here +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + for line in contents.lines() { + if line.contains(query) { + // do something with line + } + } +} +// ANCHOR_END: here + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_result() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } +} diff --git a/listings/ch12-an-io-project/listing-12-18/src/main.rs b/listings/ch12-an-io-project/listing-12-18/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-18/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/listings/ch12-an-io-project/listing-12-19/Cargo.lock b/listings/ch12-an-io-project/listing-12-19/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-19/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-19/Cargo.toml b/listings/ch12-an-io-project/listing-12-19/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-19/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-19/output.txt b/listings/ch12-an-io-project/listing-12-19/output.txt new file mode 100644 index 0000000000..aa679d9c26 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-19/output.txt @@ -0,0 +1,22 @@ +$ cargo test + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished test [unoptimized + debuginfo] target(s) in 1.22s + Running target/debug/deps/minigrep-7003bffd2dda3b01 + +running 1 test +test tests::one_result ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Running target/debug/deps/minigrep-bf1f738c1c9dea06 + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests minigrep + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/listings/ch12-an-io-project/listing-12-19/poem.txt b/listings/ch12-an-io-project/listing-12-19/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-19/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-19/src/lib.rs b/listings/ch12-an-io-project/listing-12-19/src/lib.rs new file mode 100644 index 0000000000..de8897b8d1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-19/src/lib.rs @@ -0,0 +1,58 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + Ok(()) +} + +// ANCHOR: here +// ANCHOR: ch13 +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} +// ANCHOR_END: ch13 +// ANCHOR_END: here + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_result() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } +} diff --git a/listings/ch12-an-io-project/listing-12-19/src/main.rs b/listings/ch12-an-io-project/listing-12-19/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-19/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/listings/ch12-an-io-project/listing-12-20/Cargo.lock b/listings/ch12-an-io-project/listing-12-20/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-20/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-20/Cargo.toml b/listings/ch12-an-io-project/listing-12-20/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-20/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-20/poem.txt b/listings/ch12-an-io-project/listing-12-20/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-20/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-20/src/lib.rs b/listings/ch12-an-io-project/listing-12-20/src/lib.rs new file mode 100644 index 0000000000..52ba2bd51c --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-20/src/lib.rs @@ -0,0 +1,78 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + for line in search(&config.query, &contents) { + println!("{}", line); + } + + Ok(()) +} + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +// ANCHOR: here +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch12-an-io-project/listing-12-20/src/main.rs b/listings/ch12-an-io-project/listing-12-20/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-20/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/listings/ch12-an-io-project/listing-12-21/Cargo.lock b/listings/ch12-an-io-project/listing-12-21/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-21/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-21/Cargo.toml b/listings/ch12-an-io-project/listing-12-21/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-21/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-21/output.txt b/listings/ch12-an-io-project/listing-12-21/output.txt new file mode 100644 index 0000000000..5d3cfcc6fc --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-21/output.txt @@ -0,0 +1,23 @@ +$ cargo test + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished test [unoptimized + debuginfo] target(s) in 1.33s + Running target/debug/deps/minigrep-7003bffd2dda3b01 + +running 2 tests +test tests::case_insensitive ... ok +test tests::case_sensitive ... ok + +test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Running target/debug/deps/minigrep-bf1f738c1c9dea06 + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests minigrep + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/listings/ch12-an-io-project/listing-12-21/poem.txt b/listings/ch12-an-io-project/listing-12-21/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-21/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-21/src/lib.rs b/listings/ch12-an-io-project/listing-12-21/src/lib.rs new file mode 100644 index 0000000000..873c8b53d0 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-21/src/lib.rs @@ -0,0 +1,94 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + for line in search(&config.query, &contents) { + println!("{}", line); + } + + Ok(()) +} + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +// ANCHOR: here +pub fn search_case_insensitive<'a>( + query: &str, + contents: &'a str, +) -> Vec<&'a str> { + let query = query.to_lowercase(); + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(&query) { + results.push(line); + } + } + + results +} +// ANCHOR_END: here + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} + +fn main() {} diff --git a/listings/ch12-an-io-project/listing-12-21/src/main.rs b/listings/ch12-an-io-project/listing-12-21/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-21/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/listings/ch12-an-io-project/listing-12-22/Cargo.lock b/listings/ch12-an-io-project/listing-12-22/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-22/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-22/Cargo.toml b/listings/ch12-an-io-project/listing-12-22/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-22/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-22/poem.txt b/listings/ch12-an-io-project/listing-12-22/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-22/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-22/src/lib.rs b/listings/ch12-an-io-project/listing-12-22/src/lib.rs new file mode 100644 index 0000000000..2df82b7e2f --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-22/src/lib.rs @@ -0,0 +1,103 @@ +use std::error::Error; +use std::fs; + +// ANCHOR: here +pub struct Config { + pub query: String, + pub filename: String, + pub case_sensitive: bool, +} +// ANCHOR_END: here + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +// ANCHOR: there +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + let results = if config.case_sensitive { + search(&config.query, &contents) + } else { + search_case_insensitive(&config.query, &contents) + }; + + for line in results { + println!("{}", line); + } + + Ok(()) +} +// ANCHOR_END: there + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +pub fn search_case_insensitive<'a>( + query: &str, + contents: &'a str, +) -> Vec<&'a str> { + let query = query.to_lowercase(); + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(&query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} + +fn main() {} diff --git a/listings/ch12-an-io-project/listing-12-22/src/main.rs b/listings/ch12-an-io-project/listing-12-22/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-22/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/listings/ch12-an-io-project/listing-12-23/Cargo.lock b/listings/ch12-an-io-project/listing-12-23/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-23/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-23/Cargo.toml b/listings/ch12-an-io-project/listing-12-23/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-23/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-23/output.txt b/listings/ch12-an-io-project/listing-12-23/output.txt new file mode 100644 index 0000000000..0f0f07f751 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-23/output.txt @@ -0,0 +1,6 @@ +$ cargo run to poem.txt + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 0.0s + Running `target/debug/minigrep to poem.txt` +Are you nobody, too? +How dreary to be somebody! diff --git a/listings/ch12-an-io-project/listing-12-23/poem.txt b/listings/ch12-an-io-project/listing-12-23/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-23/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-23/src/lib.rs b/listings/ch12-an-io-project/listing-12-23/src/lib.rs new file mode 100644 index 0000000000..e6dc51a0ed --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-23/src/lib.rs @@ -0,0 +1,112 @@ +// ANCHOR: here +use std::env; +// --snip-- + +// ANCHOR_END: here +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, + pub case_sensitive: bool, +} + +// ANCHOR: here +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); + + Ok(Config { + query, + filename, + case_sensitive, + }) + } +} +// ANCHOR_END: here + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + let results = if config.case_sensitive { + search(&config.query, &contents) + } else { + search_case_insensitive(&config.query, &contents) + }; + + for line in results { + println!("{}", line); + } + + Ok(()) +} + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +pub fn search_case_insensitive<'a>( + query: &str, + contents: &'a str, +) -> Vec<&'a str> { + let query = query.to_lowercase(); + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(&query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} + +fn main() {} diff --git a/listings/ch12-an-io-project/listing-12-23/src/main.rs b/listings/ch12-an-io-project/listing-12-23/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-23/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/listings/ch12-an-io-project/listing-12-24/Cargo.lock b/listings/ch12-an-io-project/listing-12-24/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-24/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/listing-12-24/Cargo.toml b/listings/ch12-an-io-project/listing-12-24/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-24/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/listing-12-24/poem.txt b/listings/ch12-an-io-project/listing-12-24/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-24/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/listing-12-24/src/lib.rs b/listings/ch12-an-io-project/listing-12-24/src/lib.rs new file mode 100644 index 0000000000..fe1dccf4ee --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-24/src/lib.rs @@ -0,0 +1,104 @@ +use std::env; +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, + pub case_sensitive: bool, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); + + Ok(Config { + query, + filename, + case_sensitive, + }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + let results = if config.case_sensitive { + search(&config.query, &contents) + } else { + search_case_insensitive(&config.query, &contents) + }; + + for line in results { + println!("{}", line); + } + + Ok(()) +} + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +pub fn search_case_insensitive<'a>( + query: &str, + contents: &'a str, +) -> Vec<&'a str> { + let query = query.to_lowercase(); + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(&query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} diff --git a/listings/ch12-an-io-project/listing-12-24/src/main.rs b/listings/ch12-an-io-project/listing-12-24/src/main.rs new file mode 100644 index 0000000000..9e38553c56 --- /dev/null +++ b/listings/ch12-an-io-project/listing-12-24/src/main.rs @@ -0,0 +1,21 @@ +use std::env; +use std::process; + +use minigrep::Config; + +// ANCHOR: here +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + eprintln!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + eprintln!("Application error: {}", e); + + process::exit(1); + } +} +// ANCHOR_END: here diff --git a/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/Cargo.lock b/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/Cargo.toml b/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/poem.txt b/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/src/main.rs b/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/src/main.rs new file mode 100644 index 0000000000..44bcfeab30 --- /dev/null +++ b/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/src/main.rs @@ -0,0 +1,54 @@ +use std::env; +use std::error::Error; +use std::fs; +use std::process; + +// ANCHOR: here +fn main() { + // --snip-- + + // ANCHOR_END: here + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + // ANCHOR: here + println!("Searching for {}", config.query); + println!("In file {}", config.filename); + + if let Err(e) = run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} +// ANCHOR_END: here + +fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + println!("With text:\n{}", contents); + + Ok(()) +} + +struct Config { + query: String, + filename: String, +} + +impl Config { + fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} diff --git a/listings/ch12-an-io-project/no-listing-02-using-search-in-run/Cargo.lock b/listings/ch12-an-io-project/no-listing-02-using-search-in-run/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/no-listing-02-using-search-in-run/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/no-listing-02-using-search-in-run/Cargo.toml b/listings/ch12-an-io-project/no-listing-02-using-search-in-run/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/no-listing-02-using-search-in-run/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/no-listing-02-using-search-in-run/output.txt b/listings/ch12-an-io-project/no-listing-02-using-search-in-run/output.txt new file mode 100644 index 0000000000..91532d0cd5 --- /dev/null +++ b/listings/ch12-an-io-project/no-listing-02-using-search-in-run/output.txt @@ -0,0 +1,5 @@ +$ cargo run frog poem.txt + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 0.38s + Running `target/debug/minigrep frog poem.txt` +How public, like a frog diff --git a/listings/ch12-an-io-project/no-listing-02-using-search-in-run/poem.txt b/listings/ch12-an-io-project/no-listing-02-using-search-in-run/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/no-listing-02-using-search-in-run/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/no-listing-02-using-search-in-run/src/lib.rs b/listings/ch12-an-io-project/no-listing-02-using-search-in-run/src/lib.rs new file mode 100644 index 0000000000..ede4eb49a0 --- /dev/null +++ b/listings/ch12-an-io-project/no-listing-02-using-search-in-run/src/lib.rs @@ -0,0 +1,60 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +// ANCHOR: here +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + for line in search(&config.query, &contents) { + println!("{}", line); + } + + Ok(()) +} +// ANCHOR_END: here + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_result() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } +} diff --git a/listings/ch12-an-io-project/no-listing-02-using-search-in-run/src/main.rs b/listings/ch12-an-io-project/no-listing-02-using-search-in-run/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/listings/ch12-an-io-project/no-listing-02-using-search-in-run/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/listings/ch12-an-io-project/output-only-01-with-args/Cargo.lock b/listings/ch12-an-io-project/output-only-01-with-args/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/output-only-01-with-args/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/output-only-01-with-args/Cargo.toml b/listings/ch12-an-io-project/output-only-01-with-args/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/output-only-01-with-args/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/output-only-01-with-args/output.txt b/listings/ch12-an-io-project/output-only-01-with-args/output.txt new file mode 100644 index 0000000000..eb88d9a9b1 --- /dev/null +++ b/listings/ch12-an-io-project/output-only-01-with-args/output.txt @@ -0,0 +1,5 @@ +$ cargo run needle haystack + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 1.57s + Running `target/debug/minigrep needle haystack` +["target/debug/minigrep", "needle", "haystack"] diff --git a/listings/ch12-an-io-project/output-only-01-with-args/src/main.rs b/listings/ch12-an-io-project/output-only-01-with-args/src/main.rs new file mode 100644 index 0000000000..aa3056de60 --- /dev/null +++ b/listings/ch12-an-io-project/output-only-01-with-args/src/main.rs @@ -0,0 +1,6 @@ +use std::env; + +fn main() { + let args: Vec = env::args().collect(); + println!("{:?}", args); +} diff --git a/listings/ch12-an-io-project/output-only-02-missing-lifetimes/Cargo.lock b/listings/ch12-an-io-project/output-only-02-missing-lifetimes/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/output-only-02-missing-lifetimes/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/output-only-02-missing-lifetimes/Cargo.toml b/listings/ch12-an-io-project/output-only-02-missing-lifetimes/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/output-only-02-missing-lifetimes/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/output-only-02-missing-lifetimes/output.txt b/listings/ch12-an-io-project/output-only-02-missing-lifetimes/output.txt new file mode 100644 index 0000000000..b76084b0f1 --- /dev/null +++ b/listings/ch12-an-io-project/output-only-02-missing-lifetimes/output.txt @@ -0,0 +1,16 @@ +$ cargo build + Compiling minigrep v0.1.0 (file:///projects/minigrep) +error[E0106]: missing lifetime specifier + --> src/lib.rs:28:51 + | +28 | pub fn search(query: &str, contents: &str) -> Vec<&str> { + | ^ expected lifetime parameter + | + = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `query` or `contents` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0106`. +error: could not compile `minigrep`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch12-an-io-project/output-only-02-missing-lifetimes/poem.txt b/listings/ch12-an-io-project/output-only-02-missing-lifetimes/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/output-only-02-missing-lifetimes/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/output-only-02-missing-lifetimes/src/lib.rs b/listings/ch12-an-io-project/output-only-02-missing-lifetimes/src/lib.rs new file mode 100644 index 0000000000..c60405c219 --- /dev/null +++ b/listings/ch12-an-io-project/output-only-02-missing-lifetimes/src/lib.rs @@ -0,0 +1,50 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + Ok(()) +} + +// ANCHOR: here +pub fn search(query: &str, contents: &str) -> Vec<&str> { + vec![] +} +// ANCHOR_END: here + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_result() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } +} + +fn main() {} diff --git a/listings/ch12-an-io-project/output-only-02-missing-lifetimes/src/main.rs b/listings/ch12-an-io-project/output-only-02-missing-lifetimes/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/listings/ch12-an-io-project/output-only-02-missing-lifetimes/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/listings/ch12-an-io-project/output-only-03-multiple-matches/Cargo.lock b/listings/ch12-an-io-project/output-only-03-multiple-matches/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/output-only-03-multiple-matches/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/output-only-03-multiple-matches/Cargo.toml b/listings/ch12-an-io-project/output-only-03-multiple-matches/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/output-only-03-multiple-matches/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/output-only-03-multiple-matches/output.txt b/listings/ch12-an-io-project/output-only-03-multiple-matches/output.txt new file mode 100644 index 0000000000..c0ab7efd97 --- /dev/null +++ b/listings/ch12-an-io-project/output-only-03-multiple-matches/output.txt @@ -0,0 +1,7 @@ +$ cargo run body poem.txt + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 0.0s + Running `target/debug/minigrep body poem.txt` +I’m nobody! Who are you? +Are you nobody, too? +How dreary to be somebody! diff --git a/listings/ch12-an-io-project/output-only-03-multiple-matches/poem.txt b/listings/ch12-an-io-project/output-only-03-multiple-matches/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/output-only-03-multiple-matches/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/output-only-03-multiple-matches/src/lib.rs b/listings/ch12-an-io-project/output-only-03-multiple-matches/src/lib.rs new file mode 100644 index 0000000000..ede4eb49a0 --- /dev/null +++ b/listings/ch12-an-io-project/output-only-03-multiple-matches/src/lib.rs @@ -0,0 +1,60 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +// ANCHOR: here +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + for line in search(&config.query, &contents) { + println!("{}", line); + } + + Ok(()) +} +// ANCHOR_END: here + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_result() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } +} diff --git a/listings/ch12-an-io-project/output-only-03-multiple-matches/src/main.rs b/listings/ch12-an-io-project/output-only-03-multiple-matches/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/listings/ch12-an-io-project/output-only-03-multiple-matches/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/listings/ch12-an-io-project/output-only-04-no-matches/Cargo.lock b/listings/ch12-an-io-project/output-only-04-no-matches/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch12-an-io-project/output-only-04-no-matches/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch12-an-io-project/output-only-04-no-matches/Cargo.toml b/listings/ch12-an-io-project/output-only-04-no-matches/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch12-an-io-project/output-only-04-no-matches/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch12-an-io-project/output-only-04-no-matches/output.txt b/listings/ch12-an-io-project/output-only-04-no-matches/output.txt new file mode 100644 index 0000000000..4cd6c8a0ae --- /dev/null +++ b/listings/ch12-an-io-project/output-only-04-no-matches/output.txt @@ -0,0 +1,4 @@ +$ cargo run monomorphization poem.txt + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 0.0s + Running `target/debug/minigrep monomorphization poem.txt` diff --git a/listings/ch12-an-io-project/output-only-04-no-matches/poem.txt b/listings/ch12-an-io-project/output-only-04-no-matches/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/listings/ch12-an-io-project/output-only-04-no-matches/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch12-an-io-project/output-only-04-no-matches/src/lib.rs b/listings/ch12-an-io-project/output-only-04-no-matches/src/lib.rs new file mode 100644 index 0000000000..ede4eb49a0 --- /dev/null +++ b/listings/ch12-an-io-project/output-only-04-no-matches/src/lib.rs @@ -0,0 +1,60 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +// ANCHOR: here +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + for line in search(&config.query, &contents) { + println!("{}", line); + } + + Ok(()) +} +// ANCHOR_END: here + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_result() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } +} diff --git a/listings/ch12-an-io-project/output-only-04-no-matches/src/main.rs b/listings/ch12-an-io-project/output-only-04-no-matches/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/listings/ch12-an-io-project/output-only-04-no-matches/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/listings/ch13-functional-features/listing-12-23-reproduced/Cargo.lock b/listings/ch13-functional-features/listing-12-23-reproduced/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch13-functional-features/listing-12-23-reproduced/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-12-23-reproduced/Cargo.toml b/listings/ch13-functional-features/listing-12-23-reproduced/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch13-functional-features/listing-12-23-reproduced/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-12-23-reproduced/poem.txt b/listings/ch13-functional-features/listing-12-23-reproduced/poem.txt new file mode 100644 index 0000000000..8707527313 --- /dev/null +++ b/listings/ch13-functional-features/listing-12-23-reproduced/poem.txt @@ -0,0 +1,9 @@ +I'm nobody! Who are you? +Are you nobody, too? +Then there's a pair of us - don't tell! +They'd banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch13-functional-features/listing-12-23-reproduced/src/lib.rs b/listings/ch13-functional-features/listing-12-23-reproduced/src/lib.rs new file mode 100644 index 0000000000..5397d7f617 --- /dev/null +++ b/listings/ch13-functional-features/listing-12-23-reproduced/src/lib.rs @@ -0,0 +1,108 @@ +use std::env; +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, + pub case_sensitive: bool, +} + +// ANCHOR: ch13 +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); + + Ok(Config { + query, + filename, + case_sensitive, + }) + } +} +// ANCHOR_END: ch13 + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + let results = if config.case_sensitive { + search(&config.query, &contents) + } else { + search_case_insensitive(&config.query, &contents) + }; + + for line in results { + println!("{}", line); + } + + Ok(()) +} + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +pub fn search_case_insensitive<'a>( + query: &str, + contents: &'a str, +) -> Vec<&'a str> { + let query = query.to_lowercase(); + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(&query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} + +fn main() {} diff --git a/listings/ch13-functional-features/listing-12-23-reproduced/src/main.rs b/listings/ch13-functional-features/listing-12-23-reproduced/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/listings/ch13-functional-features/listing-12-23-reproduced/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/listings/ch13-functional-features/listing-12-24-reproduced/Cargo.lock b/listings/ch13-functional-features/listing-12-24-reproduced/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch13-functional-features/listing-12-24-reproduced/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-12-24-reproduced/Cargo.toml b/listings/ch13-functional-features/listing-12-24-reproduced/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch13-functional-features/listing-12-24-reproduced/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-12-24-reproduced/poem.txt b/listings/ch13-functional-features/listing-12-24-reproduced/poem.txt new file mode 100644 index 0000000000..8707527313 --- /dev/null +++ b/listings/ch13-functional-features/listing-12-24-reproduced/poem.txt @@ -0,0 +1,9 @@ +I'm nobody! Who are you? +Are you nobody, too? +Then there's a pair of us - don't tell! +They'd banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch13-functional-features/listing-12-24-reproduced/src/lib.rs b/listings/ch13-functional-features/listing-12-24-reproduced/src/lib.rs new file mode 100644 index 0000000000..fe1dccf4ee --- /dev/null +++ b/listings/ch13-functional-features/listing-12-24-reproduced/src/lib.rs @@ -0,0 +1,104 @@ +use std::env; +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, + pub case_sensitive: bool, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); + + Ok(Config { + query, + filename, + case_sensitive, + }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + let results = if config.case_sensitive { + search(&config.query, &contents) + } else { + search_case_insensitive(&config.query, &contents) + }; + + for line in results { + println!("{}", line); + } + + Ok(()) +} + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +pub fn search_case_insensitive<'a>( + query: &str, + contents: &'a str, +) -> Vec<&'a str> { + let query = query.to_lowercase(); + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(&query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} diff --git a/listings/ch13-functional-features/listing-12-24-reproduced/src/main.rs b/listings/ch13-functional-features/listing-12-24-reproduced/src/main.rs new file mode 100644 index 0000000000..ec27e67f99 --- /dev/null +++ b/listings/ch13-functional-features/listing-12-24-reproduced/src/main.rs @@ -0,0 +1,25 @@ +use std::env; +use std::process; + +use minigrep::Config; + +// ANCHOR: ch13 +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + eprintln!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + // --snip-- + // ANCHOR_END: ch13 + + if let Err(e) = minigrep::run(config) { + eprintln!("Application error: {}", e); + + process::exit(1); + } + // ANCHOR: ch13 +} +// ANCHOR_END: ch13 diff --git a/listings/ch13-functional-features/listing-13-01/Cargo.lock b/listings/ch13-functional-features/listing-13-01/Cargo.lock new file mode 100644 index 0000000000..75ff09e51b --- /dev/null +++ b/listings/ch13-functional-features/listing-13-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "workout-app" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-01/Cargo.toml b/listings/ch13-functional-features/listing-13-01/Cargo.toml new file mode 100644 index 0000000000..8e64540e73 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "workout-app" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-01/src/main.rs b/listings/ch13-functional-features/listing-13-01/src/main.rs new file mode 100644 index 0000000000..97eace01d7 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-01/src/main.rs @@ -0,0 +1,12 @@ +// ANCHOR: here +use std::thread; +use std::time::Duration; + +fn simulated_expensive_calculation(intensity: u32) -> u32 { + println!("calculating slowly..."); + thread::sleep(Duration::from_secs(2)); + intensity +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch13-functional-features/listing-13-02/Cargo.lock b/listings/ch13-functional-features/listing-13-02/Cargo.lock new file mode 100644 index 0000000000..75ff09e51b --- /dev/null +++ b/listings/ch13-functional-features/listing-13-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "workout-app" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-02/Cargo.toml b/listings/ch13-functional-features/listing-13-02/Cargo.toml new file mode 100644 index 0000000000..8e64540e73 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "workout-app" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-02/src/main.rs b/listings/ch13-functional-features/listing-13-02/src/main.rs new file mode 100644 index 0000000000..96d06c77d4 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-02/src/main.rs @@ -0,0 +1,19 @@ +use std::thread; +use std::time::Duration; + +fn simulated_expensive_calculation(intensity: u32) -> u32 { + println!("calculating slowly..."); + thread::sleep(Duration::from_secs(2)); + intensity +} + +fn generate_workout(intensity: u32, random_number: u32) {} + +// ANCHOR: here +fn main() { + let simulated_user_specified_value = 10; + let simulated_random_number = 7; + + generate_workout(simulated_user_specified_value, simulated_random_number); +} +// ANCHOR_END: here diff --git a/listings/ch13-functional-features/listing-13-03/Cargo.lock b/listings/ch13-functional-features/listing-13-03/Cargo.lock new file mode 100644 index 0000000000..75ff09e51b --- /dev/null +++ b/listings/ch13-functional-features/listing-13-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "workout-app" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-03/Cargo.toml b/listings/ch13-functional-features/listing-13-03/Cargo.toml new file mode 100644 index 0000000000..8e64540e73 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "workout-app" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-03/src/main.rs b/listings/ch13-functional-features/listing-13-03/src/main.rs new file mode 100644 index 0000000000..d43c9b2116 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-03/src/main.rs @@ -0,0 +1,39 @@ +use std::thread; +use std::time::Duration; + +fn simulated_expensive_calculation(intensity: u32) -> u32 { + println!("calculating slowly..."); + thread::sleep(Duration::from_secs(2)); + intensity +} + +// ANCHOR: here +fn generate_workout(intensity: u32, random_number: u32) { + if intensity < 25 { + println!( + "Today, do {} pushups!", + simulated_expensive_calculation(intensity) + ); + println!( + "Next, do {} situps!", + simulated_expensive_calculation(intensity) + ); + } else { + if random_number == 3 { + println!("Take a break today! Remember to stay hydrated!"); + } else { + println!( + "Today, run for {} minutes!", + simulated_expensive_calculation(intensity) + ); + } + } +} +// ANCHOR_END: here + +fn main() { + let simulated_user_specified_value = 10; + let simulated_random_number = 7; + + generate_workout(simulated_user_specified_value, simulated_random_number); +} diff --git a/listings/ch13-functional-features/listing-13-04/Cargo.lock b/listings/ch13-functional-features/listing-13-04/Cargo.lock new file mode 100644 index 0000000000..75ff09e51b --- /dev/null +++ b/listings/ch13-functional-features/listing-13-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "workout-app" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-04/Cargo.toml b/listings/ch13-functional-features/listing-13-04/Cargo.toml new file mode 100644 index 0000000000..8e64540e73 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "workout-app" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-04/src/main.rs b/listings/ch13-functional-features/listing-13-04/src/main.rs new file mode 100644 index 0000000000..fabe0fb01d --- /dev/null +++ b/listings/ch13-functional-features/listing-13-04/src/main.rs @@ -0,0 +1,32 @@ +use std::thread; +use std::time::Duration; + +fn simulated_expensive_calculation(intensity: u32) -> u32 { + println!("calculating slowly..."); + thread::sleep(Duration::from_secs(2)); + intensity +} + +// ANCHOR: here +fn generate_workout(intensity: u32, random_number: u32) { + let expensive_result = simulated_expensive_calculation(intensity); + + if intensity < 25 { + println!("Today, do {} pushups!", expensive_result); + println!("Next, do {} situps!", expensive_result); + } else { + if random_number == 3 { + println!("Take a break today! Remember to stay hydrated!"); + } else { + println!("Today, run for {} minutes!", expensive_result); + } + } +} +// ANCHOR_END: here + +fn main() { + let simulated_user_specified_value = 10; + let simulated_random_number = 7; + + generate_workout(simulated_user_specified_value, simulated_random_number); +} diff --git a/listings/ch13-functional-features/listing-13-05/Cargo.lock b/listings/ch13-functional-features/listing-13-05/Cargo.lock new file mode 100644 index 0000000000..75ff09e51b --- /dev/null +++ b/listings/ch13-functional-features/listing-13-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "workout-app" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-05/Cargo.toml b/listings/ch13-functional-features/listing-13-05/Cargo.toml new file mode 100644 index 0000000000..8e64540e73 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "workout-app" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-05/src/main.rs b/listings/ch13-functional-features/listing-13-05/src/main.rs new file mode 100644 index 0000000000..6984a27a0e --- /dev/null +++ b/listings/ch13-functional-features/listing-13-05/src/main.rs @@ -0,0 +1,33 @@ +use std::thread; +use std::time::Duration; + +fn generate_workout(intensity: u32, random_number: u32) { + // ANCHOR: here + let expensive_closure = |num| { + println!("calculating slowly..."); + thread::sleep(Duration::from_secs(2)); + num + }; + // ANCHOR_END: here + + if intensity < 25 { + println!("Today, do {} pushups!", expensive_closure(intensity)); + println!("Next, do {} situps!", expensive_closure(intensity)); + } else { + if random_number == 3 { + println!("Take a break today! Remember to stay hydrated!"); + } else { + println!( + "Today, run for {} minutes!", + expensive_closure(intensity) + ); + } + } +} + +fn main() { + let simulated_user_specified_value = 10; + let simulated_random_number = 7; + + generate_workout(simulated_user_specified_value, simulated_random_number); +} diff --git a/listings/ch13-functional-features/listing-13-06/Cargo.lock b/listings/ch13-functional-features/listing-13-06/Cargo.lock new file mode 100644 index 0000000000..75ff09e51b --- /dev/null +++ b/listings/ch13-functional-features/listing-13-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "workout-app" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-06/Cargo.toml b/listings/ch13-functional-features/listing-13-06/Cargo.toml new file mode 100644 index 0000000000..8e64540e73 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "workout-app" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-06/src/main.rs b/listings/ch13-functional-features/listing-13-06/src/main.rs new file mode 100644 index 0000000000..8850e58a76 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-06/src/main.rs @@ -0,0 +1,33 @@ +use std::thread; +use std::time::Duration; + +// ANCHOR: here +fn generate_workout(intensity: u32, random_number: u32) { + let expensive_closure = |num| { + println!("calculating slowly..."); + thread::sleep(Duration::from_secs(2)); + num + }; + + if intensity < 25 { + println!("Today, do {} pushups!", expensive_closure(intensity)); + println!("Next, do {} situps!", expensive_closure(intensity)); + } else { + if random_number == 3 { + println!("Take a break today! Remember to stay hydrated!"); + } else { + println!( + "Today, run for {} minutes!", + expensive_closure(intensity) + ); + } + } +} +// ANCHOR_END: here + +fn main() { + let simulated_user_specified_value = 10; + let simulated_random_number = 7; + + generate_workout(simulated_user_specified_value, simulated_random_number); +} diff --git a/listings/ch13-functional-features/listing-13-07/Cargo.lock b/listings/ch13-functional-features/listing-13-07/Cargo.lock new file mode 100644 index 0000000000..75ff09e51b --- /dev/null +++ b/listings/ch13-functional-features/listing-13-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "workout-app" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-07/Cargo.toml b/listings/ch13-functional-features/listing-13-07/Cargo.toml new file mode 100644 index 0000000000..8e64540e73 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "workout-app" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-07/src/main.rs b/listings/ch13-functional-features/listing-13-07/src/main.rs new file mode 100644 index 0000000000..b3f4cc2c2a --- /dev/null +++ b/listings/ch13-functional-features/listing-13-07/src/main.rs @@ -0,0 +1,33 @@ +use std::thread; +use std::time::Duration; + +fn generate_workout(intensity: u32, random_number: u32) { + // ANCHOR: here + let expensive_closure = |num: u32| -> u32 { + println!("calculating slowly..."); + thread::sleep(Duration::from_secs(2)); + num + }; + // ANCHOR_END: here + + if intensity < 25 { + println!("Today, do {} pushups!", expensive_closure(intensity)); + println!("Next, do {} situps!", expensive_closure(intensity)); + } else { + if random_number == 3 { + println!("Take a break today! Remember to stay hydrated!"); + } else { + println!( + "Today, run for {} minutes!", + expensive_closure(intensity) + ); + } + } +} + +fn main() { + let simulated_user_specified_value = 10; + let simulated_random_number = 7; + + generate_workout(simulated_user_specified_value, simulated_random_number); +} diff --git a/listings/ch13-functional-features/listing-13-08/Cargo.lock b/listings/ch13-functional-features/listing-13-08/Cargo.lock new file mode 100644 index 0000000000..c190d3a411 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "closure-example" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-08/Cargo.toml b/listings/ch13-functional-features/listing-13-08/Cargo.toml new file mode 100644 index 0000000000..54b904e411 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "closure-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-08/output.txt b/listings/ch13-functional-features/listing-13-08/output.txt new file mode 100644 index 0000000000..ad266adaca --- /dev/null +++ b/listings/ch13-functional-features/listing-13-08/output.txt @@ -0,0 +1,20 @@ +$ cargo run + Compiling closure-example v0.1.0 (file:///projects/closure-example) +error[E0308]: mismatched types + --> src/main.rs:5:29 + | +5 | let n = example_closure(5); + | ^ + | | + | expected struct `std::string::String`, found integer + | help: try using a conversion method: `5.to_string()` + | + = note: expected type `std::string::String` + found type `{integer}` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. +error: could not compile `closure-example`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch13-functional-features/listing-13-08/src/main.rs b/listings/ch13-functional-features/listing-13-08/src/main.rs new file mode 100644 index 0000000000..ebb2489bf7 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-08/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let example_closure = |x| x; + + let s = example_closure(String::from("hello")); + let n = example_closure(5); + // ANCHOR_END: here +} diff --git a/listings/ch13-functional-features/listing-13-09/Cargo.lock b/listings/ch13-functional-features/listing-13-09/Cargo.lock new file mode 100644 index 0000000000..e090432bc9 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cacher" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-09/Cargo.toml b/listings/ch13-functional-features/listing-13-09/Cargo.toml new file mode 100644 index 0000000000..54ab6f2173 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cacher" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-09/src/main.rs b/listings/ch13-functional-features/listing-13-09/src/main.rs new file mode 100644 index 0000000000..3fd4ed067f --- /dev/null +++ b/listings/ch13-functional-features/listing-13-09/src/main.rs @@ -0,0 +1,11 @@ +// ANCHOR: here +struct Cacher +where + T: Fn(u32) -> u32, +{ + calculation: T, + value: Option, +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch13-functional-features/listing-13-10/Cargo.lock b/listings/ch13-functional-features/listing-13-10/Cargo.lock new file mode 100644 index 0000000000..e090432bc9 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cacher" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-10/Cargo.toml b/listings/ch13-functional-features/listing-13-10/Cargo.toml new file mode 100644 index 0000000000..54ab6f2173 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cacher" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-10/src/main.rs b/listings/ch13-functional-features/listing-13-10/src/main.rs new file mode 100644 index 0000000000..4d1034db94 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-10/src/main.rs @@ -0,0 +1,34 @@ +struct Cacher +where + T: Fn(u32) -> u32, +{ + calculation: T, + value: Option, +} + +// ANCHOR: here +impl Cacher +where + T: Fn(u32) -> u32, +{ + fn new(calculation: T) -> Cacher { + Cacher { + calculation, + value: None, + } + } + + fn value(&mut self, arg: u32) -> u32 { + match self.value { + Some(v) => v, + None => { + let v = (self.calculation)(arg); + self.value = Some(v); + v + } + } + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch13-functional-features/listing-13-11/Cargo.lock b/listings/ch13-functional-features/listing-13-11/Cargo.lock new file mode 100644 index 0000000000..75ff09e51b --- /dev/null +++ b/listings/ch13-functional-features/listing-13-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "workout-app" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-11/Cargo.toml b/listings/ch13-functional-features/listing-13-11/Cargo.toml new file mode 100644 index 0000000000..8e64540e73 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "workout-app" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-11/src/main.rs b/listings/ch13-functional-features/listing-13-11/src/main.rs new file mode 100644 index 0000000000..9f378b7935 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-11/src/main.rs @@ -0,0 +1,64 @@ +use std::thread; +use std::time::Duration; + +struct Cacher +where + T: Fn(u32) -> u32, +{ + calculation: T, + value: Option, +} + +impl Cacher +where + T: Fn(u32) -> u32, +{ + fn new(calculation: T) -> Cacher { + Cacher { + calculation, + value: None, + } + } + + fn value(&mut self, arg: u32) -> u32 { + match self.value { + Some(v) => v, + None => { + let v = (self.calculation)(arg); + self.value = Some(v); + v + } + } + } +} + +// ANCHOR: here +fn generate_workout(intensity: u32, random_number: u32) { + let mut expensive_result = Cacher::new(|num| { + println!("calculating slowly..."); + thread::sleep(Duration::from_secs(2)); + num + }); + + if intensity < 25 { + println!("Today, do {} pushups!", expensive_result.value(intensity)); + println!("Next, do {} situps!", expensive_result.value(intensity)); + } else { + if random_number == 3 { + println!("Take a break today! Remember to stay hydrated!"); + } else { + println!( + "Today, run for {} minutes!", + expensive_result.value(intensity) + ); + } + } +} +// ANCHOR_END: here + +fn main() { + let simulated_user_specified_value = 10; + let simulated_random_number = 7; + + generate_workout(simulated_user_specified_value, simulated_random_number); +} diff --git a/listings/ch13-functional-features/listing-13-12/Cargo.lock b/listings/ch13-functional-features/listing-13-12/Cargo.lock new file mode 100644 index 0000000000..a96532addb --- /dev/null +++ b/listings/ch13-functional-features/listing-13-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "equal-to-x" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-12/Cargo.toml b/listings/ch13-functional-features/listing-13-12/Cargo.toml new file mode 100644 index 0000000000..4fd5d85234 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "equal-to-x" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-12/src/main.rs b/listings/ch13-functional-features/listing-13-12/src/main.rs new file mode 100644 index 0000000000..7352b80b23 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-12/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let x = 4; + + let equal_to_x = |z| z == x; + + let y = 4; + + assert!(equal_to_x(y)); +} diff --git a/listings/ch13-functional-features/listing-13-13/Cargo.lock b/listings/ch13-functional-features/listing-13-13/Cargo.lock new file mode 100644 index 0000000000..e91eaa8d4c --- /dev/null +++ b/listings/ch13-functional-features/listing-13-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "iterators" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-13/Cargo.toml b/listings/ch13-functional-features/listing-13-13/Cargo.toml new file mode 100644 index 0000000000..015f9512f7 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "iterators" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-13/src/main.rs b/listings/ch13-functional-features/listing-13-13/src/main.rs new file mode 100644 index 0000000000..55a0dd37e9 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-13/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + // ANCHOR: here + let v1 = vec![1, 2, 3]; + + let v1_iter = v1.iter(); + // ANCHOR_END: here +} diff --git a/listings/ch13-functional-features/listing-13-14/Cargo.lock b/listings/ch13-functional-features/listing-13-14/Cargo.lock new file mode 100644 index 0000000000..e91eaa8d4c --- /dev/null +++ b/listings/ch13-functional-features/listing-13-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "iterators" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-14/Cargo.toml b/listings/ch13-functional-features/listing-13-14/Cargo.toml new file mode 100644 index 0000000000..015f9512f7 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "iterators" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-14/src/main.rs b/listings/ch13-functional-features/listing-13-14/src/main.rs new file mode 100644 index 0000000000..712aff4085 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-14/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let v1 = vec![1, 2, 3]; + + let v1_iter = v1.iter(); + + for val in v1_iter { + println!("Got: {}", val); + } + // ANCHOR_END: here +} diff --git a/listings/ch13-functional-features/listing-13-15/Cargo.lock b/listings/ch13-functional-features/listing-13-15/Cargo.lock new file mode 100644 index 0000000000..e91eaa8d4c --- /dev/null +++ b/listings/ch13-functional-features/listing-13-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "iterators" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-15/Cargo.toml b/listings/ch13-functional-features/listing-13-15/Cargo.toml new file mode 100644 index 0000000000..015f9512f7 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "iterators" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-15/src/lib.rs b/listings/ch13-functional-features/listing-13-15/src/lib.rs new file mode 100644 index 0000000000..afea80d22e --- /dev/null +++ b/listings/ch13-functional-features/listing-13-15/src/lib.rs @@ -0,0 +1,18 @@ +#[cfg(test)] +mod tests { + // ANCHOR: here + #[test] + fn iterator_demonstration() { + let v1 = vec![1, 2, 3]; + + let mut v1_iter = v1.iter(); + + assert_eq!(v1_iter.next(), Some(&1)); + assert_eq!(v1_iter.next(), Some(&2)); + assert_eq!(v1_iter.next(), Some(&3)); + assert_eq!(v1_iter.next(), None); + } + // ANCHOR_END: here +} + +fn main() {} diff --git a/listings/ch13-functional-features/listing-13-16/Cargo.lock b/listings/ch13-functional-features/listing-13-16/Cargo.lock new file mode 100644 index 0000000000..e91eaa8d4c --- /dev/null +++ b/listings/ch13-functional-features/listing-13-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "iterators" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-16/Cargo.toml b/listings/ch13-functional-features/listing-13-16/Cargo.toml new file mode 100644 index 0000000000..015f9512f7 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "iterators" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-16/src/lib.rs b/listings/ch13-functional-features/listing-13-16/src/lib.rs new file mode 100644 index 0000000000..198b3c834b --- /dev/null +++ b/listings/ch13-functional-features/listing-13-16/src/lib.rs @@ -0,0 +1,17 @@ +#[cfg(test)] +mod tests { + // ANCHOR: here + #[test] + fn iterator_sum() { + let v1 = vec![1, 2, 3]; + + let v1_iter = v1.iter(); + + let total: i32 = v1_iter.sum(); + + assert_eq!(total, 6); + } + // ANCHOR_END: here +} + +fn main() {} diff --git a/listings/ch13-functional-features/listing-13-17/Cargo.lock b/listings/ch13-functional-features/listing-13-17/Cargo.lock new file mode 100644 index 0000000000..e91eaa8d4c --- /dev/null +++ b/listings/ch13-functional-features/listing-13-17/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "iterators" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-17/Cargo.toml b/listings/ch13-functional-features/listing-13-17/Cargo.toml new file mode 100644 index 0000000000..015f9512f7 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-17/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "iterators" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-17/output.txt b/listings/ch13-functional-features/listing-13-17/output.txt new file mode 100644 index 0000000000..ff02254be7 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-17/output.txt @@ -0,0 +1,13 @@ +$ cargo run + Compiling iterators v0.1.0 (file:///projects/iterators) +warning: unused `std::iter::Map` that must be used + --> src/main.rs:4:5 + | +4 | v1.iter().map(|x| x + 1); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: `#[warn(unused_must_use)]` on by default + = note: iterators are lazy and do nothing unless consumed + + Finished dev [unoptimized + debuginfo] target(s) in 0.47s + Running `target/debug/iterators` diff --git a/listings/ch13-functional-features/listing-13-17/src/main.rs b/listings/ch13-functional-features/listing-13-17/src/main.rs new file mode 100644 index 0000000000..62a68be9b3 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-17/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + // ANCHOR: here + let v1: Vec = vec![1, 2, 3]; + + v1.iter().map(|x| x + 1); + // ANCHOR_END: here +} diff --git a/listings/ch13-functional-features/listing-13-18/Cargo.lock b/listings/ch13-functional-features/listing-13-18/Cargo.lock new file mode 100644 index 0000000000..e91eaa8d4c --- /dev/null +++ b/listings/ch13-functional-features/listing-13-18/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "iterators" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-18/Cargo.toml b/listings/ch13-functional-features/listing-13-18/Cargo.toml new file mode 100644 index 0000000000..015f9512f7 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-18/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "iterators" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-18/src/main.rs b/listings/ch13-functional-features/listing-13-18/src/main.rs new file mode 100644 index 0000000000..db9025d6fd --- /dev/null +++ b/listings/ch13-functional-features/listing-13-18/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + // ANCHOR: here + let v1: Vec = vec![1, 2, 3]; + + let v2: Vec<_> = v1.iter().map(|x| x + 1).collect(); + + assert_eq!(v2, vec![2, 3, 4]); + // ANCHOR_END: here +} diff --git a/listings/ch13-functional-features/listing-13-19/Cargo.lock b/listings/ch13-functional-features/listing-13-19/Cargo.lock new file mode 100644 index 0000000000..0b15e2157a --- /dev/null +++ b/listings/ch13-functional-features/listing-13-19/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "shoe_size" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-19/Cargo.toml b/listings/ch13-functional-features/listing-13-19/Cargo.toml new file mode 100644 index 0000000000..d0ecdac67b --- /dev/null +++ b/listings/ch13-functional-features/listing-13-19/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "shoe_size" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-19/src/lib.rs b/listings/ch13-functional-features/listing-13-19/src/lib.rs new file mode 100644 index 0000000000..c7ca364c28 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-19/src/lib.rs @@ -0,0 +1,50 @@ +#[derive(PartialEq, Debug)] +struct Shoe { + size: u32, + style: String, +} + +fn shoes_in_my_size(shoes: Vec, shoe_size: u32) -> Vec { + shoes.into_iter().filter(|s| s.size == shoe_size).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn filters_by_size() { + let shoes = vec![ + Shoe { + size: 10, + style: String::from("sneaker"), + }, + Shoe { + size: 13, + style: String::from("sandal"), + }, + Shoe { + size: 10, + style: String::from("boot"), + }, + ]; + + let in_my_size = shoes_in_my_size(shoes, 10); + + assert_eq!( + in_my_size, + vec![ + Shoe { + size: 10, + style: String::from("sneaker") + }, + Shoe { + size: 10, + style: String::from("boot") + }, + ] + ); + } +} + +fn main() {} diff --git a/listings/ch13-functional-features/listing-13-20/Cargo.lock b/listings/ch13-functional-features/listing-13-20/Cargo.lock new file mode 100644 index 0000000000..58b70c5b74 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-20/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "counter" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-20/Cargo.toml b/listings/ch13-functional-features/listing-13-20/Cargo.toml new file mode 100644 index 0000000000..4eb29e80c1 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-20/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "counter" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-20/src/lib.rs b/listings/ch13-functional-features/listing-13-20/src/lib.rs new file mode 100644 index 0000000000..897804c429 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-20/src/lib.rs @@ -0,0 +1,11 @@ +struct Counter { + count: u32, +} + +impl Counter { + fn new() -> Counter { + Counter { count: 0 } + } +} + +fn main() {} diff --git a/listings/ch13-functional-features/listing-13-21/Cargo.lock b/listings/ch13-functional-features/listing-13-21/Cargo.lock new file mode 100644 index 0000000000..58b70c5b74 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-21/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "counter" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-21/Cargo.toml b/listings/ch13-functional-features/listing-13-21/Cargo.toml new file mode 100644 index 0000000000..4eb29e80c1 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-21/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "counter" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-21/src/lib.rs b/listings/ch13-functional-features/listing-13-21/src/lib.rs new file mode 100644 index 0000000000..76de1b7ac4 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-21/src/lib.rs @@ -0,0 +1,27 @@ +struct Counter { + count: u32, +} + +impl Counter { + fn new() -> Counter { + Counter { count: 0 } + } +} + +// ANCHOR: here +impl Iterator for Counter { + type Item = u32; + + fn next(&mut self) -> Option { + self.count += 1; + + if self.count < 6 { + Some(self.count) + } else { + None + } + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch13-functional-features/listing-13-22/Cargo.lock b/listings/ch13-functional-features/listing-13-22/Cargo.lock new file mode 100644 index 0000000000..58b70c5b74 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-22/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "counter" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-22/Cargo.toml b/listings/ch13-functional-features/listing-13-22/Cargo.toml new file mode 100644 index 0000000000..4eb29e80c1 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-22/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "counter" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-22/src/lib.rs b/listings/ch13-functional-features/listing-13-22/src/lib.rs new file mode 100644 index 0000000000..0b85a9e68c --- /dev/null +++ b/listings/ch13-functional-features/listing-13-22/src/lib.rs @@ -0,0 +1,44 @@ +struct Counter { + count: u32, +} + +impl Counter { + fn new() -> Counter { + Counter { count: 0 } + } +} + +impl Iterator for Counter { + type Item = u32; + + fn next(&mut self) -> Option { + self.count += 1; + + if self.count < 6 { + Some(self.count) + } else { + None + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // ANCHOR: here + #[test] + fn calling_next_directly() { + let mut counter = Counter::new(); + + assert_eq!(counter.next(), Some(1)); + assert_eq!(counter.next(), Some(2)); + assert_eq!(counter.next(), Some(3)); + assert_eq!(counter.next(), Some(4)); + assert_eq!(counter.next(), Some(5)); + assert_eq!(counter.next(), None); + } + // ANCHOR_END: here +} + +fn main() {} diff --git a/listings/ch13-functional-features/listing-13-23/Cargo.lock b/listings/ch13-functional-features/listing-13-23/Cargo.lock new file mode 100644 index 0000000000..58b70c5b74 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-23/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "counter" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-23/Cargo.toml b/listings/ch13-functional-features/listing-13-23/Cargo.toml new file mode 100644 index 0000000000..4eb29e80c1 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-23/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "counter" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-23/src/lib.rs b/listings/ch13-functional-features/listing-13-23/src/lib.rs new file mode 100644 index 0000000000..941e294573 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-23/src/lib.rs @@ -0,0 +1,54 @@ +struct Counter { + count: u32, +} + +impl Counter { + fn new() -> Counter { + Counter { count: 0 } + } +} + +impl Iterator for Counter { + type Item = u32; + + fn next(&mut self) -> Option { + self.count += 1; + + if self.count < 6 { + Some(self.count) + } else { + None + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn calling_next_directly() { + let mut counter = Counter::new(); + + assert_eq!(counter.next(), Some(1)); + assert_eq!(counter.next(), Some(2)); + assert_eq!(counter.next(), Some(3)); + assert_eq!(counter.next(), Some(4)); + assert_eq!(counter.next(), Some(5)); + assert_eq!(counter.next(), None); + } + + // ANCHOR: here + #[test] + fn using_other_iterator_trait_methods() { + let sum: u32 = Counter::new() + .zip(Counter::new().skip(1)) + .map(|(a, b)| a * b) + .filter(|x| x % 3 == 0) + .sum(); + assert_eq!(18, sum); + } + // ANCHOR_END: here +} + +fn main() {} diff --git a/listings/ch13-functional-features/listing-13-25/Cargo.lock b/listings/ch13-functional-features/listing-13-25/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-25/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-25/Cargo.toml b/listings/ch13-functional-features/listing-13-25/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-25/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-25/poem.txt b/listings/ch13-functional-features/listing-13-25/poem.txt new file mode 100644 index 0000000000..8707527313 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-25/poem.txt @@ -0,0 +1,9 @@ +I'm nobody! Who are you? +Are you nobody, too? +Then there's a pair of us - don't tell! +They'd banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch13-functional-features/listing-13-25/src/lib.rs b/listings/ch13-functional-features/listing-13-25/src/lib.rs new file mode 100644 index 0000000000..fe1dccf4ee --- /dev/null +++ b/listings/ch13-functional-features/listing-13-25/src/lib.rs @@ -0,0 +1,104 @@ +use std::env; +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, + pub case_sensitive: bool, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); + + Ok(Config { + query, + filename, + case_sensitive, + }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + let results = if config.case_sensitive { + search(&config.query, &contents) + } else { + search_case_insensitive(&config.query, &contents) + }; + + for line in results { + println!("{}", line); + } + + Ok(()) +} + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +pub fn search_case_insensitive<'a>( + query: &str, + contents: &'a str, +) -> Vec<&'a str> { + let query = query.to_lowercase(); + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(&query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} diff --git a/listings/ch13-functional-features/listing-13-25/src/main.rs b/listings/ch13-functional-features/listing-13-25/src/main.rs new file mode 100644 index 0000000000..d09966e416 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-25/src/main.rs @@ -0,0 +1,23 @@ +use std::env; +use std::process; + +use minigrep::Config; + +// ANCHOR: here +fn main() { + let config = Config::new(env::args()).unwrap_or_else(|err| { + eprintln!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + // --snip-- + // ANCHOR_END: here + + if let Err(e) = minigrep::run(config) { + eprintln!("Application error: {}", e); + + process::exit(1); + } + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/listings/ch13-functional-features/listing-13-26/Cargo.lock b/listings/ch13-functional-features/listing-13-26/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-26/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-26/Cargo.toml b/listings/ch13-functional-features/listing-13-26/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-26/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-26/poem.txt b/listings/ch13-functional-features/listing-13-26/poem.txt new file mode 100644 index 0000000000..8707527313 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-26/poem.txt @@ -0,0 +1,9 @@ +I'm nobody! Who are you? +Are you nobody, too? +Then there's a pair of us - don't tell! +They'd banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch13-functional-features/listing-13-26/src/lib.rs b/listings/ch13-functional-features/listing-13-26/src/lib.rs new file mode 100644 index 0000000000..44f0c7ee21 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-26/src/lib.rs @@ -0,0 +1,107 @@ +use std::env; +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, + pub case_sensitive: bool, +} + +// ANCHOR: here +impl Config { + pub fn new(mut args: std::env::Args) -> Result { + // --snip-- + // ANCHOR_END: here + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); + + Ok(Config { + query, + filename, + case_sensitive, + }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + let results = if config.case_sensitive { + search(&config.query, &contents) + } else { + search_case_insensitive(&config.query, &contents) + }; + + for line in results { + println!("{}", line); + } + + Ok(()) +} + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +pub fn search_case_insensitive<'a>( + query: &str, + contents: &'a str, +) -> Vec<&'a str> { + let query = query.to_lowercase(); + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(&query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} diff --git a/listings/ch13-functional-features/listing-13-26/src/main.rs b/listings/ch13-functional-features/listing-13-26/src/main.rs new file mode 100644 index 0000000000..06aac30e73 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-26/src/main.rs @@ -0,0 +1,17 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let config = Config::new(env::args()).unwrap_or_else(|err| { + eprintln!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + eprintln!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/listings/ch13-functional-features/listing-13-27/Cargo.lock b/listings/ch13-functional-features/listing-13-27/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-27/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-27/Cargo.toml b/listings/ch13-functional-features/listing-13-27/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-27/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-27/poem.txt b/listings/ch13-functional-features/listing-13-27/poem.txt new file mode 100644 index 0000000000..8707527313 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-27/poem.txt @@ -0,0 +1,9 @@ +I'm nobody! Who are you? +Are you nobody, too? +Then there's a pair of us - don't tell! +They'd banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch13-functional-features/listing-13-27/src/lib.rs b/listings/ch13-functional-features/listing-13-27/src/lib.rs new file mode 100644 index 0000000000..a4c58d9bdd --- /dev/null +++ b/listings/ch13-functional-features/listing-13-27/src/lib.rs @@ -0,0 +1,113 @@ +use std::env; +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, + pub case_sensitive: bool, +} + +// ANCHOR: here +impl Config { + pub fn new(mut args: std::env::Args) -> Result { + args.next(); + + let query = match args.next() { + Some(arg) => arg, + None => return Err("Didn't get a query string"), + }; + + let filename = match args.next() { + Some(arg) => arg, + None => return Err("Didn't get a file name"), + }; + + let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); + + Ok(Config { + query, + filename, + case_sensitive, + }) + } +} +// ANCHOR_END: here + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + let results = if config.case_sensitive { + search(&config.query, &contents) + } else { + search_case_insensitive(&config.query, &contents) + }; + + for line in results { + println!("{}", line); + } + + Ok(()) +} + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +pub fn search_case_insensitive<'a>( + query: &str, + contents: &'a str, +) -> Vec<&'a str> { + let query = query.to_lowercase(); + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(&query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} + +fn main() {} diff --git a/listings/ch13-functional-features/listing-13-27/src/main.rs b/listings/ch13-functional-features/listing-13-27/src/main.rs new file mode 100644 index 0000000000..06aac30e73 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-27/src/main.rs @@ -0,0 +1,17 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let config = Config::new(env::args()).unwrap_or_else(|err| { + eprintln!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + eprintln!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/listings/ch13-functional-features/listing-13-29/Cargo.lock b/listings/ch13-functional-features/listing-13-29/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-29/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/listing-13-29/Cargo.toml b/listings/ch13-functional-features/listing-13-29/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-29/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/listing-13-29/poem.txt b/listings/ch13-functional-features/listing-13-29/poem.txt new file mode 100644 index 0000000000..8707527313 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-29/poem.txt @@ -0,0 +1,9 @@ +I'm nobody! Who are you? +Are you nobody, too? +Then there's a pair of us - don't tell! +They'd banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/listings/ch13-functional-features/listing-13-29/src/lib.rs b/listings/ch13-functional-features/listing-13-29/src/lib.rs new file mode 100644 index 0000000000..bc8a77ef6e --- /dev/null +++ b/listings/ch13-functional-features/listing-13-29/src/lib.rs @@ -0,0 +1,106 @@ +use std::env; +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, + pub case_sensitive: bool, +} + +impl Config { + pub fn new(mut args: std::env::Args) -> Result { + args.next(); + + let query = match args.next() { + Some(arg) => arg, + None => return Err("Didn't get a query string"), + }; + + let filename = match args.next() { + Some(arg) => arg, + None => return Err("Didn't get a file name"), + }; + + let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); + + Ok(Config { + query, + filename, + case_sensitive, + }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + let results = if config.case_sensitive { + search(&config.query, &contents) + } else { + search_case_insensitive(&config.query, &contents) + }; + + for line in results { + println!("{}", line); + } + + Ok(()) +} + +// ANCHOR: here +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + contents + .lines() + .filter(|line| line.contains(query)) + .collect() +} +// ANCHOR_END: here + +pub fn search_case_insensitive<'a>( + query: &str, + contents: &'a str, +) -> Vec<&'a str> { + let query = query.to_lowercase(); + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(&query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} diff --git a/listings/ch13-functional-features/listing-13-29/src/main.rs b/listings/ch13-functional-features/listing-13-29/src/main.rs new file mode 100644 index 0000000000..06aac30e73 --- /dev/null +++ b/listings/ch13-functional-features/listing-13-29/src/main.rs @@ -0,0 +1,17 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let config = Config::new(env::args()).unwrap_or_else(|err| { + eprintln!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + eprintln!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/listings/ch13-functional-features/no-listing-01-failing-cacher-test/Cargo.lock b/listings/ch13-functional-features/no-listing-01-failing-cacher-test/Cargo.lock new file mode 100644 index 0000000000..e090432bc9 --- /dev/null +++ b/listings/ch13-functional-features/no-listing-01-failing-cacher-test/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cacher" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/no-listing-01-failing-cacher-test/Cargo.toml b/listings/ch13-functional-features/no-listing-01-failing-cacher-test/Cargo.toml new file mode 100644 index 0000000000..54ab6f2173 --- /dev/null +++ b/listings/ch13-functional-features/no-listing-01-failing-cacher-test/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cacher" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/no-listing-01-failing-cacher-test/output.txt b/listings/ch13-functional-features/no-listing-01-failing-cacher-test/output.txt new file mode 100644 index 0000000000..9f904f83fa --- /dev/null +++ b/listings/ch13-functional-features/no-listing-01-failing-cacher-test/output.txt @@ -0,0 +1,23 @@ +$ cargo test + Compiling cacher v0.1.0 (file:///projects/cacher) + Finished test [unoptimized + debuginfo] target(s) in 0.72s + Running target/debug/deps/cacher-35748700da794293 + +running 1 test +test tests::call_with_different_values ... FAILED + +failures: + +---- tests::call_with_different_values stdout ---- +thread 'main' panicked at 'assertion failed: `(left == right)` + left: `1`, + right: `2`', src/lib.rs:43:9 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. + + +failures: + tests::call_with_different_values + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/listings/ch13-functional-features/no-listing-01-failing-cacher-test/src/lib.rs b/listings/ch13-functional-features/no-listing-01-failing-cacher-test/src/lib.rs new file mode 100644 index 0000000000..e7d677d0e3 --- /dev/null +++ b/listings/ch13-functional-features/no-listing-01-failing-cacher-test/src/lib.rs @@ -0,0 +1,47 @@ +struct Cacher +where + T: Fn(u32) -> u32, +{ + calculation: T, + value: Option, +} + +impl Cacher +where + T: Fn(u32) -> u32, +{ + fn new(calculation: T) -> Cacher { + Cacher { + calculation, + value: None, + } + } + + fn value(&mut self, arg: u32) -> u32 { + match self.value { + Some(v) => v, + None => { + let v = (self.calculation)(arg); + self.value = Some(v); + v + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // ANCHOR: here + #[test] + fn call_with_different_values() { + let mut c = Cacher::new(|a| a); + + let v1 = c.value(1); + let v2 = c.value(2); + + assert_eq!(v2, 2); + } + // ANCHOR_END: here +} diff --git a/listings/ch13-functional-features/no-listing-02-functions-cant-capture/Cargo.lock b/listings/ch13-functional-features/no-listing-02-functions-cant-capture/Cargo.lock new file mode 100644 index 0000000000..a96532addb --- /dev/null +++ b/listings/ch13-functional-features/no-listing-02-functions-cant-capture/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "equal-to-x" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/no-listing-02-functions-cant-capture/Cargo.toml b/listings/ch13-functional-features/no-listing-02-functions-cant-capture/Cargo.toml new file mode 100644 index 0000000000..4fd5d85234 --- /dev/null +++ b/listings/ch13-functional-features/no-listing-02-functions-cant-capture/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "equal-to-x" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/no-listing-02-functions-cant-capture/output.txt b/listings/ch13-functional-features/no-listing-02-functions-cant-capture/output.txt new file mode 100644 index 0000000000..a8d9e16d38 --- /dev/null +++ b/listings/ch13-functional-features/no-listing-02-functions-cant-capture/output.txt @@ -0,0 +1,16 @@ +$ cargo run + Compiling equal-to-x v0.1.0 (file:///projects/equal-to-x) +error[E0434]: can't capture dynamic environment in a fn item + --> src/main.rs:5:14 + | +5 | z == x + | ^ + | + = help: use the `|| { ... }` closure form instead + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0434`. +error: could not compile `equal-to-x`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch13-functional-features/no-listing-02-functions-cant-capture/src/main.rs b/listings/ch13-functional-features/no-listing-02-functions-cant-capture/src/main.rs new file mode 100644 index 0000000000..1b5d2b930b --- /dev/null +++ b/listings/ch13-functional-features/no-listing-02-functions-cant-capture/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + let x = 4; + + fn equal_to_x(z: i32) -> bool { + z == x + } + + let y = 4; + + assert!(equal_to_x(y)); +} diff --git a/listings/ch13-functional-features/no-listing-03-move-closures/Cargo.lock b/listings/ch13-functional-features/no-listing-03-move-closures/Cargo.lock new file mode 100644 index 0000000000..a96532addb --- /dev/null +++ b/listings/ch13-functional-features/no-listing-03-move-closures/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "equal-to-x" +version = "0.1.0" + diff --git a/listings/ch13-functional-features/no-listing-03-move-closures/Cargo.toml b/listings/ch13-functional-features/no-listing-03-move-closures/Cargo.toml new file mode 100644 index 0000000000..4fd5d85234 --- /dev/null +++ b/listings/ch13-functional-features/no-listing-03-move-closures/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "equal-to-x" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch13-functional-features/no-listing-03-move-closures/output.txt b/listings/ch13-functional-features/no-listing-03-move-closures/output.txt new file mode 100644 index 0000000000..43490332ed --- /dev/null +++ b/listings/ch13-functional-features/no-listing-03-move-closures/output.txt @@ -0,0 +1,22 @@ +$ cargo run + Compiling equal-to-x v0.1.0 (file:///projects/equal-to-x) +error[E0382]: borrow of moved value: `x` + --> src/main.rs:6:40 + | +2 | let x = vec![1, 2, 3]; + | - move occurs because `x` has type `std::vec::Vec`, which does not implement the `Copy` trait +3 | +4 | let equal_to_x = move |z| z == x; + | -------- - variable moved due to use in closure + | | + | value moved into closure here +5 | +6 | println!("can't use x here: {:?}", x); + | ^ value borrowed here after move + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0382`. +error: could not compile `equal-to-x`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch13-functional-features/no-listing-03-move-closures/src/main.rs b/listings/ch13-functional-features/no-listing-03-move-closures/src/main.rs new file mode 100644 index 0000000000..19d4776088 --- /dev/null +++ b/listings/ch13-functional-features/no-listing-03-move-closures/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + let x = vec![1, 2, 3]; + + let equal_to_x = move |z| z == x; + + println!("can't use x here: {:?}", x); + + let y = vec![1, 2, 3]; + + assert!(equal_to_x(y)); +} diff --git a/listings/ch14-more-about-cargo/listing-14-01/Cargo.lock b/listings/ch14-more-about-cargo/listing-14-01/Cargo.lock new file mode 100644 index 0000000000..b304dd7c75 --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "my_crate" +version = "0.1.0" + diff --git a/listings/ch14-more-about-cargo/listing-14-01/Cargo.toml b/listings/ch14-more-about-cargo/listing-14-01/Cargo.toml new file mode 100644 index 0000000000..716953ae12 --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "my_crate" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch14-more-about-cargo/listing-14-01/src/lib.rs b/listings/ch14-more-about-cargo/listing-14-01/src/lib.rs new file mode 100644 index 0000000000..ed7abb7277 --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-01/src/lib.rs @@ -0,0 +1,13 @@ +/// Adds one to the number given. +/// +/// # Examples +/// +/// ``` +/// let arg = 5; +/// let answer = my_crate::add_one(arg); +/// +/// assert_eq!(6, answer); +/// ``` +pub fn add_one(x: i32) -> i32 { + x + 1 +} diff --git a/listings/ch14-more-about-cargo/listing-14-02/Cargo.lock b/listings/ch14-more-about-cargo/listing-14-02/Cargo.lock new file mode 100644 index 0000000000..b304dd7c75 --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "my_crate" +version = "0.1.0" + diff --git a/listings/ch14-more-about-cargo/listing-14-02/Cargo.toml b/listings/ch14-more-about-cargo/listing-14-02/Cargo.toml new file mode 100644 index 0000000000..716953ae12 --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "my_crate" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch14-more-about-cargo/listing-14-02/src/lib.rs b/listings/ch14-more-about-cargo/listing-14-02/src/lib.rs new file mode 100644 index 0000000000..64c9c439cc --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-02/src/lib.rs @@ -0,0 +1,21 @@ +// ANCHOR: here +//! # My Crate +//! +//! `my_crate` is a collection of utilities to make performing certain +//! calculations more convenient. + +/// Adds one to the number given. +// --snip-- +// ANCHOR_END: here +/// +/// # Examples +/// +/// ``` +/// let arg = 5; +/// let answer = my_crate::add_one(arg); +/// +/// assert_eq!(6, answer); +/// ``` +pub fn add_one(x: i32) -> i32 { + x + 1 +} diff --git a/listings/ch14-more-about-cargo/listing-14-03/Cargo.lock b/listings/ch14-more-about-cargo/listing-14-03/Cargo.lock new file mode 100644 index 0000000000..df19c247b7 --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "art" +version = "0.1.0" + diff --git a/listings/ch14-more-about-cargo/listing-14-03/Cargo.toml b/listings/ch14-more-about-cargo/listing-14-03/Cargo.toml new file mode 100644 index 0000000000..a2e9e369bc --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "art" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch14-more-about-cargo/listing-14-03/src/lib.rs b/listings/ch14-more-about-cargo/listing-14-03/src/lib.rs new file mode 100644 index 0000000000..00a81c5082 --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-03/src/lib.rs @@ -0,0 +1,36 @@ +// ANCHOR: here +//! # Art +//! +//! A library for modeling artistic concepts. + +pub mod kinds { + /// The primary colors according to the RYB color model. + pub enum PrimaryColor { + Red, + Yellow, + Blue, + } + + /// The secondary colors according to the RYB color model. + pub enum SecondaryColor { + Orange, + Green, + Purple, + } +} + +pub mod utils { + use crate::kinds::*; + + /// Combines two primary colors in equal amounts to create + /// a secondary color. + pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor { + // --snip-- + // ANCHOR_END: here + SecondaryColor::Orange + // ANCHOR: here + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch14-more-about-cargo/listing-14-04/Cargo.lock b/listings/ch14-more-about-cargo/listing-14-04/Cargo.lock new file mode 100644 index 0000000000..df19c247b7 --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "art" +version = "0.1.0" + diff --git a/listings/ch14-more-about-cargo/listing-14-04/Cargo.toml b/listings/ch14-more-about-cargo/listing-14-04/Cargo.toml new file mode 100644 index 0000000000..a2e9e369bc --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "art" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch14-more-about-cargo/listing-14-04/src/lib.rs b/listings/ch14-more-about-cargo/listing-14-04/src/lib.rs new file mode 100644 index 0000000000..b077a9a71a --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-04/src/lib.rs @@ -0,0 +1,29 @@ +//! # Art +//! +//! A library for modeling artistic concepts. + +pub mod kinds { + /// The primary colors according to the RYB color model. + pub enum PrimaryColor { + Red, + Yellow, + Blue, + } + + /// The secondary colors according to the RYB color model. + pub enum SecondaryColor { + Orange, + Green, + Purple, + } +} + +pub mod utils { + use crate::kinds::*; + + /// Combines two primary colors in equal amounts to create + /// a secondary color. + pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor { + SecondaryColor::Orange + } +} diff --git a/listings/ch14-more-about-cargo/listing-14-04/src/main.rs b/listings/ch14-more-about-cargo/listing-14-04/src/main.rs new file mode 100644 index 0000000000..b1a4bf7922 --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-04/src/main.rs @@ -0,0 +1,8 @@ +use art::kinds::PrimaryColor; +use art::utils::mix; + +fn main() { + let red = PrimaryColor::Red; + let yellow = PrimaryColor::Yellow; + mix(red, yellow); +} diff --git a/listings/ch14-more-about-cargo/listing-14-05/Cargo.lock b/listings/ch14-more-about-cargo/listing-14-05/Cargo.lock new file mode 100644 index 0000000000..df19c247b7 --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "art" +version = "0.1.0" + diff --git a/listings/ch14-more-about-cargo/listing-14-05/Cargo.toml b/listings/ch14-more-about-cargo/listing-14-05/Cargo.toml new file mode 100644 index 0000000000..a2e9e369bc --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "art" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch14-more-about-cargo/listing-14-05/src/lib.rs b/listings/ch14-more-about-cargo/listing-14-05/src/lib.rs new file mode 100644 index 0000000000..c5aa9e7b00 --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-05/src/lib.rs @@ -0,0 +1,41 @@ +// ANCHOR: here +//! # Art +//! +//! A library for modeling artistic concepts. + +pub use self::kinds::PrimaryColor; +pub use self::kinds::SecondaryColor; +pub use self::utils::mix; + +pub mod kinds { + // --snip-- + // ANCHOR_END: here + /// The primary colors according to the RYB color model. + pub enum PrimaryColor { + Red, + Yellow, + Blue, + } + + /// The secondary colors according to the RYB color model. + pub enum SecondaryColor { + Orange, + Green, + Purple, + } + // ANCHOR: here +} + +pub mod utils { + // --snip-- + // ANCHOR_END: here + use crate::kinds::*; + + /// Combines two primary colors in equal amounts to create + /// a secondary color. + pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor { + SecondaryColor::Orange + } + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/listings/ch14-more-about-cargo/listing-14-06/Cargo.lock b/listings/ch14-more-about-cargo/listing-14-06/Cargo.lock new file mode 100644 index 0000000000..df19c247b7 --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "art" +version = "0.1.0" + diff --git a/listings/ch14-more-about-cargo/listing-14-06/Cargo.toml b/listings/ch14-more-about-cargo/listing-14-06/Cargo.toml new file mode 100644 index 0000000000..a2e9e369bc --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "art" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch14-more-about-cargo/listing-14-06/src/lib.rs b/listings/ch14-more-about-cargo/listing-14-06/src/lib.rs new file mode 100644 index 0000000000..daabd006df --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-06/src/lib.rs @@ -0,0 +1,33 @@ +//! # Art +//! +//! A library for modeling artistic concepts. + +pub use self::kinds::PrimaryColor; +pub use self::kinds::SecondaryColor; +pub use self::utils::mix; + +pub mod kinds { + /// The primary colors according to the RYB color model. + pub enum PrimaryColor { + Red, + Yellow, + Blue, + } + + /// The secondary colors according to the RYB color model. + pub enum SecondaryColor { + Orange, + Green, + Purple, + } +} + +pub mod utils { + use crate::kinds::*; + + /// Combines two primary colors in equal amounts to create + /// a secondary color. + pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor { + SecondaryColor::Orange + } +} diff --git a/listings/ch14-more-about-cargo/listing-14-06/src/main.rs b/listings/ch14-more-about-cargo/listing-14-06/src/main.rs new file mode 100644 index 0000000000..51f3b761db --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-06/src/main.rs @@ -0,0 +1,13 @@ +// ANCHOR: here +use art::mix; +use art::PrimaryColor; + +fn main() { + // --snip-- + // ANCHOR_END: here + let red = PrimaryColor::Red; + let yellow = PrimaryColor::Yellow; + mix(red, yellow); + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/listings/ch14-more-about-cargo/listing-14-07/add/Cargo.lock b/listings/ch14-more-about-cargo/listing-14-07/add/Cargo.lock new file mode 100644 index 0000000000..77292f6149 --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-07/add/Cargo.lock @@ -0,0 +1,13 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "add-one" +version = "0.1.0" + +[[package]] +name = "adder" +version = "0.1.0" +dependencies = [ + "add-one 0.1.0", +] + diff --git a/listings/ch14-more-about-cargo/listing-14-07/add/Cargo.toml b/listings/ch14-more-about-cargo/listing-14-07/add/Cargo.toml new file mode 100644 index 0000000000..d26e7cfb4d --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-07/add/Cargo.toml @@ -0,0 +1,6 @@ +[workspace] + +members = [ + "adder", + "add-one", +] diff --git a/listings/ch14-more-about-cargo/listing-14-07/add/add-one/Cargo.toml b/listings/ch14-more-about-cargo/listing-14-07/add/add-one/Cargo.toml new file mode 100644 index 0000000000..8260fb541b --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-07/add/add-one/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "add-one" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch14-more-about-cargo/listing-14-07/add/add-one/src/lib.rs b/listings/ch14-more-about-cargo/listing-14-07/add/add-one/src/lib.rs new file mode 100644 index 0000000000..b0bb869432 --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-07/add/add-one/src/lib.rs @@ -0,0 +1,3 @@ +pub fn add_one(x: i32) -> i32 { + x + 1 +} diff --git a/listings/ch14-more-about-cargo/listing-14-07/add/adder/Cargo.toml b/listings/ch14-more-about-cargo/listing-14-07/add/adder/Cargo.toml new file mode 100644 index 0000000000..e73f1becaf --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-07/add/adder/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] + +add-one = { path = "../add-one" } diff --git a/listings/ch14-more-about-cargo/listing-14-07/add/adder/src/main.rs b/listings/ch14-more-about-cargo/listing-14-07/add/adder/src/main.rs new file mode 100644 index 0000000000..7deb7962f4 --- /dev/null +++ b/listings/ch14-more-about-cargo/listing-14-07/add/adder/src/main.rs @@ -0,0 +1,10 @@ +use add_one; + +fn main() { + let num = 10; + println!( + "Hello, world! {} plus one is {}!", + num, + add_one::add_one(num) + ); +} diff --git a/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/Cargo.lock b/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/Cargo.toml b/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/Cargo.toml new file mode 100644 index 0000000000..c5ea8e510b --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/Cargo.toml @@ -0,0 +1,5 @@ +[workspace] + +members = [ + "adder", +] diff --git a/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/adder/Cargo.toml b/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/adder/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/adder/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/adder/src/main.rs b/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/adder/src/main.rs new file mode 100644 index 0000000000..e7a11a969c --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/adder/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} diff --git a/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/Cargo.lock b/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/Cargo.lock new file mode 100644 index 0000000000..77292f6149 --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/Cargo.lock @@ -0,0 +1,13 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "add-one" +version = "0.1.0" + +[[package]] +name = "adder" +version = "0.1.0" +dependencies = [ + "add-one 0.1.0", +] + diff --git a/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/Cargo.toml b/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/Cargo.toml new file mode 100644 index 0000000000..d26e7cfb4d --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/Cargo.toml @@ -0,0 +1,6 @@ +[workspace] + +members = [ + "adder", + "add-one", +] diff --git a/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/add-one/Cargo.toml b/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/add-one/Cargo.toml new file mode 100644 index 0000000000..8260fb541b --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/add-one/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "add-one" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/add-one/src/lib.rs b/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/add-one/src/lib.rs new file mode 100644 index 0000000000..b0bb869432 --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/add-one/src/lib.rs @@ -0,0 +1,3 @@ +pub fn add_one(x: i32) -> i32 { + x + 1 +} diff --git a/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/adder/Cargo.toml b/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/adder/Cargo.toml new file mode 100644 index 0000000000..e73f1becaf --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/adder/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] + +add-one = { path = "../add-one" } diff --git a/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/adder/src/main.rs b/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/adder/src/main.rs new file mode 100644 index 0000000000..e7a11a969c --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/adder/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} diff --git a/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/Cargo.lock b/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/Cargo.lock new file mode 100644 index 0000000000..f17f35e860 --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/Cargo.lock @@ -0,0 +1,94 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "add-one" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "adder" +version = "0.1.0" +dependencies = [ + "add-one 0.1.0", +] + +[[package]] +name = "bitflags" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "libc" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.54 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.54 (registry+https://github.com/rust-lang/crates.io-index)" = "c6785aa7dd976f5fbf3b71cfd9cd49d7f783c1ff565a858d71031c6c313aa5c6" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/Cargo.toml b/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/Cargo.toml new file mode 100644 index 0000000000..d26e7cfb4d --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/Cargo.toml @@ -0,0 +1,6 @@ +[workspace] + +members = [ + "adder", + "add-one", +] diff --git a/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/add-one/Cargo.toml b/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/add-one/Cargo.toml new file mode 100644 index 0000000000..5b52051a63 --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/add-one/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "add-one" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] +rand = "0.5.5" diff --git a/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/add-one/src/lib.rs b/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/add-one/src/lib.rs new file mode 100644 index 0000000000..7b61b40a40 --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/add-one/src/lib.rs @@ -0,0 +1,5 @@ +use rand; + +pub fn add_one(x: i32) -> i32 { + x + 1 +} diff --git a/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/adder/Cargo.toml b/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/adder/Cargo.toml new file mode 100644 index 0000000000..e73f1becaf --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/adder/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] + +add-one = { path = "../add-one" } diff --git a/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/adder/src/main.rs b/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/adder/src/main.rs new file mode 100644 index 0000000000..7deb7962f4 --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/adder/src/main.rs @@ -0,0 +1,10 @@ +use add_one; + +fn main() { + let num = 10; + println!( + "Hello, world! {} plus one is {}!", + num, + add_one::add_one(num) + ); +} diff --git a/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/Cargo.lock b/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/Cargo.lock new file mode 100644 index 0000000000..77292f6149 --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/Cargo.lock @@ -0,0 +1,13 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "add-one" +version = "0.1.0" + +[[package]] +name = "adder" +version = "0.1.0" +dependencies = [ + "add-one 0.1.0", +] + diff --git a/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/Cargo.toml b/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/Cargo.toml new file mode 100644 index 0000000000..d26e7cfb4d --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/Cargo.toml @@ -0,0 +1,6 @@ +[workspace] + +members = [ + "adder", + "add-one", +] diff --git a/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/add-one/Cargo.toml b/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/add-one/Cargo.toml new file mode 100644 index 0000000000..8260fb541b --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/add-one/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "add-one" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/add-one/src/lib.rs b/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/add-one/src/lib.rs new file mode 100644 index 0000000000..40ceb12859 --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/add-one/src/lib.rs @@ -0,0 +1,13 @@ +pub fn add_one(x: i32) -> i32 { + x + 1 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_works() { + assert_eq!(3, add_one(2)); + } +} diff --git a/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/adder/Cargo.toml b/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/adder/Cargo.toml new file mode 100644 index 0000000000..e73f1becaf --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/adder/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] + +add-one = { path = "../add-one" } diff --git a/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/adder/src/main.rs b/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/adder/src/main.rs new file mode 100644 index 0000000000..7deb7962f4 --- /dev/null +++ b/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/adder/src/main.rs @@ -0,0 +1,10 @@ +use add_one; + +fn main() { + let num = 10; + println!( + "Hello, world! {} plus one is {}!", + num, + add_one::add_one(num) + ); +} diff --git a/listings/ch14-more-about-cargo/output-only-01-adder-crate/add/.gitignore b/listings/ch14-more-about-cargo/output-only-01-adder-crate/add/.gitignore new file mode 100644 index 0000000000..b46d5c4644 --- /dev/null +++ b/listings/ch14-more-about-cargo/output-only-01-adder-crate/add/.gitignore @@ -0,0 +1 @@ +adder diff --git a/listings/ch14-more-about-cargo/output-only-01-adder-crate/add/Cargo.toml b/listings/ch14-more-about-cargo/output-only-01-adder-crate/add/Cargo.toml new file mode 100644 index 0000000000..c5ea8e510b --- /dev/null +++ b/listings/ch14-more-about-cargo/output-only-01-adder-crate/add/Cargo.toml @@ -0,0 +1,5 @@ +[workspace] + +members = [ + "adder", +] diff --git a/listings/ch14-more-about-cargo/output-only-01-adder-crate/add/rustfmt-ignore b/listings/ch14-more-about-cargo/output-only-01-adder-crate/add/rustfmt-ignore new file mode 100644 index 0000000000..958e568374 --- /dev/null +++ b/listings/ch14-more-about-cargo/output-only-01-adder-crate/add/rustfmt-ignore @@ -0,0 +1,2 @@ +This listing is used for demonstrating how to set up a workspace, but the workspace isn't +completely set up yet, so rustfmt complains the crate mentioned in Cargo.toml doesn't exist yet. diff --git a/listings/ch14-more-about-cargo/output-only-02-add-one/add/.gitignore b/listings/ch14-more-about-cargo/output-only-02-add-one/add/.gitignore new file mode 100644 index 0000000000..64904e06d9 --- /dev/null +++ b/listings/ch14-more-about-cargo/output-only-02-add-one/add/.gitignore @@ -0,0 +1 @@ +add-one diff --git a/listings/ch14-more-about-cargo/output-only-02-add-one/add/Cargo.lock b/listings/ch14-more-about-cargo/output-only-02-add-one/add/Cargo.lock new file mode 100644 index 0000000000..77292f6149 --- /dev/null +++ b/listings/ch14-more-about-cargo/output-only-02-add-one/add/Cargo.lock @@ -0,0 +1,13 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "add-one" +version = "0.1.0" + +[[package]] +name = "adder" +version = "0.1.0" +dependencies = [ + "add-one 0.1.0", +] + diff --git a/listings/ch14-more-about-cargo/output-only-02-add-one/add/Cargo.toml b/listings/ch14-more-about-cargo/output-only-02-add-one/add/Cargo.toml new file mode 100644 index 0000000000..d26e7cfb4d --- /dev/null +++ b/listings/ch14-more-about-cargo/output-only-02-add-one/add/Cargo.toml @@ -0,0 +1,6 @@ +[workspace] + +members = [ + "adder", + "add-one", +] diff --git a/listings/ch14-more-about-cargo/output-only-02-add-one/add/adder/Cargo.toml b/listings/ch14-more-about-cargo/output-only-02-add-one/add/adder/Cargo.toml new file mode 100644 index 0000000000..e73f1becaf --- /dev/null +++ b/listings/ch14-more-about-cargo/output-only-02-add-one/add/adder/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] + +add-one = { path = "../add-one" } diff --git a/listings/ch14-more-about-cargo/output-only-02-add-one/add/adder/src/main.rs b/listings/ch14-more-about-cargo/output-only-02-add-one/add/adder/src/main.rs new file mode 100644 index 0000000000..e7a11a969c --- /dev/null +++ b/listings/ch14-more-about-cargo/output-only-02-add-one/add/adder/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} diff --git a/listings/ch14-more-about-cargo/output-only-03-use-rand/add/Cargo.lock b/listings/ch14-more-about-cargo/output-only-03-use-rand/add/Cargo.lock new file mode 100644 index 0000000000..f17f35e860 --- /dev/null +++ b/listings/ch14-more-about-cargo/output-only-03-use-rand/add/Cargo.lock @@ -0,0 +1,94 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "add-one" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "adder" +version = "0.1.0" +dependencies = [ + "add-one 0.1.0", +] + +[[package]] +name = "bitflags" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "libc" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.54 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.54 (registry+https://github.com/rust-lang/crates.io-index)" = "c6785aa7dd976f5fbf3b71cfd9cd49d7f783c1ff565a858d71031c6c313aa5c6" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/listings/ch14-more-about-cargo/output-only-03-use-rand/add/Cargo.toml b/listings/ch14-more-about-cargo/output-only-03-use-rand/add/Cargo.toml new file mode 100644 index 0000000000..d26e7cfb4d --- /dev/null +++ b/listings/ch14-more-about-cargo/output-only-03-use-rand/add/Cargo.toml @@ -0,0 +1,6 @@ +[workspace] + +members = [ + "adder", + "add-one", +] diff --git a/listings/ch14-more-about-cargo/output-only-03-use-rand/add/add-one/Cargo.toml b/listings/ch14-more-about-cargo/output-only-03-use-rand/add/add-one/Cargo.toml new file mode 100644 index 0000000000..5b52051a63 --- /dev/null +++ b/listings/ch14-more-about-cargo/output-only-03-use-rand/add/add-one/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "add-one" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] +rand = "0.5.5" diff --git a/listings/ch14-more-about-cargo/output-only-03-use-rand/add/add-one/src/lib.rs b/listings/ch14-more-about-cargo/output-only-03-use-rand/add/add-one/src/lib.rs new file mode 100644 index 0000000000..7b61b40a40 --- /dev/null +++ b/listings/ch14-more-about-cargo/output-only-03-use-rand/add/add-one/src/lib.rs @@ -0,0 +1,5 @@ +use rand; + +pub fn add_one(x: i32) -> i32 { + x + 1 +} diff --git a/listings/ch14-more-about-cargo/output-only-03-use-rand/add/adder/Cargo.toml b/listings/ch14-more-about-cargo/output-only-03-use-rand/add/adder/Cargo.toml new file mode 100644 index 0000000000..e73f1becaf --- /dev/null +++ b/listings/ch14-more-about-cargo/output-only-03-use-rand/add/adder/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] + +add-one = { path = "../add-one" } diff --git a/listings/ch14-more-about-cargo/output-only-03-use-rand/add/adder/src/main.rs b/listings/ch14-more-about-cargo/output-only-03-use-rand/add/adder/src/main.rs new file mode 100644 index 0000000000..eb4050dc36 --- /dev/null +++ b/listings/ch14-more-about-cargo/output-only-03-use-rand/add/adder/src/main.rs @@ -0,0 +1,11 @@ +use add_one; +use rand; + +fn main() { + let num = 10; + println!( + "Hello, world! {} plus one is {}!", + num, + add_one::add_one(num) + ); +} diff --git a/listings/ch15-smart-pointers/listing-15-01/Cargo.lock b/listings/ch15-smart-pointers/listing-15-01/Cargo.lock new file mode 100644 index 0000000000..8c125fc84b --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "box-example" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-01/Cargo.toml b/listings/ch15-smart-pointers/listing-15-01/Cargo.toml new file mode 100644 index 0000000000..4a0bb9d2f9 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "box-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-01/src/main.rs b/listings/ch15-smart-pointers/listing-15-01/src/main.rs new file mode 100644 index 0000000000..8da1d905d6 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-01/src/main.rs @@ -0,0 +1,4 @@ +fn main() { + let b = Box::new(5); + println!("b = {}", b); +} diff --git a/listings/ch15-smart-pointers/listing-15-02/Cargo.lock b/listings/ch15-smart-pointers/listing-15-02/Cargo.lock new file mode 100644 index 0000000000..a792c49aaf --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cons-list" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-02/Cargo.toml b/listings/ch15-smart-pointers/listing-15-02/Cargo.toml new file mode 100644 index 0000000000..86c8e956e1 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cons-list" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-02/src/main.rs b/listings/ch15-smart-pointers/listing-15-02/src/main.rs new file mode 100644 index 0000000000..84640b9b90 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-02/src/main.rs @@ -0,0 +1,8 @@ +// ANCHOR: here +enum List { + Cons(i32, List), + Nil, +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch15-smart-pointers/listing-15-03/Cargo.lock b/listings/ch15-smart-pointers/listing-15-03/Cargo.lock new file mode 100644 index 0000000000..a792c49aaf --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cons-list" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-03/Cargo.toml b/listings/ch15-smart-pointers/listing-15-03/Cargo.toml new file mode 100644 index 0000000000..86c8e956e1 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cons-list" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-03/output.txt b/listings/ch15-smart-pointers/listing-15-03/output.txt new file mode 100644 index 0000000000..f15aaacb9a --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-03/output.txt @@ -0,0 +1,28 @@ +$ cargo run + Compiling cons-list v0.1.0 (file:///projects/cons-list) +error[E0072]: recursive type `List` has infinite size + --> src/main.rs:1:1 + | +1 | enum List { + | ^^^^^^^^^ recursive type has infinite size +2 | Cons(i32, List), + | ---- recursive without indirection + | + = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `List` representable + +error[E0391]: cycle detected when processing `List` + --> src/main.rs:1:1 + | +1 | enum List { + | ^^^^^^^^^ + | + = note: ...which again requires processing `List`, completing the cycle + = note: cycle used when computing dropck types for `Canonical { max_universe: U0, variables: [], value: ParamEnvAnd { param_env: ParamEnv { caller_bounds: [], reveal: UserFacing, def_id: None }, value: List } }` + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0072, E0391. +For more information about an error, try `rustc --explain E0072`. +error: could not compile `cons-list`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch15-smart-pointers/listing-15-03/src/main.rs b/listings/ch15-smart-pointers/listing-15-03/src/main.rs new file mode 100644 index 0000000000..a96f3d7b18 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-03/src/main.rs @@ -0,0 +1,12 @@ +enum List { + Cons(i32, List), + Nil, +} + +// ANCHOR: here +use crate::List::{Cons, Nil}; + +fn main() { + let list = Cons(1, Cons(2, Cons(3, Nil))); +} +// ANCHOR_END: here diff --git a/listings/ch15-smart-pointers/listing-15-05/Cargo.lock b/listings/ch15-smart-pointers/listing-15-05/Cargo.lock new file mode 100644 index 0000000000..a792c49aaf --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cons-list" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-05/Cargo.toml b/listings/ch15-smart-pointers/listing-15-05/Cargo.toml new file mode 100644 index 0000000000..86c8e956e1 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cons-list" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-05/src/main.rs b/listings/ch15-smart-pointers/listing-15-05/src/main.rs new file mode 100644 index 0000000000..22f7d8338a --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-05/src/main.rs @@ -0,0 +1,10 @@ +enum List { + Cons(i32, Box), + Nil, +} + +use crate::List::{Cons, Nil}; + +fn main() { + let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil)))))); +} diff --git a/listings/ch15-smart-pointers/listing-15-06/Cargo.lock b/listings/ch15-smart-pointers/listing-15-06/Cargo.lock new file mode 100644 index 0000000000..4297c6733d --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "deref-example" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-06/Cargo.toml b/listings/ch15-smart-pointers/listing-15-06/Cargo.toml new file mode 100644 index 0000000000..2a9630fe4a --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "deref-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-06/src/main.rs b/listings/ch15-smart-pointers/listing-15-06/src/main.rs new file mode 100644 index 0000000000..174b620cf4 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-06/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + let x = 5; + let y = &x; + + assert_eq!(5, x); + assert_eq!(5, *y); +} diff --git a/listings/ch15-smart-pointers/listing-15-07/Cargo.lock b/listings/ch15-smart-pointers/listing-15-07/Cargo.lock new file mode 100644 index 0000000000..4297c6733d --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "deref-example" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-07/Cargo.toml b/listings/ch15-smart-pointers/listing-15-07/Cargo.toml new file mode 100644 index 0000000000..2a9630fe4a --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "deref-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-07/src/main.rs b/listings/ch15-smart-pointers/listing-15-07/src/main.rs new file mode 100644 index 0000000000..4933a416ba --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-07/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + let x = 5; + let y = Box::new(x); + + assert_eq!(5, x); + assert_eq!(5, *y); +} diff --git a/listings/ch15-smart-pointers/listing-15-08/Cargo.lock b/listings/ch15-smart-pointers/listing-15-08/Cargo.lock new file mode 100644 index 0000000000..4297c6733d --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "deref-example" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-08/Cargo.toml b/listings/ch15-smart-pointers/listing-15-08/Cargo.toml new file mode 100644 index 0000000000..2a9630fe4a --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "deref-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-08/src/main.rs b/listings/ch15-smart-pointers/listing-15-08/src/main.rs new file mode 100644 index 0000000000..f485946731 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-08/src/main.rs @@ -0,0 +1,11 @@ +// ANCHOR: here +struct MyBox(T); + +impl MyBox { + fn new(x: T) -> MyBox { + MyBox(x) + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch15-smart-pointers/listing-15-09/Cargo.lock b/listings/ch15-smart-pointers/listing-15-09/Cargo.lock new file mode 100644 index 0000000000..4297c6733d --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "deref-example" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-09/Cargo.toml b/listings/ch15-smart-pointers/listing-15-09/Cargo.toml new file mode 100644 index 0000000000..2a9630fe4a --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "deref-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-09/output.txt b/listings/ch15-smart-pointers/listing-15-09/output.txt new file mode 100644 index 0000000000..8fbd56124b --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-09/output.txt @@ -0,0 +1,14 @@ +$ cargo run + Compiling deref-example v0.1.0 (file:///projects/deref-example) +error[E0614]: type `MyBox<{integer}>` cannot be dereferenced + --> src/main.rs:14:19 + | +14 | assert_eq!(5, *y); + | ^^ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0614`. +error: could not compile `deref-example`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch15-smart-pointers/listing-15-09/src/main.rs b/listings/ch15-smart-pointers/listing-15-09/src/main.rs new file mode 100644 index 0000000000..d07f2d78a0 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-09/src/main.rs @@ -0,0 +1,17 @@ +struct MyBox(T); + +impl MyBox { + fn new(x: T) -> MyBox { + MyBox(x) + } +} + +// ANCHOR: here +fn main() { + let x = 5; + let y = MyBox::new(x); + + assert_eq!(5, x); + assert_eq!(5, *y); +} +// ANCHOR_END: here diff --git a/listings/ch15-smart-pointers/listing-15-10/Cargo.lock b/listings/ch15-smart-pointers/listing-15-10/Cargo.lock new file mode 100644 index 0000000000..4297c6733d --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "deref-example" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-10/Cargo.toml b/listings/ch15-smart-pointers/listing-15-10/Cargo.toml new file mode 100644 index 0000000000..2a9630fe4a --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "deref-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-10/src/main.rs b/listings/ch15-smart-pointers/listing-15-10/src/main.rs new file mode 100644 index 0000000000..a97f97c9b7 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-10/src/main.rs @@ -0,0 +1,27 @@ +// ANCHOR: here +use std::ops::Deref; + +impl Deref for MyBox { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} +// ANCHOR_END: here + +struct MyBox(T); + +impl MyBox { + fn new(x: T) -> MyBox { + MyBox(x) + } +} + +fn main() { + let x = 5; + let y = MyBox::new(x); + + assert_eq!(5, x); + assert_eq!(5, *y); +} diff --git a/listings/ch15-smart-pointers/listing-15-11/Cargo.lock b/listings/ch15-smart-pointers/listing-15-11/Cargo.lock new file mode 100644 index 0000000000..4297c6733d --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "deref-example" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-11/Cargo.toml b/listings/ch15-smart-pointers/listing-15-11/Cargo.toml new file mode 100644 index 0000000000..2a9630fe4a --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "deref-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-11/src/main.rs b/listings/ch15-smart-pointers/listing-15-11/src/main.rs new file mode 100644 index 0000000000..b73ad89c25 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-11/src/main.rs @@ -0,0 +1,7 @@ +// ANCHOR: here +fn hello(name: &str) { + println!("Hello, {}!", name); +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch15-smart-pointers/listing-15-12/Cargo.lock b/listings/ch15-smart-pointers/listing-15-12/Cargo.lock new file mode 100644 index 0000000000..4297c6733d --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "deref-example" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-12/Cargo.toml b/listings/ch15-smart-pointers/listing-15-12/Cargo.toml new file mode 100644 index 0000000000..2a9630fe4a --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "deref-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-12/src/main.rs b/listings/ch15-smart-pointers/listing-15-12/src/main.rs new file mode 100644 index 0000000000..6a3e143cc3 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-12/src/main.rs @@ -0,0 +1,28 @@ +use std::ops::Deref; + +impl Deref for MyBox { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +struct MyBox(T); + +impl MyBox { + fn new(x: T) -> MyBox { + MyBox(x) + } +} + +fn hello(name: &str) { + println!("Hello, {}!", name); +} + +// ANCHOR: here +fn main() { + let m = MyBox::new(String::from("Rust")); + hello(&m); +} +// ANCHOR_END: here diff --git a/listings/ch15-smart-pointers/listing-15-13/Cargo.lock b/listings/ch15-smart-pointers/listing-15-13/Cargo.lock new file mode 100644 index 0000000000..4297c6733d --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "deref-example" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-13/Cargo.toml b/listings/ch15-smart-pointers/listing-15-13/Cargo.toml new file mode 100644 index 0000000000..2a9630fe4a --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "deref-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-13/src/main.rs b/listings/ch15-smart-pointers/listing-15-13/src/main.rs new file mode 100644 index 0000000000..ef5361c120 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-13/src/main.rs @@ -0,0 +1,28 @@ +use std::ops::Deref; + +impl Deref for MyBox { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +struct MyBox(T); + +impl MyBox { + fn new(x: T) -> MyBox { + MyBox(x) + } +} + +fn hello(name: &str) { + println!("Hello, {}!", name); +} + +// ANCHOR: here +fn main() { + let m = MyBox::new(String::from("Rust")); + hello(&(*m)[..]); +} +// ANCHOR_END: here diff --git a/listings/ch15-smart-pointers/listing-15-14/Cargo.lock b/listings/ch15-smart-pointers/listing-15-14/Cargo.lock new file mode 100644 index 0000000000..eb8a2817ac --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "drop-example" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-14/Cargo.toml b/listings/ch15-smart-pointers/listing-15-14/Cargo.toml new file mode 100644 index 0000000000..e9ad457cf2 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "drop-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-14/output.txt b/listings/ch15-smart-pointers/listing-15-14/output.txt new file mode 100644 index 0000000000..4e795949a0 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-14/output.txt @@ -0,0 +1,7 @@ +$ cargo run + Compiling drop-example v0.1.0 (file:///projects/drop-example) + Finished dev [unoptimized + debuginfo] target(s) in 0.60s + Running `target/debug/drop-example` +CustomSmartPointers created. +Dropping CustomSmartPointer with data `other stuff`! +Dropping CustomSmartPointer with data `my stuff`! diff --git a/listings/ch15-smart-pointers/listing-15-14/src/main.rs b/listings/ch15-smart-pointers/listing-15-14/src/main.rs new file mode 100644 index 0000000000..231612ae62 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-14/src/main.rs @@ -0,0 +1,19 @@ +struct CustomSmartPointer { + data: String, +} + +impl Drop for CustomSmartPointer { + fn drop(&mut self) { + println!("Dropping CustomSmartPointer with data `{}`!", self.data); + } +} + +fn main() { + let c = CustomSmartPointer { + data: String::from("my stuff"), + }; + let d = CustomSmartPointer { + data: String::from("other stuff"), + }; + println!("CustomSmartPointers created."); +} diff --git a/listings/ch15-smart-pointers/listing-15-15/Cargo.lock b/listings/ch15-smart-pointers/listing-15-15/Cargo.lock new file mode 100644 index 0000000000..eb8a2817ac --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "drop-example" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-15/Cargo.toml b/listings/ch15-smart-pointers/listing-15-15/Cargo.toml new file mode 100644 index 0000000000..e9ad457cf2 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "drop-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-15/output.txt b/listings/ch15-smart-pointers/listing-15-15/output.txt new file mode 100644 index 0000000000..4af05876e1 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-15/output.txt @@ -0,0 +1,14 @@ +$ cargo run + Compiling drop-example v0.1.0 (file:///projects/drop-example) +error[E0040]: explicit use of destructor method + --> src/main.rs:16:7 + | +16 | c.drop(); + | ^^^^ explicit destructor calls not allowed + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0040`. +error: could not compile `drop-example`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch15-smart-pointers/listing-15-15/src/main.rs b/listings/ch15-smart-pointers/listing-15-15/src/main.rs new file mode 100644 index 0000000000..ff3b391a91 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-15/src/main.rs @@ -0,0 +1,20 @@ +struct CustomSmartPointer { + data: String, +} + +impl Drop for CustomSmartPointer { + fn drop(&mut self) { + println!("Dropping CustomSmartPointer with data `{}`!", self.data); + } +} + +// ANCHOR: here +fn main() { + let c = CustomSmartPointer { + data: String::from("some data"), + }; + println!("CustomSmartPointer created."); + c.drop(); + println!("CustomSmartPointer dropped before the end of main."); +} +// ANCHOR_END: here diff --git a/listings/ch15-smart-pointers/listing-15-16/Cargo.lock b/listings/ch15-smart-pointers/listing-15-16/Cargo.lock new file mode 100644 index 0000000000..eb8a2817ac --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "drop-example" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-16/Cargo.toml b/listings/ch15-smart-pointers/listing-15-16/Cargo.toml new file mode 100644 index 0000000000..e9ad457cf2 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "drop-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-16/output.txt b/listings/ch15-smart-pointers/listing-15-16/output.txt new file mode 100644 index 0000000000..e960cd89a2 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-16/output.txt @@ -0,0 +1,7 @@ +$ cargo run + Compiling drop-example v0.1.0 (file:///projects/drop-example) + Finished dev [unoptimized + debuginfo] target(s) in 0.73s + Running `target/debug/drop-example` +CustomSmartPointer created. +Dropping CustomSmartPointer with data `some data`! +CustomSmartPointer dropped before the end of main. diff --git a/listings/ch15-smart-pointers/listing-15-16/src/main.rs b/listings/ch15-smart-pointers/listing-15-16/src/main.rs new file mode 100644 index 0000000000..f11715c45e --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-16/src/main.rs @@ -0,0 +1,20 @@ +struct CustomSmartPointer { + data: String, +} + +impl Drop for CustomSmartPointer { + fn drop(&mut self) { + println!("Dropping CustomSmartPointer with data `{}`!", self.data); + } +} + +// ANCHOR: here +fn main() { + let c = CustomSmartPointer { + data: String::from("some data"), + }; + println!("CustomSmartPointer created."); + drop(c); + println!("CustomSmartPointer dropped before the end of main."); +} +// ANCHOR_END: here diff --git a/listings/ch15-smart-pointers/listing-15-17/Cargo.lock b/listings/ch15-smart-pointers/listing-15-17/Cargo.lock new file mode 100644 index 0000000000..a792c49aaf --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-17/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cons-list" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-17/Cargo.toml b/listings/ch15-smart-pointers/listing-15-17/Cargo.toml new file mode 100644 index 0000000000..86c8e956e1 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-17/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cons-list" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-17/output.txt b/listings/ch15-smart-pointers/listing-15-17/output.txt new file mode 100644 index 0000000000..5966a71ec2 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-17/output.txt @@ -0,0 +1,18 @@ +$ cargo run + Compiling cons-list v0.1.0 (file:///projects/cons-list) +error[E0382]: use of moved value: `a` + --> src/main.rs:11:30 + | +9 | let a = Cons(5, Box::new(Cons(10, Box::new(Nil)))); + | - move occurs because `a` has type `List`, which does not implement the `Copy` trait +10 | let b = Cons(3, Box::new(a)); + | - value moved here +11 | let c = Cons(4, Box::new(a)); + | ^ value used here after move + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0382`. +error: could not compile `cons-list`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch15-smart-pointers/listing-15-17/src/main.rs b/listings/ch15-smart-pointers/listing-15-17/src/main.rs new file mode 100644 index 0000000000..47c33e4c46 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-17/src/main.rs @@ -0,0 +1,12 @@ +enum List { + Cons(i32, Box), + Nil, +} + +use crate::List::{Cons, Nil}; + +fn main() { + let a = Cons(5, Box::new(Cons(10, Box::new(Nil)))); + let b = Cons(3, Box::new(a)); + let c = Cons(4, Box::new(a)); +} diff --git a/listings/ch15-smart-pointers/listing-15-18/Cargo.lock b/listings/ch15-smart-pointers/listing-15-18/Cargo.lock new file mode 100644 index 0000000000..a792c49aaf --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-18/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cons-list" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-18/Cargo.toml b/listings/ch15-smart-pointers/listing-15-18/Cargo.toml new file mode 100644 index 0000000000..86c8e956e1 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-18/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cons-list" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-18/src/main.rs b/listings/ch15-smart-pointers/listing-15-18/src/main.rs new file mode 100644 index 0000000000..602f7de40d --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-18/src/main.rs @@ -0,0 +1,13 @@ +enum List { + Cons(i32, Rc), + Nil, +} + +use crate::List::{Cons, Nil}; +use std::rc::Rc; + +fn main() { + let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); + let b = Cons(3, Rc::clone(&a)); + let c = Cons(4, Rc::clone(&a)); +} diff --git a/listings/ch15-smart-pointers/listing-15-19/Cargo.lock b/listings/ch15-smart-pointers/listing-15-19/Cargo.lock new file mode 100644 index 0000000000..a792c49aaf --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-19/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cons-list" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-19/Cargo.toml b/listings/ch15-smart-pointers/listing-15-19/Cargo.toml new file mode 100644 index 0000000000..86c8e956e1 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-19/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cons-list" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-19/output.txt b/listings/ch15-smart-pointers/listing-15-19/output.txt new file mode 100644 index 0000000000..6a8cc8efe1 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-19/output.txt @@ -0,0 +1,8 @@ +$ cargo run + Compiling cons-list v0.1.0 (file:///projects/cons-list) + Finished dev [unoptimized + debuginfo] target(s) in 0.45s + Running `target/debug/cons-list` +count after creating a = 1 +count after creating b = 2 +count after creating c = 3 +count after c goes out of scope = 2 diff --git a/listings/ch15-smart-pointers/listing-15-19/src/main.rs b/listings/ch15-smart-pointers/listing-15-19/src/main.rs new file mode 100644 index 0000000000..1bd7bc533a --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-19/src/main.rs @@ -0,0 +1,21 @@ +enum List { + Cons(i32, Rc), + Nil, +} + +use crate::List::{Cons, Nil}; +use std::rc::Rc; + +// ANCHOR: here +fn main() { + let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); + println!("count after creating a = {}", Rc::strong_count(&a)); + let b = Cons(3, Rc::clone(&a)); + println!("count after creating b = {}", Rc::strong_count(&a)); + { + let c = Cons(4, Rc::clone(&a)); + println!("count after creating c = {}", Rc::strong_count(&a)); + } + println!("count after c goes out of scope = {}", Rc::strong_count(&a)); +} +// ANCHOR_END: here diff --git a/listings/ch15-smart-pointers/listing-15-20/Cargo.lock b/listings/ch15-smart-pointers/listing-15-20/Cargo.lock new file mode 100644 index 0000000000..4dc2226a57 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-20/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "limit-tracker" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-20/Cargo.toml b/listings/ch15-smart-pointers/listing-15-20/Cargo.toml new file mode 100644 index 0000000000..b230a2326b --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-20/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "limit-tracker" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-20/src/lib.rs b/listings/ch15-smart-pointers/listing-15-20/src/lib.rs new file mode 100644 index 0000000000..d3a9003736 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-20/src/lib.rs @@ -0,0 +1,38 @@ +pub trait Messenger { + fn send(&self, msg: &str); +} + +pub struct LimitTracker<'a, T: Messenger> { + messenger: &'a T, + value: usize, + max: usize, +} + +impl<'a, T> LimitTracker<'a, T> +where + T: Messenger, +{ + pub fn new(messenger: &T, max: usize) -> LimitTracker { + LimitTracker { + messenger, + value: 0, + max, + } + } + + pub fn set_value(&mut self, value: usize) { + self.value = value; + + let percentage_of_max = self.value as f64 / self.max as f64; + + if percentage_of_max >= 1.0 { + self.messenger.send("Error: You are over your quota!"); + } else if percentage_of_max >= 0.9 { + self.messenger + .send("Urgent warning: You've used up over 90% of your quota!"); + } else if percentage_of_max >= 0.75 { + self.messenger + .send("Warning: You've used up over 75% of your quota!"); + } + } +} diff --git a/listings/ch15-smart-pointers/listing-15-21/Cargo.lock b/listings/ch15-smart-pointers/listing-15-21/Cargo.lock new file mode 100644 index 0000000000..4dc2226a57 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-21/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "limit-tracker" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-21/Cargo.toml b/listings/ch15-smart-pointers/listing-15-21/Cargo.toml new file mode 100644 index 0000000000..b230a2326b --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-21/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "limit-tracker" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-21/output.txt b/listings/ch15-smart-pointers/listing-15-21/output.txt new file mode 100644 index 0000000000..851b5caf98 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-21/output.txt @@ -0,0 +1,16 @@ +$ cargo test + Compiling limit-tracker v0.1.0 (file:///projects/limit-tracker) +error[E0596]: cannot borrow `self.sent_messages` as mutable, as it is behind a `&` reference + --> src/lib.rs:58:13 + | +57 | fn send(&self, message: &str) { + | ----- help: consider changing this to be a mutable reference: `&mut self` +58 | self.sent_messages.push(String::from(message)); + | ^^^^^^^^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0596`. +error: could not compile `limit-tracker`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch15-smart-pointers/listing-15-21/src/lib.rs b/listings/ch15-smart-pointers/listing-15-21/src/lib.rs new file mode 100644 index 0000000000..9e403e3ca8 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-21/src/lib.rs @@ -0,0 +1,73 @@ +pub trait Messenger { + fn send(&self, msg: &str); +} + +pub struct LimitTracker<'a, T: Messenger> { + messenger: &'a T, + value: usize, + max: usize, +} + +impl<'a, T> LimitTracker<'a, T> +where + T: Messenger, +{ + pub fn new(messenger: &T, max: usize) -> LimitTracker { + LimitTracker { + messenger, + value: 0, + max, + } + } + + pub fn set_value(&mut self, value: usize) { + self.value = value; + + let percentage_of_max = self.value as f64 / self.max as f64; + + if percentage_of_max >= 1.0 { + self.messenger.send("Error: You are over your quota!"); + } else if percentage_of_max >= 0.9 { + self.messenger + .send("Urgent warning: You've used up over 90% of your quota!"); + } else if percentage_of_max >= 0.75 { + self.messenger + .send("Warning: You've used up over 75% of your quota!"); + } + } +} + +// ANCHOR: here +#[cfg(test)] +mod tests { + use super::*; + + struct MockMessenger { + sent_messages: Vec, + } + + impl MockMessenger { + fn new() -> MockMessenger { + MockMessenger { + sent_messages: vec![], + } + } + } + + impl Messenger for MockMessenger { + fn send(&self, message: &str) { + self.sent_messages.push(String::from(message)); + } + } + + #[test] + fn it_sends_an_over_75_percent_warning_message() { + let mock_messenger = MockMessenger::new(); + let mut limit_tracker = LimitTracker::new(&mock_messenger, 100); + + limit_tracker.set_value(80); + + assert_eq!(mock_messenger.sent_messages.len(), 1); + } +} +// ANCHOR_END: here diff --git a/listings/ch15-smart-pointers/listing-15-22/Cargo.lock b/listings/ch15-smart-pointers/listing-15-22/Cargo.lock new file mode 100644 index 0000000000..4dc2226a57 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-22/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "limit-tracker" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-22/Cargo.toml b/listings/ch15-smart-pointers/listing-15-22/Cargo.toml new file mode 100644 index 0000000000..b230a2326b --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-22/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "limit-tracker" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-22/src/lib.rs b/listings/ch15-smart-pointers/listing-15-22/src/lib.rs new file mode 100644 index 0000000000..dc259f7fca --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-22/src/lib.rs @@ -0,0 +1,80 @@ +pub trait Messenger { + fn send(&self, msg: &str); +} + +pub struct LimitTracker<'a, T: Messenger> { + messenger: &'a T, + value: usize, + max: usize, +} + +impl<'a, T> LimitTracker<'a, T> +where + T: Messenger, +{ + pub fn new(messenger: &T, max: usize) -> LimitTracker { + LimitTracker { + messenger, + value: 0, + max, + } + } + + pub fn set_value(&mut self, value: usize) { + self.value = value; + + let percentage_of_max = self.value as f64 / self.max as f64; + + if percentage_of_max >= 1.0 { + self.messenger.send("Error: You are over your quota!"); + } else if percentage_of_max >= 0.9 { + self.messenger + .send("Urgent warning: You've used up over 90% of your quota!"); + } else if percentage_of_max >= 0.75 { + self.messenger + .send("Warning: You've used up over 75% of your quota!"); + } + } +} + +// ANCHOR: here +#[cfg(test)] +mod tests { + use super::*; + use std::cell::RefCell; + + struct MockMessenger { + sent_messages: RefCell>, + } + + impl MockMessenger { + fn new() -> MockMessenger { + MockMessenger { + sent_messages: RefCell::new(vec![]), + } + } + } + + impl Messenger for MockMessenger { + fn send(&self, message: &str) { + self.sent_messages.borrow_mut().push(String::from(message)); + } + } + + #[test] + fn it_sends_an_over_75_percent_warning_message() { + // --snip-- + // ANCHOR_END: here + let mock_messenger = MockMessenger::new(); + let mut limit_tracker = LimitTracker::new(&mock_messenger, 100); + + limit_tracker.set_value(80); + // ANCHOR: here + + // ANCHOR: here + assert_eq!(mock_messenger.sent_messages.borrow().len(), 1); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch15-smart-pointers/listing-15-23/Cargo.lock b/listings/ch15-smart-pointers/listing-15-23/Cargo.lock new file mode 100644 index 0000000000..4dc2226a57 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-23/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "limit-tracker" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-23/Cargo.toml b/listings/ch15-smart-pointers/listing-15-23/Cargo.toml new file mode 100644 index 0000000000..b230a2326b --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-23/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "limit-tracker" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-23/output.txt b/listings/ch15-smart-pointers/listing-15-23/output.txt new file mode 100644 index 0000000000..a60385bac1 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-23/output.txt @@ -0,0 +1,21 @@ +$ cargo test + Compiling limit-tracker v0.1.0 (file:///projects/limit-tracker) + Finished test [unoptimized + debuginfo] target(s) in 0.91s + Running target/debug/deps/limit_tracker-6c079de0866a6d36 + +running 1 test +test tests::it_sends_an_over_75_percent_warning_message ... FAILED + +failures: + +---- tests::it_sends_an_over_75_percent_warning_message stdout ---- +thread 'main' panicked at 'already borrowed: BorrowMutError', src/libcore/result.rs:1165:5 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. + + +failures: + tests::it_sends_an_over_75_percent_warning_message + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/listings/ch15-smart-pointers/listing-15-23/src/lib.rs b/listings/ch15-smart-pointers/listing-15-23/src/lib.rs new file mode 100644 index 0000000000..4e599ddc8c --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-23/src/lib.rs @@ -0,0 +1,78 @@ +pub trait Messenger { + fn send(&self, msg: &str); +} + +pub struct LimitTracker<'a, T: Messenger> { + messenger: &'a T, + value: usize, + max: usize, +} + +impl<'a, T> LimitTracker<'a, T> +where + T: Messenger, +{ + pub fn new(messenger: &T, max: usize) -> LimitTracker { + LimitTracker { + messenger, + value: 0, + max, + } + } + + pub fn set_value(&mut self, value: usize) { + self.value = value; + + let percentage_of_max = self.value as f64 / self.max as f64; + + if percentage_of_max >= 1.0 { + self.messenger.send("Error: You are over your quota!"); + } else if percentage_of_max >= 0.9 { + self.messenger + .send("Urgent warning: You've used up over 90% of your quota!"); + } else if percentage_of_max >= 0.75 { + self.messenger + .send("Warning: You've used up over 75% of your quota!"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::RefCell; + + struct MockMessenger { + sent_messages: RefCell>, + } + + impl MockMessenger { + fn new() -> MockMessenger { + MockMessenger { + sent_messages: RefCell::new(vec![]), + } + } + } + + // ANCHOR: here + impl Messenger for MockMessenger { + fn send(&self, message: &str) { + let mut one_borrow = self.sent_messages.borrow_mut(); + let mut two_borrow = self.sent_messages.borrow_mut(); + + one_borrow.push(String::from(message)); + two_borrow.push(String::from(message)); + } + } + // ANCHOR_END: here + + #[test] + fn it_sends_an_over_75_percent_warning_message() { + let mock_messenger = MockMessenger::new(); + let mut limit_tracker = LimitTracker::new(&mock_messenger, 100); + + limit_tracker.set_value(80); + + assert_eq!(mock_messenger.sent_messages.borrow().len(), 1); + } +} diff --git a/listings/ch15-smart-pointers/listing-15-24/Cargo.lock b/listings/ch15-smart-pointers/listing-15-24/Cargo.lock new file mode 100644 index 0000000000..a792c49aaf --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-24/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cons-list" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-24/Cargo.toml b/listings/ch15-smart-pointers/listing-15-24/Cargo.toml new file mode 100644 index 0000000000..86c8e956e1 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-24/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cons-list" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-24/output.txt b/listings/ch15-smart-pointers/listing-15-24/output.txt new file mode 100644 index 0000000000..bfe217bf41 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-24/output.txt @@ -0,0 +1,7 @@ +$ cargo run + Compiling cons-list v0.1.0 (file:///projects/cons-list) + Finished dev [unoptimized + debuginfo] target(s) in 0.63s + Running `target/debug/cons-list` +a after = Cons(RefCell { value: 15 }, Nil) +b after = Cons(RefCell { value: 6 }, Cons(RefCell { value: 15 }, Nil)) +c after = Cons(RefCell { value: 10 }, Cons(RefCell { value: 15 }, Nil)) diff --git a/listings/ch15-smart-pointers/listing-15-24/src/main.rs b/listings/ch15-smart-pointers/listing-15-24/src/main.rs new file mode 100644 index 0000000000..ac271fa21f --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-24/src/main.rs @@ -0,0 +1,24 @@ +#[derive(Debug)] +enum List { + Cons(Rc>, Rc), + Nil, +} + +use crate::List::{Cons, Nil}; +use std::cell::RefCell; +use std::rc::Rc; + +fn main() { + let value = Rc::new(RefCell::new(5)); + + let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil))); + + let b = Cons(Rc::new(RefCell::new(6)), Rc::clone(&a)); + let c = Cons(Rc::new(RefCell::new(10)), Rc::clone(&a)); + + *value.borrow_mut() += 10; + + println!("a after = {:?}", a); + println!("b after = {:?}", b); + println!("c after = {:?}", c); +} diff --git a/listings/ch15-smart-pointers/listing-15-25/Cargo.lock b/listings/ch15-smart-pointers/listing-15-25/Cargo.lock new file mode 100644 index 0000000000..a792c49aaf --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-25/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cons-list" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-25/Cargo.toml b/listings/ch15-smart-pointers/listing-15-25/Cargo.toml new file mode 100644 index 0000000000..86c8e956e1 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-25/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cons-list" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-25/src/main.rs b/listings/ch15-smart-pointers/listing-15-25/src/main.rs new file mode 100644 index 0000000000..f36c7fd06d --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-25/src/main.rs @@ -0,0 +1,20 @@ +use crate::List::{Cons, Nil}; +use std::cell::RefCell; +use std::rc::Rc; + +#[derive(Debug)] +enum List { + Cons(i32, RefCell>), + Nil, +} + +impl List { + fn tail(&self) -> Option<&RefCell>> { + match self { + Cons(_, item) => Some(item), + Nil => None, + } + } +} + +fn main() {} diff --git a/listings/ch15-smart-pointers/listing-15-26/Cargo.lock b/listings/ch15-smart-pointers/listing-15-26/Cargo.lock new file mode 100644 index 0000000000..a792c49aaf --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-26/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cons-list" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-26/Cargo.toml b/listings/ch15-smart-pointers/listing-15-26/Cargo.toml new file mode 100644 index 0000000000..86c8e956e1 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-26/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cons-list" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-26/output.txt b/listings/ch15-smart-pointers/listing-15-26/output.txt new file mode 100644 index 0000000000..8b8eb40b60 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-26/output.txt @@ -0,0 +1,11 @@ +$ cargo run + Compiling cons-list v0.1.0 (file:///projects/cons-list) + Finished dev [unoptimized + debuginfo] target(s) in 0.53s + Running `target/debug/cons-list` +a initial rc count = 1 +a next item = Some(RefCell { value: Nil }) +a rc count after b creation = 2 +b initial rc count = 1 +b next item = Some(RefCell { value: Cons(5, RefCell { value: Nil }) }) +b rc count after changing a = 2 +a rc count after changing a = 2 diff --git a/listings/ch15-smart-pointers/listing-15-26/src/main.rs b/listings/ch15-smart-pointers/listing-15-26/src/main.rs new file mode 100644 index 0000000000..08963aaa51 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-26/src/main.rs @@ -0,0 +1,44 @@ +use crate::List::{Cons, Nil}; +use std::cell::RefCell; +use std::rc::Rc; + +#[derive(Debug)] +enum List { + Cons(i32, RefCell>), + Nil, +} + +impl List { + fn tail(&self) -> Option<&RefCell>> { + match self { + Cons(_, item) => Some(item), + Nil => None, + } + } +} + +// ANCHOR: here +fn main() { + let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil)))); + + println!("a initial rc count = {}", Rc::strong_count(&a)); + println!("a next item = {:?}", a.tail()); + + let b = Rc::new(Cons(10, RefCell::new(Rc::clone(&a)))); + + println!("a rc count after b creation = {}", Rc::strong_count(&a)); + println!("b initial rc count = {}", Rc::strong_count(&b)); + println!("b next item = {:?}", b.tail()); + + if let Some(link) = a.tail() { + *link.borrow_mut() = Rc::clone(&b); + } + + println!("b rc count after changing a = {}", Rc::strong_count(&b)); + println!("a rc count after changing a = {}", Rc::strong_count(&a)); + + // Uncomment the next line to see that we have a cycle; + // it will overflow the stack + // println!("a next item = {:?}", a.tail()); +} +// ANCHOR_END: here diff --git a/listings/ch15-smart-pointers/listing-15-27/Cargo.lock b/listings/ch15-smart-pointers/listing-15-27/Cargo.lock new file mode 100644 index 0000000000..dd1f00a874 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-27/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "tree" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-27/Cargo.toml b/listings/ch15-smart-pointers/listing-15-27/Cargo.toml new file mode 100644 index 0000000000..d6774b817a --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-27/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "tree" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-27/src/main.rs b/listings/ch15-smart-pointers/listing-15-27/src/main.rs new file mode 100644 index 0000000000..335d154ddb --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-27/src/main.rs @@ -0,0 +1,24 @@ +// ANCHOR: here +use std::cell::RefCell; +use std::rc::Rc; + +#[derive(Debug)] +struct Node { + value: i32, + children: RefCell>>, +} +// ANCHOR_END: here + +// ANCHOR: there +fn main() { + let leaf = Rc::new(Node { + value: 3, + children: RefCell::new(vec![]), + }); + + let branch = Rc::new(Node { + value: 5, + children: RefCell::new(vec![Rc::clone(&leaf)]), + }); +} +// ANCHOR_END: there diff --git a/listings/ch15-smart-pointers/listing-15-28/Cargo.lock b/listings/ch15-smart-pointers/listing-15-28/Cargo.lock new file mode 100644 index 0000000000..dd1f00a874 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-28/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "tree" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-28/Cargo.toml b/listings/ch15-smart-pointers/listing-15-28/Cargo.toml new file mode 100644 index 0000000000..d6774b817a --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-28/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "tree" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-28/src/main.rs b/listings/ch15-smart-pointers/listing-15-28/src/main.rs new file mode 100644 index 0000000000..fabd1cbceb --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-28/src/main.rs @@ -0,0 +1,33 @@ +// ANCHOR: here +use std::cell::RefCell; +use std::rc::{Rc, Weak}; + +#[derive(Debug)] +struct Node { + value: i32, + parent: RefCell>, + children: RefCell>>, +} +// ANCHOR_END: here + +// ANCHOR: there +fn main() { + let leaf = Rc::new(Node { + value: 3, + parent: RefCell::new(Weak::new()), + children: RefCell::new(vec![]), + }); + + println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); + + let branch = Rc::new(Node { + value: 5, + parent: RefCell::new(Weak::new()), + children: RefCell::new(vec![Rc::clone(&leaf)]), + }); + + *leaf.parent.borrow_mut() = Rc::downgrade(&branch); + + println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); +} +// ANCHOR_END: there diff --git a/listings/ch15-smart-pointers/listing-15-29/Cargo.lock b/listings/ch15-smart-pointers/listing-15-29/Cargo.lock new file mode 100644 index 0000000000..dd1f00a874 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-29/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "tree" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/listing-15-29/Cargo.toml b/listings/ch15-smart-pointers/listing-15-29/Cargo.toml new file mode 100644 index 0000000000..d6774b817a --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-29/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "tree" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/listing-15-29/src/main.rs b/listings/ch15-smart-pointers/listing-15-29/src/main.rs new file mode 100644 index 0000000000..ea13df0eb4 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-29/src/main.rs @@ -0,0 +1,54 @@ +use std::cell::RefCell; +use std::rc::{Rc, Weak}; + +#[derive(Debug)] +struct Node { + value: i32, + parent: RefCell>, + children: RefCell>>, +} + +// ANCHOR: here +fn main() { + let leaf = Rc::new(Node { + value: 3, + parent: RefCell::new(Weak::new()), + children: RefCell::new(vec![]), + }); + + println!( + "leaf strong = {}, weak = {}", + Rc::strong_count(&leaf), + Rc::weak_count(&leaf), + ); + + { + let branch = Rc::new(Node { + value: 5, + parent: RefCell::new(Weak::new()), + children: RefCell::new(vec![Rc::clone(&leaf)]), + }); + + *leaf.parent.borrow_mut() = Rc::downgrade(&branch); + + println!( + "branch strong = {}, weak = {}", + Rc::strong_count(&branch), + Rc::weak_count(&branch), + ); + + println!( + "leaf strong = {}, weak = {}", + Rc::strong_count(&leaf), + Rc::weak_count(&leaf), + ); + } + + println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); + println!( + "leaf strong = {}, weak = {}", + Rc::strong_count(&leaf), + Rc::weak_count(&leaf), + ); +} +// ANCHOR_END: here diff --git a/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/Cargo.lock b/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/Cargo.lock new file mode 100644 index 0000000000..340f6604a2 --- /dev/null +++ b/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "borrowing" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/Cargo.toml b/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/Cargo.toml new file mode 100644 index 0000000000..1558eb615e --- /dev/null +++ b/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "borrowing" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/output.txt b/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/output.txt new file mode 100644 index 0000000000..c8e5592de7 --- /dev/null +++ b/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/output.txt @@ -0,0 +1,16 @@ +$ cargo run + Compiling borrowing v0.1.0 (file:///projects/borrowing) +error[E0596]: cannot borrow `x` as mutable, as it is not declared as mutable + --> src/main.rs:3:13 + | +2 | let x = 5; + | - help: consider changing this to be mutable: `mut x` +3 | let y = &mut x; + | ^^^^^^ cannot borrow as mutable + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0596`. +error: could not compile `borrowing`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/src/main.rs b/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/src/main.rs new file mode 100644 index 0000000000..8f48d41c15 --- /dev/null +++ b/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/src/main.rs @@ -0,0 +1,4 @@ +fn main() { + let x = 5; + let y = &mut x; +} diff --git a/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/Cargo.lock b/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/Cargo.lock new file mode 100644 index 0000000000..4297c6733d --- /dev/null +++ b/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "deref-example" +version = "0.1.0" + diff --git a/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/Cargo.toml b/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/Cargo.toml new file mode 100644 index 0000000000..2a9630fe4a --- /dev/null +++ b/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "deref-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/output.txt b/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/output.txt new file mode 100644 index 0000000000..4368ee65f6 --- /dev/null +++ b/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/output.txt @@ -0,0 +1,17 @@ +$ cargo run + Compiling deref-example v0.1.0 (file:///projects/deref-example) +error[E0277]: can't compare `{integer}` with `&{integer}` + --> src/main.rs:6:5 + | +6 | assert_eq!(5, y); + | ^^^^^^^^^^^^^^^^^ no implementation for `{integer} == &{integer}` + | + = help: the trait `std::cmp::PartialEq<&{integer}>` is not implemented for `{integer}` + = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info) + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. +error: could not compile `deref-example`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/src/main.rs b/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/src/main.rs new file mode 100644 index 0000000000..4e20cae0b8 --- /dev/null +++ b/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + let x = 5; + let y = &x; + + assert_eq!(5, x); + assert_eq!(5, y); +} diff --git a/listings/ch16-fearless-concurrency/listing-16-01/Cargo.lock b/listings/ch16-fearless-concurrency/listing-16-01/Cargo.lock new file mode 100644 index 0000000000..8ecc3ae17e --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "threads" +version = "0.1.0" + diff --git a/listings/ch16-fearless-concurrency/listing-16-01/Cargo.toml b/listings/ch16-fearless-concurrency/listing-16-01/Cargo.toml new file mode 100644 index 0000000000..68a31e10b3 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "threads" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch16-fearless-concurrency/listing-16-01/src/main.rs b/listings/ch16-fearless-concurrency/listing-16-01/src/main.rs new file mode 100644 index 0000000000..6305a98e3d --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-01/src/main.rs @@ -0,0 +1,16 @@ +use std::thread; +use std::time::Duration; + +fn main() { + thread::spawn(|| { + for i in 1..10 { + println!("hi number {} from the spawned thread!", i); + thread::sleep(Duration::from_millis(1)); + } + }); + + for i in 1..5 { + println!("hi number {} from the main thread!", i); + thread::sleep(Duration::from_millis(1)); + } +} diff --git a/listings/ch16-fearless-concurrency/listing-16-02/Cargo.lock b/listings/ch16-fearless-concurrency/listing-16-02/Cargo.lock new file mode 100644 index 0000000000..8ecc3ae17e --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "threads" +version = "0.1.0" + diff --git a/listings/ch16-fearless-concurrency/listing-16-02/Cargo.toml b/listings/ch16-fearless-concurrency/listing-16-02/Cargo.toml new file mode 100644 index 0000000000..68a31e10b3 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "threads" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch16-fearless-concurrency/listing-16-02/src/main.rs b/listings/ch16-fearless-concurrency/listing-16-02/src/main.rs new file mode 100644 index 0000000000..e37607f1d6 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-02/src/main.rs @@ -0,0 +1,18 @@ +use std::thread; +use std::time::Duration; + +fn main() { + let handle = thread::spawn(|| { + for i in 1..10 { + println!("hi number {} from the spawned thread!", i); + thread::sleep(Duration::from_millis(1)); + } + }); + + for i in 1..5 { + println!("hi number {} from the main thread!", i); + thread::sleep(Duration::from_millis(1)); + } + + handle.join().unwrap(); +} diff --git a/listings/ch16-fearless-concurrency/listing-16-03/Cargo.lock b/listings/ch16-fearless-concurrency/listing-16-03/Cargo.lock new file mode 100644 index 0000000000..8ecc3ae17e --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "threads" +version = "0.1.0" + diff --git a/listings/ch16-fearless-concurrency/listing-16-03/Cargo.toml b/listings/ch16-fearless-concurrency/listing-16-03/Cargo.toml new file mode 100644 index 0000000000..68a31e10b3 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "threads" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch16-fearless-concurrency/listing-16-03/output.txt b/listings/ch16-fearless-concurrency/listing-16-03/output.txt new file mode 100644 index 0000000000..1dd4deeb2e --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-03/output.txt @@ -0,0 +1,29 @@ +$ cargo run + Compiling threads v0.1.0 (file:///projects/threads) +error[E0373]: closure may outlive the current function, but it borrows `v`, which is owned by the current function + --> src/main.rs:6:32 + | +6 | let handle = thread::spawn(|| { + | ^^ may outlive borrowed value `v` +7 | println!("Here's a vector: {:?}", v); + | - `v` is borrowed here + | +note: function requires argument type to outlive `'static` + --> src/main.rs:6:18 + | +6 | let handle = thread::spawn(|| { + | __________________^ +7 | | println!("Here's a vector: {:?}", v); +8 | | }); + | |______^ +help: to force the closure to take ownership of `v` (and any other referenced variables), use the `move` keyword + | +6 | let handle = thread::spawn(move || { + | ^^^^^^^ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0373`. +error: could not compile `threads`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch16-fearless-concurrency/listing-16-03/src/main.rs b/listings/ch16-fearless-concurrency/listing-16-03/src/main.rs new file mode 100644 index 0000000000..defc876482 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-03/src/main.rs @@ -0,0 +1,11 @@ +use std::thread; + +fn main() { + let v = vec![1, 2, 3]; + + let handle = thread::spawn(|| { + println!("Here's a vector: {:?}", v); + }); + + handle.join().unwrap(); +} diff --git a/listings/ch16-fearless-concurrency/listing-16-04/Cargo.lock b/listings/ch16-fearless-concurrency/listing-16-04/Cargo.lock new file mode 100644 index 0000000000..8ecc3ae17e --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "threads" +version = "0.1.0" + diff --git a/listings/ch16-fearless-concurrency/listing-16-04/Cargo.toml b/listings/ch16-fearless-concurrency/listing-16-04/Cargo.toml new file mode 100644 index 0000000000..68a31e10b3 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "threads" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch16-fearless-concurrency/listing-16-04/src/main.rs b/listings/ch16-fearless-concurrency/listing-16-04/src/main.rs new file mode 100644 index 0000000000..0bccc5f56f --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-04/src/main.rs @@ -0,0 +1,13 @@ +use std::thread; + +fn main() { + let v = vec![1, 2, 3]; + + let handle = thread::spawn(|| { + println!("Here's a vector: {:?}", v); + }); + + drop(v); // oh no! + + handle.join().unwrap(); +} diff --git a/listings/ch16-fearless-concurrency/listing-16-05/Cargo.lock b/listings/ch16-fearless-concurrency/listing-16-05/Cargo.lock new file mode 100644 index 0000000000..8ecc3ae17e --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "threads" +version = "0.1.0" + diff --git a/listings/ch16-fearless-concurrency/listing-16-05/Cargo.toml b/listings/ch16-fearless-concurrency/listing-16-05/Cargo.toml new file mode 100644 index 0000000000..68a31e10b3 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "threads" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch16-fearless-concurrency/listing-16-05/src/main.rs b/listings/ch16-fearless-concurrency/listing-16-05/src/main.rs new file mode 100644 index 0000000000..a6547dc4c1 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-05/src/main.rs @@ -0,0 +1,11 @@ +use std::thread; + +fn main() { + let v = vec![1, 2, 3]; + + let handle = thread::spawn(move || { + println!("Here's a vector: {:?}", v); + }); + + handle.join().unwrap(); +} diff --git a/listings/ch16-fearless-concurrency/listing-16-06/Cargo.lock b/listings/ch16-fearless-concurrency/listing-16-06/Cargo.lock new file mode 100644 index 0000000000..55d2252da5 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "message-passing" +version = "0.1.0" + diff --git a/listings/ch16-fearless-concurrency/listing-16-06/Cargo.toml b/listings/ch16-fearless-concurrency/listing-16-06/Cargo.toml new file mode 100644 index 0000000000..8fd8808ea5 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "message-passing" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch16-fearless-concurrency/listing-16-06/src/main.rs b/listings/ch16-fearless-concurrency/listing-16-06/src/main.rs new file mode 100644 index 0000000000..d80dac4a0a --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-06/src/main.rs @@ -0,0 +1,5 @@ +use std::sync::mpsc; + +fn main() { + let (tx, rx) = mpsc::channel(); +} diff --git a/listings/ch16-fearless-concurrency/listing-16-07/Cargo.lock b/listings/ch16-fearless-concurrency/listing-16-07/Cargo.lock new file mode 100644 index 0000000000..55d2252da5 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "message-passing" +version = "0.1.0" + diff --git a/listings/ch16-fearless-concurrency/listing-16-07/Cargo.toml b/listings/ch16-fearless-concurrency/listing-16-07/Cargo.toml new file mode 100644 index 0000000000..8fd8808ea5 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "message-passing" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch16-fearless-concurrency/listing-16-07/src/main.rs b/listings/ch16-fearless-concurrency/listing-16-07/src/main.rs new file mode 100644 index 0000000000..7859b64dae --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-07/src/main.rs @@ -0,0 +1,11 @@ +use std::sync::mpsc; +use std::thread; + +fn main() { + let (tx, rx) = mpsc::channel(); + + thread::spawn(move || { + let val = String::from("hi"); + tx.send(val).unwrap(); + }); +} diff --git a/listings/ch16-fearless-concurrency/listing-16-08/Cargo.lock b/listings/ch16-fearless-concurrency/listing-16-08/Cargo.lock new file mode 100644 index 0000000000..55d2252da5 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "message-passing" +version = "0.1.0" + diff --git a/listings/ch16-fearless-concurrency/listing-16-08/Cargo.toml b/listings/ch16-fearless-concurrency/listing-16-08/Cargo.toml new file mode 100644 index 0000000000..8fd8808ea5 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "message-passing" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch16-fearless-concurrency/listing-16-08/src/main.rs b/listings/ch16-fearless-concurrency/listing-16-08/src/main.rs new file mode 100644 index 0000000000..fbba9167d4 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-08/src/main.rs @@ -0,0 +1,14 @@ +use std::sync::mpsc; +use std::thread; + +fn main() { + let (tx, rx) = mpsc::channel(); + + thread::spawn(move || { + let val = String::from("hi"); + tx.send(val).unwrap(); + }); + + let received = rx.recv().unwrap(); + println!("Got: {}", received); +} diff --git a/listings/ch16-fearless-concurrency/listing-16-09/Cargo.lock b/listings/ch16-fearless-concurrency/listing-16-09/Cargo.lock new file mode 100644 index 0000000000..55d2252da5 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "message-passing" +version = "0.1.0" + diff --git a/listings/ch16-fearless-concurrency/listing-16-09/Cargo.toml b/listings/ch16-fearless-concurrency/listing-16-09/Cargo.toml new file mode 100644 index 0000000000..8fd8808ea5 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "message-passing" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch16-fearless-concurrency/listing-16-09/output.txt b/listings/ch16-fearless-concurrency/listing-16-09/output.txt new file mode 100644 index 0000000000..11bfc6fe32 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-09/output.txt @@ -0,0 +1,18 @@ +$ cargo run + Compiling message-passing v0.1.0 (file:///projects/message-passing) +error[E0382]: borrow of moved value: `val` + --> src/main.rs:10:31 + | +8 | let val = String::from("hi"); + | --- move occurs because `val` has type `std::string::String`, which does not implement the `Copy` trait +9 | tx.send(val).unwrap(); + | --- value moved here +10 | println!("val is {}", val); + | ^^^ value borrowed here after move + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0382`. +error: could not compile `message-passing`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch16-fearless-concurrency/listing-16-09/src/main.rs b/listings/ch16-fearless-concurrency/listing-16-09/src/main.rs new file mode 100644 index 0000000000..98a8129ab3 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-09/src/main.rs @@ -0,0 +1,15 @@ +use std::sync::mpsc; +use std::thread; + +fn main() { + let (tx, rx) = mpsc::channel(); + + thread::spawn(move || { + let val = String::from("hi"); + tx.send(val).unwrap(); + println!("val is {}", val); + }); + + let received = rx.recv().unwrap(); + println!("Got: {}", received); +} diff --git a/listings/ch16-fearless-concurrency/listing-16-10/Cargo.lock b/listings/ch16-fearless-concurrency/listing-16-10/Cargo.lock new file mode 100644 index 0000000000..55d2252da5 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "message-passing" +version = "0.1.0" + diff --git a/listings/ch16-fearless-concurrency/listing-16-10/Cargo.toml b/listings/ch16-fearless-concurrency/listing-16-10/Cargo.toml new file mode 100644 index 0000000000..8fd8808ea5 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "message-passing" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch16-fearless-concurrency/listing-16-10/src/main.rs b/listings/ch16-fearless-concurrency/listing-16-10/src/main.rs new file mode 100644 index 0000000000..82b220de45 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-10/src/main.rs @@ -0,0 +1,25 @@ +use std::sync::mpsc; +use std::thread; +use std::time::Duration; + +fn main() { + let (tx, rx) = mpsc::channel(); + + thread::spawn(move || { + let vals = vec![ + String::from("hi"), + String::from("from"), + String::from("the"), + String::from("thread"), + ]; + + for val in vals { + tx.send(val).unwrap(); + thread::sleep(Duration::from_secs(1)); + } + }); + + for received in rx { + println!("Got: {}", received); + } +} diff --git a/listings/ch16-fearless-concurrency/listing-16-11/Cargo.lock b/listings/ch16-fearless-concurrency/listing-16-11/Cargo.lock new file mode 100644 index 0000000000..55d2252da5 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "message-passing" +version = "0.1.0" + diff --git a/listings/ch16-fearless-concurrency/listing-16-11/Cargo.toml b/listings/ch16-fearless-concurrency/listing-16-11/Cargo.toml new file mode 100644 index 0000000000..8fd8808ea5 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "message-passing" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch16-fearless-concurrency/listing-16-11/src/main.rs b/listings/ch16-fearless-concurrency/listing-16-11/src/main.rs new file mode 100644 index 0000000000..f0acf4c2d2 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-11/src/main.rs @@ -0,0 +1,46 @@ +use std::sync::mpsc; +use std::thread; +use std::time::Duration; + +fn main() { + // ANCHOR: here + // --snip-- + + let (tx, rx) = mpsc::channel(); + + let tx1 = mpsc::Sender::clone(&tx); + thread::spawn(move || { + let vals = vec![ + String::from("hi"), + String::from("from"), + String::from("the"), + String::from("thread"), + ]; + + for val in vals { + tx1.send(val).unwrap(); + thread::sleep(Duration::from_secs(1)); + } + }); + + thread::spawn(move || { + let vals = vec![ + String::from("more"), + String::from("messages"), + String::from("for"), + String::from("you"), + ]; + + for val in vals { + tx.send(val).unwrap(); + thread::sleep(Duration::from_secs(1)); + } + }); + + for received in rx { + println!("Got: {}", received); + } + + // --snip-- + // ANCHOR_END: here +} diff --git a/listings/ch16-fearless-concurrency/listing-16-12/Cargo.lock b/listings/ch16-fearless-concurrency/listing-16-12/Cargo.lock new file mode 100644 index 0000000000..8e7ba9cf5d --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "shared-state" +version = "0.1.0" + diff --git a/listings/ch16-fearless-concurrency/listing-16-12/Cargo.toml b/listings/ch16-fearless-concurrency/listing-16-12/Cargo.toml new file mode 100644 index 0000000000..e7c75ac918 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "shared-state" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch16-fearless-concurrency/listing-16-12/src/main.rs b/listings/ch16-fearless-concurrency/listing-16-12/src/main.rs new file mode 100644 index 0000000000..0c0d6767ad --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-12/src/main.rs @@ -0,0 +1,12 @@ +use std::sync::Mutex; + +fn main() { + let m = Mutex::new(5); + + { + let mut num = m.lock().unwrap(); + *num = 6; + } + + println!("m = {:?}", m); +} diff --git a/listings/ch16-fearless-concurrency/listing-16-13/Cargo.lock b/listings/ch16-fearless-concurrency/listing-16-13/Cargo.lock new file mode 100644 index 0000000000..8e7ba9cf5d --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "shared-state" +version = "0.1.0" + diff --git a/listings/ch16-fearless-concurrency/listing-16-13/Cargo.toml b/listings/ch16-fearless-concurrency/listing-16-13/Cargo.toml new file mode 100644 index 0000000000..e7c75ac918 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "shared-state" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch16-fearless-concurrency/listing-16-13/output.txt b/listings/ch16-fearless-concurrency/listing-16-13/output.txt new file mode 100644 index 0000000000..7369ec41b5 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-13/output.txt @@ -0,0 +1,19 @@ +$ cargo run + Compiling shared-state v0.1.0 (file:///projects/shared-state) +error[E0382]: use of moved value: `counter` + --> src/main.rs:9:36 + | +5 | let counter = Mutex::new(0); + | ------- move occurs because `counter` has type `std::sync::Mutex`, which does not implement the `Copy` trait +... +9 | let handle = thread::spawn(move || { + | ^^^^^^^ value moved into closure here, in previous iteration of loop +10 | let mut num = counter.lock().unwrap(); + | ------- use occurs due to use in closure + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0382`. +error: could not compile `shared-state`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch16-fearless-concurrency/listing-16-13/src/main.rs b/listings/ch16-fearless-concurrency/listing-16-13/src/main.rs new file mode 100644 index 0000000000..4e380a59ac --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-13/src/main.rs @@ -0,0 +1,22 @@ +use std::sync::Mutex; +use std::thread; + +fn main() { + let counter = Mutex::new(0); + let mut handles = vec![]; + + for _ in 0..10 { + let handle = thread::spawn(move || { + let mut num = counter.lock().unwrap(); + + *num += 1; + }); + handles.push(handle); + } + + for handle in handles { + handle.join().unwrap(); + } + + println!("Result: {}", *counter.lock().unwrap()); +} diff --git a/listings/ch16-fearless-concurrency/listing-16-14/Cargo.lock b/listings/ch16-fearless-concurrency/listing-16-14/Cargo.lock new file mode 100644 index 0000000000..8e7ba9cf5d --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "shared-state" +version = "0.1.0" + diff --git a/listings/ch16-fearless-concurrency/listing-16-14/Cargo.toml b/listings/ch16-fearless-concurrency/listing-16-14/Cargo.toml new file mode 100644 index 0000000000..e7c75ac918 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "shared-state" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch16-fearless-concurrency/listing-16-14/output.txt b/listings/ch16-fearless-concurrency/listing-16-14/output.txt new file mode 100644 index 0000000000..200c55e220 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-14/output.txt @@ -0,0 +1,17 @@ +$ cargo run + Compiling shared-state v0.1.0 (file:///projects/shared-state) +error[E0277]: `std::rc::Rc>` cannot be sent between threads safely + --> src/main.rs:11:22 + | +11 | let handle = thread::spawn(move || { + | ^^^^^^^^^^^^^ `std::rc::Rc>` cannot be sent between threads safely + | + = help: within `[closure@src/main.rs:11:36: 15:10 counter:std::rc::Rc>]`, the trait `std::marker::Send` is not implemented for `std::rc::Rc>` + = note: required because it appears within the type `[closure@src/main.rs:11:36: 15:10 counter:std::rc::Rc>]` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. +error: could not compile `shared-state`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch16-fearless-concurrency/listing-16-14/src/main.rs b/listings/ch16-fearless-concurrency/listing-16-14/src/main.rs new file mode 100644 index 0000000000..d940b1a344 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-14/src/main.rs @@ -0,0 +1,24 @@ +use std::rc::Rc; +use std::sync::Mutex; +use std::thread; + +fn main() { + let counter = Rc::new(Mutex::new(0)); + let mut handles = vec![]; + + for _ in 0..10 { + let counter = Rc::clone(&counter); + let handle = thread::spawn(move || { + let mut num = counter.lock().unwrap(); + + *num += 1; + }); + handles.push(handle); + } + + for handle in handles { + handle.join().unwrap(); + } + + println!("Result: {}", *counter.lock().unwrap()); +} diff --git a/listings/ch16-fearless-concurrency/listing-16-15/Cargo.lock b/listings/ch16-fearless-concurrency/listing-16-15/Cargo.lock new file mode 100644 index 0000000000..8e7ba9cf5d --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "shared-state" +version = "0.1.0" + diff --git a/listings/ch16-fearless-concurrency/listing-16-15/Cargo.toml b/listings/ch16-fearless-concurrency/listing-16-15/Cargo.toml new file mode 100644 index 0000000000..e7c75ac918 --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "shared-state" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch16-fearless-concurrency/listing-16-15/src/main.rs b/listings/ch16-fearless-concurrency/listing-16-15/src/main.rs new file mode 100644 index 0000000000..30247dd52f --- /dev/null +++ b/listings/ch16-fearless-concurrency/listing-16-15/src/main.rs @@ -0,0 +1,23 @@ +use std::sync::{Arc, Mutex}; +use std::thread; + +fn main() { + let counter = Arc::new(Mutex::new(0)); + let mut handles = vec![]; + + for _ in 0..10 { + let counter = Arc::clone(&counter); + let handle = thread::spawn(move || { + let mut num = counter.lock().unwrap(); + + *num += 1; + }); + handles.push(handle); + } + + for handle in handles { + handle.join().unwrap(); + } + + println!("Result: {}", *counter.lock().unwrap()); +} diff --git a/listings/ch16-fearless-concurrency/no-listing-01-join-too-early/Cargo.lock b/listings/ch16-fearless-concurrency/no-listing-01-join-too-early/Cargo.lock new file mode 100644 index 0000000000..8ecc3ae17e --- /dev/null +++ b/listings/ch16-fearless-concurrency/no-listing-01-join-too-early/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "threads" +version = "0.1.0" + diff --git a/listings/ch16-fearless-concurrency/no-listing-01-join-too-early/Cargo.toml b/listings/ch16-fearless-concurrency/no-listing-01-join-too-early/Cargo.toml new file mode 100644 index 0000000000..68a31e10b3 --- /dev/null +++ b/listings/ch16-fearless-concurrency/no-listing-01-join-too-early/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "threads" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch16-fearless-concurrency/no-listing-01-join-too-early/src/main.rs b/listings/ch16-fearless-concurrency/no-listing-01-join-too-early/src/main.rs new file mode 100644 index 0000000000..6205e57d33 --- /dev/null +++ b/listings/ch16-fearless-concurrency/no-listing-01-join-too-early/src/main.rs @@ -0,0 +1,18 @@ +use std::thread; +use std::time::Duration; + +fn main() { + let handle = thread::spawn(|| { + for i in 1..10 { + println!("hi number {} from the spawned thread!", i); + thread::sleep(Duration::from_millis(1)); + } + }); + + handle.join().unwrap(); + + for i in 1..5 { + println!("hi number {} from the main thread!", i); + thread::sleep(Duration::from_millis(1)); + } +} diff --git a/listings/ch16-fearless-concurrency/no-listing-02-no-loop-to-understand-error/Cargo.lock b/listings/ch16-fearless-concurrency/no-listing-02-no-loop-to-understand-error/Cargo.lock new file mode 100644 index 0000000000..8e7ba9cf5d --- /dev/null +++ b/listings/ch16-fearless-concurrency/no-listing-02-no-loop-to-understand-error/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "shared-state" +version = "0.1.0" + diff --git a/listings/ch16-fearless-concurrency/no-listing-02-no-loop-to-understand-error/Cargo.toml b/listings/ch16-fearless-concurrency/no-listing-02-no-loop-to-understand-error/Cargo.toml new file mode 100644 index 0000000000..e7c75ac918 --- /dev/null +++ b/listings/ch16-fearless-concurrency/no-listing-02-no-loop-to-understand-error/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "shared-state" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch16-fearless-concurrency/no-listing-02-no-loop-to-understand-error/src/main.rs b/listings/ch16-fearless-concurrency/no-listing-02-no-loop-to-understand-error/src/main.rs new file mode 100644 index 0000000000..dbb1397719 --- /dev/null +++ b/listings/ch16-fearless-concurrency/no-listing-02-no-loop-to-understand-error/src/main.rs @@ -0,0 +1,27 @@ +use std::sync::Mutex; +use std::thread; + +fn main() { + let counter = Mutex::new(0); + let mut handles = vec![]; + + let handle = thread::spawn(move || { + let mut num = counter.lock().unwrap(); + + *num += 1; + }); + handles.push(handle); + + let handle2 = thread::spawn(move || { + let mut num2 = counter.lock().unwrap(); + + *num2 += 1; + }); + handles.push(handle2); + + for handle in handles { + handle.join().unwrap(); + } + + println!("Result: {}", *counter.lock().unwrap()); +} diff --git a/listings/ch16-fearless-concurrency/output-only-01-move-drop/Cargo.lock b/listings/ch16-fearless-concurrency/output-only-01-move-drop/Cargo.lock new file mode 100644 index 0000000000..8ecc3ae17e --- /dev/null +++ b/listings/ch16-fearless-concurrency/output-only-01-move-drop/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "threads" +version = "0.1.0" + diff --git a/listings/ch16-fearless-concurrency/output-only-01-move-drop/Cargo.toml b/listings/ch16-fearless-concurrency/output-only-01-move-drop/Cargo.toml new file mode 100644 index 0000000000..68a31e10b3 --- /dev/null +++ b/listings/ch16-fearless-concurrency/output-only-01-move-drop/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "threads" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch16-fearless-concurrency/output-only-01-move-drop/output.txt b/listings/ch16-fearless-concurrency/output-only-01-move-drop/output.txt new file mode 100644 index 0000000000..2d1cb3c8b7 --- /dev/null +++ b/listings/ch16-fearless-concurrency/output-only-01-move-drop/output.txt @@ -0,0 +1,22 @@ +$ cargo run + Compiling threads v0.1.0 (file:///projects/threads) +error[E0382]: use of moved value: `v` + --> src/main.rs:10:10 + | +4 | let v = vec![1, 2, 3]; + | - move occurs because `v` has type `std::vec::Vec`, which does not implement the `Copy` trait +5 | +6 | let handle = thread::spawn(move || { + | ------- value moved into closure here +7 | println!("Here's a vector: {:?}", v); + | - variable moved due to use in closure +... +10 | drop(v); // oh no! + | ^ value used here after move + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0382`. +error: could not compile `threads`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch16-fearless-concurrency/output-only-01-move-drop/src/main.rs b/listings/ch16-fearless-concurrency/output-only-01-move-drop/src/main.rs new file mode 100644 index 0000000000..70f659c5f6 --- /dev/null +++ b/listings/ch16-fearless-concurrency/output-only-01-move-drop/src/main.rs @@ -0,0 +1,13 @@ +use std::thread; + +fn main() { + let v = vec![1, 2, 3]; + + let handle = thread::spawn(move || { + println!("Here's a vector: {:?}", v); + }); + + drop(v); // oh no! + + handle.join().unwrap(); +} diff --git a/listings/ch17-oop/listing-17-01/Cargo.lock b/listings/ch17-oop/listing-17-01/Cargo.lock new file mode 100644 index 0000000000..471d8dfc3c --- /dev/null +++ b/listings/ch17-oop/listing-17-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "averaged-collection" +version = "0.1.0" + diff --git a/listings/ch17-oop/listing-17-01/Cargo.toml b/listings/ch17-oop/listing-17-01/Cargo.toml new file mode 100644 index 0000000000..ab96488d1e --- /dev/null +++ b/listings/ch17-oop/listing-17-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "averaged-collection" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/listing-17-01/src/lib.rs b/listings/ch17-oop/listing-17-01/src/lib.rs new file mode 100644 index 0000000000..b5ce2ab642 --- /dev/null +++ b/listings/ch17-oop/listing-17-01/src/lib.rs @@ -0,0 +1,4 @@ +pub struct AveragedCollection { + list: Vec, + average: f64, +} diff --git a/listings/ch17-oop/listing-17-02/Cargo.lock b/listings/ch17-oop/listing-17-02/Cargo.lock new file mode 100644 index 0000000000..471d8dfc3c --- /dev/null +++ b/listings/ch17-oop/listing-17-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "averaged-collection" +version = "0.1.0" + diff --git a/listings/ch17-oop/listing-17-02/Cargo.toml b/listings/ch17-oop/listing-17-02/Cargo.toml new file mode 100644 index 0000000000..ab96488d1e --- /dev/null +++ b/listings/ch17-oop/listing-17-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "averaged-collection" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/listing-17-02/src/lib.rs b/listings/ch17-oop/listing-17-02/src/lib.rs new file mode 100644 index 0000000000..bb407ec5fe --- /dev/null +++ b/listings/ch17-oop/listing-17-02/src/lib.rs @@ -0,0 +1,33 @@ +pub struct AveragedCollection { + list: Vec, + average: f64, +} + +// ANCHOR: here +impl AveragedCollection { + pub fn add(&mut self, value: i32) { + self.list.push(value); + self.update_average(); + } + + pub fn remove(&mut self) -> Option { + let result = self.list.pop(); + match result { + Some(value) => { + self.update_average(); + Some(value) + } + None => None, + } + } + + pub fn average(&self) -> f64 { + self.average + } + + fn update_average(&mut self) { + let total: i32 = self.list.iter().sum(); + self.average = total as f64 / self.list.len() as f64; + } +} +// ANCHOR_END: here diff --git a/listings/ch17-oop/listing-17-03/Cargo.lock b/listings/ch17-oop/listing-17-03/Cargo.lock new file mode 100644 index 0000000000..00d7b21826 --- /dev/null +++ b/listings/ch17-oop/listing-17-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "gui" +version = "0.1.0" + diff --git a/listings/ch17-oop/listing-17-03/Cargo.toml b/listings/ch17-oop/listing-17-03/Cargo.toml new file mode 100644 index 0000000000..1f61cd20ec --- /dev/null +++ b/listings/ch17-oop/listing-17-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "gui" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/listing-17-03/src/lib.rs b/listings/ch17-oop/listing-17-03/src/lib.rs new file mode 100644 index 0000000000..3a5cb779c4 --- /dev/null +++ b/listings/ch17-oop/listing-17-03/src/lib.rs @@ -0,0 +1,3 @@ +pub trait Draw { + fn draw(&self); +} diff --git a/listings/ch17-oop/listing-17-04/Cargo.lock b/listings/ch17-oop/listing-17-04/Cargo.lock new file mode 100644 index 0000000000..00d7b21826 --- /dev/null +++ b/listings/ch17-oop/listing-17-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "gui" +version = "0.1.0" + diff --git a/listings/ch17-oop/listing-17-04/Cargo.toml b/listings/ch17-oop/listing-17-04/Cargo.toml new file mode 100644 index 0000000000..1f61cd20ec --- /dev/null +++ b/listings/ch17-oop/listing-17-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "gui" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/listing-17-04/src/lib.rs b/listings/ch17-oop/listing-17-04/src/lib.rs new file mode 100644 index 0000000000..0c45e2a624 --- /dev/null +++ b/listings/ch17-oop/listing-17-04/src/lib.rs @@ -0,0 +1,9 @@ +pub trait Draw { + fn draw(&self); +} + +// ANCHOR: here +pub struct Screen { + pub components: Vec>, +} +// ANCHOR_END: here diff --git a/listings/ch17-oop/listing-17-05/Cargo.lock b/listings/ch17-oop/listing-17-05/Cargo.lock new file mode 100644 index 0000000000..00d7b21826 --- /dev/null +++ b/listings/ch17-oop/listing-17-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "gui" +version = "0.1.0" + diff --git a/listings/ch17-oop/listing-17-05/Cargo.toml b/listings/ch17-oop/listing-17-05/Cargo.toml new file mode 100644 index 0000000000..1f61cd20ec --- /dev/null +++ b/listings/ch17-oop/listing-17-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "gui" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/listing-17-05/src/lib.rs b/listings/ch17-oop/listing-17-05/src/lib.rs new file mode 100644 index 0000000000..57ebb5782a --- /dev/null +++ b/listings/ch17-oop/listing-17-05/src/lib.rs @@ -0,0 +1,17 @@ +pub trait Draw { + fn draw(&self); +} + +pub struct Screen { + pub components: Vec>, +} + +// ANCHOR: here +impl Screen { + pub fn run(&self) { + for component in self.components.iter() { + component.draw(); + } + } +} +// ANCHOR_END: here diff --git a/listings/ch17-oop/listing-17-06/Cargo.lock b/listings/ch17-oop/listing-17-06/Cargo.lock new file mode 100644 index 0000000000..00d7b21826 --- /dev/null +++ b/listings/ch17-oop/listing-17-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "gui" +version = "0.1.0" + diff --git a/listings/ch17-oop/listing-17-06/Cargo.toml b/listings/ch17-oop/listing-17-06/Cargo.toml new file mode 100644 index 0000000000..1f61cd20ec --- /dev/null +++ b/listings/ch17-oop/listing-17-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "gui" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/listing-17-06/src/lib.rs b/listings/ch17-oop/listing-17-06/src/lib.rs new file mode 100644 index 0000000000..63a8907d36 --- /dev/null +++ b/listings/ch17-oop/listing-17-06/src/lib.rs @@ -0,0 +1,20 @@ +pub trait Draw { + fn draw(&self); +} + +// ANCHOR: here +pub struct Screen { + pub components: Vec, +} + +impl Screen +where + T: Draw, +{ + pub fn run(&self) { + for component in self.components.iter() { + component.draw(); + } + } +} +// ANCHOR_END: here diff --git a/listings/ch17-oop/listing-17-07/Cargo.lock b/listings/ch17-oop/listing-17-07/Cargo.lock new file mode 100644 index 0000000000..00d7b21826 --- /dev/null +++ b/listings/ch17-oop/listing-17-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "gui" +version = "0.1.0" + diff --git a/listings/ch17-oop/listing-17-07/Cargo.toml b/listings/ch17-oop/listing-17-07/Cargo.toml new file mode 100644 index 0000000000..1f61cd20ec --- /dev/null +++ b/listings/ch17-oop/listing-17-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "gui" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/listing-17-07/src/lib.rs b/listings/ch17-oop/listing-17-07/src/lib.rs new file mode 100644 index 0000000000..413dc6ff16 --- /dev/null +++ b/listings/ch17-oop/listing-17-07/src/lib.rs @@ -0,0 +1,31 @@ +pub trait Draw { + fn draw(&self); +} + +pub struct Screen { + pub components: Vec>, +} + +impl Screen { + pub fn run(&self) { + for component in self.components.iter() { + component.draw(); + } + } +} + +// ANCHOR: here +pub struct Button { + pub width: u32, + pub height: u32, + pub label: String, +} + +impl Draw for Button { + fn draw(&self) { + // code to actually draw a button + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch17-oop/listing-17-08/Cargo.lock b/listings/ch17-oop/listing-17-08/Cargo.lock new file mode 100644 index 0000000000..00d7b21826 --- /dev/null +++ b/listings/ch17-oop/listing-17-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "gui" +version = "0.1.0" + diff --git a/listings/ch17-oop/listing-17-08/Cargo.toml b/listings/ch17-oop/listing-17-08/Cargo.toml new file mode 100644 index 0000000000..1f61cd20ec --- /dev/null +++ b/listings/ch17-oop/listing-17-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "gui" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/listing-17-08/src/lib.rs b/listings/ch17-oop/listing-17-08/src/lib.rs new file mode 100644 index 0000000000..960fee23da --- /dev/null +++ b/listings/ch17-oop/listing-17-08/src/lib.rs @@ -0,0 +1,27 @@ +pub trait Draw { + fn draw(&self); +} + +pub struct Screen { + pub components: Vec>, +} + +impl Screen { + pub fn run(&self) { + for component in self.components.iter() { + component.draw(); + } + } +} + +pub struct Button { + pub width: u32, + pub height: u32, + pub label: String, +} + +impl Draw for Button { + fn draw(&self) { + // code to actually draw a button + } +} diff --git a/listings/ch17-oop/listing-17-08/src/main.rs b/listings/ch17-oop/listing-17-08/src/main.rs new file mode 100644 index 0000000000..9575d407e3 --- /dev/null +++ b/listings/ch17-oop/listing-17-08/src/main.rs @@ -0,0 +1,17 @@ +// ANCHOR: here +use gui::Draw; + +struct SelectBox { + width: u32, + height: u32, + options: Vec, +} + +impl Draw for SelectBox { + fn draw(&self) { + // code to actually draw a select box + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch17-oop/listing-17-09/Cargo.lock b/listings/ch17-oop/listing-17-09/Cargo.lock new file mode 100644 index 0000000000..00d7b21826 --- /dev/null +++ b/listings/ch17-oop/listing-17-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "gui" +version = "0.1.0" + diff --git a/listings/ch17-oop/listing-17-09/Cargo.toml b/listings/ch17-oop/listing-17-09/Cargo.toml new file mode 100644 index 0000000000..1f61cd20ec --- /dev/null +++ b/listings/ch17-oop/listing-17-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "gui" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/listing-17-09/src/lib.rs b/listings/ch17-oop/listing-17-09/src/lib.rs new file mode 100644 index 0000000000..960fee23da --- /dev/null +++ b/listings/ch17-oop/listing-17-09/src/lib.rs @@ -0,0 +1,27 @@ +pub trait Draw { + fn draw(&self); +} + +pub struct Screen { + pub components: Vec>, +} + +impl Screen { + pub fn run(&self) { + for component in self.components.iter() { + component.draw(); + } + } +} + +pub struct Button { + pub width: u32, + pub height: u32, + pub label: String, +} + +impl Draw for Button { + fn draw(&self) { + // code to actually draw a button + } +} diff --git a/listings/ch17-oop/listing-17-09/src/main.rs b/listings/ch17-oop/listing-17-09/src/main.rs new file mode 100644 index 0000000000..4eb13f6b73 --- /dev/null +++ b/listings/ch17-oop/listing-17-09/src/main.rs @@ -0,0 +1,40 @@ +use gui::Draw; + +struct SelectBox { + width: u32, + height: u32, + options: Vec, +} + +impl Draw for SelectBox { + fn draw(&self) { + // code to actually draw a select box + } +} + +// ANCHOR: here +use gui::{Button, Screen}; + +fn main() { + let screen = Screen { + components: vec![ + Box::new(SelectBox { + width: 75, + height: 10, + options: vec![ + String::from("Yes"), + String::from("Maybe"), + String::from("No"), + ], + }), + Box::new(Button { + width: 50, + height: 10, + label: String::from("OK"), + }), + ], + }; + + screen.run(); +} +// ANCHOR_END: here diff --git a/listings/ch17-oop/listing-17-10/Cargo.lock b/listings/ch17-oop/listing-17-10/Cargo.lock new file mode 100644 index 0000000000..00d7b21826 --- /dev/null +++ b/listings/ch17-oop/listing-17-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "gui" +version = "0.1.0" + diff --git a/listings/ch17-oop/listing-17-10/Cargo.toml b/listings/ch17-oop/listing-17-10/Cargo.toml new file mode 100644 index 0000000000..1f61cd20ec --- /dev/null +++ b/listings/ch17-oop/listing-17-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "gui" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/listing-17-10/output.txt b/listings/ch17-oop/listing-17-10/output.txt new file mode 100644 index 0000000000..b18e1e9b4e --- /dev/null +++ b/listings/ch17-oop/listing-17-10/output.txt @@ -0,0 +1,16 @@ +$ cargo run + Compiling gui v0.1.0 (file:///projects/gui) +error[E0277]: the trait bound `std::string::String: gui::Draw` is not satisfied + --> src/main.rs:5:26 + | +5 | components: vec![Box::new(String::from("Hi"))], + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `gui::Draw` is not implemented for `std::string::String` + | + = note: required for the cast to the object type `dyn gui::Draw` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. +error: could not compile `gui`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch17-oop/listing-17-10/src/lib.rs b/listings/ch17-oop/listing-17-10/src/lib.rs new file mode 100644 index 0000000000..960fee23da --- /dev/null +++ b/listings/ch17-oop/listing-17-10/src/lib.rs @@ -0,0 +1,27 @@ +pub trait Draw { + fn draw(&self); +} + +pub struct Screen { + pub components: Vec>, +} + +impl Screen { + pub fn run(&self) { + for component in self.components.iter() { + component.draw(); + } + } +} + +pub struct Button { + pub width: u32, + pub height: u32, + pub label: String, +} + +impl Draw for Button { + fn draw(&self) { + // code to actually draw a button + } +} diff --git a/listings/ch17-oop/listing-17-10/src/main.rs b/listings/ch17-oop/listing-17-10/src/main.rs new file mode 100644 index 0000000000..2ede87ab78 --- /dev/null +++ b/listings/ch17-oop/listing-17-10/src/main.rs @@ -0,0 +1,9 @@ +use gui::Screen; + +fn main() { + let screen = Screen { + components: vec![Box::new(String::from("Hi"))], + }; + + screen.run(); +} diff --git a/listings/ch17-oop/listing-17-11/Cargo.lock b/listings/ch17-oop/listing-17-11/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/listings/ch17-oop/listing-17-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/listings/ch17-oop/listing-17-11/Cargo.toml b/listings/ch17-oop/listing-17-11/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/listings/ch17-oop/listing-17-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/listing-17-11/src/main.rs b/listings/ch17-oop/listing-17-11/src/main.rs new file mode 100644 index 0000000000..d99170a973 --- /dev/null +++ b/listings/ch17-oop/listing-17-11/src/main.rs @@ -0,0 +1,20 @@ +// ANCHOR: all +use blog::Post; + +// ANCHOR: here +fn main() { + let mut post = Post::new(); + + post.add_text("I ate a salad for lunch today"); + assert_eq!("", post.content()); + // ANCHOR_END: here + + post.request_review(); + assert_eq!("", post.content()); + + post.approve(); + assert_eq!("I ate a salad for lunch today", post.content()); + // ANCHOR: here +} +// ANCHOR_END: here +// ANCHOR_END: all diff --git a/listings/ch17-oop/listing-17-12/Cargo.lock b/listings/ch17-oop/listing-17-12/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/listings/ch17-oop/listing-17-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/listings/ch17-oop/listing-17-12/Cargo.toml b/listings/ch17-oop/listing-17-12/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/listings/ch17-oop/listing-17-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/listing-17-12/src/lib.rs b/listings/ch17-oop/listing-17-12/src/lib.rs new file mode 100644 index 0000000000..b8156c39de --- /dev/null +++ b/listings/ch17-oop/listing-17-12/src/lib.rs @@ -0,0 +1,19 @@ +pub struct Post { + state: Option>, + content: String, +} + +impl Post { + pub fn new() -> Post { + Post { + state: Some(Box::new(Draft {})), + content: String::new(), + } + } +} + +trait State {} + +struct Draft {} + +impl State for Draft {} diff --git a/listings/ch17-oop/listing-17-12/src/main.rs b/listings/ch17-oop/listing-17-12/src/main.rs new file mode 100644 index 0000000000..14b4c0824c --- /dev/null +++ b/listings/ch17-oop/listing-17-12/src/main.rs @@ -0,0 +1,14 @@ +use blog::Post; + +fn main() { + let mut post = Post::new(); + + post.add_text("I ate a salad for lunch today"); + assert_eq!("", post.content()); + + post.request_review(); + assert_eq!("", post.content()); + + post.approve(); + assert_eq!("I ate a salad for lunch today", post.content()); +} diff --git a/listings/ch17-oop/listing-17-13/Cargo.lock b/listings/ch17-oop/listing-17-13/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/listings/ch17-oop/listing-17-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/listings/ch17-oop/listing-17-13/Cargo.toml b/listings/ch17-oop/listing-17-13/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/listings/ch17-oop/listing-17-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/listing-17-13/src/lib.rs b/listings/ch17-oop/listing-17-13/src/lib.rs new file mode 100644 index 0000000000..0ae3fa6e81 --- /dev/null +++ b/listings/ch17-oop/listing-17-13/src/lib.rs @@ -0,0 +1,30 @@ +pub struct Post { + state: Option>, + content: String, +} + +// ANCHOR: here +impl Post { + // --snip-- + // ANCHOR_END: here + pub fn new() -> Post { + Post { + state: Some(Box::new(Draft {})), + content: String::new(), + } + } + + // ANCHOR: here + pub fn add_text(&mut self, text: &str) { + self.content.push_str(text); + } +} +// ANCHOR_END: here + +trait State {} + +struct Draft {} + +impl State for Draft {} + +fn main() {} diff --git a/listings/ch17-oop/listing-17-13/src/main.rs b/listings/ch17-oop/listing-17-13/src/main.rs new file mode 100644 index 0000000000..14b4c0824c --- /dev/null +++ b/listings/ch17-oop/listing-17-13/src/main.rs @@ -0,0 +1,14 @@ +use blog::Post; + +fn main() { + let mut post = Post::new(); + + post.add_text("I ate a salad for lunch today"); + assert_eq!("", post.content()); + + post.request_review(); + assert_eq!("", post.content()); + + post.approve(); + assert_eq!("I ate a salad for lunch today", post.content()); +} diff --git a/listings/ch17-oop/listing-17-14/Cargo.lock b/listings/ch17-oop/listing-17-14/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/listings/ch17-oop/listing-17-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/listings/ch17-oop/listing-17-14/Cargo.toml b/listings/ch17-oop/listing-17-14/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/listings/ch17-oop/listing-17-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/listing-17-14/src/lib.rs b/listings/ch17-oop/listing-17-14/src/lib.rs new file mode 100644 index 0000000000..0d010f50c5 --- /dev/null +++ b/listings/ch17-oop/listing-17-14/src/lib.rs @@ -0,0 +1,34 @@ +pub struct Post { + state: Option>, + content: String, +} + +// ANCHOR: here +impl Post { + // --snip-- + // ANCHOR_END: here + pub fn new() -> Post { + Post { + state: Some(Box::new(Draft {})), + content: String::new(), + } + } + + pub fn add_text(&mut self, text: &str) { + self.content.push_str(text); + } + + // ANCHOR: here + pub fn content(&self) -> &str { + "" + } +} +// ANCHOR_END: here + +trait State {} + +struct Draft {} + +impl State for Draft {} + +fn main() {} diff --git a/listings/ch17-oop/listing-17-14/src/main.rs b/listings/ch17-oop/listing-17-14/src/main.rs new file mode 100644 index 0000000000..14b4c0824c --- /dev/null +++ b/listings/ch17-oop/listing-17-14/src/main.rs @@ -0,0 +1,14 @@ +use blog::Post; + +fn main() { + let mut post = Post::new(); + + post.add_text("I ate a salad for lunch today"); + assert_eq!("", post.content()); + + post.request_review(); + assert_eq!("", post.content()); + + post.approve(); + assert_eq!("I ate a salad for lunch today", post.content()); +} diff --git a/listings/ch17-oop/listing-17-15/Cargo.lock b/listings/ch17-oop/listing-17-15/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/listings/ch17-oop/listing-17-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/listings/ch17-oop/listing-17-15/Cargo.toml b/listings/ch17-oop/listing-17-15/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/listings/ch17-oop/listing-17-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/listing-17-15/src/lib.rs b/listings/ch17-oop/listing-17-15/src/lib.rs new file mode 100644 index 0000000000..806b4e49db --- /dev/null +++ b/listings/ch17-oop/listing-17-15/src/lib.rs @@ -0,0 +1,54 @@ +pub struct Post { + state: Option>, + content: String, +} + +// ANCHOR: here +impl Post { + // --snip-- + // ANCHOR_END: here + pub fn new() -> Post { + Post { + state: Some(Box::new(Draft {})), + content: String::new(), + } + } + + pub fn add_text(&mut self, text: &str) { + self.content.push_str(text); + } + + pub fn content(&self) -> &str { + "" + } + + // ANCHOR: here + pub fn request_review(&mut self) { + if let Some(s) = self.state.take() { + self.state = Some(s.request_review()) + } + } +} + +trait State { + fn request_review(self: Box) -> Box; +} + +struct Draft {} + +impl State for Draft { + fn request_review(self: Box) -> Box { + Box::new(PendingReview {}) + } +} + +struct PendingReview {} + +impl State for PendingReview { + fn request_review(self: Box) -> Box { + self + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch17-oop/listing-17-15/src/main.rs b/listings/ch17-oop/listing-17-15/src/main.rs new file mode 100644 index 0000000000..14b4c0824c --- /dev/null +++ b/listings/ch17-oop/listing-17-15/src/main.rs @@ -0,0 +1,14 @@ +use blog::Post; + +fn main() { + let mut post = Post::new(); + + post.add_text("I ate a salad for lunch today"); + assert_eq!("", post.content()); + + post.request_review(); + assert_eq!("", post.content()); + + post.approve(); + assert_eq!("I ate a salad for lunch today", post.content()); +} diff --git a/listings/ch17-oop/listing-17-16/Cargo.lock b/listings/ch17-oop/listing-17-16/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/listings/ch17-oop/listing-17-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/listings/ch17-oop/listing-17-16/Cargo.toml b/listings/ch17-oop/listing-17-16/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/listings/ch17-oop/listing-17-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/listing-17-16/src/lib.rs b/listings/ch17-oop/listing-17-16/src/lib.rs new file mode 100644 index 0000000000..92cb298134 --- /dev/null +++ b/listings/ch17-oop/listing-17-16/src/lib.rs @@ -0,0 +1,85 @@ +pub struct Post { + state: Option>, + content: String, +} + +// ANCHOR: here +impl Post { + // --snip-- + // ANCHOR_END: here + pub fn new() -> Post { + Post { + state: Some(Box::new(Draft {})), + content: String::new(), + } + } + + pub fn add_text(&mut self, text: &str) { + self.content.push_str(text); + } + + pub fn content(&self) -> &str { + "" + } + + pub fn request_review(&mut self) { + if let Some(s) = self.state.take() { + self.state = Some(s.request_review()) + } + } + + // ANCHOR: here + pub fn approve(&mut self) { + if let Some(s) = self.state.take() { + self.state = Some(s.approve()) + } + } +} + +trait State { + fn request_review(self: Box) -> Box; + fn approve(self: Box) -> Box; +} + +struct Draft {} + +impl State for Draft { + // --snip-- + // ANCHOR_END: here + fn request_review(self: Box) -> Box { + Box::new(PendingReview {}) + } + + // ANCHOR: here + fn approve(self: Box) -> Box { + self + } +} + +struct PendingReview {} + +impl State for PendingReview { + // --snip-- + // ANCHOR_END: here + fn request_review(self: Box) -> Box { + self + } + + // ANCHOR: here + fn approve(self: Box) -> Box { + Box::new(Published {}) + } +} + +struct Published {} + +impl State for Published { + fn request_review(self: Box) -> Box { + self + } + + fn approve(self: Box) -> Box { + self + } +} +// ANCHOR_END: here diff --git a/listings/ch17-oop/listing-17-16/src/main.rs b/listings/ch17-oop/listing-17-16/src/main.rs new file mode 100644 index 0000000000..14b4c0824c --- /dev/null +++ b/listings/ch17-oop/listing-17-16/src/main.rs @@ -0,0 +1,14 @@ +use blog::Post; + +fn main() { + let mut post = Post::new(); + + post.add_text("I ate a salad for lunch today"); + assert_eq!("", post.content()); + + post.request_review(); + assert_eq!("", post.content()); + + post.approve(); + assert_eq!("I ate a salad for lunch today", post.content()); +} diff --git a/listings/ch17-oop/listing-17-17/Cargo.lock b/listings/ch17-oop/listing-17-17/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/listings/ch17-oop/listing-17-17/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/listings/ch17-oop/listing-17-17/Cargo.toml b/listings/ch17-oop/listing-17-17/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/listings/ch17-oop/listing-17-17/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/listing-17-17/src/lib.rs b/listings/ch17-oop/listing-17-17/src/lib.rs new file mode 100644 index 0000000000..0beee7b8da --- /dev/null +++ b/listings/ch17-oop/listing-17-17/src/lib.rs @@ -0,0 +1,82 @@ +pub struct Post { + state: Option>, + content: String, +} + +// ANCHOR: here +impl Post { + // --snip-- + // ANCHOR_END: here + pub fn new() -> Post { + Post { + state: Some(Box::new(Draft {})), + content: String::new(), + } + } + + pub fn add_text(&mut self, text: &str) { + self.content.push_str(text); + } + + // ANCHOR: here + pub fn content(&self) -> &str { + self.state.as_ref().unwrap().content(self) + } + // --snip-- + // ANCHOR_END: here + + pub fn request_review(&mut self) { + if let Some(s) = self.state.take() { + self.state = Some(s.request_review()) + } + } + + pub fn approve(&mut self) { + if let Some(s) = self.state.take() { + self.state = Some(s.approve()) + } + } + // ANCHOR: here +} +// ANCHOR_END: here + +trait State { + fn request_review(self: Box) -> Box; + fn approve(self: Box) -> Box; +} + +struct Draft {} + +impl State for Draft { + fn request_review(self: Box) -> Box { + Box::new(PendingReview {}) + } + + fn approve(self: Box) -> Box { + self + } +} + +struct PendingReview {} + +impl State for PendingReview { + fn request_review(self: Box) -> Box { + self + } + + fn approve(self: Box) -> Box { + Box::new(Published {}) + } +} + +struct Published {} + +impl State for Published { + fn request_review(self: Box) -> Box { + self + } + + fn approve(self: Box) -> Box { + self + } +} diff --git a/listings/ch17-oop/listing-17-17/src/main.rs b/listings/ch17-oop/listing-17-17/src/main.rs new file mode 100644 index 0000000000..14b4c0824c --- /dev/null +++ b/listings/ch17-oop/listing-17-17/src/main.rs @@ -0,0 +1,14 @@ +use blog::Post; + +fn main() { + let mut post = Post::new(); + + post.add_text("I ate a salad for lunch today"); + assert_eq!("", post.content()); + + post.request_review(); + assert_eq!("", post.content()); + + post.approve(); + assert_eq!("I ate a salad for lunch today", post.content()); +} diff --git a/listings/ch17-oop/listing-17-18/Cargo.lock b/listings/ch17-oop/listing-17-18/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/listings/ch17-oop/listing-17-18/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/listings/ch17-oop/listing-17-18/Cargo.toml b/listings/ch17-oop/listing-17-18/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/listings/ch17-oop/listing-17-18/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/listing-17-18/src/lib.rs b/listings/ch17-oop/listing-17-18/src/lib.rs new file mode 100644 index 0000000000..1bac8a87aa --- /dev/null +++ b/listings/ch17-oop/listing-17-18/src/lib.rs @@ -0,0 +1,94 @@ +pub struct Post { + state: Option>, + content: String, +} + +impl Post { + pub fn new() -> Post { + Post { + state: Some(Box::new(Draft {})), + content: String::new(), + } + } + + pub fn add_text(&mut self, text: &str) { + self.content.push_str(text); + } + + pub fn content(&self) -> &str { + self.state.as_ref().unwrap().content(self) + } + + pub fn request_review(&mut self) { + if let Some(s) = self.state.take() { + self.state = Some(s.request_review()) + } + } + + pub fn approve(&mut self) { + if let Some(s) = self.state.take() { + self.state = Some(s.approve()) + } + } +} + +// ANCHOR: here +trait State { + // --snip-- + // ANCHOR_END: here + fn request_review(self: Box) -> Box; + fn approve(self: Box) -> Box; + + // ANCHOR: here + fn content<'a>(&self, post: &'a Post) -> &'a str { + "" + } +} + +// --snip-- +// ANCHOR_END: here + +struct Draft {} + +impl State for Draft { + fn request_review(self: Box) -> Box { + Box::new(PendingReview {}) + } + + fn approve(self: Box) -> Box { + self + } +} + +struct PendingReview {} + +impl State for PendingReview { + fn request_review(self: Box) -> Box { + self + } + + fn approve(self: Box) -> Box { + Box::new(Published {}) + } +} + +// ANCHOR: here +struct Published {} + +impl State for Published { + // --snip-- + // ANCHOR_END: here + fn request_review(self: Box) -> Box { + self + } + + fn approve(self: Box) -> Box { + self + } + + // ANCHOR: here + fn content<'a>(&self, post: &'a Post) -> &'a str { + &post.content + } +} +// ANCHOR_END: here diff --git a/listings/ch17-oop/listing-17-18/src/main.rs b/listings/ch17-oop/listing-17-18/src/main.rs new file mode 100644 index 0000000000..14b4c0824c --- /dev/null +++ b/listings/ch17-oop/listing-17-18/src/main.rs @@ -0,0 +1,14 @@ +use blog::Post; + +fn main() { + let mut post = Post::new(); + + post.add_text("I ate a salad for lunch today"); + assert_eq!("", post.content()); + + post.request_review(); + assert_eq!("", post.content()); + + post.approve(); + assert_eq!("I ate a salad for lunch today", post.content()); +} diff --git a/listings/ch17-oop/listing-17-19/Cargo.lock b/listings/ch17-oop/listing-17-19/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/listings/ch17-oop/listing-17-19/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/listings/ch17-oop/listing-17-19/Cargo.toml b/listings/ch17-oop/listing-17-19/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/listings/ch17-oop/listing-17-19/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/listing-17-19/src/lib.rs b/listings/ch17-oop/listing-17-19/src/lib.rs new file mode 100644 index 0000000000..bfe034eaf1 --- /dev/null +++ b/listings/ch17-oop/listing-17-19/src/lib.rs @@ -0,0 +1,25 @@ +pub struct Post { + content: String, +} + +pub struct DraftPost { + content: String, +} + +impl Post { + pub fn new() -> DraftPost { + DraftPost { + content: String::new(), + } + } + + pub fn content(&self) -> &str { + &self.content + } +} + +impl DraftPost { + pub fn add_text(&mut self, text: &str) { + self.content.push_str(text); + } +} diff --git a/listings/ch17-oop/listing-17-20/Cargo.lock b/listings/ch17-oop/listing-17-20/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/listings/ch17-oop/listing-17-20/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/listings/ch17-oop/listing-17-20/Cargo.toml b/listings/ch17-oop/listing-17-20/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/listings/ch17-oop/listing-17-20/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/listing-17-20/src/lib.rs b/listings/ch17-oop/listing-17-20/src/lib.rs new file mode 100644 index 0000000000..3b82ec05dc --- /dev/null +++ b/listings/ch17-oop/listing-17-20/src/lib.rs @@ -0,0 +1,48 @@ +pub struct Post { + content: String, +} + +pub struct DraftPost { + content: String, +} + +impl Post { + pub fn new() -> DraftPost { + DraftPost { + content: String::new(), + } + } + + pub fn content(&self) -> &str { + &self.content + } +} + +// ANCHOR: here +impl DraftPost { + // --snip-- + // ANCHOR_END: here + pub fn add_text(&mut self, text: &str) { + self.content.push_str(text); + } + + // ANCHOR: here + pub fn request_review(self) -> PendingReviewPost { + PendingReviewPost { + content: self.content, + } + } +} + +pub struct PendingReviewPost { + content: String, +} + +impl PendingReviewPost { + pub fn approve(self) -> Post { + Post { + content: self.content, + } + } +} +// ANCHOR_END: here diff --git a/listings/ch17-oop/listing-17-21/Cargo.lock b/listings/ch17-oop/listing-17-21/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/listings/ch17-oop/listing-17-21/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/listings/ch17-oop/listing-17-21/Cargo.toml b/listings/ch17-oop/listing-17-21/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/listings/ch17-oop/listing-17-21/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/listing-17-21/src/lib.rs b/listings/ch17-oop/listing-17-21/src/lib.rs new file mode 100644 index 0000000000..38500a651b --- /dev/null +++ b/listings/ch17-oop/listing-17-21/src/lib.rs @@ -0,0 +1,43 @@ +pub struct Post { + content: String, +} + +pub struct DraftPost { + content: String, +} + +impl Post { + pub fn new() -> DraftPost { + DraftPost { + content: String::new(), + } + } + + pub fn content(&self) -> &str { + &self.content + } +} + +impl DraftPost { + pub fn add_text(&mut self, text: &str) { + self.content.push_str(text); + } + + pub fn request_review(self) -> PendingReviewPost { + PendingReviewPost { + content: self.content, + } + } +} + +pub struct PendingReviewPost { + content: String, +} + +impl PendingReviewPost { + pub fn approve(self) -> Post { + Post { + content: self.content, + } + } +} diff --git a/listings/ch17-oop/listing-17-21/src/main.rs b/listings/ch17-oop/listing-17-21/src/main.rs new file mode 100644 index 0000000000..720c55e6aa --- /dev/null +++ b/listings/ch17-oop/listing-17-21/src/main.rs @@ -0,0 +1,13 @@ +use blog::Post; + +fn main() { + let mut post = Post::new(); + + post.add_text("I ate a salad for lunch today"); + + let post = post.request_review(); + + let post = post.approve(); + + assert_eq!("I ate a salad for lunch today", post.content()); +} diff --git a/listings/ch17-oop/no-listing-01-trait-object-of-clone/Cargo.lock b/listings/ch17-oop/no-listing-01-trait-object-of-clone/Cargo.lock new file mode 100644 index 0000000000..00d7b21826 --- /dev/null +++ b/listings/ch17-oop/no-listing-01-trait-object-of-clone/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "gui" +version = "0.1.0" + diff --git a/listings/ch17-oop/no-listing-01-trait-object-of-clone/Cargo.toml b/listings/ch17-oop/no-listing-01-trait-object-of-clone/Cargo.toml new file mode 100644 index 0000000000..1f61cd20ec --- /dev/null +++ b/listings/ch17-oop/no-listing-01-trait-object-of-clone/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "gui" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch17-oop/no-listing-01-trait-object-of-clone/output.txt b/listings/ch17-oop/no-listing-01-trait-object-of-clone/output.txt new file mode 100644 index 0000000000..33a492556d --- /dev/null +++ b/listings/ch17-oop/no-listing-01-trait-object-of-clone/output.txt @@ -0,0 +1,16 @@ +$ cargo build + Compiling gui v0.1.0 (file:///projects/gui) +error[E0038]: the trait `std::clone::Clone` cannot be made into an object + --> src/lib.rs:2:5 + | +2 | pub components: Vec>, + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::clone::Clone` cannot be made into an object + | + = note: the trait cannot require that `Self : Sized` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0038`. +error: could not compile `gui`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch17-oop/no-listing-01-trait-object-of-clone/src/lib.rs b/listings/ch17-oop/no-listing-01-trait-object-of-clone/src/lib.rs new file mode 100644 index 0000000000..e6b1a37f0a --- /dev/null +++ b/listings/ch17-oop/no-listing-01-trait-object-of-clone/src/lib.rs @@ -0,0 +1,3 @@ +pub struct Screen { + pub components: Vec>, +} diff --git a/listings/ch18-patterns-and-matching/listing-18-01/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-01/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-01/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-01/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-01/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-01/src/main.rs new file mode 100644 index 0000000000..d28c369f56 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-01/src/main.rs @@ -0,0 +1,19 @@ +fn main() { + let favorite_color: Option<&str> = None; + let is_tuesday = false; + let age: Result = "34".parse(); + + if let Some(color) = favorite_color { + println!("Using your favorite color, {}, as the background", color); + } else if is_tuesday { + println!("Tuesday is green day!"); + } else if let Ok(age) = age { + if age > 30 { + println!("Using purple as the background color"); + } else { + println!("Using orange as the background color"); + } + } else { + println!("Using blue as the background color"); + } +} diff --git a/listings/ch18-patterns-and-matching/listing-18-02/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-02/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-02/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-02/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-02/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-02/src/main.rs new file mode 100644 index 0000000000..5f75a4f2db --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-02/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + // ANCHOR: here + let mut stack = Vec::new(); + + stack.push(1); + stack.push(2); + stack.push(3); + + while let Some(top) = stack.pop() { + println!("{}", top); + } + // ANCHOR_END: here +} diff --git a/listings/ch18-patterns-and-matching/listing-18-03/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-03/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-03/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-03/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-03/output.txt b/listings/ch18-patterns-and-matching/listing-18-03/output.txt new file mode 100644 index 0000000000..02fdecbf5c --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-03/output.txt @@ -0,0 +1,7 @@ +$ cargo run + Compiling patterns v0.1.0 (file:///projects/patterns) + Finished dev [unoptimized + debuginfo] target(s) in 0.52s + Running `target/debug/patterns` +a is at index 0 +b is at index 1 +c is at index 2 diff --git a/listings/ch18-patterns-and-matching/listing-18-03/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-03/src/main.rs new file mode 100644 index 0000000000..eb922d62cd --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-03/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + // ANCHOR: here + let v = vec!['a', 'b', 'c']; + + for (index, value) in v.iter().enumerate() { + println!("{} is at index {}", value, index); + } + // ANCHOR_END: here +} diff --git a/listings/ch18-patterns-and-matching/listing-18-04/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-04/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-04/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-04/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-04/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-04/src/main.rs new file mode 100644 index 0000000000..27b0c3fbdc --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-04/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + // ANCHOR: here + let (x, y, z) = (1, 2, 3); + // ANCHOR_END: here +} diff --git a/listings/ch18-patterns-and-matching/listing-18-05/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-05/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-05/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-05/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-05/output.txt b/listings/ch18-patterns-and-matching/listing-18-05/output.txt new file mode 100644 index 0000000000..0672793804 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-05/output.txt @@ -0,0 +1,17 @@ +$ cargo run + Compiling patterns v0.1.0 (file:///projects/patterns) +error[E0308]: mismatched types + --> src/main.rs:2:9 + | +2 | let (x, y) = (1, 2, 3); + | ^^^^^^ expected a tuple with 3 elements, found one with 2 elements + | + = note: expected type `({integer}, {integer}, {integer})` + found type `(_, _)` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. +error: could not compile `patterns`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch18-patterns-and-matching/listing-18-05/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-05/src/main.rs new file mode 100644 index 0000000000..39f768e29e --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-05/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + // ANCHOR: here + let (x, y) = (1, 2, 3); + // ANCHOR_END: here +} diff --git a/listings/ch18-patterns-and-matching/listing-18-06/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-06/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-06/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-06/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-06/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-06/src/main.rs new file mode 100644 index 0000000000..c5d71e6c13 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-06/src/main.rs @@ -0,0 +1,7 @@ +// ANCHOR: here +fn foo(x: i32) { + // code goes here +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch18-patterns-and-matching/listing-18-07/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-07/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-07/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-07/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-07/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-07/src/main.rs new file mode 100644 index 0000000000..4eccb8088c --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-07/src/main.rs @@ -0,0 +1,8 @@ +fn print_coordinates(&(x, y): &(i32, i32)) { + println!("Current location: ({}, {})", x, y); +} + +fn main() { + let point = (3, 5); + print_coordinates(&point); +} diff --git a/listings/ch18-patterns-and-matching/listing-18-08/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-08/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-08/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-08/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-08/output.txt b/listings/ch18-patterns-and-matching/listing-18-08/output.txt new file mode 100644 index 0000000000..551250ff87 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-08/output.txt @@ -0,0 +1,21 @@ +$ cargo run + Compiling patterns v0.1.0 (file:///projects/patterns) +error[E0005]: refutable pattern in local binding: `None` not covered + --> src/main.rs:3:9 + | +3 | let Some(x) = some_option_value; + | ^^^^^^^ pattern `None` not covered + | + = note: `let` bindings require an "irrefutable pattern", like a `struct` or an `enum` with only one variant + = note: for more information, visit https://doc.rust-lang.org/book/ch18-02-refutability.html +help: you might want to use `if let` to ignore the variant that isn't matched + | +3 | if let Some(x) = some_option_value { /* */ } + | + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0005`. +error: could not compile `patterns`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch18-patterns-and-matching/listing-18-08/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-08/src/main.rs new file mode 100644 index 0000000000..7baa02a49b --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-08/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + let some_option_value: Option = None; + // ANCHOR: here + let Some(x) = some_option_value; + // ANCHOR_END: here +} diff --git a/listings/ch18-patterns-and-matching/listing-18-09/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-09/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-09/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-09/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-09/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-09/src/main.rs new file mode 100644 index 0000000000..d6274fc0e1 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-09/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + let some_option_value: Option = None; + // ANCHOR: here + if let Some(x) = some_option_value { + println!("{}", x); + } + // ANCHOR_END: here +} diff --git a/listings/ch18-patterns-and-matching/listing-18-10/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-10/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-10/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-10/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-10/output.txt b/listings/ch18-patterns-and-matching/listing-18-10/output.txt new file mode 100644 index 0000000000..8b72e18134 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-10/output.txt @@ -0,0 +1,15 @@ +$ cargo run + Compiling patterns v0.1.0 (file:///projects/patterns) +warning: irrefutable if-let pattern + --> src/main.rs:2:5 + | +2 | / if let x = 5 { +3 | | println!("{}", x); +4 | | }; + | |_____^ + | + = note: `#[warn(irrefutable_let_patterns)]` on by default + + Finished dev [unoptimized + debuginfo] target(s) in 0.39s + Running `target/debug/patterns` +5 diff --git a/listings/ch18-patterns-and-matching/listing-18-10/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-10/src/main.rs new file mode 100644 index 0000000000..cb81772e0c --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-10/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + // ANCHOR: here + if let x = 5 { + println!("{}", x); + }; + // ANCHOR_END: here +} diff --git a/listings/ch18-patterns-and-matching/listing-18-11/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-11/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-11/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-11/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-11/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-11/src/main.rs new file mode 100644 index 0000000000..25eaa79ff8 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-11/src/main.rs @@ -0,0 +1,14 @@ +fn main() { + // ANCHOR: here + let x = Some(5); + let y = 10; + + match x { + Some(50) => println!("Got 50"), + Some(y) => println!("Matched, y = {:?}", y), + _ => println!("Default case, x = {:?}", x), + } + + println!("at the end: x = {:?}, y = {:?}", x, y); + // ANCHOR_END: here +} diff --git a/listings/ch18-patterns-and-matching/listing-18-12/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-12/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-12/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-12/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-12/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-12/src/main.rs new file mode 100644 index 0000000000..62f4ccbf1e --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-12/src/main.rs @@ -0,0 +1,12 @@ +struct Point { + x: i32, + y: i32, +} + +fn main() { + let p = Point { x: 0, y: 7 }; + + let Point { x: a, y: b } = p; + assert_eq!(0, a); + assert_eq!(7, b); +} diff --git a/listings/ch18-patterns-and-matching/listing-18-13/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-13/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-13/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-13/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-13/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-13/src/main.rs new file mode 100644 index 0000000000..5badc1594f --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-13/src/main.rs @@ -0,0 +1,12 @@ +struct Point { + x: i32, + y: i32, +} + +fn main() { + let p = Point { x: 0, y: 7 }; + + let Point { x, y } = p; + assert_eq!(0, x); + assert_eq!(7, y); +} diff --git a/listings/ch18-patterns-and-matching/listing-18-14/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-14/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-14/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-14/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-14/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-14/src/main.rs new file mode 100644 index 0000000000..8d445d9b9d --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-14/src/main.rs @@ -0,0 +1,16 @@ +struct Point { + x: i32, + y: i32, +} + +// ANCHOR: here +fn main() { + let p = Point { x: 0, y: 7 }; + + match p { + Point { x, y: 0 } => println!("On the x axis at {}", x), + Point { x: 0, y } => println!("On the y axis at {}", y), + Point { x, y } => println!("On neither axis: ({}, {})", x, y), + } +} +// ANCHOR_END: here diff --git a/listings/ch18-patterns-and-matching/listing-18-15/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-15/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-15/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-15/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-15/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-15/src/main.rs new file mode 100644 index 0000000000..9b8dac1938 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-15/src/main.rs @@ -0,0 +1,27 @@ +enum Message { + Quit, + Move { x: i32, y: i32 }, + Write(String), + ChangeColor(i32, i32, i32), +} + +fn main() { + let msg = Message::ChangeColor(0, 160, 255); + + match msg { + Message::Quit => { + println!("The Quit variant has no data to destructure.") + } + Message::Move { x, y } => { + println!( + "Move in the x direction {} and in the y direction {}", + x, y + ); + } + Message::Write(text) => println!("Text message: {}", text), + Message::ChangeColor(r, g, b) => println!( + "Change the color to red {}, green {}, and blue {}", + r, g, b + ), + } +} diff --git a/listings/ch18-patterns-and-matching/listing-18-16/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-16/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-16/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-16/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-16/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-16/src/main.rs new file mode 100644 index 0000000000..ed6a20bf47 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-16/src/main.rs @@ -0,0 +1,27 @@ +enum Color { + Rgb(i32, i32, i32), + Hsv(i32, i32, i32), +} + +enum Message { + Quit, + Move { x: i32, y: i32 }, + Write(String), + ChangeColor(Color), +} + +fn main() { + let msg = Message::ChangeColor(Color::Hsv(0, 160, 255)); + + match msg { + Message::ChangeColor(Color::Rgb(r, g, b)) => println!( + "Change the color to red {}, green {}, and blue {}", + r, g, b + ), + Message::ChangeColor(Color::Hsv(h, s, v)) => println!( + "Change the color to hue {}, saturation {}, and value {}", + h, s, v + ), + _ => (), + } +} diff --git a/listings/ch18-patterns-and-matching/listing-18-17/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-17/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-17/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-17/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-17/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-17/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-17/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-17/src/main.rs new file mode 100644 index 0000000000..cf1fbe0721 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-17/src/main.rs @@ -0,0 +1,7 @@ +fn foo(_: i32, y: i32) { + println!("This code only uses the y parameter: {}", y); +} + +fn main() { + foo(3, 4); +} diff --git a/listings/ch18-patterns-and-matching/listing-18-18/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-18/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-18/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-18/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-18/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-18/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-18/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-18/src/main.rs new file mode 100644 index 0000000000..b776c64c42 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-18/src/main.rs @@ -0,0 +1,17 @@ +fn main() { + // ANCHOR: here + let mut setting_value = Some(5); + let new_setting_value = Some(10); + + match (setting_value, new_setting_value) { + (Some(_), Some(_)) => { + println!("Can't overwrite an existing customized value"); + } + _ => { + setting_value = new_setting_value; + } + } + + println!("setting is {:?}", setting_value); + // ANCHOR_END: here +} diff --git a/listings/ch18-patterns-and-matching/listing-18-19/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-19/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-19/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-19/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-19/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-19/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-19/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-19/src/main.rs new file mode 100644 index 0000000000..59b48c94d8 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-19/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let numbers = (2, 4, 8, 16, 32); + + match numbers { + (first, _, third, _, fifth) => { + println!("Some numbers: {}, {}, {}", first, third, fifth) + } + } + // ANCHOR_END: here +} diff --git a/listings/ch18-patterns-and-matching/listing-18-20/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-20/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-20/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-20/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-20/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-20/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-20/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-20/src/main.rs new file mode 100644 index 0000000000..1ffc46bad3 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-20/src/main.rs @@ -0,0 +1,4 @@ +fn main() { + let _x = 5; + let y = 10; +} diff --git a/listings/ch18-patterns-and-matching/listing-18-21/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-21/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-21/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-21/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-21/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-21/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-21/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-21/src/main.rs new file mode 100644 index 0000000000..980610503f --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-21/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let s = Some(String::from("Hello!")); + + if let Some(_s) = s { + println!("found a string"); + } + + println!("{:?}", s); + // ANCHOR_END: here +} diff --git a/listings/ch18-patterns-and-matching/listing-18-22/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-22/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-22/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-22/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-22/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-22/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-22/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-22/src/main.rs new file mode 100644 index 0000000000..e2faa345bc --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-22/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let s = Some(String::from("Hello!")); + + if let Some(_) = s { + println!("found a string"); + } + + println!("{:?}", s); + // ANCHOR_END: here +} diff --git a/listings/ch18-patterns-and-matching/listing-18-23/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-23/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-23/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-23/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-23/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-23/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-23/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-23/src/main.rs new file mode 100644 index 0000000000..7a9d9bb36f --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-23/src/main.rs @@ -0,0 +1,15 @@ +fn main() { + // ANCHOR: here + struct Point { + x: i32, + y: i32, + z: i32, + } + + let origin = Point { x: 0, y: 0, z: 0 }; + + match origin { + Point { x, .. } => println!("x is {}", x), + } + // ANCHOR_END: here +} diff --git a/listings/ch18-patterns-and-matching/listing-18-24/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-24/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-24/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-24/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-24/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-24/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-24/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-24/src/main.rs new file mode 100644 index 0000000000..f22dbe8edf --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-24/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let numbers = (2, 4, 8, 16, 32); + + match numbers { + (first, .., last) => { + println!("Some numbers: {}, {}", first, last); + } + } +} diff --git a/listings/ch18-patterns-and-matching/listing-18-25/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-25/Cargo.lock new file mode 100644 index 0000000000..a233623e55 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-25/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-25/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-25/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-25/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-25/output.txt b/listings/ch18-patterns-and-matching/listing-18-25/output.txt new file mode 100644 index 0000000000..3044c4b30c --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-25/output.txt @@ -0,0 +1,15 @@ +$ cargo run + Compiling patterns v0.1.0 (file:///projects/patterns) +error: `..` can only be used once per tuple pattern + --> src/main.rs:5:22 + | +5 | (.., second, ..) => { + | -- ^^ can only be used once per tuple pattern + | | + | previously used here + +error: aborting due to previous error + +error: could not compile `patterns`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch18-patterns-and-matching/listing-18-25/rustfmt-ignore b/listings/ch18-patterns-and-matching/listing-18-25/rustfmt-ignore new file mode 100644 index 0000000000..06a976dd46 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-25/rustfmt-ignore @@ -0,0 +1 @@ +This listing deliberately doesn't parse so rustfmt fails. diff --git a/listings/ch18-patterns-and-matching/listing-18-25/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-25/src/main.rs new file mode 100644 index 0000000000..b90884eb9c --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-25/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let numbers = (2, 4, 8, 16, 32); + + match numbers { + (.., second, ..) => { + println!("Some numbers: {}", second) + }, + } +} diff --git a/listings/ch18-patterns-and-matching/listing-18-26/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-26/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-26/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-26/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-26/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-26/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-26/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-26/src/main.rs new file mode 100644 index 0000000000..4ec86cba76 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-26/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let num = Some(4); + + match num { + Some(x) if x < 5 => println!("less than five: {}", x), + Some(x) => println!("{}", x), + None => (), + } + // ANCHOR_END: here +} diff --git a/listings/ch18-patterns-and-matching/listing-18-27/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-27/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-27/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-27/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-27/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-27/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-27/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-27/src/main.rs new file mode 100644 index 0000000000..348e367233 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-27/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + let x = Some(5); + let y = 10; + + match x { + Some(50) => println!("Got 50"), + Some(n) if n == y => println!("Matched, n = {}", n), + _ => println!("Default case, x = {:?}", x), + } + + println!("at the end: x = {:?}, y = {}", x, y); +} diff --git a/listings/ch18-patterns-and-matching/listing-18-28/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-28/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-28/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-28/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-28/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-28/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-28/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-28/src/main.rs new file mode 100644 index 0000000000..15804553fa --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-28/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let x = 4; + let y = false; + + match x { + 4 | 5 | 6 if y => println!("yes"), + _ => println!("no"), + } + // ANCHOR_END: here +} diff --git a/listings/ch18-patterns-and-matching/listing-18-29/Cargo.lock b/listings/ch18-patterns-and-matching/listing-18-29/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-29/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/listing-18-29/Cargo.toml b/listings/ch18-patterns-and-matching/listing-18-29/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-29/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/listing-18-29/src/main.rs b/listings/ch18-patterns-and-matching/listing-18-29/src/main.rs new file mode 100644 index 0000000000..3514deb636 --- /dev/null +++ b/listings/ch18-patterns-and-matching/listing-18-29/src/main.rs @@ -0,0 +1,19 @@ +fn main() { + // ANCHOR: here + enum Message { + Hello { id: i32 }, + } + + let msg = Message::Hello { id: 5 }; + + match msg { + Message::Hello { + id: id_variable @ 3..=7, + } => println!("Found an id in range: {}", id_variable), + Message::Hello { id: 10..=12 } => { + println!("Found an id in another range") + } + Message::Hello { id } => println!("Found some other id: {}", id), + } + // ANCHOR_END: here +} diff --git a/listings/ch18-patterns-and-matching/no-listing-01-literals/Cargo.lock b/listings/ch18-patterns-and-matching/no-listing-01-literals/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/no-listing-01-literals/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/no-listing-01-literals/Cargo.toml b/listings/ch18-patterns-and-matching/no-listing-01-literals/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/no-listing-01-literals/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/no-listing-01-literals/src/main.rs b/listings/ch18-patterns-and-matching/no-listing-01-literals/src/main.rs new file mode 100644 index 0000000000..7978e1adeb --- /dev/null +++ b/listings/ch18-patterns-and-matching/no-listing-01-literals/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + // ANCHOR: here + let x = 1; + + match x { + 1 => println!("one"), + 2 => println!("two"), + 3 => println!("three"), + _ => println!("anything"), + } + // ANCHOR_END: here +} diff --git a/listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/Cargo.lock b/listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/Cargo.toml b/listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/src/main.rs b/listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/src/main.rs new file mode 100644 index 0000000000..e52d815d84 --- /dev/null +++ b/listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let x = 1; + + match x { + 1 | 2 => println!("one or two"), + 3 => println!("three"), + _ => println!("anything"), + } + // ANCHOR_END: here +} diff --git a/listings/ch18-patterns-and-matching/no-listing-03-ranges/Cargo.lock b/listings/ch18-patterns-and-matching/no-listing-03-ranges/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/no-listing-03-ranges/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/no-listing-03-ranges/Cargo.toml b/listings/ch18-patterns-and-matching/no-listing-03-ranges/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/no-listing-03-ranges/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/no-listing-03-ranges/src/main.rs b/listings/ch18-patterns-and-matching/no-listing-03-ranges/src/main.rs new file mode 100644 index 0000000000..a3ebe7af06 --- /dev/null +++ b/listings/ch18-patterns-and-matching/no-listing-03-ranges/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + // ANCHOR: here + let x = 5; + + match x { + 1..=5 => println!("one through five"), + _ => println!("something else"), + } + // ANCHOR_END: here +} diff --git a/listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/Cargo.lock b/listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/Cargo.toml b/listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/src/main.rs b/listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/src/main.rs new file mode 100644 index 0000000000..8cebfef5ed --- /dev/null +++ b/listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let x = 'c'; + + match x { + 'a'..='j' => println!("early ASCII letter"), + 'k'..='z' => println!("late ASCII letter"), + _ => println!("something else"), + } + // ANCHOR_END: here +} diff --git a/listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/Cargo.lock b/listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/Cargo.toml b/listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/src/main.rs b/listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/src/main.rs new file mode 100644 index 0000000000..962d093491 --- /dev/null +++ b/listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + struct Point { + x: i32, + y: i32, + } + + // ANCHOR: here + let ((feet, inches), Point { x, y }) = ((3, 10), Point { x: 3, y: -10 }); + // ANCHOR_END: here +} diff --git a/listings/ch19-advanced-features/listing-13-21-reproduced/Cargo.lock b/listings/ch19-advanced-features/listing-13-21-reproduced/Cargo.lock new file mode 100644 index 0000000000..58b70c5b74 --- /dev/null +++ b/listings/ch19-advanced-features/listing-13-21-reproduced/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "counter" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-13-21-reproduced/Cargo.toml b/listings/ch19-advanced-features/listing-13-21-reproduced/Cargo.toml new file mode 100644 index 0000000000..4eb29e80c1 --- /dev/null +++ b/listings/ch19-advanced-features/listing-13-21-reproduced/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "counter" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-13-21-reproduced/src/lib.rs b/listings/ch19-advanced-features/listing-13-21-reproduced/src/lib.rs new file mode 100644 index 0000000000..0e65a017af --- /dev/null +++ b/listings/ch19-advanced-features/listing-13-21-reproduced/src/lib.rs @@ -0,0 +1,28 @@ +struct Counter { + count: u32, +} + +impl Counter { + fn new() -> Counter { + Counter { count: 0 } + } +} + +// ANCHOR: ch19 +impl Iterator for Counter { + type Item = u32; + + fn next(&mut self) -> Option { + // --snip-- + // ANCHOR_END: ch19 + self.count += 1; + + if self.count < 6 { + Some(self.count) + } else { + None + } + } +} + +fn main() {} diff --git a/listings/ch19-advanced-features/listing-19-01/Cargo.lock b/listings/ch19-advanced-features/listing-19-01/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-01/Cargo.toml b/listings/ch19-advanced-features/listing-19-01/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-01/src/main.rs b/listings/ch19-advanced-features/listing-19-01/src/main.rs new file mode 100644 index 0000000000..893f578905 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-01/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let mut num = 5; + + let r1 = &num as *const i32; + let r2 = &mut num as *mut i32; + // ANCHOR_END: here +} diff --git a/listings/ch19-advanced-features/listing-19-02/Cargo.lock b/listings/ch19-advanced-features/listing-19-02/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-02/Cargo.toml b/listings/ch19-advanced-features/listing-19-02/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-02/src/main.rs b/listings/ch19-advanced-features/listing-19-02/src/main.rs new file mode 100644 index 0000000000..849629a7cc --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-02/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + // ANCHOR: here + let address = 0x012345usize; + let r = address as *const i32; + // ANCHOR_END: here +} diff --git a/listings/ch19-advanced-features/listing-19-03/Cargo.lock b/listings/ch19-advanced-features/listing-19-03/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-03/Cargo.toml b/listings/ch19-advanced-features/listing-19-03/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-03/src/main.rs b/listings/ch19-advanced-features/listing-19-03/src/main.rs new file mode 100644 index 0000000000..02a0be6b0e --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-03/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + // ANCHOR: here + let mut num = 5; + + let r1 = &num as *const i32; + let r2 = &mut num as *mut i32; + + unsafe { + println!("r1 is: {}", *r1); + println!("r2 is: {}", *r2); + } + // ANCHOR_END: here +} diff --git a/listings/ch19-advanced-features/listing-19-04/Cargo.lock b/listings/ch19-advanced-features/listing-19-04/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-04/Cargo.toml b/listings/ch19-advanced-features/listing-19-04/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-04/src/main.rs b/listings/ch19-advanced-features/listing-19-04/src/main.rs new file mode 100644 index 0000000000..6ac58442db --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-04/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + // ANCHOR: here + let mut v = vec![1, 2, 3, 4, 5, 6]; + + let r = &mut v[..]; + + let (a, b) = r.split_at_mut(3); + + assert_eq!(a, &mut [1, 2, 3]); + assert_eq!(b, &mut [4, 5, 6]); + // ANCHOR_END: here +} diff --git a/listings/ch19-advanced-features/listing-19-05/Cargo.lock b/listings/ch19-advanced-features/listing-19-05/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-05/Cargo.toml b/listings/ch19-advanced-features/listing-19-05/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-05/output.txt b/listings/ch19-advanced-features/listing-19-05/output.txt new file mode 100644 index 0000000000..3df0e2b64c --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-05/output.txt @@ -0,0 +1,21 @@ +$ cargo run + Compiling unsafe-example v0.1.0 (file:///projects/unsafe-example) +error[E0499]: cannot borrow `*slice` as mutable more than once at a time + --> src/main.rs:6:30 + | +1 | fn split_at_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) { + | - let's call the lifetime of this reference `'1` +... +6 | (&mut slice[..mid], &mut slice[mid..]) + | -------------------------^^^^^-------- + | | | | + | | | second mutable borrow occurs here + | | first mutable borrow occurs here + | returning this value requires that `*slice` is borrowed for `'1` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0499`. +error: could not compile `unsafe-example`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch19-advanced-features/listing-19-05/src/main.rs b/listings/ch19-advanced-features/listing-19-05/src/main.rs new file mode 100644 index 0000000000..c4b83effaf --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-05/src/main.rs @@ -0,0 +1,14 @@ +// ANCHOR: here +fn split_at_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) { + let len = slice.len(); + + assert!(mid <= len); + + (&mut slice[..mid], &mut slice[mid..]) +} +// ANCHOR_END: here + +fn main() { + let mut vector = vec![1, 2, 3, 4, 5, 6]; + let (left, right) = split_at_mut(&mut vector, 3); +} diff --git a/listings/ch19-advanced-features/listing-19-06/Cargo.lock b/listings/ch19-advanced-features/listing-19-06/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-06/Cargo.toml b/listings/ch19-advanced-features/listing-19-06/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-06/src/main.rs b/listings/ch19-advanced-features/listing-19-06/src/main.rs new file mode 100644 index 0000000000..2bc2e5c70c --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-06/src/main.rs @@ -0,0 +1,22 @@ +// ANCHOR: here +use std::slice; + +fn split_at_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) { + let len = slice.len(); + let ptr = slice.as_mut_ptr(); + + assert!(mid <= len); + + unsafe { + ( + slice::from_raw_parts_mut(ptr, mid), + slice::from_raw_parts_mut(ptr.offset(mid as isize), len - mid), + ) + } +} +// ANCHOR_END: here + +fn main() { + let mut vector = vec![1, 2, 3, 4, 5, 6]; + let (left, right) = split_at_mut(&mut vector, 3); +} diff --git a/listings/ch19-advanced-features/listing-19-07/Cargo.lock b/listings/ch19-advanced-features/listing-19-07/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-07/Cargo.toml b/listings/ch19-advanced-features/listing-19-07/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-07/src/main.rs b/listings/ch19-advanced-features/listing-19-07/src/main.rs new file mode 100644 index 0000000000..0ab39ae1d2 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-07/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + // ANCHOR: here + use std::slice; + + let address = 0x01234usize; + let r = address as *mut i32; + + let slice: &[i32] = unsafe { slice::from_raw_parts_mut(r, 10000) }; + // ANCHOR_END: here +} diff --git a/listings/ch19-advanced-features/listing-19-08/Cargo.lock b/listings/ch19-advanced-features/listing-19-08/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-08/Cargo.toml b/listings/ch19-advanced-features/listing-19-08/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-08/src/main.rs b/listings/ch19-advanced-features/listing-19-08/src/main.rs new file mode 100644 index 0000000000..8b56630c95 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-08/src/main.rs @@ -0,0 +1,9 @@ +extern "C" { + fn abs(input: i32) -> i32; +} + +fn main() { + unsafe { + println!("Absolute value of -3 according to C: {}", abs(-3)); + } +} diff --git a/listings/ch19-advanced-features/listing-19-09/Cargo.lock b/listings/ch19-advanced-features/listing-19-09/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-09/Cargo.toml b/listings/ch19-advanced-features/listing-19-09/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-09/src/main.rs b/listings/ch19-advanced-features/listing-19-09/src/main.rs new file mode 100644 index 0000000000..82a4b4219f --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-09/src/main.rs @@ -0,0 +1,5 @@ +static HELLO_WORLD: &str = "Hello, world!"; + +fn main() { + println!("name is: {}", HELLO_WORLD); +} diff --git a/listings/ch19-advanced-features/listing-19-10/Cargo.lock b/listings/ch19-advanced-features/listing-19-10/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-10/Cargo.toml b/listings/ch19-advanced-features/listing-19-10/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-10/src/main.rs b/listings/ch19-advanced-features/listing-19-10/src/main.rs new file mode 100644 index 0000000000..e8dab68e0d --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-10/src/main.rs @@ -0,0 +1,15 @@ +static mut COUNTER: u32 = 0; + +fn add_to_count(inc: u32) { + unsafe { + COUNTER += inc; + } +} + +fn main() { + add_to_count(3); + + unsafe { + println!("COUNTER: {}", COUNTER); + } +} diff --git a/listings/ch19-advanced-features/listing-19-11/Cargo.lock b/listings/ch19-advanced-features/listing-19-11/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-11/Cargo.toml b/listings/ch19-advanced-features/listing-19-11/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-11/src/main.rs b/listings/ch19-advanced-features/listing-19-11/src/main.rs new file mode 100644 index 0000000000..885c1aa1d8 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-11/src/main.rs @@ -0,0 +1,9 @@ +unsafe trait Foo { + // methods go here +} + +unsafe impl Foo for i32 { + // method implementations go here +} + +fn main() {} diff --git a/listings/ch19-advanced-features/listing-19-12/Cargo.lock b/listings/ch19-advanced-features/listing-19-12/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-12/Cargo.toml b/listings/ch19-advanced-features/listing-19-12/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-12/src/lib.rs b/listings/ch19-advanced-features/listing-19-12/src/lib.rs new file mode 100644 index 0000000000..dbe04620ef --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-12/src/lib.rs @@ -0,0 +1,5 @@ +pub trait Iterator { + type Item; + + fn next(&mut self) -> Option; +} diff --git a/listings/ch19-advanced-features/listing-19-13/Cargo.lock b/listings/ch19-advanced-features/listing-19-13/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-13/Cargo.toml b/listings/ch19-advanced-features/listing-19-13/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-13/src/lib.rs b/listings/ch19-advanced-features/listing-19-13/src/lib.rs new file mode 100644 index 0000000000..7c9479c5b5 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-13/src/lib.rs @@ -0,0 +1,3 @@ +pub trait Iterator { + fn next(&mut self) -> Option; +} diff --git a/listings/ch19-advanced-features/listing-19-14/Cargo.lock b/listings/ch19-advanced-features/listing-19-14/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-14/Cargo.toml b/listings/ch19-advanced-features/listing-19-14/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-14/src/main.rs b/listings/ch19-advanced-features/listing-19-14/src/main.rs new file mode 100644 index 0000000000..7dea568d92 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-14/src/main.rs @@ -0,0 +1,25 @@ +use std::ops::Add; + +#[derive(Debug, PartialEq)] +struct Point { + x: i32, + y: i32, +} + +impl Add for Point { + type Output = Point; + + fn add(self, other: Point) -> Point { + Point { + x: self.x + other.x, + y: self.y + other.y, + } + } +} + +fn main() { + assert_eq!( + Point { x: 1, y: 0 } + Point { x: 2, y: 3 }, + Point { x: 3, y: 3 } + ); +} diff --git a/listings/ch19-advanced-features/listing-19-15/Cargo.lock b/listings/ch19-advanced-features/listing-19-15/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-15/Cargo.toml b/listings/ch19-advanced-features/listing-19-15/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-15/src/lib.rs b/listings/ch19-advanced-features/listing-19-15/src/lib.rs new file mode 100644 index 0000000000..f38bf475c0 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-15/src/lib.rs @@ -0,0 +1,12 @@ +use std::ops::Add; + +struct Millimeters(u32); +struct Meters(u32); + +impl Add for Millimeters { + type Output = Millimeters; + + fn add(self, other: Meters) -> Millimeters { + Millimeters(self.0 + (other.0 * 1000)) + } +} diff --git a/listings/ch19-advanced-features/listing-19-16/Cargo.lock b/listings/ch19-advanced-features/listing-19-16/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-16/Cargo.toml b/listings/ch19-advanced-features/listing-19-16/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-16/src/main.rs b/listings/ch19-advanced-features/listing-19-16/src/main.rs new file mode 100644 index 0000000000..d854e287df --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-16/src/main.rs @@ -0,0 +1,31 @@ +// ANCHOR: here +trait Pilot { + fn fly(&self); +} + +trait Wizard { + fn fly(&self); +} + +struct Human; + +impl Pilot for Human { + fn fly(&self) { + println!("This is your captain speaking."); + } +} + +impl Wizard for Human { + fn fly(&self) { + println!("Up!"); + } +} + +impl Human { + fn fly(&self) { + println!("*waving arms furiously*"); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch19-advanced-features/listing-19-17/Cargo.lock b/listings/ch19-advanced-features/listing-19-17/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-17/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-17/Cargo.toml b/listings/ch19-advanced-features/listing-19-17/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-17/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-17/src/main.rs b/listings/ch19-advanced-features/listing-19-17/src/main.rs new file mode 100644 index 0000000000..3df65a7ce2 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-17/src/main.rs @@ -0,0 +1,34 @@ +trait Pilot { + fn fly(&self); +} + +trait Wizard { + fn fly(&self); +} + +struct Human; + +impl Pilot for Human { + fn fly(&self) { + println!("This is your captain speaking."); + } +} + +impl Wizard for Human { + fn fly(&self) { + println!("Up!"); + } +} + +impl Human { + fn fly(&self) { + println!("*waving arms furiously*"); + } +} + +// ANCHOR: here +fn main() { + let person = Human; + person.fly(); +} +// ANCHOR_END: here diff --git a/listings/ch19-advanced-features/listing-19-18/Cargo.lock b/listings/ch19-advanced-features/listing-19-18/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-18/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-18/Cargo.toml b/listings/ch19-advanced-features/listing-19-18/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-18/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-18/output.txt b/listings/ch19-advanced-features/listing-19-18/output.txt new file mode 100644 index 0000000000..2e9da17d65 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-18/output.txt @@ -0,0 +1,7 @@ +$ cargo run + Compiling traits-example v0.1.0 (file:///projects/traits-example) + Finished dev [unoptimized + debuginfo] target(s) in 0.46s + Running `target/debug/traits-example` +This is your captain speaking. +Up! +*waving arms furiously* diff --git a/listings/ch19-advanced-features/listing-19-18/src/main.rs b/listings/ch19-advanced-features/listing-19-18/src/main.rs new file mode 100644 index 0000000000..fa01c09ccc --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-18/src/main.rs @@ -0,0 +1,36 @@ +trait Pilot { + fn fly(&self); +} + +trait Wizard { + fn fly(&self); +} + +struct Human; + +impl Pilot for Human { + fn fly(&self) { + println!("This is your captain speaking."); + } +} + +impl Wizard for Human { + fn fly(&self) { + println!("Up!"); + } +} + +impl Human { + fn fly(&self) { + println!("*waving arms furiously*"); + } +} + +// ANCHOR: here +fn main() { + let person = Human; + Pilot::fly(&person); + Wizard::fly(&person); + person.fly(); +} +// ANCHOR_END: here diff --git a/listings/ch19-advanced-features/listing-19-19/Cargo.lock b/listings/ch19-advanced-features/listing-19-19/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-19/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-19/Cargo.toml b/listings/ch19-advanced-features/listing-19-19/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-19/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-19/output.txt b/listings/ch19-advanced-features/listing-19-19/output.txt new file mode 100644 index 0000000000..087e802b1a --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-19/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling traits-example v0.1.0 (file:///projects/traits-example) + Finished dev [unoptimized + debuginfo] target(s) in 0.54s + Running `target/debug/traits-example` +A baby dog is called a Spot diff --git a/listings/ch19-advanced-features/listing-19-19/src/main.rs b/listings/ch19-advanced-features/listing-19-19/src/main.rs new file mode 100644 index 0000000000..44affe0ee2 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-19/src/main.rs @@ -0,0 +1,21 @@ +trait Animal { + fn baby_name() -> String; +} + +struct Dog; + +impl Dog { + fn baby_name() -> String { + String::from("Spot") + } +} + +impl Animal for Dog { + fn baby_name() -> String { + String::from("puppy") + } +} + +fn main() { + println!("A baby dog is called a {}", Dog::baby_name()); +} diff --git a/listings/ch19-advanced-features/listing-19-20/Cargo.lock b/listings/ch19-advanced-features/listing-19-20/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-20/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-20/Cargo.toml b/listings/ch19-advanced-features/listing-19-20/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-20/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-20/output.txt b/listings/ch19-advanced-features/listing-19-20/output.txt new file mode 100644 index 0000000000..b810f4e8df --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-20/output.txt @@ -0,0 +1,17 @@ +$ cargo run + Compiling traits-example v0.1.0 (file:///projects/traits-example) +error[E0283]: type annotations needed: cannot resolve `_: Animal` + --> src/main.rs:20:43 + | +2 | fn baby_name() -> String; + | ------------------------- required by `Animal::baby_name` +... +20 | println!("A baby dog is called a {}", Animal::baby_name()); + | ^^^^^^^^^^^^^^^^^ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0283`. +error: could not compile `traits-example`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch19-advanced-features/listing-19-20/src/main.rs b/listings/ch19-advanced-features/listing-19-20/src/main.rs new file mode 100644 index 0000000000..8e295c9b65 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-20/src/main.rs @@ -0,0 +1,23 @@ +trait Animal { + fn baby_name() -> String; +} + +struct Dog; + +impl Dog { + fn baby_name() -> String { + String::from("Spot") + } +} + +impl Animal for Dog { + fn baby_name() -> String { + String::from("puppy") + } +} + +// ANCHOR: here +fn main() { + println!("A baby dog is called a {}", Animal::baby_name()); +} +// ANCHOR_END: here diff --git a/listings/ch19-advanced-features/listing-19-21/Cargo.lock b/listings/ch19-advanced-features/listing-19-21/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-21/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-21/Cargo.toml b/listings/ch19-advanced-features/listing-19-21/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-21/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-21/output.txt b/listings/ch19-advanced-features/listing-19-21/output.txt new file mode 100644 index 0000000000..4d1ee5ab48 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-21/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling traits-example v0.1.0 (file:///projects/traits-example) + Finished dev [unoptimized + debuginfo] target(s) in 0.48s + Running `target/debug/traits-example` +A baby dog is called a puppy diff --git a/listings/ch19-advanced-features/listing-19-21/src/main.rs b/listings/ch19-advanced-features/listing-19-21/src/main.rs new file mode 100644 index 0000000000..b1df728951 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-21/src/main.rs @@ -0,0 +1,23 @@ +trait Animal { + fn baby_name() -> String; +} + +struct Dog; + +impl Dog { + fn baby_name() -> String { + String::from("Spot") + } +} + +impl Animal for Dog { + fn baby_name() -> String { + String::from("puppy") + } +} + +// ANCHOR: here +fn main() { + println!("A baby dog is called a {}", ::baby_name()); +} +// ANCHOR_END: here diff --git a/listings/ch19-advanced-features/listing-19-22/Cargo.lock b/listings/ch19-advanced-features/listing-19-22/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-22/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-22/Cargo.toml b/listings/ch19-advanced-features/listing-19-22/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-22/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-22/src/main.rs b/listings/ch19-advanced-features/listing-19-22/src/main.rs new file mode 100644 index 0000000000..febe58b0c5 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-22/src/main.rs @@ -0,0 +1,17 @@ +// ANCHOR: here +use std::fmt; + +trait OutlinePrint: fmt::Display { + fn outline_print(&self) { + let output = self.to_string(); + let len = output.len(); + println!("{}", "*".repeat(len + 4)); + println!("*{}*", " ".repeat(len + 2)); + println!("* {} *", output); + println!("*{}*", " ".repeat(len + 2)); + println!("{}", "*".repeat(len + 4)); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch19-advanced-features/listing-19-23/Cargo.lock b/listings/ch19-advanced-features/listing-19-23/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-23/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-23/Cargo.toml b/listings/ch19-advanced-features/listing-19-23/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-23/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-23/src/main.rs b/listings/ch19-advanced-features/listing-19-23/src/main.rs new file mode 100644 index 0000000000..eae46c92f3 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-23/src/main.rs @@ -0,0 +1,14 @@ +use std::fmt; + +struct Wrapper(Vec); + +impl fmt::Display for Wrapper { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "[{}]", self.0.join(", ")) + } +} + +fn main() { + let w = Wrapper(vec![String::from("hello"), String::from("world")]); + println!("w = {}", w); +} diff --git a/listings/ch19-advanced-features/listing-19-24/Cargo.lock b/listings/ch19-advanced-features/listing-19-24/Cargo.lock new file mode 100644 index 0000000000..c0c98a79cf --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-24/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "types-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-24/Cargo.toml b/listings/ch19-advanced-features/listing-19-24/Cargo.toml new file mode 100644 index 0000000000..9b4ee689bf --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-24/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "types-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-24/src/main.rs b/listings/ch19-advanced-features/listing-19-24/src/main.rs new file mode 100644 index 0000000000..d604ae8d6a --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-24/src/main.rs @@ -0,0 +1,16 @@ +fn main() { + // ANCHOR: here + let f: Box = Box::new(|| println!("hi")); + + fn takes_long_type(f: Box) { + // --snip-- + } + + fn returns_long_type() -> Box { + // --snip-- + // ANCHOR_END: here + Box::new(|| ()) + // ANCHOR: here + } + // ANCHOR_END: here +} diff --git a/listings/ch19-advanced-features/listing-19-25/Cargo.lock b/listings/ch19-advanced-features/listing-19-25/Cargo.lock new file mode 100644 index 0000000000..c0c98a79cf --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-25/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "types-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-25/Cargo.toml b/listings/ch19-advanced-features/listing-19-25/Cargo.toml new file mode 100644 index 0000000000..9b4ee689bf --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-25/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "types-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-25/src/main.rs b/listings/ch19-advanced-features/listing-19-25/src/main.rs new file mode 100644 index 0000000000..af35bed2c9 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-25/src/main.rs @@ -0,0 +1,18 @@ +fn main() { + // ANCHOR: here + type Thunk = Box; + + let f: Thunk = Box::new(|| println!("hi")); + + fn takes_long_type(f: Thunk) { + // --snip-- + } + + fn returns_long_type() -> Thunk { + // --snip-- + // ANCHOR_END: here + Box::new(|| ()) + // ANCHOR: here + } + // ANCHOR_END: here +} diff --git a/listings/ch19-advanced-features/listing-19-27/Cargo.lock b/listings/ch19-advanced-features/listing-19-27/Cargo.lock new file mode 100644 index 0000000000..b2327c755a --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-27/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-27/Cargo.toml b/listings/ch19-advanced-features/listing-19-27/Cargo.toml new file mode 100644 index 0000000000..2bed56c367 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-27/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-27/src/main.rs b/listings/ch19-advanced-features/listing-19-27/src/main.rs new file mode 100644 index 0000000000..91b2cf04bf --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-27/src/main.rs @@ -0,0 +1,13 @@ +fn add_one(x: i32) -> i32 { + x + 1 +} + +fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 { + f(arg) + f(arg) +} + +fn main() { + let answer = do_twice(add_one, 5); + + println!("The answer is: {}", answer); +} diff --git a/listings/ch19-advanced-features/listing-19-28/Cargo.lock b/listings/ch19-advanced-features/listing-19-28/Cargo.lock new file mode 100644 index 0000000000..b2d9257545 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-28/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "macros-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-28/Cargo.toml b/listings/ch19-advanced-features/listing-19-28/Cargo.toml new file mode 100644 index 0000000000..1829b0fa66 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-28/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "macros-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-28/src/lib.rs b/listings/ch19-advanced-features/listing-19-28/src/lib.rs new file mode 100644 index 0000000000..7c7c4756c8 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-28/src/lib.rs @@ -0,0 +1,12 @@ +#[macro_export] +macro_rules! vec { + ( $( $x:expr ),* ) => { + { + let mut temp_vec = Vec::new(); + $( + temp_vec.push($x); + )* + temp_vec + } + }; +} diff --git a/listings/ch19-advanced-features/listing-19-30/Cargo.lock b/listings/ch19-advanced-features/listing-19-30/Cargo.lock new file mode 100644 index 0000000000..39afcf282f --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-30/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello_macro" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-30/Cargo.toml b/listings/ch19-advanced-features/listing-19-30/Cargo.toml new file mode 100644 index 0000000000..5a93a685c0 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-30/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello_macro" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-30/src/main.rs b/listings/ch19-advanced-features/listing-19-30/src/main.rs new file mode 100644 index 0000000000..468c30aa48 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-30/src/main.rs @@ -0,0 +1,9 @@ +use hello_macro::HelloMacro; +use hello_macro_derive::HelloMacro; + +#[derive(HelloMacro)] +struct Pancakes; + +fn main() { + Pancakes::hello_macro(); +} diff --git a/listings/ch19-advanced-features/listing-19-31/hello_macro/Cargo.lock b/listings/ch19-advanced-features/listing-19-31/hello_macro/Cargo.lock new file mode 100644 index 0000000000..39afcf282f --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-31/hello_macro/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello_macro" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-31/hello_macro/Cargo.toml b/listings/ch19-advanced-features/listing-19-31/hello_macro/Cargo.toml new file mode 100644 index 0000000000..5a93a685c0 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-31/hello_macro/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello_macro" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/Cargo.lock b/listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/Cargo.lock new file mode 100644 index 0000000000..d6a2f84a96 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/Cargo.lock @@ -0,0 +1,46 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello_macro_derive" +version = "0.1.0" +dependencies = [ + "quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.14.9 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "proc-macro2" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "quote" +version = "0.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.29 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "syn" +version = "0.14.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.29 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "unicode-xid" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum proc-macro2 0.4.29 (registry+https://github.com/rust-lang/crates.io-index)" = "64c827cea7a7ab30ce4593e5e04d7a11617ad6ece2fa230605a78b00ff965316" +"checksum quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)" = "faf4799c5d274f3868a4aae320a0a182cbd2baee377b378f080e16a23e9d80db" +"checksum syn 0.14.9 (registry+https://github.com/rust-lang/crates.io-index)" = "261ae9ecaa397c42b960649561949d69311f08eeaea86a65696e6e46517cf741" +"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" diff --git a/listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/Cargo.toml b/listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/Cargo.toml new file mode 100644 index 0000000000..a6df8313ef --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "hello_macro_derive" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[lib] +proc-macro = true + +[dependencies] +syn = "0.14.4" +quote = "0.6.3" diff --git a/listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/src/lib.rs b/listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/src/lib.rs new file mode 100644 index 0000000000..a295f37c73 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/src/lib.rs @@ -0,0 +1,15 @@ +extern crate proc_macro; + +use crate::proc_macro::TokenStream; +use quote::quote; +use syn; + +#[proc_macro_derive(HelloMacro)] +pub fn hello_macro_derive(input: TokenStream) -> TokenStream { + // Construct a representation of Rust code as a syntax tree + // that we can manipulate + let ast = syn::parse(input).unwrap(); + + // Build the trait implementation + impl_hello_macro(&ast) +} diff --git a/listings/ch19-advanced-features/listing-19-31/hello_macro/src/lib.rs b/listings/ch19-advanced-features/listing-19-31/hello_macro/src/lib.rs new file mode 100644 index 0000000000..e74793184b --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-31/hello_macro/src/lib.rs @@ -0,0 +1,3 @@ +pub trait HelloMacro { + fn hello_macro(); +} diff --git a/listings/ch19-advanced-features/listing-19-31/hello_macro/src/main.rs b/listings/ch19-advanced-features/listing-19-31/hello_macro/src/main.rs new file mode 100644 index 0000000000..10b028b2d4 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-31/hello_macro/src/main.rs @@ -0,0 +1,13 @@ +use hello_macro::HelloMacro; + +struct Pancakes; + +impl HelloMacro for Pancakes { + fn hello_macro() { + println!("Hello, Macro! My name is Pancakes!"); + } +} + +fn main() { + Pancakes::hello_macro(); +} diff --git a/listings/ch19-advanced-features/listing-19-33/hello_macro/Cargo.lock b/listings/ch19-advanced-features/listing-19-33/hello_macro/Cargo.lock new file mode 100644 index 0000000000..39afcf282f --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-33/hello_macro/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello_macro" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/listing-19-33/hello_macro/Cargo.toml b/listings/ch19-advanced-features/listing-19-33/hello_macro/Cargo.toml new file mode 100644 index 0000000000..5a93a685c0 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-33/hello_macro/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello_macro" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/Cargo.lock b/listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/Cargo.lock new file mode 100644 index 0000000000..d6a2f84a96 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/Cargo.lock @@ -0,0 +1,46 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello_macro_derive" +version = "0.1.0" +dependencies = [ + "quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.14.9 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "proc-macro2" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "quote" +version = "0.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.29 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "syn" +version = "0.14.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.29 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "unicode-xid" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum proc-macro2 0.4.29 (registry+https://github.com/rust-lang/crates.io-index)" = "64c827cea7a7ab30ce4593e5e04d7a11617ad6ece2fa230605a78b00ff965316" +"checksum quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)" = "faf4799c5d274f3868a4aae320a0a182cbd2baee377b378f080e16a23e9d80db" +"checksum syn 0.14.9 (registry+https://github.com/rust-lang/crates.io-index)" = "261ae9ecaa397c42b960649561949d69311f08eeaea86a65696e6e46517cf741" +"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" diff --git a/listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/Cargo.toml b/listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/Cargo.toml new file mode 100644 index 0000000000..a6df8313ef --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "hello_macro_derive" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[lib] +proc-macro = true + +[dependencies] +syn = "0.14.4" +quote = "0.6.3" diff --git a/listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/src/lib.rs b/listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/src/lib.rs new file mode 100644 index 0000000000..9d3f10bd17 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/src/lib.rs @@ -0,0 +1,29 @@ +extern crate proc_macro; + +use crate::proc_macro::TokenStream; +use quote::quote; +use syn; + +#[proc_macro_derive(HelloMacro)] +pub fn hello_macro_derive(input: TokenStream) -> TokenStream { + // Construct a representation of Rust code as a syntax tree + // that we can manipulate + let ast = syn::parse(input).unwrap(); + + // Build the trait implementation + impl_hello_macro(&ast) +} + +// ANCHOR: here +fn impl_hello_macro(ast: &syn::DeriveInput) -> TokenStream { + let name = &ast.ident; + let gen = quote! { + impl HelloMacro for #name { + fn hello_macro() { + println!("Hello, Macro! My name is {}", stringify!(#name)); + } + } + }; + gen.into() +} +// ANCHOR_END: here diff --git a/listings/ch19-advanced-features/listing-19-33/hello_macro/src/lib.rs b/listings/ch19-advanced-features/listing-19-33/hello_macro/src/lib.rs new file mode 100644 index 0000000000..e74793184b --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-33/hello_macro/src/lib.rs @@ -0,0 +1,3 @@ +pub trait HelloMacro { + fn hello_macro(); +} diff --git a/listings/ch19-advanced-features/listing-19-33/hello_macro/src/main.rs b/listings/ch19-advanced-features/listing-19-33/hello_macro/src/main.rs new file mode 100644 index 0000000000..10b028b2d4 --- /dev/null +++ b/listings/ch19-advanced-features/listing-19-33/hello_macro/src/main.rs @@ -0,0 +1,13 @@ +use hello_macro::HelloMacro; + +struct Pancakes; + +impl HelloMacro for Pancakes { + fn hello_macro() { + println!("Hello, Macro! My name is Pancakes!"); + } +} + +fn main() { + Pancakes::hello_macro(); +} diff --git a/listings/ch19-advanced-features/no-listing-01-unsafe-fn/Cargo.lock b/listings/ch19-advanced-features/no-listing-01-unsafe-fn/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-01-unsafe-fn/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/no-listing-01-unsafe-fn/Cargo.toml b/listings/ch19-advanced-features/no-listing-01-unsafe-fn/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-01-unsafe-fn/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/no-listing-01-unsafe-fn/src/main.rs b/listings/ch19-advanced-features/no-listing-01-unsafe-fn/src/main.rs new file mode 100644 index 0000000000..21ecdbe5af --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-01-unsafe-fn/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + // ANCHOR: here + unsafe fn dangerous() {} + + unsafe { + dangerous(); + } + // ANCHOR_END: here +} diff --git a/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/Cargo.lock b/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/Cargo.toml b/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/output.txt b/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/output.txt new file mode 100644 index 0000000000..e7a028e351 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/output.txt @@ -0,0 +1,17 @@ +$ cargo run + Compiling traits-example v0.1.0 (file:///projects/traits-example) +error[E0277]: `Point` doesn't implement `std::fmt::Display` + --> src/main.rs:20:6 + | +20 | impl OutlinePrint for Point {} + | ^^^^^^^^^^^^ `Point` cannot be formatted with the default formatter + | + = help: the trait `std::fmt::Display` is not implemented for `Point` + = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. +error: could not compile `traits-example`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/src/main.rs b/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/src/main.rs new file mode 100644 index 0000000000..a1e2fe4c46 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/src/main.rs @@ -0,0 +1,27 @@ +use std::fmt; + +trait OutlinePrint: fmt::Display { + fn outline_print(&self) { + let output = self.to_string(); + let len = output.len(); + println!("{}", "*".repeat(len + 4)); + println!("*{}*", " ".repeat(len + 2)); + println!("* {} *", output); + println!("*{}*", " ".repeat(len + 2)); + println!("{}", "*".repeat(len + 4)); + } +} + +// ANCHOR: here +struct Point { + x: i32, + y: i32, +} + +impl OutlinePrint for Point {} +// ANCHOR_END: here + +fn main() { + let p = Point { x: 1, y: 3 }; + p.outline_print(); +} diff --git a/listings/ch19-advanced-features/no-listing-03-impl-display-for-point/Cargo.lock b/listings/ch19-advanced-features/no-listing-03-impl-display-for-point/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-03-impl-display-for-point/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/no-listing-03-impl-display-for-point/Cargo.toml b/listings/ch19-advanced-features/no-listing-03-impl-display-for-point/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-03-impl-display-for-point/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/no-listing-03-impl-display-for-point/src/main.rs b/listings/ch19-advanced-features/no-listing-03-impl-display-for-point/src/main.rs new file mode 100644 index 0000000000..c7bbb6a708 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-03-impl-display-for-point/src/main.rs @@ -0,0 +1,33 @@ +trait OutlinePrint: fmt::Display { + fn outline_print(&self) { + let output = self.to_string(); + let len = output.len(); + println!("{}", "*".repeat(len + 4)); + println!("*{}*", " ".repeat(len + 2)); + println!("* {} *", output); + println!("*{}*", " ".repeat(len + 2)); + println!("{}", "*".repeat(len + 4)); + } +} + +struct Point { + x: i32, + y: i32, +} + +impl OutlinePrint for Point {} + +// ANCHOR: here +use std::fmt; + +impl fmt::Display for Point { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "({}, {})", self.x, self.y) + } +} +// ANCHOR_END: here + +fn main() { + let p = Point { x: 1, y: 3 }; + p.outline_print(); +} diff --git a/listings/ch19-advanced-features/no-listing-04-kilometers-alias/Cargo.lock b/listings/ch19-advanced-features/no-listing-04-kilometers-alias/Cargo.lock new file mode 100644 index 0000000000..c0c98a79cf --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-04-kilometers-alias/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "types-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/no-listing-04-kilometers-alias/Cargo.toml b/listings/ch19-advanced-features/no-listing-04-kilometers-alias/Cargo.toml new file mode 100644 index 0000000000..9b4ee689bf --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-04-kilometers-alias/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "types-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/no-listing-04-kilometers-alias/src/main.rs b/listings/ch19-advanced-features/no-listing-04-kilometers-alias/src/main.rs new file mode 100644 index 0000000000..d3fe32e2f0 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-04-kilometers-alias/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + // ANCHOR: there + // ANCHOR: here + type Kilometers = i32; + // ANCHOR_END: here + + let x: i32 = 5; + let y: Kilometers = 5; + + println!("x + y = {}", x + y); + // ANCHOR_END: there +} diff --git a/listings/ch19-advanced-features/no-listing-05-write-trait/Cargo.lock b/listings/ch19-advanced-features/no-listing-05-write-trait/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-05-write-trait/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/no-listing-05-write-trait/Cargo.toml b/listings/ch19-advanced-features/no-listing-05-write-trait/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-05-write-trait/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/no-listing-05-write-trait/src/lib.rs b/listings/ch19-advanced-features/no-listing-05-write-trait/src/lib.rs new file mode 100644 index 0000000000..8300dcceee --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-05-write-trait/src/lib.rs @@ -0,0 +1,10 @@ +use std::fmt; +use std::io::Error; + +pub trait Write { + fn write(&mut self, buf: &[u8]) -> Result; + fn flush(&mut self) -> Result<(), Error>; + + fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>; + fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<(), Error>; +} diff --git a/listings/ch19-advanced-features/no-listing-06-result-alias/Cargo.lock b/listings/ch19-advanced-features/no-listing-06-result-alias/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-06-result-alias/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/no-listing-06-result-alias/Cargo.toml b/listings/ch19-advanced-features/no-listing-06-result-alias/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-06-result-alias/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/no-listing-06-result-alias/src/lib.rs b/listings/ch19-advanced-features/no-listing-06-result-alias/src/lib.rs new file mode 100644 index 0000000000..c53a927e32 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-06-result-alias/src/lib.rs @@ -0,0 +1,17 @@ +use std::fmt; + +// ANCHOR: here +type Result = std::result::Result; +// ANCHOR_END: here + +// ANCHOR: there +pub trait Write { + fn write(&mut self, buf: &[u8]) -> Result; + fn flush(&mut self) -> Result<()>; + + fn write_all(&mut self, buf: &[u8]) -> Result<()>; + fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()>; +} +// ANCHOR_END: there + +fn main() {} diff --git a/listings/ch19-advanced-features/no-listing-07-never-type/Cargo.lock b/listings/ch19-advanced-features/no-listing-07-never-type/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-07-never-type/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/no-listing-07-never-type/Cargo.toml b/listings/ch19-advanced-features/no-listing-07-never-type/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-07-never-type/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/no-listing-07-never-type/src/lib.rs b/listings/ch19-advanced-features/no-listing-07-never-type/src/lib.rs new file mode 100644 index 0000000000..236224186e --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-07-never-type/src/lib.rs @@ -0,0 +1,10 @@ +// ANCHOR: here +fn bar() -> ! { + // --snip-- + // ANCHOR_END: here + panic!(); + // ANCHOR: here +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch19-advanced-features/no-listing-08-match-arms-different-types/Cargo.lock b/listings/ch19-advanced-features/no-listing-08-match-arms-different-types/Cargo.lock new file mode 100644 index 0000000000..c0c98a79cf --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-08-match-arms-different-types/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "types-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/no-listing-08-match-arms-different-types/Cargo.toml b/listings/ch19-advanced-features/no-listing-08-match-arms-different-types/Cargo.toml new file mode 100644 index 0000000000..9b4ee689bf --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-08-match-arms-different-types/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "types-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/no-listing-08-match-arms-different-types/src/main.rs b/listings/ch19-advanced-features/no-listing-08-match-arms-different-types/src/main.rs new file mode 100644 index 0000000000..6d56008add --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-08-match-arms-different-types/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let guess = "3"; + // ANCHOR: here + let guess = match guess.trim().parse() { + Ok(_) => 5, + Err(_) => "hello", + }; + // ANCHOR_END: here +} diff --git a/listings/ch19-advanced-features/no-listing-09-unwrap-definition/Cargo.lock b/listings/ch19-advanced-features/no-listing-09-unwrap-definition/Cargo.lock new file mode 100644 index 0000000000..c0c98a79cf --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-09-unwrap-definition/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "types-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/no-listing-09-unwrap-definition/Cargo.toml b/listings/ch19-advanced-features/no-listing-09-unwrap-definition/Cargo.toml new file mode 100644 index 0000000000..9b4ee689bf --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-09-unwrap-definition/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "types-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/no-listing-09-unwrap-definition/src/lib.rs b/listings/ch19-advanced-features/no-listing-09-unwrap-definition/src/lib.rs new file mode 100644 index 0000000000..aa4f937ff0 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-09-unwrap-definition/src/lib.rs @@ -0,0 +1,17 @@ +enum Option { + Some(T), + None, +} + +use crate::Option::*; + +// ANCHOR: here +impl Option { + pub fn unwrap(self) -> T { + match self { + Some(val) => val, + None => panic!("called `Option::unwrap()` on a `None` value"), + } + } +} +// ANCHOR_END: here diff --git a/listings/ch19-advanced-features/no-listing-10-loop-returns-never/Cargo.lock b/listings/ch19-advanced-features/no-listing-10-loop-returns-never/Cargo.lock new file mode 100644 index 0000000000..c0c98a79cf --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-10-loop-returns-never/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "types-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/no-listing-10-loop-returns-never/Cargo.toml b/listings/ch19-advanced-features/no-listing-10-loop-returns-never/Cargo.toml new file mode 100644 index 0000000000..9b4ee689bf --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-10-loop-returns-never/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "types-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/no-listing-10-loop-returns-never/src/main.rs b/listings/ch19-advanced-features/no-listing-10-loop-returns-never/src/main.rs new file mode 100644 index 0000000000..e7768913b7 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-10-loop-returns-never/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + // ANCHOR: here + print!("forever "); + + loop { + print!("and ever "); + } + // ANCHOR_END: here +} diff --git a/listings/ch19-advanced-features/no-listing-11-cant-create-str/Cargo.lock b/listings/ch19-advanced-features/no-listing-11-cant-create-str/Cargo.lock new file mode 100644 index 0000000000..c0c98a79cf --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-11-cant-create-str/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "types-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/no-listing-11-cant-create-str/Cargo.toml b/listings/ch19-advanced-features/no-listing-11-cant-create-str/Cargo.toml new file mode 100644 index 0000000000..9b4ee689bf --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-11-cant-create-str/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "types-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/no-listing-11-cant-create-str/src/main.rs b/listings/ch19-advanced-features/no-listing-11-cant-create-str/src/main.rs new file mode 100644 index 0000000000..075d5110c0 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-11-cant-create-str/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + // ANCHOR: here + let s1: str = "Hello there!"; + let s2: str = "How's it going?"; + // ANCHOR_END: here +} diff --git a/listings/ch19-advanced-features/no-listing-12-generic-fn-definition/Cargo.lock b/listings/ch19-advanced-features/no-listing-12-generic-fn-definition/Cargo.lock new file mode 100644 index 0000000000..c0c98a79cf --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-12-generic-fn-definition/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "types-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/no-listing-12-generic-fn-definition/Cargo.toml b/listings/ch19-advanced-features/no-listing-12-generic-fn-definition/Cargo.toml new file mode 100644 index 0000000000..9b4ee689bf --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-12-generic-fn-definition/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "types-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/no-listing-12-generic-fn-definition/src/lib.rs b/listings/ch19-advanced-features/no-listing-12-generic-fn-definition/src/lib.rs new file mode 100644 index 0000000000..69186ddfb6 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-12-generic-fn-definition/src/lib.rs @@ -0,0 +1,3 @@ +fn generic(t: T) { + // --snip-- +} diff --git a/listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/Cargo.lock b/listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/Cargo.lock new file mode 100644 index 0000000000..c0c98a79cf --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "types-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/Cargo.toml b/listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/Cargo.toml new file mode 100644 index 0000000000..9b4ee689bf --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "types-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/src/lib.rs b/listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/src/lib.rs new file mode 100644 index 0000000000..c2d00e2163 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/src/lib.rs @@ -0,0 +1,3 @@ +fn generic(t: T) { + // --snip-- +} diff --git a/listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/Cargo.lock b/listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/Cargo.lock new file mode 100644 index 0000000000..c0c98a79cf --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "types-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/Cargo.toml b/listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/Cargo.toml new file mode 100644 index 0000000000..9b4ee689bf --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "types-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/src/lib.rs b/listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/src/lib.rs new file mode 100644 index 0000000000..e4722267ab --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/src/lib.rs @@ -0,0 +1,3 @@ +fn generic(t: &T) { + // --snip-- +} diff --git a/listings/ch19-advanced-features/no-listing-15-map-closure/Cargo.lock b/listings/ch19-advanced-features/no-listing-15-map-closure/Cargo.lock new file mode 100644 index 0000000000..b2327c755a --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-15-map-closure/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/no-listing-15-map-closure/Cargo.toml b/listings/ch19-advanced-features/no-listing-15-map-closure/Cargo.toml new file mode 100644 index 0000000000..2bed56c367 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-15-map-closure/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/no-listing-15-map-closure/src/main.rs b/listings/ch19-advanced-features/no-listing-15-map-closure/src/main.rs new file mode 100644 index 0000000000..b4fcf7eb85 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-15-map-closure/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + // ANCHOR: here + let list_of_numbers = vec![1, 2, 3]; + let list_of_strings: Vec = + list_of_numbers.iter().map(|i| i.to_string()).collect(); + // ANCHOR_END: here +} diff --git a/listings/ch19-advanced-features/no-listing-16-map-function/Cargo.lock b/listings/ch19-advanced-features/no-listing-16-map-function/Cargo.lock new file mode 100644 index 0000000000..b2327c755a --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-16-map-function/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/no-listing-16-map-function/Cargo.toml b/listings/ch19-advanced-features/no-listing-16-map-function/Cargo.toml new file mode 100644 index 0000000000..2bed56c367 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-16-map-function/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/no-listing-16-map-function/src/main.rs b/listings/ch19-advanced-features/no-listing-16-map-function/src/main.rs new file mode 100644 index 0000000000..dff20fe71b --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-16-map-function/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + // ANCHOR: here + let list_of_numbers = vec![1, 2, 3]; + let list_of_strings: Vec = + list_of_numbers.iter().map(ToString::to_string).collect(); + // ANCHOR_END: here +} diff --git a/listings/ch19-advanced-features/no-listing-17-map-initializer/Cargo.lock b/listings/ch19-advanced-features/no-listing-17-map-initializer/Cargo.lock new file mode 100644 index 0000000000..b2327c755a --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-17-map-initializer/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/no-listing-17-map-initializer/Cargo.toml b/listings/ch19-advanced-features/no-listing-17-map-initializer/Cargo.toml new file mode 100644 index 0000000000..2bed56c367 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-17-map-initializer/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/no-listing-17-map-initializer/src/main.rs b/listings/ch19-advanced-features/no-listing-17-map-initializer/src/main.rs new file mode 100644 index 0000000000..60fb730057 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-17-map-initializer/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + // ANCHOR: here + enum Status { + Value(u32), + Stop, + } + + let list_of_statuses: Vec = (0u32..20).map(Status::Value).collect(); + // ANCHOR_END: here +} diff --git a/listings/ch19-advanced-features/no-listing-18-returns-closure/Cargo.lock b/listings/ch19-advanced-features/no-listing-18-returns-closure/Cargo.lock new file mode 100644 index 0000000000..b2327c755a --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-18-returns-closure/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/no-listing-18-returns-closure/Cargo.toml b/listings/ch19-advanced-features/no-listing-18-returns-closure/Cargo.toml new file mode 100644 index 0000000000..2bed56c367 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-18-returns-closure/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/no-listing-18-returns-closure/output.txt b/listings/ch19-advanced-features/no-listing-18-returns-closure/output.txt new file mode 100644 index 0000000000..e315cbc5f0 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-18-returns-closure/output.txt @@ -0,0 +1,30 @@ +$ cargo build + Compiling functions-example v0.1.0 (file:///projects/functions-example) +error[E0277]: the size for values of type `(dyn std::ops::Fn(i32) -> i32 + 'static)` cannot be known at compilation time + --> src/lib.rs:1:25 + | +1 | fn returns_closure() -> dyn Fn(i32) -> i32 { + | ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time + | + = help: the trait `std::marker::Sized` is not implemented for `(dyn std::ops::Fn(i32) -> i32 + 'static)` + = note: to learn more, visit + = note: the return type of a function must have a statically known size + +error[E0308]: mismatched types + --> src/lib.rs:2:5 + | +1 | fn returns_closure() -> dyn Fn(i32) -> i32 { + | ------------------ expected `(dyn std::ops::Fn(i32) -> i32 + 'static)` because of return type +2 | |x| x + 1 + | ^^^^^^^^^ expected trait std::ops::Fn, found closure + | + = note: expected type `(dyn std::ops::Fn(i32) -> i32 + 'static)` + found type `[closure@src/lib.rs:2:5: 2:14]` + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0277, E0308. +For more information about an error, try `rustc --explain E0277`. +error: could not compile `functions-example`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch19-advanced-features/no-listing-18-returns-closure/src/lib.rs b/listings/ch19-advanced-features/no-listing-18-returns-closure/src/lib.rs new file mode 100644 index 0000000000..d699ac34eb --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-18-returns-closure/src/lib.rs @@ -0,0 +1,3 @@ +fn returns_closure() -> dyn Fn(i32) -> i32 { + |x| x + 1 +} diff --git a/listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/Cargo.lock b/listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/Cargo.lock new file mode 100644 index 0000000000..b2327c755a --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/Cargo.toml b/listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/Cargo.toml new file mode 100644 index 0000000000..2bed56c367 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/src/lib.rs b/listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/src/lib.rs new file mode 100644 index 0000000000..b114077472 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/src/lib.rs @@ -0,0 +1,3 @@ +fn returns_closure() -> Box i32> { + Box::new(|x| x + 1) +} diff --git a/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/Cargo.lock b/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/Cargo.lock new file mode 100644 index 0000000000..39afcf282f --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello_macro" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/Cargo.toml b/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/Cargo.toml new file mode 100644 index 0000000000..5a93a685c0 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello_macro" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/src/lib.rs b/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/src/lib.rs new file mode 100644 index 0000000000..e74793184b --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/src/lib.rs @@ -0,0 +1,3 @@ +pub trait HelloMacro { + fn hello_macro(); +} diff --git a/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/Cargo.lock b/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/Cargo.lock new file mode 100644 index 0000000000..881cd3f6df --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/Cargo.lock @@ -0,0 +1,13 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello_macro" +version = "0.1.0" + +[[package]] +name = "pancakes" +version = "0.1.0" +dependencies = [ + "hello_macro 0.1.0", +] + diff --git a/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/Cargo.toml b/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/Cargo.toml new file mode 100644 index 0000000000..4b6c267b42 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "pancakes" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] +hello_macro = { path = "../hello_macro" } \ No newline at end of file diff --git a/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/src/main.rs b/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/src/main.rs new file mode 100644 index 0000000000..10b028b2d4 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/src/main.rs @@ -0,0 +1,13 @@ +use hello_macro::HelloMacro; + +struct Pancakes; + +impl HelloMacro for Pancakes { + fn hello_macro() { + println!("Hello, Macro! My name is Pancakes!"); + } +} + +fn main() { + Pancakes::hello_macro(); +} diff --git a/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/Cargo.lock b/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/Cargo.lock new file mode 100644 index 0000000000..39afcf282f --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello_macro" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/Cargo.toml b/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/Cargo.toml new file mode 100644 index 0000000000..5a93a685c0 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello_macro" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/hello_macro_derive/Cargo.lock b/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/hello_macro_derive/Cargo.lock new file mode 100644 index 0000000000..d6a2f84a96 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/hello_macro_derive/Cargo.lock @@ -0,0 +1,46 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello_macro_derive" +version = "0.1.0" +dependencies = [ + "quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.14.9 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "proc-macro2" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "quote" +version = "0.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.29 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "syn" +version = "0.14.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.29 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "unicode-xid" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum proc-macro2 0.4.29 (registry+https://github.com/rust-lang/crates.io-index)" = "64c827cea7a7ab30ce4593e5e04d7a11617ad6ece2fa230605a78b00ff965316" +"checksum quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)" = "faf4799c5d274f3868a4aae320a0a182cbd2baee377b378f080e16a23e9d80db" +"checksum syn 0.14.9 (registry+https://github.com/rust-lang/crates.io-index)" = "261ae9ecaa397c42b960649561949d69311f08eeaea86a65696e6e46517cf741" +"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" diff --git a/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/hello_macro_derive/Cargo.toml b/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/hello_macro_derive/Cargo.toml new file mode 100644 index 0000000000..a6df8313ef --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/hello_macro_derive/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "hello_macro_derive" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[lib] +proc-macro = true + +[dependencies] +syn = "0.14.4" +quote = "0.6.3" diff --git a/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/hello_macro_derive/src/lib.rs b/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/hello_macro_derive/src/lib.rs new file mode 100644 index 0000000000..2ba3d8a63d --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/hello_macro_derive/src/lib.rs @@ -0,0 +1,27 @@ +extern crate proc_macro; + +use crate::proc_macro::TokenStream; +use quote::quote; +use syn; + +#[proc_macro_derive(HelloMacro)] +pub fn hello_macro_derive(input: TokenStream) -> TokenStream { + // Construct a representation of Rust code as a syntax tree + // that we can manipulate + let ast = syn::parse(input).unwrap(); + + // Build the trait implementation + impl_hello_macro(&ast) +} + +fn impl_hello_macro(ast: &syn::DeriveInput) -> TokenStream { + let name = &ast.ident; + let gen = quote! { + impl HelloMacro for #name { + fn hello_macro() { + println!("Hello, Macro! My name is {}", stringify!(#name)); + } + } + }; + gen.into() +} diff --git a/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/src/lib.rs b/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/src/lib.rs new file mode 100644 index 0000000000..e74793184b --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/src/lib.rs @@ -0,0 +1,3 @@ +pub trait HelloMacro { + fn hello_macro(); +} diff --git a/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/src/main.rs b/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/src/main.rs new file mode 100644 index 0000000000..10b028b2d4 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/src/main.rs @@ -0,0 +1,13 @@ +use hello_macro::HelloMacro; + +struct Pancakes; + +impl HelloMacro for Pancakes { + fn hello_macro() { + println!("Hello, Macro! My name is Pancakes!"); + } +} + +fn main() { + Pancakes::hello_macro(); +} diff --git a/listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/Cargo.lock b/listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/Cargo.lock new file mode 100644 index 0000000000..51efd639aa --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/Cargo.lock @@ -0,0 +1,58 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello_macro" +version = "0.1.0" + +[[package]] +name = "hello_macro_derive" +version = "0.1.0" +dependencies = [ + "quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.14.9 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "pancakes" +version = "0.1.0" +dependencies = [ + "hello_macro 0.1.0", + "hello_macro_derive 0.1.0", +] + +[[package]] +name = "proc-macro2" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "quote" +version = "0.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.29 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "syn" +version = "0.14.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.29 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "unicode-xid" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum proc-macro2 0.4.29 (registry+https://github.com/rust-lang/crates.io-index)" = "64c827cea7a7ab30ce4593e5e04d7a11617ad6ece2fa230605a78b00ff965316" +"checksum quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)" = "faf4799c5d274f3868a4aae320a0a182cbd2baee377b378f080e16a23e9d80db" +"checksum syn 0.14.9 (registry+https://github.com/rust-lang/crates.io-index)" = "261ae9ecaa397c42b960649561949d69311f08eeaea86a65696e6e46517cf741" +"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" diff --git a/listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/Cargo.toml b/listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/Cargo.toml new file mode 100644 index 0000000000..cc0addaa4a --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "pancakes" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] +hello_macro = { path = "../hello_macro" } +hello_macro_derive = { path = "../hello_macro/hello_macro_derive" } diff --git a/listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/src/main.rs b/listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/src/main.rs new file mode 100644 index 0000000000..468c30aa48 --- /dev/null +++ b/listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/src/main.rs @@ -0,0 +1,9 @@ +use hello_macro::HelloMacro; +use hello_macro_derive::HelloMacro; + +#[derive(HelloMacro)] +struct Pancakes; + +fn main() { + Pancakes::hello_macro(); +} diff --git a/listings/ch19-advanced-features/output-only-01-missing-unsafe/Cargo.lock b/listings/ch19-advanced-features/output-only-01-missing-unsafe/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/listings/ch19-advanced-features/output-only-01-missing-unsafe/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/listings/ch19-advanced-features/output-only-01-missing-unsafe/Cargo.toml b/listings/ch19-advanced-features/output-only-01-missing-unsafe/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/listings/ch19-advanced-features/output-only-01-missing-unsafe/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch19-advanced-features/output-only-01-missing-unsafe/output.txt b/listings/ch19-advanced-features/output-only-01-missing-unsafe/output.txt new file mode 100644 index 0000000000..bfe082a8b9 --- /dev/null +++ b/listings/ch19-advanced-features/output-only-01-missing-unsafe/output.txt @@ -0,0 +1,16 @@ +$ cargo run + Compiling unsafe-example v0.1.0 (file:///projects/unsafe-example) +error[E0133]: call to unsafe function is unsafe and requires unsafe function or block + --> src/main.rs:4:5 + | +4 | dangerous(); + | ^^^^^^^^^^^ call to unsafe function + | + = note: consult the function's documentation for information on how to avoid undefined behavior + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0133`. +error: could not compile `unsafe-example`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch19-advanced-features/output-only-01-missing-unsafe/src/main.rs b/listings/ch19-advanced-features/output-only-01-missing-unsafe/src/main.rs new file mode 100644 index 0000000000..01305be749 --- /dev/null +++ b/listings/ch19-advanced-features/output-only-01-missing-unsafe/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + // ANCHOR: here + unsafe fn dangerous() {} + + dangerous(); + // ANCHOR_END: here +} diff --git a/listings/ch20-web-server/listing-20-01/Cargo.lock b/listings/ch20-web-server/listing-20-01/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-01/Cargo.toml b/listings/ch20-web-server/listing-20-01/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-01/src/main.rs b/listings/ch20-web-server/listing-20-01/src/main.rs new file mode 100644 index 0000000000..d868c3ec16 --- /dev/null +++ b/listings/ch20-web-server/listing-20-01/src/main.rs @@ -0,0 +1,11 @@ +use std::net::TcpListener; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + println!("Connection established!"); + } +} diff --git a/listings/ch20-web-server/listing-20-02/Cargo.lock b/listings/ch20-web-server/listing-20-02/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-02/Cargo.toml b/listings/ch20-web-server/listing-20-02/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-02/src/main.rs b/listings/ch20-web-server/listing-20-02/src/main.rs new file mode 100644 index 0000000000..7dfdc2d897 --- /dev/null +++ b/listings/ch20-web-server/listing-20-02/src/main.rs @@ -0,0 +1,21 @@ +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + handle_connection(stream); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + + stream.read(&mut buffer).unwrap(); + + println!("Request: {}", String::from_utf8_lossy(&buffer[..])); +} diff --git a/listings/ch20-web-server/listing-20-03/Cargo.lock b/listings/ch20-web-server/listing-20-03/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-03/Cargo.toml b/listings/ch20-web-server/listing-20-03/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-03/src/main.rs b/listings/ch20-web-server/listing-20-03/src/main.rs new file mode 100644 index 0000000000..33f4fb732d --- /dev/null +++ b/listings/ch20-web-server/listing-20-03/src/main.rs @@ -0,0 +1,26 @@ +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + handle_connection(stream); + } +} + +// ANCHOR: here +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + + stream.read(&mut buffer).unwrap(); + + let response = "HTTP/1.1 200 OK\r\n\r\n"; + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} +// ANCHOR_END: here diff --git a/listings/ch20-web-server/listing-20-04/Cargo.lock b/listings/ch20-web-server/listing-20-04/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-04/Cargo.toml b/listings/ch20-web-server/listing-20-04/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-04/hello.html b/listings/ch20-web-server/listing-20-04/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-04/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-04/src/main.rs b/listings/ch20-web-server/listing-20-04/src/main.rs new file mode 100644 index 0000000000..22e5d1da2d --- /dev/null +++ b/listings/ch20-web-server/listing-20-04/src/main.rs @@ -0,0 +1,24 @@ +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + handle_connection(stream); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + + stream.read(&mut buffer).unwrap(); + + let response = "HTTP/1.1 200 OK\r\n\r\n"; + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/listing-20-05/Cargo.lock b/listings/ch20-web-server/listing-20-05/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-05/Cargo.toml b/listings/ch20-web-server/listing-20-05/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-05/hello.html b/listings/ch20-web-server/listing-20-05/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-05/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-05/src/main.rs b/listings/ch20-web-server/listing-20-05/src/main.rs new file mode 100644 index 0000000000..0b3a284a77 --- /dev/null +++ b/listings/ch20-web-server/listing-20-05/src/main.rs @@ -0,0 +1,32 @@ +// ANCHOR: here +use std::fs; +// --snip-- + +// ANCHOR_END: here +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + handle_connection(stream); + } +} + +// ANCHOR: here +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let contents = fs::read_to_string("hello.html").unwrap(); + + let response = format!("HTTP/1.1 200 OK\r\n\r\n{}", contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} +// ANCHOR_END: here diff --git a/listings/ch20-web-server/listing-20-06/Cargo.lock b/listings/ch20-web-server/listing-20-06/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-06/Cargo.toml b/listings/ch20-web-server/listing-20-06/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-06/hello.html b/listings/ch20-web-server/listing-20-06/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-06/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-06/src/main.rs b/listings/ch20-web-server/listing-20-06/src/main.rs new file mode 100644 index 0000000000..dc192d76bd --- /dev/null +++ b/listings/ch20-web-server/listing-20-06/src/main.rs @@ -0,0 +1,36 @@ +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + handle_connection(stream); + } +} + +// ANCHOR: here +// --snip-- + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + + if buffer.starts_with(get) { + let contents = fs::read_to_string("hello.html").unwrap(); + + let response = format!("HTTP/1.1 200 OK\r\n\r\n{}", contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); + } else { + // some other request + } +} +// ANCHOR_END: here diff --git a/listings/ch20-web-server/listing-20-07/Cargo.lock b/listings/ch20-web-server/listing-20-07/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-07/Cargo.toml b/listings/ch20-web-server/listing-20-07/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-07/hello.html b/listings/ch20-web-server/listing-20-07/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-07/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-07/src/main.rs b/listings/ch20-web-server/listing-20-07/src/main.rs new file mode 100644 index 0000000000..9fab0c76be --- /dev/null +++ b/listings/ch20-web-server/listing-20-07/src/main.rs @@ -0,0 +1,41 @@ +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + handle_connection(stream); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + + if buffer.starts_with(get) { + let contents = fs::read_to_string("hello.html").unwrap(); + + let response = format!("HTTP/1.1 200 OK\r\n\r\n{}", contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); + // ANCHOR: here + // --snip-- + } else { + let status_line = "HTTP/1.1 404 NOT FOUND\r\n\r\n"; + let contents = fs::read_to_string("404.html").unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); + } + // ANCHOR_END: here +} diff --git a/listings/ch20-web-server/listing-20-08/404.html b/listings/ch20-web-server/listing-20-08/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/listing-20-08/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/listing-20-08/Cargo.lock b/listings/ch20-web-server/listing-20-08/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-08/Cargo.toml b/listings/ch20-web-server/listing-20-08/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-08/hello.html b/listings/ch20-web-server/listing-20-08/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-08/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-08/src/main.rs b/listings/ch20-web-server/listing-20-08/src/main.rs new file mode 100644 index 0000000000..cbcc4c01ff --- /dev/null +++ b/listings/ch20-web-server/listing-20-08/src/main.rs @@ -0,0 +1,38 @@ +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + handle_connection(stream); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + + if buffer.starts_with(get) { + let contents = fs::read_to_string("hello.html").unwrap(); + + let response = format!("HTTP/1.1 200 OK\r\n\r\n{}", contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); + } else { + let status_line = "HTTP/1.1 404 NOT FOUND\r\n\r\n"; + let contents = fs::read_to_string("404.html").unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); + } +} diff --git a/listings/ch20-web-server/listing-20-09/404.html b/listings/ch20-web-server/listing-20-09/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/listing-20-09/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/listing-20-09/Cargo.lock b/listings/ch20-web-server/listing-20-09/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-09/Cargo.toml b/listings/ch20-web-server/listing-20-09/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-09/hello.html b/listings/ch20-web-server/listing-20-09/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-09/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-09/src/main.rs b/listings/ch20-web-server/listing-20-09/src/main.rs new file mode 100644 index 0000000000..c91bb660df --- /dev/null +++ b/listings/ch20-web-server/listing-20-09/src/main.rs @@ -0,0 +1,42 @@ +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + handle_connection(stream); + } +} + +// ANCHOR: here +// --snip-- + +fn handle_connection(mut stream: TcpStream) { + // --snip-- + + // ANCHOR_END: here + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + + // ANCHOR: here + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} +// ANCHOR_END: here diff --git a/listings/ch20-web-server/listing-20-10/404.html b/listings/ch20-web-server/listing-20-10/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/listing-20-10/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/listing-20-10/Cargo.lock b/listings/ch20-web-server/listing-20-10/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-10/Cargo.toml b/listings/ch20-web-server/listing-20-10/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-10/hello.html b/listings/ch20-web-server/listing-20-10/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-10/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-10/src/main.rs b/listings/ch20-web-server/listing-20-10/src/main.rs new file mode 100644 index 0000000000..6ea692fcb3 --- /dev/null +++ b/listings/ch20-web-server/listing-20-10/src/main.rs @@ -0,0 +1,53 @@ +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +// ANCHOR: here +use std::thread; +use std::time::Duration; +// --snip-- +// ANCHOR_END: here + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + handle_connection(stream); + } +} +// ANCHOR: here + +fn handle_connection(mut stream: TcpStream) { + // --snip-- + + // ANCHOR_END: here + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + // ANCHOR: here + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + // --snip-- + // ANCHOR_END: here + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/listings/ch20-web-server/listing-20-11/404.html b/listings/ch20-web-server/listing-20-11/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/listing-20-11/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/listing-20-11/Cargo.lock b/listings/ch20-web-server/listing-20-11/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-11/Cargo.toml b/listings/ch20-web-server/listing-20-11/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-11/hello.html b/listings/ch20-web-server/listing-20-11/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-11/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-11/src/main.rs b/listings/ch20-web-server/listing-20-11/src/main.rs new file mode 100644 index 0000000000..7eb3372ba6 --- /dev/null +++ b/listings/ch20-web-server/listing-20-11/src/main.rs @@ -0,0 +1,44 @@ +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +// ANCHOR: here +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + thread::spawn(|| { + handle_connection(stream); + }); + } +} +// ANCHOR_END: here + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/listing-20-12/404.html b/listings/ch20-web-server/listing-20-12/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/listing-20-12/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/listing-20-12/Cargo.lock b/listings/ch20-web-server/listing-20-12/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-12/Cargo.toml b/listings/ch20-web-server/listing-20-12/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-12/hello.html b/listings/ch20-web-server/listing-20-12/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-12/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-12/output.txt b/listings/ch20-web-server/listing-20-12/output.txt new file mode 100644 index 0000000000..3a798ef120 --- /dev/null +++ b/listings/ch20-web-server/listing-20-12/output.txt @@ -0,0 +1,14 @@ +$ cargo check + Checking hello v0.1.0 (file:///projects/hello) +error[E0433]: failed to resolve: use of undeclared type or module `ThreadPool` + --> src/main.rs:10:16 + | +10 | let pool = ThreadPool::new(4); + | ^^^^^^^^^^ use of undeclared type or module `ThreadPool` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0433`. +error: could not compile `hello`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch20-web-server/listing-20-12/src/main.rs b/listings/ch20-web-server/listing-20-12/src/main.rs new file mode 100644 index 0000000000..1381e6d6d2 --- /dev/null +++ b/listings/ch20-web-server/listing-20-12/src/main.rs @@ -0,0 +1,45 @@ +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +// ANCHOR: here +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} +// ANCHOR_END: here + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/listing-20-13/404.html b/listings/ch20-web-server/listing-20-13/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/listing-20-13/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/listing-20-13/Cargo.lock b/listings/ch20-web-server/listing-20-13/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-13/Cargo.toml b/listings/ch20-web-server/listing-20-13/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-13/hello.html b/listings/ch20-web-server/listing-20-13/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-13/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-13/src/bin/main.rs b/listings/ch20-web-server/listing-20-13/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/listings/ch20-web-server/listing-20-13/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/listing-20-13/src/lib.rs b/listings/ch20-web-server/listing-20-13/src/lib.rs new file mode 100644 index 0000000000..ffa3c6a254 --- /dev/null +++ b/listings/ch20-web-server/listing-20-13/src/lib.rs @@ -0,0 +1,30 @@ +pub struct ThreadPool; + +// ANCHOR: here +impl ThreadPool { + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + ThreadPool + } + + // --snip-- + // ANCHOR_END: here + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + } + // ANCHOR: here +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch20-web-server/listing-20-14/404.html b/listings/ch20-web-server/listing-20-14/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/listing-20-14/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/listing-20-14/Cargo.lock b/listings/ch20-web-server/listing-20-14/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-14/Cargo.toml b/listings/ch20-web-server/listing-20-14/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-14/hello.html b/listings/ch20-web-server/listing-20-14/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-14/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-14/src/bin/main.rs b/listings/ch20-web-server/listing-20-14/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/listings/ch20-web-server/listing-20-14/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/listing-20-14/src/lib.rs b/listings/ch20-web-server/listing-20-14/src/lib.rs new file mode 100644 index 0000000000..509a62e1f9 --- /dev/null +++ b/listings/ch20-web-server/listing-20-14/src/lib.rs @@ -0,0 +1,41 @@ +// ANCHOR: here +use std::thread; + +pub struct ThreadPool { + threads: Vec>, +} + +impl ThreadPool { + // --snip-- + // ANCHOR_END: here + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + // ANCHOR: here + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let mut threads = Vec::with_capacity(size); + + for _ in 0..size { + // create some threads and store them in the vector + } + + ThreadPool { threads } + } + + // --snip-- + // ANCHOR_END: here + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + } + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/listings/ch20-web-server/listing-20-15/404.html b/listings/ch20-web-server/listing-20-15/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/listing-20-15/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/listing-20-15/Cargo.lock b/listings/ch20-web-server/listing-20-15/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-15/Cargo.toml b/listings/ch20-web-server/listing-20-15/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-15/hello.html b/listings/ch20-web-server/listing-20-15/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-15/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-15/src/bin/main.rs b/listings/ch20-web-server/listing-20-15/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/listings/ch20-web-server/listing-20-15/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/listing-20-15/src/lib.rs b/listings/ch20-web-server/listing-20-15/src/lib.rs new file mode 100644 index 0000000000..d2ad3ca176 --- /dev/null +++ b/listings/ch20-web-server/listing-20-15/src/lib.rs @@ -0,0 +1,55 @@ +// ANCHOR: here +use std::thread; + +pub struct ThreadPool { + workers: Vec, +} + +impl ThreadPool { + // --snip-- + // ANCHOR_END: here + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + // ANCHOR: here + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id)); + } + + ThreadPool { workers } + } + // --snip-- + // ANCHOR_END: here + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + } + // ANCHOR: here +} + +struct Worker { + id: usize, + thread: thread::JoinHandle<()>, +} + +impl Worker { + fn new(id: usize) -> Worker { + let thread = thread::spawn(|| {}); + + Worker { id, thread } + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch20-web-server/listing-20-16/404.html b/listings/ch20-web-server/listing-20-16/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/listing-20-16/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/listing-20-16/Cargo.lock b/listings/ch20-web-server/listing-20-16/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-16/Cargo.toml b/listings/ch20-web-server/listing-20-16/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-16/hello.html b/listings/ch20-web-server/listing-20-16/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-16/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-16/src/bin/main.rs b/listings/ch20-web-server/listing-20-16/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/listings/ch20-web-server/listing-20-16/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/listing-20-16/src/lib.rs b/listings/ch20-web-server/listing-20-16/src/lib.rs new file mode 100644 index 0000000000..28b374eed3 --- /dev/null +++ b/listings/ch20-web-server/listing-20-16/src/lib.rs @@ -0,0 +1,62 @@ +use std::thread; +// ANCHOR: here +// --snip-- +use std::sync::mpsc; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +struct Job; + +impl ThreadPool { + // --snip-- + // ANCHOR_END: here + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + // ANCHOR: here + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id)); + } + + ThreadPool { workers, sender } + } + // --snip-- + // ANCHOR_END: here + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + } + // ANCHOR: here +} +// ANCHOR_END: here + +struct Worker { + id: usize, + thread: thread::JoinHandle<()>, +} + +impl Worker { + fn new(id: usize) -> Worker { + let thread = thread::spawn(|| {}); + + Worker { id, thread } + } +} + +fn main() {} diff --git a/listings/ch20-web-server/listing-20-17/404.html b/listings/ch20-web-server/listing-20-17/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/listing-20-17/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/listing-20-17/Cargo.lock b/listings/ch20-web-server/listing-20-17/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-17/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-17/Cargo.toml b/listings/ch20-web-server/listing-20-17/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-17/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-17/hello.html b/listings/ch20-web-server/listing-20-17/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-17/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-17/output.txt b/listings/ch20-web-server/listing-20-17/output.txt new file mode 100644 index 0000000000..f9749e1214 --- /dev/null +++ b/listings/ch20-web-server/listing-20-17/output.txt @@ -0,0 +1,17 @@ +$ cargo check + Checking hello v0.1.0 (file:///projects/hello) +error[E0382]: use of moved value: `receiver` + --> src/lib.rs:27:42 + | +22 | let (sender, receiver) = mpsc::channel(); + | -------- move occurs because `receiver` has type `std::sync::mpsc::Receiver`, which does not implement the `Copy` trait +... +27 | workers.push(Worker::new(id, receiver)); + | ^^^^^^^^ value moved here, in previous iteration of loop + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0382`. +error: could not compile `hello`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch20-web-server/listing-20-17/src/bin/main.rs b/listings/ch20-web-server/listing-20-17/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/listings/ch20-web-server/listing-20-17/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/listing-20-17/src/lib.rs b/listings/ch20-web-server/listing-20-17/src/lib.rs new file mode 100644 index 0000000000..f3ce7d06e6 --- /dev/null +++ b/listings/ch20-web-server/listing-20-17/src/lib.rs @@ -0,0 +1,66 @@ +use std::sync::mpsc; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +struct Job; + +// ANCHOR: here +impl ThreadPool { + // --snip-- + // ANCHOR_END: here + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + // ANCHOR: here + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, receiver)); + } + + ThreadPool { workers, sender } + } + // --snip-- + // ANCHOR_END: here + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + } + // ANCHOR: here +} + +// --snip-- + +// ANCHOR_END: here + +struct Worker { + id: usize, + thread: thread::JoinHandle<()>, +} + +// ANCHOR: here +impl Worker { + fn new(id: usize, receiver: mpsc::Receiver) -> Worker { + let thread = thread::spawn(|| { + receiver; + }); + + Worker { id, thread } + } +} +// ANCHOR_END: here diff --git a/listings/ch20-web-server/listing-20-18/404.html b/listings/ch20-web-server/listing-20-18/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/listing-20-18/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/listing-20-18/Cargo.lock b/listings/ch20-web-server/listing-20-18/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-18/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-18/Cargo.toml b/listings/ch20-web-server/listing-20-18/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-18/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-18/hello.html b/listings/ch20-web-server/listing-20-18/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-18/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-18/src/bin/main.rs b/listings/ch20-web-server/listing-20-18/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/listings/ch20-web-server/listing-20-18/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/listing-20-18/src/lib.rs b/listings/ch20-web-server/listing-20-18/src/lib.rs new file mode 100644 index 0000000000..d47eef869e --- /dev/null +++ b/listings/ch20-web-server/listing-20-18/src/lib.rs @@ -0,0 +1,78 @@ +use std::sync::mpsc; +use std::thread; +// ANCHOR: here +use std::sync::Arc; +use std::sync::Mutex; +// --snip-- + +// ANCHOR_END: here +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +struct Job; + +// ANCHOR: here +impl ThreadPool { + // --snip-- + // ANCHOR_END: here + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + // ANCHOR: here + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + // --snip-- + // ANCHOR_END: here + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + } + // ANCHOR: here +} + +// --snip-- + +// ANCHOR_END: here +struct Worker { + id: usize, + thread: thread::JoinHandle<()>, +} + +// ANCHOR: here +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + // --snip-- + // ANCHOR_END: here + let thread = thread::spawn(|| { + receiver; + }); + + Worker { id, thread } + // ANCHOR: here + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch20-web-server/listing-20-19/404.html b/listings/ch20-web-server/listing-20-19/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/listing-20-19/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/listing-20-19/Cargo.lock b/listings/ch20-web-server/listing-20-19/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-19/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-19/Cargo.toml b/listings/ch20-web-server/listing-20-19/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-19/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-19/hello.html b/listings/ch20-web-server/listing-20-19/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-19/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-19/src/bin/main.rs b/listings/ch20-web-server/listing-20-19/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/listings/ch20-web-server/listing-20-19/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/listing-20-19/src/lib.rs b/listings/ch20-web-server/listing-20-19/src/lib.rs new file mode 100644 index 0000000000..bf8127b8e5 --- /dev/null +++ b/listings/ch20-web-server/listing-20-19/src/lib.rs @@ -0,0 +1,71 @@ +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +// ANCHOR: here +// --snip-- + +type Job = Box; + +impl ThreadPool { + // --snip-- + // ANCHOR_END: here + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + // ANCHOR: here + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(job).unwrap(); + } +} + +// --snip-- +// ANCHOR_END: here + +struct Worker { + id: usize, + thread: thread::JoinHandle<()>, +} + +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + let thread = thread::spawn(|| { + receiver; + }); + + Worker { id, thread } + } +} + +fn main() {} diff --git a/listings/ch20-web-server/listing-20-20/404.html b/listings/ch20-web-server/listing-20-20/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/listing-20-20/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/listing-20-20/Cargo.lock b/listings/ch20-web-server/listing-20-20/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-20/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-20/Cargo.toml b/listings/ch20-web-server/listing-20-20/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-20/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-20/hello.html b/listings/ch20-web-server/listing-20-20/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-20/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-20/src/bin/main.rs b/listings/ch20-web-server/listing-20-20/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/listings/ch20-web-server/listing-20-20/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/listing-20-20/src/lib.rs b/listings/ch20-web-server/listing-20-20/src/lib.rs new file mode 100644 index 0000000000..5fdc32e8b0 --- /dev/null +++ b/listings/ch20-web-server/listing-20-20/src/lib.rs @@ -0,0 +1,68 @@ +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +type Job = Box; + +impl ThreadPool { + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(job).unwrap(); + } +} + +struct Worker { + id: usize, + thread: thread::JoinHandle<()>, +} + +// ANCHOR: here +// --snip-- + +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + let thread = thread::spawn(move || loop { + let job = receiver.lock().unwrap().recv().unwrap(); + + println!("Worker {} got a job; executing.", id); + + job(); + }); + + Worker { id, thread } + } +} +// ANCHOR_END: here diff --git a/listings/ch20-web-server/listing-20-21/404.html b/listings/ch20-web-server/listing-20-21/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/listing-20-21/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/listing-20-21/Cargo.lock b/listings/ch20-web-server/listing-20-21/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-21/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-21/Cargo.toml b/listings/ch20-web-server/listing-20-21/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-21/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-21/hello.html b/listings/ch20-web-server/listing-20-21/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-21/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-21/src/bin/main.rs b/listings/ch20-web-server/listing-20-21/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/listings/ch20-web-server/listing-20-21/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/listing-20-21/src/lib.rs b/listings/ch20-web-server/listing-20-21/src/lib.rs new file mode 100644 index 0000000000..6bde524885 --- /dev/null +++ b/listings/ch20-web-server/listing-20-21/src/lib.rs @@ -0,0 +1,67 @@ +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +type Job = Box; + +impl ThreadPool { + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(job).unwrap(); + } +} + +struct Worker { + id: usize, + thread: thread::JoinHandle<()>, +} +// ANCHOR: here +// --snip-- + +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + let thread = thread::spawn(move || { + while let Ok(job) = receiver.lock().unwrap().recv() { + println!("Worker {} got a job; executing.", id); + + job(); + } + }); + + Worker { id, thread } + } +} +// ANCHOR_END: here diff --git a/listings/ch20-web-server/listing-20-22/404.html b/listings/ch20-web-server/listing-20-22/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/listing-20-22/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/listing-20-22/Cargo.lock b/listings/ch20-web-server/listing-20-22/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-22/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-22/Cargo.toml b/listings/ch20-web-server/listing-20-22/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-22/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-22/hello.html b/listings/ch20-web-server/listing-20-22/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-22/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-22/output.txt b/listings/ch20-web-server/listing-20-22/output.txt new file mode 100644 index 0000000000..f5dd1ba13b --- /dev/null +++ b/listings/ch20-web-server/listing-20-22/output.txt @@ -0,0 +1,14 @@ +$ cargo check + Checking hello v0.1.0 (file:///projects/hello) +error[E0507]: cannot move out of `worker.thread` which is behind a mutable reference + --> src/lib.rs:52:13 + | +52 | worker.thread.join().unwrap(); + | ^^^^^^^^^^^^^ move occurs because `worker.thread` has type `std::thread::JoinHandle<()>`, which does not implement the `Copy` trait + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0507`. +error: could not compile `hello`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch20-web-server/listing-20-22/src/bin/main.rs b/listings/ch20-web-server/listing-20-22/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/listings/ch20-web-server/listing-20-22/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/listing-20-22/src/lib.rs b/listings/ch20-web-server/listing-20-22/src/lib.rs new file mode 100644 index 0000000000..824257898c --- /dev/null +++ b/listings/ch20-web-server/listing-20-22/src/lib.rs @@ -0,0 +1,76 @@ +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +type Job = Box; + +impl ThreadPool { + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(job).unwrap(); + } +} + +// ANCHOR: here +impl Drop for ThreadPool { + fn drop(&mut self) { + for worker in &mut self.workers { + println!("Shutting down worker {}", worker.id); + + worker.thread.join().unwrap(); + } + } +} +// ANCHOR_END: here + +struct Worker { + id: usize, + thread: thread::JoinHandle<()>, +} + +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + let thread = thread::spawn(move || loop { + let job = receiver.lock().unwrap().recv().unwrap(); + + println!("Worker {} got a job; executing.", id); + + job(); + }); + + Worker { id, thread } + } +} diff --git a/listings/ch20-web-server/listing-20-23/404.html b/listings/ch20-web-server/listing-20-23/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/listing-20-23/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/listing-20-23/Cargo.lock b/listings/ch20-web-server/listing-20-23/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-23/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-23/Cargo.toml b/listings/ch20-web-server/listing-20-23/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-23/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-23/hello.html b/listings/ch20-web-server/listing-20-23/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-23/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-23/src/bin/main.rs b/listings/ch20-web-server/listing-20-23/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/listings/ch20-web-server/listing-20-23/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/listing-20-23/src/lib.rs b/listings/ch20-web-server/listing-20-23/src/lib.rs new file mode 100644 index 0000000000..6ccaee73f6 --- /dev/null +++ b/listings/ch20-web-server/listing-20-23/src/lib.rs @@ -0,0 +1,107 @@ +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +// ANCHOR: here +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +// --snip-- + +// ANCHOR_END: here +type Job = Box; + +enum Message { + NewJob(Job), + Terminate, +} + +// ANCHOR: here +impl ThreadPool { + // --snip-- + + // ANCHOR_END: here + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + // ANCHOR: here + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(Message::NewJob(job)).unwrap(); + } +} + +// --snip-- + +// ANCHOR_END: here +impl Drop for ThreadPool { + fn drop(&mut self) { + for worker in &mut self.workers { + println!("Shutting down worker {}", worker.id); + + if let Some(thread) = worker.thread.take() { + thread.join().unwrap(); + } + } + } +} + +struct Worker { + id: usize, + thread: Option>, +} + +// ANCHOR: here +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + let thread = thread::spawn(move || loop { + let message = receiver.lock().unwrap().recv().unwrap(); + + match message { + Message::NewJob(job) => { + println!("Worker {} got a job; executing.", id); + + job(); + } + Message::Terminate => { + println!("Worker {} was told to terminate.", id); + + break; + } + } + }); + + Worker { + id, + thread: Some(thread), + } + } +} +// ANCHOR_END: here diff --git a/listings/ch20-web-server/listing-20-24/404.html b/listings/ch20-web-server/listing-20-24/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/listing-20-24/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/listing-20-24/Cargo.lock b/listings/ch20-web-server/listing-20-24/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-24/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-24/Cargo.toml b/listings/ch20-web-server/listing-20-24/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-24/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-24/hello.html b/listings/ch20-web-server/listing-20-24/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-24/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-24/src/bin/main.rs b/listings/ch20-web-server/listing-20-24/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/listings/ch20-web-server/listing-20-24/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/listing-20-24/src/lib.rs b/listings/ch20-web-server/listing-20-24/src/lib.rs new file mode 100644 index 0000000000..211d105b5e --- /dev/null +++ b/listings/ch20-web-server/listing-20-24/src/lib.rs @@ -0,0 +1,103 @@ +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +type Job = Box; + +enum Message { + NewJob(Job), + Terminate, +} + +impl ThreadPool { + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(Message::NewJob(job)).unwrap(); + } +} + +// ANCHOR: here +impl Drop for ThreadPool { + fn drop(&mut self) { + println!("Sending terminate message to all workers."); + + for _ in &mut self.workers { + self.sender.send(Message::Terminate).unwrap(); + } + + println!("Shutting down all workers."); + + for worker in &mut self.workers { + println!("Shutting down worker {}", worker.id); + + if let Some(thread) = worker.thread.take() { + thread.join().unwrap(); + } + } + } +} +// ANCHOR_END: here + +struct Worker { + id: usize, + thread: Option>, +} + +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + let thread = thread::spawn(move || loop { + let message = receiver.lock().unwrap().recv().unwrap(); + + match message { + Message::NewJob(job) => { + println!("Worker {} got a job; executing.", id); + + job(); + } + Message::Terminate => { + println!("Worker {} was told to terminate.", id); + + break; + } + } + }); + + Worker { + id, + thread: Some(thread), + } + } +} diff --git a/listings/ch20-web-server/listing-20-25/404.html b/listings/ch20-web-server/listing-20-25/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/listing-20-25/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/listing-20-25/Cargo.lock b/listings/ch20-web-server/listing-20-25/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/listing-20-25/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/listing-20-25/Cargo.toml b/listings/ch20-web-server/listing-20-25/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/listing-20-25/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/listing-20-25/hello.html b/listings/ch20-web-server/listing-20-25/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/listing-20-25/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/listing-20-25/src/bin/main.rs b/listings/ch20-web-server/listing-20-25/src/bin/main.rs new file mode 100644 index 0000000000..8d9310eaec --- /dev/null +++ b/listings/ch20-web-server/listing-20-25/src/bin/main.rs @@ -0,0 +1,50 @@ +// ANCHOR: all +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +// ANCHOR: here +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming().take(2) { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } + + println!("Shutting down."); +} +// ANCHOR_END: here + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} +// ANCHOR_END: all diff --git a/listings/ch20-web-server/listing-20-25/src/lib.rs b/listings/ch20-web-server/listing-20-25/src/lib.rs new file mode 100644 index 0000000000..ee52dd22cd --- /dev/null +++ b/listings/ch20-web-server/listing-20-25/src/lib.rs @@ -0,0 +1,105 @@ +// ANCHOR: here +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +type Job = Box; + +enum Message { + NewJob(Job), + Terminate, +} + +impl ThreadPool { + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(Message::NewJob(job)).unwrap(); + } +} + +impl Drop for ThreadPool { + fn drop(&mut self) { + println!("Sending terminate message to all workers."); + + for _ in &mut self.workers { + self.sender.send(Message::Terminate).unwrap(); + } + + println!("Shutting down all workers."); + + for worker in &mut self.workers { + println!("Shutting down worker {}", worker.id); + + if let Some(thread) = worker.thread.take() { + thread.join().unwrap(); + } + } + } +} + +struct Worker { + id: usize, + thread: Option>, +} + +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + let thread = thread::spawn(move || loop { + let message = receiver.lock().unwrap().recv().unwrap(); + + match message { + Message::NewJob(job) => { + println!("Worker {} got a job; executing.", id); + + job(); + } + Message::Terminate => { + println!("Worker {} was told to terminate.", id); + + break; + } + } + }); + + Worker { + id, + thread: Some(thread), + } + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch20-web-server/no-listing-01-define-threadpool-struct/404.html b/listings/ch20-web-server/no-listing-01-define-threadpool-struct/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/no-listing-01-define-threadpool-struct/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/no-listing-01-define-threadpool-struct/Cargo.lock b/listings/ch20-web-server/no-listing-01-define-threadpool-struct/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/no-listing-01-define-threadpool-struct/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/no-listing-01-define-threadpool-struct/Cargo.toml b/listings/ch20-web-server/no-listing-01-define-threadpool-struct/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/no-listing-01-define-threadpool-struct/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/no-listing-01-define-threadpool-struct/hello.html b/listings/ch20-web-server/no-listing-01-define-threadpool-struct/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/no-listing-01-define-threadpool-struct/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/no-listing-01-define-threadpool-struct/output.txt b/listings/ch20-web-server/no-listing-01-define-threadpool-struct/output.txt new file mode 100644 index 0000000000..0161c7b2c7 --- /dev/null +++ b/listings/ch20-web-server/no-listing-01-define-threadpool-struct/output.txt @@ -0,0 +1,14 @@ +$ cargo check + Checking hello v0.1.0 (file:///projects/hello) +error[E0599]: no function or associated item named `new` found for type `hello::ThreadPool` in the current scope + --> src/bin/main.rs:11:28 + | +11 | let pool = ThreadPool::new(4); + | ^^^ function or associated item not found in `hello::ThreadPool` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0599`. +error: could not compile `hello`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch20-web-server/no-listing-01-define-threadpool-struct/src/bin/main.rs b/listings/ch20-web-server/no-listing-01-define-threadpool-struct/src/bin/main.rs new file mode 100644 index 0000000000..d4e0e0c0e0 --- /dev/null +++ b/listings/ch20-web-server/no-listing-01-define-threadpool-struct/src/bin/main.rs @@ -0,0 +1,46 @@ +// ANCHOR: here +use hello::ThreadPool; +// ANCHOR_END: here +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/no-listing-01-define-threadpool-struct/src/lib.rs b/listings/ch20-web-server/no-listing-01-define-threadpool-struct/src/lib.rs new file mode 100644 index 0000000000..7312e293d8 --- /dev/null +++ b/listings/ch20-web-server/no-listing-01-define-threadpool-struct/src/lib.rs @@ -0,0 +1 @@ +pub struct ThreadPool; diff --git a/listings/ch20-web-server/no-listing-02-impl-threadpool-new/404.html b/listings/ch20-web-server/no-listing-02-impl-threadpool-new/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/no-listing-02-impl-threadpool-new/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/no-listing-02-impl-threadpool-new/Cargo.lock b/listings/ch20-web-server/no-listing-02-impl-threadpool-new/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/no-listing-02-impl-threadpool-new/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/no-listing-02-impl-threadpool-new/Cargo.toml b/listings/ch20-web-server/no-listing-02-impl-threadpool-new/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/no-listing-02-impl-threadpool-new/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/no-listing-02-impl-threadpool-new/hello.html b/listings/ch20-web-server/no-listing-02-impl-threadpool-new/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/no-listing-02-impl-threadpool-new/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/no-listing-02-impl-threadpool-new/output.txt b/listings/ch20-web-server/no-listing-02-impl-threadpool-new/output.txt new file mode 100644 index 0000000000..c808b8986b --- /dev/null +++ b/listings/ch20-web-server/no-listing-02-impl-threadpool-new/output.txt @@ -0,0 +1,14 @@ +$ cargo check + Checking hello v0.1.0 (file:///projects/hello) +error[E0599]: no method named `execute` found for type `hello::ThreadPool` in the current scope + --> src/bin/main.rs:16:14 + | +16 | pool.execute(|| { + | ^^^^^^^ method not found in `hello::ThreadPool` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0599`. +error: could not compile `hello`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch20-web-server/no-listing-02-impl-threadpool-new/src/bin/main.rs b/listings/ch20-web-server/no-listing-02-impl-threadpool-new/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/listings/ch20-web-server/no-listing-02-impl-threadpool-new/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/no-listing-02-impl-threadpool-new/src/lib.rs b/listings/ch20-web-server/no-listing-02-impl-threadpool-new/src/lib.rs new file mode 100644 index 0000000000..3ff5ad4979 --- /dev/null +++ b/listings/ch20-web-server/no-listing-02-impl-threadpool-new/src/lib.rs @@ -0,0 +1,11 @@ +// ANCHOR: here +pub struct ThreadPool; + +impl ThreadPool { + pub fn new(size: usize) -> ThreadPool { + ThreadPool + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch20-web-server/no-listing-03-define-execute/404.html b/listings/ch20-web-server/no-listing-03-define-execute/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/no-listing-03-define-execute/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/no-listing-03-define-execute/Cargo.lock b/listings/ch20-web-server/no-listing-03-define-execute/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/no-listing-03-define-execute/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/no-listing-03-define-execute/Cargo.toml b/listings/ch20-web-server/no-listing-03-define-execute/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/no-listing-03-define-execute/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/no-listing-03-define-execute/hello.html b/listings/ch20-web-server/no-listing-03-define-execute/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/no-listing-03-define-execute/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/no-listing-03-define-execute/output.txt b/listings/ch20-web-server/no-listing-03-define-execute/output.txt new file mode 100644 index 0000000000..dc76c43d6f --- /dev/null +++ b/listings/ch20-web-server/no-listing-03-define-execute/output.txt @@ -0,0 +1,3 @@ +$ cargo check + Checking hello v0.1.0 (file:///projects/hello) + Finished dev [unoptimized + debuginfo] target(s) in 0.24s diff --git a/listings/ch20-web-server/no-listing-03-define-execute/src/bin/main.rs b/listings/ch20-web-server/no-listing-03-define-execute/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/listings/ch20-web-server/no-listing-03-define-execute/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/no-listing-03-define-execute/src/lib.rs b/listings/ch20-web-server/no-listing-03-define-execute/src/lib.rs new file mode 100644 index 0000000000..44e0ebd724 --- /dev/null +++ b/listings/ch20-web-server/no-listing-03-define-execute/src/lib.rs @@ -0,0 +1,20 @@ +pub struct ThreadPool; + +// ANCHOR: here +impl ThreadPool { + // --snip-- + // ANCHOR_END: here + pub fn new(size: usize) -> ThreadPool { + ThreadPool + } + + // ANCHOR: here + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/listings/ch20-web-server/no-listing-04-update-worker-definition/404.html b/listings/ch20-web-server/no-listing-04-update-worker-definition/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/no-listing-04-update-worker-definition/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/no-listing-04-update-worker-definition/Cargo.lock b/listings/ch20-web-server/no-listing-04-update-worker-definition/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/no-listing-04-update-worker-definition/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/no-listing-04-update-worker-definition/Cargo.toml b/listings/ch20-web-server/no-listing-04-update-worker-definition/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/no-listing-04-update-worker-definition/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/no-listing-04-update-worker-definition/hello.html b/listings/ch20-web-server/no-listing-04-update-worker-definition/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/no-listing-04-update-worker-definition/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/no-listing-04-update-worker-definition/output.txt b/listings/ch20-web-server/no-listing-04-update-worker-definition/output.txt new file mode 100644 index 0000000000..87971b2085 --- /dev/null +++ b/listings/ch20-web-server/no-listing-04-update-worker-definition/output.txt @@ -0,0 +1,27 @@ +$ cargo check + Checking hello v0.1.0 (file:///projects/hello) +error[E0599]: no method named `join` found for type `std::option::Option>` in the current scope + --> src/lib.rs:52:27 + | +52 | worker.thread.join().unwrap(); + | ^^^^ method not found in `std::option::Option>` + +error[E0308]: mismatched types + --> src/lib.rs:72:22 + | +72 | Worker { id, thread } + | ^^^^^^ + | | + | expected enum `std::option::Option`, found struct `std::thread::JoinHandle` + | help: try using a variant of the expected enum: `Some(thread)` + | + = note: expected type `std::option::Option>` + found type `std::thread::JoinHandle<_>` + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0308, E0599. +For more information about an error, try `rustc --explain E0308`. +error: could not compile `hello`. + +To learn more, run the command again with --verbose. diff --git a/listings/ch20-web-server/no-listing-04-update-worker-definition/src/bin/main.rs b/listings/ch20-web-server/no-listing-04-update-worker-definition/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/listings/ch20-web-server/no-listing-04-update-worker-definition/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/no-listing-04-update-worker-definition/src/lib.rs b/listings/ch20-web-server/no-listing-04-update-worker-definition/src/lib.rs new file mode 100644 index 0000000000..1098330b3f --- /dev/null +++ b/listings/ch20-web-server/no-listing-04-update-worker-definition/src/lib.rs @@ -0,0 +1,76 @@ +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +type Job = Box; + +impl ThreadPool { + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(job).unwrap(); + } +} + +impl Drop for ThreadPool { + fn drop(&mut self) { + for worker in &mut self.workers { + println!("Shutting down worker {}", worker.id); + + worker.thread.join().unwrap(); + } + } +} + +// ANCHOR: here +struct Worker { + id: usize, + thread: Option>, +} +// ANCHOR_END: here + +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + let thread = thread::spawn(move || loop { + let job = receiver.lock().unwrap().recv().unwrap(); + + println!("Worker {} got a job; executing.", id); + + job(); + }); + + Worker { id, thread } + } +} diff --git a/listings/ch20-web-server/no-listing-05-fix-worker-new/404.html b/listings/ch20-web-server/no-listing-05-fix-worker-new/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/no-listing-05-fix-worker-new/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/no-listing-05-fix-worker-new/Cargo.lock b/listings/ch20-web-server/no-listing-05-fix-worker-new/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/no-listing-05-fix-worker-new/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/no-listing-05-fix-worker-new/Cargo.toml b/listings/ch20-web-server/no-listing-05-fix-worker-new/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/no-listing-05-fix-worker-new/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/no-listing-05-fix-worker-new/hello.html b/listings/ch20-web-server/no-listing-05-fix-worker-new/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/no-listing-05-fix-worker-new/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/no-listing-05-fix-worker-new/src/bin/main.rs b/listings/ch20-web-server/no-listing-05-fix-worker-new/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/listings/ch20-web-server/no-listing-05-fix-worker-new/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/no-listing-05-fix-worker-new/src/lib.rs b/listings/ch20-web-server/no-listing-05-fix-worker-new/src/lib.rs new file mode 100644 index 0000000000..6bef23a16d --- /dev/null +++ b/listings/ch20-web-server/no-listing-05-fix-worker-new/src/lib.rs @@ -0,0 +1,83 @@ +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +type Job = Box; + +impl ThreadPool { + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(job).unwrap(); + } +} + +impl Drop for ThreadPool { + fn drop(&mut self) { + for worker in &mut self.workers { + println!("Shutting down worker {}", worker.id); + + worker.thread.join().unwrap(); + } + } +} + +struct Worker { + id: usize, + thread: Option>, +} + +// ANCHOR: here +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + // --snip-- + + // ANCHOR_END: here + let thread = thread::spawn(move || loop { + let job = receiver.lock().unwrap().recv().unwrap(); + + println!("Worker {} got a job; executing.", id); + + job(); + }); + + // ANCHOR: here + Worker { + id, + thread: Some(thread), + } + } +} +// ANCHOR_END: here diff --git a/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/404.html b/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/Cargo.lock b/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/Cargo.toml b/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/hello.html b/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/src/bin/main.rs b/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/src/lib.rs b/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/src/lib.rs new file mode 100644 index 0000000000..d5b38a635d --- /dev/null +++ b/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/src/lib.rs @@ -0,0 +1,81 @@ +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +type Job = Box; + +impl ThreadPool { + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(job).unwrap(); + } +} + +// ANCHOR: here +impl Drop for ThreadPool { + fn drop(&mut self) { + for worker in &mut self.workers { + println!("Shutting down worker {}", worker.id); + + if let Some(thread) = worker.thread.take() { + thread.join().unwrap(); + } + } + } +} +// ANCHOR_END: here + +struct Worker { + id: usize, + thread: Option>, +} + +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + let thread = thread::spawn(move || loop { + let job = receiver.lock().unwrap().recv().unwrap(); + + println!("Worker {} got a job; executing.", id); + + job(); + }); + + Worker { + id, + thread: Some(thread), + } + } +} diff --git a/listings/ch20-web-server/no-listing-07-define-message-enum/404.html b/listings/ch20-web-server/no-listing-07-define-message-enum/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/listings/ch20-web-server/no-listing-07-define-message-enum/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/listings/ch20-web-server/no-listing-07-define-message-enum/Cargo.lock b/listings/ch20-web-server/no-listing-07-define-message-enum/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/listings/ch20-web-server/no-listing-07-define-message-enum/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/listings/ch20-web-server/no-listing-07-define-message-enum/Cargo.toml b/listings/ch20-web-server/no-listing-07-define-message-enum/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/listings/ch20-web-server/no-listing-07-define-message-enum/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/listings/ch20-web-server/no-listing-07-define-message-enum/hello.html b/listings/ch20-web-server/no-listing-07-define-message-enum/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/listings/ch20-web-server/no-listing-07-define-message-enum/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/listings/ch20-web-server/no-listing-07-define-message-enum/src/bin/main.rs b/listings/ch20-web-server/no-listing-07-define-message-enum/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/listings/ch20-web-server/no-listing-07-define-message-enum/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/listings/ch20-web-server/no-listing-07-define-message-enum/src/lib.rs b/listings/ch20-web-server/no-listing-07-define-message-enum/src/lib.rs new file mode 100644 index 0000000000..ed1913b293 --- /dev/null +++ b/listings/ch20-web-server/no-listing-07-define-message-enum/src/lib.rs @@ -0,0 +1,88 @@ +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +type Job = Box; + +// ANCHOR: here +enum Message { + NewJob(Job), + Terminate, +} +// ANCHOR_END: here + +impl ThreadPool { + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(job).unwrap(); + } +} + +impl Drop for ThreadPool { + fn drop(&mut self) { + for worker in &mut self.workers { + println!("Shutting down worker {}", worker.id); + + if let Some(thread) = worker.thread.take() { + thread.join().unwrap(); + } + } + } +} + +struct Worker { + id: usize, + thread: Option>, +} + +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + let thread = thread::spawn(move || loop { + let job = receiver.lock().unwrap().recv().unwrap(); + + println!("Worker {} got a job; executing.", id); + + job(); + }); + + Worker { + id, + thread: Some(thread), + } + } +} + +fn main() {} diff --git a/redirects/associated-types.md b/redirects/associated-types.md index 4083f93986..b222f3298f 100644 --- a/redirects/associated-types.md +++ b/redirects/associated-types.md @@ -13,11 +13,5 @@ pub trait Iterator { --- -Here are the relevant sections in the new and old books: - -* **[In the second edition: Ch 19.03 — Advanced Traits][2]** -* [In the first edition: Ch 3.30 — Associated Types][1] - - -[1]: first-edition/associated-types.html -[2]: second-edition/ch19-03-advanced-traits.html#associated-types-specify-placeholder-types-in-trait-definitions +You can find the latest version of this information +[here](ch19-03-advanced-traits.html#specifying-placeholder-types-in-trait-definitions-with-associated-types). \ No newline at end of file diff --git a/redirects/attributes.md b/redirects/attributes.md index 2d7b05d065..812cbbcd33 100644 --- a/redirects/attributes.md +++ b/redirects/attributes.md @@ -16,9 +16,9 @@ fn test_foo() { Here are the relevant sections in the new and old books: -* **[In the Rust Reference: Ch 5.3 — Attributes][2]** +* **[In the Rust Reference: Ch 6.5 — Attributes][2]** * [In the first edition: Ch 3.27 — Attributes][1] -[1]: first-edition/attributes.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/attributes.html [2]: ../reference/attributes.html diff --git a/redirects/bibliography.md b/redirects/bibliography.md index 740a26b3d3..aca777e397 100644 --- a/redirects/bibliography.md +++ b/redirects/bibliography.md @@ -9,6 +9,6 @@ You might be interested in a similar page in [the Rust Reference][3]. * [In the first edition: Section 7 — Bibliography][1] -[1]: first-edition/bibliography.html -[2]: second-edition/index.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/bibliography.html +[2]: index.html [3]: ../reference/influences.html diff --git a/redirects/borrow-and-asref.md b/redirects/borrow-and-asref.md index 2b8255bf19..6541e59baf 100644 --- a/redirects/borrow-and-asref.md +++ b/redirects/borrow-and-asref.md @@ -20,6 +20,6 @@ The best place to learn more about this is [the Rust documentation][3]. * [In the first edition: Ch 4.10 — Borrow and AsRef][1] -[1]: first-edition/borrow-and-asref.html -[2]: second-edition/index.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/borrow-and-asref.html +[2]: index.html [3]: ../std/convert/trait.AsRef.html diff --git a/redirects/casting-between-types.md b/redirects/casting-between-types.md index 9d773149aa..7e1eb7744d 100644 --- a/redirects/casting-between-types.md +++ b/redirects/casting-between-types.md @@ -20,13 +20,13 @@ fn average(values: &[f64]) -> f64 { Here are the relevant sections in the new and old books: -* **[In the second edition: Appendix A — Keywords][2]** +* **[in the current edition: Appendix A — Keywords][2]** * [In the Rust Reference: Type Cast Expressions][3] * [In the Rust documentation: `mem::transmute`][4] * [In the first edition: Ch 3.29 — Casting between types][1] -[1]: first-edition/casting-between-types.html -[2]: second-edition/appendix-01-keywords.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/casting-between-types.html +[2]: appendix-01-keywords.html [3]: ../reference/expressions/operator-expr.html#type-cast-expressions [4]: ../std/mem/fn.transmute.html \ No newline at end of file diff --git a/redirects/choosing-your-guarantees.md b/redirects/choosing-your-guarantees.md index e2205284b0..3667258c66 100644 --- a/redirects/choosing-your-guarantees.md +++ b/redirects/choosing-your-guarantees.md @@ -14,9 +14,9 @@ println!("b = {}", b); Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 15.00 — Smart Pointers][2]** +* **[In the current edition: Ch 15.00 — Smart Pointers][2]** * [In the first edition: Ch 4.8 — Choosing your Guarantees][1] -[1]: first-edition/choosing-your-guarantees.html -[2]: second-edition/ch15-00-smart-pointers.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/choosing-your-guarantees.html +[2]: ch15-00-smart-pointers.html diff --git a/redirects/closures.md b/redirects/closures.md index a3c6555e2f..55b88767fb 100644 --- a/redirects/closures.md +++ b/redirects/closures.md @@ -20,9 +20,9 @@ let expensive_closure = |num| { Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 13.01 — Closures][2]** +* **[in the current edition: Ch 13.01 — Closures][2]** * [In the first edition: Ch 3.23 — Closures][1] -[1]: first-edition/closures.html -[2]: second-edition/ch13-01-closures.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/closures.html +[2]: ch13-01-closures.html diff --git a/redirects/comments.md b/redirects/comments.md index 7766940fe7..d8e94f7e93 100644 --- a/redirects/comments.md +++ b/redirects/comments.md @@ -15,9 +15,9 @@ Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 3.04 — Comments][2]** +* **[in the current edition: Ch 3.04 — Comments][2]** * [In the first edition: Ch 3.4 — Comments][1] -[1]: first-edition/comments.html -[2]: second-edition/ch03-04-comments.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/comments.html +[2]: ch03-04-comments.html diff --git a/redirects/concurrency.md b/redirects/concurrency.md index c2b96a55a3..da7fb2fb09 100644 --- a/redirects/concurrency.md +++ b/redirects/concurrency.md @@ -9,9 +9,9 @@ Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 16.00 — Fearless Concurrency][2]** +* **[in the current edition: Ch 16.00 — Fearless Concurrency][2]** * [In the first edition: Ch 4.6 — Concurrency][1] -[1]: first-edition/concurrency.html -[2]: second-edition/ch16-00-concurrency.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/concurrency.html +[2]: ch16-00-concurrency.html diff --git a/redirects/conditional-compilation.md b/redirects/conditional-compilation.md index 4e88da53b4..b25c02f741 100644 --- a/redirects/conditional-compilation.md +++ b/redirects/conditional-compilation.md @@ -19,10 +19,10 @@ fn macos_only() { This particular chapter does not exist in [the second edition][2]. The best place to learn about it is [the Rust Reference][3]. -* **[In the Rust Reference: Ch 5.3 — Attributes, Conditional Compilation section][3]** +* **[In the Rust Reference: Ch 5 — Conditional Compilation][3]** * [In the first edition: Ch 4.3 — Conditional Compilation][1] -[1]: first-edition/conditional-compilation.html -[2]: second-edition/index.html -[3]: ../reference/attributes.html#conditional-compilation +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/conditional-compilation.html +[2]: index.html +[3]: ../reference/conditional-compilation.html diff --git a/redirects/const-and-static.md b/redirects/const-and-static.md index 2d7014a24f..3d09f37dc9 100644 --- a/redirects/const-and-static.md +++ b/redirects/const-and-static.md @@ -13,13 +13,9 @@ static HELLO_WORLD: &str = "Hello, world!"; --- -Here are the relevant sections in the new and old books: +You can find the latest version about constants +[here](ch03-01-variables-and-mutability.html#differences-between-variables-and-constants), +and about statics +[here](ch19-01-unsafe-rust.html#accessing-or-modifying-a-mutable-static-variable). -* **[In the second edition: Ch 3.01 — Variables and Mutability, section Constants][2]** -* **[In the second edition: Ch 19.01 — Unsafe Rust, section Static Variables][3]** -* [In the first edition: Ch 3.26 — `const` and `static`][1] - -[1]: first-edition/const-and-static.html -[2]: second-edition/ch03-01-variables-and-mutability.html#differences-between-variables-and-constants -[3]: second-edition/ch19-01-unsafe-rust.html#accessing-or-modifying-a-mutable-static-variable diff --git a/redirects/crates-and-modules.md b/redirects/crates-and-modules.md index 3796ed37d4..d526c95641 100644 --- a/redirects/crates-and-modules.md +++ b/redirects/crates-and-modules.md @@ -18,11 +18,11 @@ mod network { Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 7.01 — `mod` and the Filesystem][2]** -* [In the second edition: Ch 14.02 — Publishing a Crate to Crates.io][2] +* **[in the current edition: Ch 7.01 — `mod` and the Filesystem][2]** +* [in the current edition: Ch 14.02 — Publishing a Crate to Crates.io][3] * [In the first edition: Ch 3.25 — Crates and Modules][1] -[1]: first-edition/crates-and-modules.html -[2]: second-edition/ch07-01-mod-and-the-filesystem.html -[3]: second-edition/ch14-02-publishing-to-crates-io.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/crates-and-modules.html +[2]: ch07-00-managing-growing-projects-with-packages-crates-and-modules.html +[3]: ch14-02-publishing-to-crates-io.html diff --git a/redirects/deref-coercions.md b/redirects/deref-coercions.md index 29de95e66c..61d407e1d5 100644 --- a/redirects/deref-coercions.md +++ b/redirects/deref-coercions.md @@ -22,9 +22,9 @@ impl Deref for MyBox { Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 15.02 — Treating Smart Pointers like Regular References with the `Deref` Trait][2]** +* **[in the current edition: Ch 15.02 — Treating Smart Pointers like Regular References with the `Deref` Trait][2]** * [In the first edition: Ch 3.33 — Deref coercions][1] -[1]: first-edition/deref-coercions.html -[2]: second-edition/ch15-02-deref.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/deref-coercions.html +[2]: ch15-02-deref.html diff --git a/redirects/documentation.md b/redirects/documentation.md index 64382f33c5..ac7c881de1 100644 --- a/redirects/documentation.md +++ b/redirects/documentation.md @@ -22,11 +22,5 @@ pub fn add_one(x: i32) -> i32 { --- -Here are the relevant sections in the new and old books: - -* **[In the second edition: Ch 14.02 — Publishing to crates.io, section Making useful documentation][2]** -* [In the first edition: Ch 4.4 — Documentation][1] - - -[1]: first-edition/documentation.html -[2]: second-edition/ch14-02-publishing-to-crates-io.html#making-useful-documentation-comments +You can find the latest version of this information +[here](ch14-02-publishing-to-crates-io.html#making-useful-documentation-comments). \ No newline at end of file diff --git a/redirects/drop.md b/redirects/drop.md index f5f01e377e..164f1d7459 100644 --- a/redirects/drop.md +++ b/redirects/drop.md @@ -26,9 +26,9 @@ fn main() { Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 15.03 — The `Drop` Trait Runs Code on Cleanup][2]** +* **[in the current edition: Ch 15.03 — The `Drop` Trait Runs Code on Cleanup][2]** * [In the first edition: Ch 3.20 — Drop][1] -[1]: first-edition/drop.html -[2]: second-edition/ch15-03-drop.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/drop.html +[2]: ch15-03-drop.html diff --git a/redirects/effective-rust.md b/redirects/effective-rust.md index 5c93d84b79..30312a3ddb 100644 --- a/redirects/effective-rust.md +++ b/redirects/effective-rust.md @@ -10,5 +10,5 @@ It is recommended to start there. * [In the first edition: Ch 4 — Effective Rust][1] -[1]: first-edition/effective-rust.html -[2]: second-edition/index.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/effective-rust.html +[2]: index.html diff --git a/redirects/enums.md b/redirects/enums.md index 9b97970909..c770d6b001 100644 --- a/redirects/enums.md +++ b/redirects/enums.md @@ -15,9 +15,9 @@ enum IpAddrKind { Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 6.01 — Defining an Enum][2]** +* **[in the current edition: Ch 6.01 — Defining an Enum][2]** * [In the first edition: Ch 3.13 — Enums][1] -[1]: first-edition/enums.html -[2]: second-edition/ch06-01-defining-an-enum.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/enums.html +[2]: ch06-01-defining-an-enum.html diff --git a/redirects/error-handling.md b/redirects/error-handling.md index e915657ea4..7abc9642b6 100644 --- a/redirects/error-handling.md +++ b/redirects/error-handling.md @@ -8,9 +8,9 @@ Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 9.00 — Error Handling][2]** +* **[in the current edition: Ch 9.00 — Error Handling][2]** * [In the first edition: Ch 4.7 — Error Handling][1] -[1]: first-edition/error-handling.html -[2]: second-edition/ch09-00-error-handling.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/error-handling.html +[2]: ch09-00-error-handling.html diff --git a/redirects/ffi.md b/redirects/ffi.md index 8a885928af..20ed3963ef 100644 --- a/redirects/ffi.md +++ b/redirects/ffi.md @@ -19,11 +19,5 @@ fn main() { --- -Here are the relevant sections in the new and old books: - -* **[In the second edition: Ch 19.01 — Unsafe Rust, section `extern` functions][2]** -* [In the first edition: Ch 4.9 — FFI][1] - - -[1]: first-edition/ffi.html -[2]: second-edition/ch19-01-unsafe-rust.html#using-extern-functions-to-call-external-code +You can find the latest version of this information +[here](ch19-01-unsafe-rust.html#using-extern-functions-to-call-external-code) \ No newline at end of file diff --git a/redirects/functions.md b/redirects/functions.md index 5c61fe56b3..eecbfd49cd 100644 --- a/redirects/functions.md +++ b/redirects/functions.md @@ -23,8 +23,8 @@ fn another_function() { Here are the relevant sections in the new and old books: * **[In the first edition: Ch 3.2 — Functions][1]** -* [In the second edition: Ch 3.03 — Functions][2] +* [in the current edition: Ch 3.03 — Functions][2] -[1]: first-edition/functions.html -[2]: second-edition/ch03-03-how-functions-work.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/functions.html +[2]: ch03-03-how-functions-work.html diff --git a/redirects/generics.md b/redirects/generics.md index 8e52802dfa..80700973fb 100644 --- a/redirects/generics.md +++ b/redirects/generics.md @@ -21,10 +21,10 @@ fn main() { Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 10.00 — Generic Types, Traits, and Lifetimes][2]** +* **[in the current edition: Ch 10.00 — Generic Types, Traits, and Lifetimes][2]** * [In the first edition: Ch 3.18 — Generics][1] -[1]: first-edition/generics.html -[2]: second-edition/ch10-00-generics.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/generics.html +[2]: ch10-00-generics.html diff --git a/redirects/getting-started.md b/redirects/getting-started.md index b93a5625ea..1c84cbbaf7 100644 --- a/redirects/getting-started.md +++ b/redirects/getting-started.md @@ -5,9 +5,9 @@ You can [continue to the exact older page][1]. If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. -* **[In the second edition: Getting Started][2]** +* **[in the current edition: Getting Started][2]** * [In the first edition: Getting Started][1] -[1]: first-edition/getting-started.html -[2]: second-edition/ch01-00-getting-started.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/getting-started.html +[2]: ch01-00-getting-started.html diff --git a/redirects/glossary.md b/redirects/glossary.md index 6891dc1e05..c0f9f8e725 100644 --- a/redirects/glossary.md +++ b/redirects/glossary.md @@ -10,5 +10,5 @@ It is recommended to start there. * [In the first edition: Glossary][1] -[1]: first-edition/glossary.html -[2]: second-edition/index.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/glossary.html +[2]: index.html diff --git a/redirects/guessing-game.md b/redirects/guessing-game.md index 3a243dd4b8..6abf4023b0 100644 --- a/redirects/guessing-game.md +++ b/redirects/guessing-game.md @@ -5,8 +5,8 @@ If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. * **[In the first edition: Tutorial — Guessing Game][1]** -* [In the second edition: Ch 2.00 — Guessing Game tutorial][2] +* [in the current edition: Ch 2.00 — Guessing Game tutorial][2] -[1]: first-edition/guessing-game.html -[2]: second-edition/ch02-00-guessing-game-tutorial.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/guessing-game.html +[2]: ch02-00-guessing-game-tutorial.html diff --git a/redirects/if-let.md b/redirects/if-let.md index 95da06a455..edbe5d88b0 100644 --- a/redirects/if-let.md +++ b/redirects/if-let.md @@ -15,9 +15,8 @@ if let Some(3) = some_u8_value { Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 6.03 — Concise Control Flow with `if let`][2]** +* [In the current edition: Ch 6.03 — Concise Control Flow with `if let`][2] * [In the first edition: Ch 3.21 — if let][1] - -[1]: first-edition/if-let.html -[2]: second-edition/ch06-03-if-let.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/if-let.html +[2]: ch06-03-if-let.html diff --git a/redirects/if.md b/redirects/if.md index cf933a44d0..ff97e94f16 100644 --- a/redirects/if.md +++ b/redirects/if.md @@ -18,11 +18,5 @@ fn main() { --- -Here are the relevant sections in the new and old books: - -* **[In the second edition: Ch 3.05 — Control flow][2]** -* [In the first edition: Ch 3.5 — if][1] - - -[1]: first-edition/if.html -[2]: second-edition/ch03-05-control-flow.html#if-expressions +You can find the latest version of this information +[here](ch03-05-control-flow.html#if-expressions). \ No newline at end of file diff --git a/redirects/iterators.md b/redirects/iterators.md index 03c7134126..26cb047668 100644 --- a/redirects/iterators.md +++ b/redirects/iterators.md @@ -19,9 +19,9 @@ for val in v1_iter { Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 13.02 — Iterators][2]** +* **[in the current edition: Ch 13.02 — Iterators][2]** * [In the first edition: Ch 4.5 — Iterators][1] -[1]: first-edition/iterators.html -[2]: second-edition/ch13-02-iterators.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/iterators.html +[2]: ch13-02-iterators.html diff --git a/redirects/lifetimes.md b/redirects/lifetimes.md index e9a5492719..21ddb38ce8 100644 --- a/redirects/lifetimes.md +++ b/redirects/lifetimes.md @@ -20,11 +20,9 @@ Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 10.03 — Lifetimes][2]** -* [In the second edition: Ch 19.02 — Advanced Lifetimes][3] +* **[in the current edition: Ch 10.03 — Lifetimes][2]** * [In the first edition: Ch 3.10 — Lifetimes][1] -[1]: first-edition/lifetimes.html -[2]: second-edition/ch10-03-lifetime-syntax.html -[3]: second-edition/ch19-02-advanced-lifetimes.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/lifetimes.html +[2]: ch10-03-lifetime-syntax.html diff --git a/redirects/loops.md b/redirects/loops.md index cabe918b4b..1686c115ee 100644 --- a/redirects/loops.md +++ b/redirects/loops.md @@ -26,11 +26,5 @@ for element in a.iter() { --- -Here are the relevant sections in the new and old books: - -* **[In the second edition: Ch 3.05 — Control flow][2]** -* [In the first edition: Ch 3.6 — Loops][1] - - -[1]: first-edition/loops.html -[2]: second-edition/ch03-05-control-flow.html#repetition-with-loops +You can find the latest version of this information +[here](ch03-05-control-flow.html#repetition-with-loops). \ No newline at end of file diff --git a/redirects/macros.md b/redirects/macros.md index d2c83ac500..08217d115d 100644 --- a/redirects/macros.md +++ b/redirects/macros.md @@ -16,16 +16,15 @@ fn main() { --- -This chapter does not exist yet in [the second edition][2]. -You can check out other resources that describe macros. +Here are the relevant sections in the new and old books: -* **[Rust By Example: Macros][3]** +* **[In the current edition: Ch 19.06 Macros][2]** +* [Rust By Example: Macros][3] * [In the Rust Reference: Ch 3.1 — Macros by Example][4] -* [In the second edition: (future) Appendix D — Macros][2] * [In the first edition: Ch 3.34 — Macros][1] -[1]: first-edition/macros.html -[2]: second-edition/appendix-04-macros.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/macros.html +[2]: ch19-06-macros.html [3]: https://rustbyexample.com/macros.html -[4]: ../reference/macros-by-example.html \ No newline at end of file +[4]: ../reference/macros-by-example.html diff --git a/redirects/match.md b/redirects/match.md index 5a32215ab4..fd28ba8dea 100644 --- a/redirects/match.md +++ b/redirects/match.md @@ -27,12 +27,12 @@ fn value_in_cents(coin: Coin) -> u32 { Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 6.02 — The `match` Control Flow Operator][2]** -* [In the second edition: Ch 18.00 — Patterns][3] +* **[in the current edition: Ch 6.02 — The `match` Control Flow Operator][2]** +* [in the current edition: Ch 18.00 — Patterns][3] * [In the first edition: Ch 3.14 — Match][1] -[1]: first-edition/match.html -[2]: second-edition/ch06-02-match.html -[3]: second-edition/ch18-00-patterns.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/match.html +[2]: ch06-02-match.html +[3]: ch18-00-patterns.html diff --git a/redirects/method-syntax.md b/redirects/method-syntax.md index a842c9badb..29cd2cd7cd 100644 --- a/redirects/method-syntax.md +++ b/redirects/method-syntax.md @@ -21,9 +21,9 @@ impl Rectangle { Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 5.03 — Method Syntax][2]** +* **[in the current edition: Ch 5.03 — Method Syntax][2]** * [In the first edition: Ch 3.16 — Method Syntax][1] -[1]: first-edition/method-syntax.html -[2]: second-edition/ch05-03-method-syntax.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/method-syntax.html +[2]: ch05-03-method-syntax.html diff --git a/redirects/mutability.md b/redirects/mutability.md index 6f48bc3065..89fc3b6f56 100644 --- a/redirects/mutability.md +++ b/redirects/mutability.md @@ -15,9 +15,9 @@ println!("The value of x is: {}", x); Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 3.01 — Variables and Mutability][2]** +* **[in the current edition: Ch 3.01 — Variables and Mutability][2]** * [In the first edition: Ch 3.11 — Mutability][1] -[1]: first-edition/mutability.html -[2]: second-edition/ch03-01-variables-and-mutability.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/mutability.html +[2]: ch03-01-variables-and-mutability.html diff --git a/redirects/operators-and-overloading.md b/redirects/operators-and-overloading.md index 8094325e17..ff9a33048a 100644 --- a/redirects/operators-and-overloading.md +++ b/redirects/operators-and-overloading.md @@ -32,12 +32,5 @@ fn main() { --- -Here are the relevant sections in the new and old books: - -* **[In the second edition: Ch 19.03 — Advanced Traits, section Operator Overloading][2]** -* [In the Rust documentation: `std::ops`][3] -* [In the first edition: Ch 3.32 — Operators and Overloading][1] - -[1]: first-edition/operators-and-overloading.html -[2]: second-edition/ch19-03-advanced-traits.html#default-generic-type-parameters-and-operator-overloading -[3]: ../std/ops/index.html +You can find the latest version of this information +[here](ch19-03-advanced-traits.html). diff --git a/redirects/ownership.md b/redirects/ownership.md index adca776217..3e7ece3b48 100644 --- a/redirects/ownership.md +++ b/redirects/ownership.md @@ -12,9 +12,9 @@ Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 4.00 — Understanding Ownership][2]** +* **[in the current edition: Ch 4.00 — Understanding Ownership][2]** * [In the first edition: Ch 3.8 — Ownership][1] -[1]: first-edition/ownership.html -[2]: second-edition/ch04-00-understanding-ownership.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/ownership.html +[2]: ch04-00-understanding-ownership.html diff --git a/redirects/patterns.md b/redirects/patterns.md index 4044f16ab6..1936368b20 100644 --- a/redirects/patterns.md +++ b/redirects/patterns.md @@ -19,13 +19,5 @@ match x { --- -Here are the relevant sections in the new and old books: - -* **[In the second edition: Ch 18.03 — Patterns][2]** -* [In the second edition: Ch 6.02 — Match][3] -* [In the first edition: Ch 3.15 — Patterns][1] - - -[1]: first-edition/patterns.html -[2]: second-edition/ch18-00-patterns.html -[3]: second-edition/ch06-02-match.html#patterns-that-bind-to-values +You can find the latest version of this information +[here](ch06-02-match.html). \ No newline at end of file diff --git a/redirects/primitive-types.md b/redirects/primitive-types.md index 7244fbaa60..aff51f782f 100644 --- a/redirects/primitive-types.md +++ b/redirects/primitive-types.md @@ -16,9 +16,9 @@ let y: f32 = 3.0; // f32 Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 3.02 — Data Types][2]** +* **[in the current edition: Ch 3.02 — Data Types][2]** * [In the first edition: Ch 3.3 — Primitive Types][1] -[1]: first-edition/primitive-types.html -[2]: second-edition/ch03-02-data-types.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/primitive-types.html +[2]: ch03-02-data-types.html diff --git a/redirects/procedural-macros.md b/redirects/procedural-macros.md index 4cf8ec6b65..bf6665f1a6 100644 --- a/redirects/procedural-macros.md +++ b/redirects/procedural-macros.md @@ -9,13 +9,13 @@ This chapter does not exist yet in [the second edition][2]. You can check out other resources that describe macros. -* **[In the Rust Reference: Ch 3.2 — Procedural Macros][4]** +* **[In the current edition: Ch 19.06 Macros][2]** +* [In the Rust Reference: Ch 3.2 — Procedural Macros][4] * [The `proc_macro` crate documentation][3] -* [In the second edition: (future) Appendix D — Macros][2] * [In the first edition: Ch 4.13 — Procedural Macros (and custom Derive)][1] -[1]: first-edition/procedural-macros.html -[2]: second-edition/appendix-04-macros.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/procedural-macros.html +[2]: ch19-06-macros.html [3]: ../proc_macro/index.html -[4]: ../reference/procedural-macros.html \ No newline at end of file +[4]: ../reference/procedural-macros.html diff --git a/redirects/raw-pointers.md b/redirects/raw-pointers.md index 08a6900d79..773f3abc48 100644 --- a/redirects/raw-pointers.md +++ b/redirects/raw-pointers.md @@ -13,11 +13,5 @@ let r2 = &mut num as *mut i32; --- -Here are the relevant sections in the new and old books: - -* **[In the second edition: Ch 19.01 — Unsafe Rust, section Dereferencing a Raw Pointer][2]** -* [In the first edition: Ch 3.35 — Raw Pointers][1] - - -[1]: first-edition/raw-pointers.html -[2]: second-edition/ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer +You can find the latest version of this information +[here](ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer) \ No newline at end of file diff --git a/redirects/references-and-borrowing.md b/redirects/references-and-borrowing.md index c3e29d671e..7eb8da2bdf 100644 --- a/redirects/references-and-borrowing.md +++ b/redirects/references-and-borrowing.md @@ -16,9 +16,9 @@ fn calculate_length(s: &String) -> usize { // s is a reference to a String Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 4.02 — References and Borrowing][2]** +* **[in the current edition: Ch 4.02 — References and Borrowing][2]** * [In the first edition: Ch 3.9 — References and Borrowing][1] -[1]: first-edition/references-and-borrowing.html -[2]: second-edition/ch04-02-references-and-borrowing.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/references-and-borrowing.html +[2]: ch04-02-references-and-borrowing.html diff --git a/redirects/release-channels.md b/redirects/release-channels.md index 62ee6d0845..6e01e227fe 100644 --- a/redirects/release-channels.md +++ b/redirects/release-channels.md @@ -16,13 +16,13 @@ You can check out other resources that describe release channels. * **[In the Rustup documentation: Keeping Rust Up-to-date][4]** * [On the website: Install Rust][5] * [In the Rust RFCs: RFC 507 — Release Channels][3] -* [In the second edition: How Rust is Made and “Nightly Rust”][2] +* [in the current edition: How Rust is Made and “Nightly Rust”][2] * [In the first edition: Ch 4.11 — Release Channels][1] -[1]: first-edition/release-channels.html -[2]: second-edition/appendix-07-nightly-rust.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/release-channels.html +[2]: appendix-07-nightly-rust.html [3]: https://github.com/rust-lang/rfcs/blob/master/text/0507-release-channels.md [4]: https://github.com/rust-lang-nursery/rustup.rs/blob/master/README.md#keeping-rust-up-to-date -[5]: https://www.rust-lang.org/en-US/install.html +[5]: https://www.rust-lang.org/en-US/tools/install diff --git a/redirects/strings.md b/redirects/strings.md index 2e50d9d88c..3084e8d457 100644 --- a/redirects/strings.md +++ b/redirects/strings.md @@ -15,15 +15,5 @@ let world = &s[6..11]; --- -Here are the relevant sections in the new and old books: - -* **[In second edition: Ch 8.02 — Strings][2]** -* [In second edition: Ch 4.01 — Ownership, section The String Type][3] -* [In second edition: Ch 4.03 — Slices, section String Slices][4] -* [In the first edition: Ch 3.17 — Strings][1] - - -[1]: first-edition/strings.html -[2]: second-edition/ch08-02-strings.html -[3]: second-edition/ch04-01-what-is-ownership.html#the-string-type -[4]: second-edition/ch04-03-slices.html#string-slices +You can find the latest version of this information +[here](ch08-02-strings.html). \ No newline at end of file diff --git a/redirects/structs.md b/redirects/structs.md index eb18820476..5c5427c55a 100644 --- a/redirects/structs.md +++ b/redirects/structs.md @@ -21,5 +21,5 @@ Here are the relevant sections in the new and old books: * [In the first edition: Ch 3.12 — Structs][1] -[1]: first-edition/structs.html -[2]: second-edition/ch05-00-structs.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/structs.html +[2]: ch05-00-structs.html diff --git a/redirects/syntax-and-semantics.md b/redirects/syntax-and-semantics.md index 293f694fac..b1f4f8acad 100644 --- a/redirects/syntax-and-semantics.md +++ b/redirects/syntax-and-semantics.md @@ -5,14 +5,14 @@ Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 3.00 — Common Programming Concepts][2]** -* [In the second edition: Appendix A — Keywords][3] -* [In the second edition: Appendix B — Operators][4] +* **[in the current edition: Ch 3.00 — Common Programming Concepts][2]** +* [in the current edition: Appendix A — Keywords][3] +* [in the current edition: Appendix B — Operators][4] * [In the first edition: Ch 3 — Syntax and Semantics][1] -[1]: first-edition/syntax-and-semantics.html -[2]: second-edition/ch03-00-common-programming-concepts.html -[3]: second-edition/appendix-01-keywords.html -[4]: second-edition/appendix-02-operators.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/syntax-and-semantics.html +[2]: ch03-00-common-programming-concepts.html +[3]: appendix-01-keywords.html +[4]: appendix-02-operators.html diff --git a/redirects/syntax-index.md b/redirects/syntax-index.md index cd03b67205..c9513bf0e5 100644 --- a/redirects/syntax-index.md +++ b/redirects/syntax-index.md @@ -4,11 +4,10 @@ Here are the relevant sections in the new and old books: -* **[In the second edition: Appendix A — Keywords][2]** -* **[In the second edition: Appendix B — Operators][3]** +* **[In the current edition: Appendix A — Keywords][2]** +* **[In the current edition: Appendix B — Operators][3]** * [In the first edition: Ch 6 — Syntax Index][1] - -[1]: first-edition/syntax-index.html -[2]: second-edition/appendix-01-keywords.html -[3]: second-edition/appendix-02-operators.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/syntax-index.html +[2]: appendix-01-keywords.html +[3]: appendix-02-operators.html diff --git a/redirects/testing.md b/redirects/testing.md index 79b325b8ed..f2030654fd 100644 --- a/redirects/testing.md +++ b/redirects/testing.md @@ -17,9 +17,9 @@ mod tests { Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 11.00 — Testing][2]** +* **[in the current edition: Ch 11.00 — Testing][2]** * [In the first edition: Ch 4.2 — Testing][1] -[1]: first-edition/testing.html -[2]: second-edition/ch11-00-testing.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/testing.html +[2]: ch11-00-testing.html diff --git a/redirects/the-stack-and-the-heap.md b/redirects/the-stack-and-the-heap.md index 59938b6bf9..e2d4d3ac93 100644 --- a/redirects/the-stack-and-the-heap.md +++ b/redirects/the-stack-and-the-heap.md @@ -9,11 +9,5 @@ --- -Here are the relevant sections in the new and old books: - -* **[In the second edition: Ch 4.01 — What is Ownership, section The Stack and the Heap][2]** -* [In the first edition: Ch 4.1 — The Stack and the Heap][1] - - -[1]: first-edition/the-stack-and-the-heap.html -[2]: second-edition/ch04-01-what-is-ownership.html#the-stack-and-the-heap +You can find the latest version of this information +[here](ch04-01-what-is-ownership.html#the-stack-and-the-heap). \ No newline at end of file diff --git a/redirects/trait-objects.md b/redirects/trait-objects.md index 869df02062..3200e26a15 100644 --- a/redirects/trait-objects.md +++ b/redirects/trait-objects.md @@ -60,9 +60,9 @@ fn main() { Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 17.02 — Trait Objects][2]** +* **[in the current edition: Ch 17.02 — Trait Objects][2]** * [In the first edition: Ch 3.22 — Trait Objects][1] -[1]: first-edition/trait-objects.html -[2]: second-edition/ch17-02-trait-objects.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/trait-objects.html +[2]: ch17-02-trait-objects.html diff --git a/redirects/traits.md b/redirects/traits.md index baffad4a43..dcb577e97b 100644 --- a/redirects/traits.md +++ b/redirects/traits.md @@ -14,11 +14,11 @@ pub trait Summarizable { Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 10.02 — Traits][2]** -* [In the second edition: Ch 19.03 — Advanced Traits][3] +* **[in the current edition: Ch 10.02 — Traits][2]** +* [in the current edition: Ch 19.03 — Advanced Traits][3] * [In the first edition: Ch 3.19 — Traits][1] -[1]: first-edition/traits.html -[2]: second-edition/ch10-02-traits.html -[3]: second-edition/ch19-03-advanced-traits.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/traits.html +[2]: ch10-02-traits.html +[3]: ch19-03-advanced-traits.html diff --git a/redirects/type-aliases.md b/redirects/type-aliases.md index 33e9f1faf7..85cd4c9ecc 100644 --- a/redirects/type-aliases.md +++ b/redirects/type-aliases.md @@ -10,12 +10,5 @@ type Kilometers = i32; --- -Here are the relevant sections in the new and old books: - -* **[In the second edition: Ch 19.04 — Advanced Types, section Type Synonyms][2]** -* [In the first edition: Ch 3.28 — `type` aliases][1] - - -[1]: first-edition/type-aliases.html -[2]: second-edition/ch19-04-advanced-types.html#type-aliases-create-type-synonyms - +You can find the latest version of this information +[here](ch19-04-advanced-types.html#creating-type-synonyms-with-type-aliases). \ No newline at end of file diff --git a/redirects/ufcs.md b/redirects/ufcs.md index eca6e6a9d9..2959c06bd0 100644 --- a/redirects/ufcs.md +++ b/redirects/ufcs.md @@ -44,11 +44,5 @@ fn main() { --- -Here are the relevant sections in the new and old books: - -* **[In the second edition: Ch 19.03 — Advanced Traits, section Fully Qualified Syntax][2]** -* [In the first edition: Ch 3.24 — Universal Function Call Syntax][1] - - -[1]: first-edition/ufcs.html -[2]: second-edition/ch19-03-advanced-traits.html#fully-qualified-syntax-for-disambiguation-calling-methods-with-the-same-name +You can find the latest version of this information +[here](ch19-03-advanced-traits.html#fully-qualified-syntax-for-disambiguation-calling-methods-with-the-same-name). \ No newline at end of file diff --git a/redirects/unsafe.md b/redirects/unsafe.md index 73685fc83d..8628c7aa95 100644 --- a/redirects/unsafe.md +++ b/redirects/unsafe.md @@ -8,11 +8,11 @@ Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 19.01 — Unsafe Rust][2]** +* **[in the current edition: Ch 19.01 — Unsafe Rust][2]** * [The Rustonomicon, The Dark Arts of Advanced and Unsafe Rust Programming][3] * [In the first edition: Ch 3.36 — `unsafe`][1] -[1]: first-edition/unsafe.html -[2]: second-edition/ch19-01-unsafe-rust.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/unsafe.html +[2]: ch19-01-unsafe-rust.html [3]: ../nomicon/index.html diff --git a/redirects/unsized-types.md b/redirects/unsized-types.md index d209c0d3bc..bd9582cbac 100644 --- a/redirects/unsized-types.md +++ b/redirects/unsized-types.md @@ -14,11 +14,5 @@ fn generic(t: &T) { --- -Here are the relevant sections in the new and old books: - -* **[In the second edition: Ch 19.04 — Advanced Types, section Dynamically Sized Types][2]** -* [In the first edition: Ch 3.31 — Unsized Types][1] - - -[1]: first-edition/unsized-types.html -[2]: second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized +You can find the latest version of this information +[here](ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait). \ No newline at end of file diff --git a/redirects/using-rust-without-the-standard-library.md b/redirects/using-rust-without-the-standard-library.md index 06deb6ee46..75145429d4 100644 --- a/redirects/using-rust-without-the-standard-library.md +++ b/redirects/using-rust-without-the-standard-library.md @@ -13,5 +13,5 @@ This particular chapter has moved to [the Unstable Book][2]. * [In the first edition: Ch 4.12 — Using Rust without the Standard Library][1] -[1]: first-edition/using-rust-without-the-standard-library.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/using-rust-without-the-standard-library.html [2]: ../unstable-book/language-features/lang-items.html#writing-an-executable-without-stdlib diff --git a/redirects/variable-bindings.md b/redirects/variable-bindings.md index fcafa7e2af..0bd437ec31 100644 --- a/redirects/variable-bindings.md +++ b/redirects/variable-bindings.md @@ -10,11 +10,5 @@ let foo = 5; --- -Here are the relevant sections in the new and old books: - -* **[In the second edition: Ch 2.00 — Guessing Game Tutorial, section Variables][2]** -* [In the first edition: Ch 3.1 — Variable Bindings][1] - - -[1]: first-edition/variable-bindings.html -[2]: second-edition/ch02-00-guessing-game-tutorial.html#storing-values-with-variables +You can find the latest version of this information +[here](ch02-00-guessing-game-tutorial.html#storing-values-with-variables). \ No newline at end of file diff --git a/redirects/vectors.md b/redirects/vectors.md index ac05844842..1359f9da84 100644 --- a/redirects/vectors.md +++ b/redirects/vectors.md @@ -14,10 +14,10 @@ let numbers = vec![1, 2, 3]; Here are the relevant sections in the new and old books: -* **[In the second edition: Ch 8.01 — Vectors][2]** +* **[in the current edition: Ch 8.01 — Vectors][2]** * [In the first edition: Ch 3.7 — Vectors][1] -[1]: first-edition/vectors.html -[2]: second-edition/ch08-01-vectors.html +[1]: https://doc.rust-lang.org/1.30.0/book/first-edition/vectors.html +[2]: ch08-01-vectors.html diff --git a/rust-toolchain b/rust-toolchain new file mode 100644 index 0000000000..32b7211cb6 --- /dev/null +++ b/rust-toolchain @@ -0,0 +1 @@ +1.40.0 diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000000..df99c69198 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1 @@ +max_width = 80 diff --git a/second-edition/LICENSE-APACHE b/second-edition/LICENSE-APACHE deleted file mode 100644 index 96e9f0458b..0000000000 --- a/second-edition/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - 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-2017 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. diff --git a/second-edition/LICENSE-MIT b/second-edition/LICENSE-MIT deleted file mode 100644 index 5a56e6e8ed..0000000000 --- a/second-edition/LICENSE-MIT +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2010-2017 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. diff --git a/second-edition/convert-quotes.sh b/second-edition/convert-quotes.sh deleted file mode 100755 index 229be88921..0000000000 --- a/second-edition/convert-quotes.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/bash -# Copyright 2017 The Rust Project Developers. See the COPYRIGHT -# file at the top-level directory of this distribution and at -# http://rust-lang.org/COPYRIGHT. -# -# Licensed under the Apache License, Version 2.0 or the MIT license -# , at your -# option. This file may not be copied, modified, or distributed -# except according to those terms. - -set -eu - -dir=$1 - -mkdir -p "tmp/$dir" - -for f in $dir/*.md -do - cat "$f" | cargo run --bin convert_quotes > "tmp/$f" - mv "tmp/$f" "$f" -done diff --git a/second-edition/doc-to-md.sh b/second-edition/doc-to-md.sh deleted file mode 100755 index 259d6f02f0..0000000000 --- a/second-edition/doc-to-md.sh +++ /dev/null @@ -1,29 +0,0 @@ -#!/bin/bash -# Copyright 2016 The Rust Project Developers. See the COPYRIGHT -# file at the top-level directory of this distribution and at -# http://rust-lang.org/COPYRIGHT. -# -# Licensed under the Apache License, Version 2.0 or the MIT license -# , at your -# option. This file may not be copied, modified, or distributed -# except according to those terms. - -set -eu - -# Get all the docx files in the tmp dir, -ls tmp/*.docx | \ -# Extract just the filename so we can reuse it easily. -xargs -n 1 basename -s .docx | \ -while IFS= read -r filename; do - # Make a directory to put the XML in - mkdir -p "tmp/$filename" - # Unzip the docx to get at the xml - unzip -o "tmp/$filename.docx" -d "tmp/$filename" - # Convert to markdown with XSL - xsltproc tools/docx-to-md.xsl "tmp/$filename/word/document.xml" | \ - # Hard wrap at 80 chars at word bourdaries - fold -w 80 -s | \ - # Remove trailing whitespace & save in the nostarch dir for comparison - sed -e "s/ *$//" > "nostarch/$filename.md" -done diff --git a/second-edition/nostarch.sh b/second-edition/nostarch.sh deleted file mode 100755 index 432add597c..0000000000 --- a/second-edition/nostarch.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/bin/bash -# Copyright 2016 The Rust Project Developers. See the COPYRIGHT -# file at the top-level directory of this distribution and at -# http://rust-lang.org/COPYRIGHT. -# -# Licensed under the Apache License, Version 2.0 or the MIT license -# , at your -# option. This file may not be copied, modified, or distributed -# except according to those terms. - -set -eu - -cargo build --release - -mkdir -p tmp -rm -rf tmp/*.md - -# Get all the markdown files in the src dir, -ls src/${1:-""}*.md | \ -# except for SUMMARY.md. -grep -v SUMMARY.md | \ -# Extract just the filename so we can reuse it easily. -xargs -n 1 basename | \ -# Remove all links followed by , then -# Change all remaining links from markdown to italicized inline text. -while IFS= read -r filename; do - < "src/$filename" ./target/release/remove_links \ - | ./target/release/link2print \ - | ./target/release/remove_markup > "tmp/$filename" -done -# Concat the files into the nostarch dir. -./target/release/concat_chapters tmp nostarch diff --git a/second-edition/nostarch/appendix.md b/second-edition/nostarch/appendix.md deleted file mode 100644 index c03ce8f966..0000000000 --- a/second-edition/nostarch/appendix.md +++ /dev/null @@ -1,912 +0,0 @@ -## Appendix A: Keywords - -The following keywords are reserved by the Rust language and may not be used as -identifiers such as names of functions, variables, parameters, struct fields, -modules, crates, constants, macros, static values, attributes, types, traits, -or lifetimes. - -### Keywords Currently in Use - -* `as` - primitive casting, disambiguating the specific trait containing an - item, or renaming items in `use` and `extern crate` statements -* `break` - exit a loop immediately -* `const` - constant items and constant raw pointers -* `continue` - continue to the next loop iteration -* `crate` - external crate linkage or a macro variable representing the crate - in which the macro is defined -* `else` - fallback for `if` and `if let` control flow constructs -* `enum` - defining an enumeration -* `extern` - external crate, function, and variable linkage -* `false` - Boolean false literal -* `fn` - function definition and function pointer type -* `for` - iterator loop, part of trait impl syntax, and higher-ranked lifetime - syntax -* `if` - conditional branching -* `impl` - inherent and trait implementation block -* `in` - part of `for` loop syntax -* `let` - variable binding -* `loop` - unconditional, infinite loop -* `match` - pattern matching -* `mod` - module declaration -* `move` - makes a closure take ownership of all its captures -* `mut` - denotes mutability in references, raw pointers, and pattern bindings -* `pub` - denotes public visibility in struct fields, `impl` blocks, and modules -* `ref` - by-reference binding -* `return` - return from function -* `Self` - type alias for the type implementing a trait -* `self` - method subject or current module -* `static` - global variable or lifetime lasting the entire program execution -* `struct` - structure definition -* `super` - parent module of the current module -* `trait` - trait definition -* `true` - Boolean true literal -* `type` - type alias and associated type definition -* `unsafe` - denotes unsafe code, functions, traits, and implementations -* `use` - import symbols into scope -* `where` - type constraint clauses -* `while` - conditional loop - -### Keywords Reserved for Future Use - -These keywords do not have any functionality, but are reserved by Rust for -potential future use. - -* `abstract` -* `alignof` -* `become` -* `box` -* `do` -* `final` -* `macro` -* `offsetof` -* `override` -* `priv` -* `proc` -* `pure` -* `sizeof` -* `typeof` -* `unsized` -* `virtual` -* `yield` - -## Appendix B: Operators and Symbols - -### Operators - -The following lists the operators in Rust, an example of how the operator would -appear in context, a short explanation, and whether that operator is -overloadable. If an operator is overloadable, the relevant trait to use to -overload that operator is listed. - -* `!` (`ident!(…)`, `ident!{…}`, `ident![…]`): denotes macro expansion. -* `!` (`!expr`): bitwise or logical complement. Overloadable (`Not`). -* `!=` (`var != expr`): nonequality comparison. Overloadable (`PartialEq`). -* `%` (`expr % expr`): arithmetic remainder. Overloadable (`Rem`). -* `%=` (`var %= expr`): arithmetic remainder and assignment. Overloadable (`RemAssign`). -* `&` (`&expr`, `&mut expr`): borrow. -* `&` (`&type`, `&mut type`, `&'a type`, `&'a mut type`): borrowed pointer type. -* `&` (`expr & expr`): bitwise AND. Overloadable (`BitAnd`). -* `&=` (`var &= expr`): bitwise AND and assignment. Overloadable (`BitAndAssign`). -* `&&` (`expr && expr`): logical AND. -* `*` (`expr * expr`): arithmetic multiplication. Overloadable (`Mul`). -* `*` (`*expr`): dereference. -* `*` (`*const type`, `*mut type`): raw pointer. -* `*=` (`var *= expr`): arithmetic multiplication and assignment. Overloadable (`MulAssign`). -* `+` (`trait + trait`, `'a + trait`): compound type constraint. -* `+` (`expr + expr`): arithmetic addition. Overloadable (`Add`). -* `+=` (`var += expr`): arithmetic addition and assignment. Overloadable (`AddAssign`). -* `,`: argument and element separator. -* `-` (`- expr`): arithmetic negation. Overloadable (`Neg`). -* `-` (`expr - expr`): arithmetic subtraction. Overloadable (`Sub`). -* `-=` (`var -= expr`): arithmetic subtraction and assignment. Overloadable (`SubAssign`). -* `->` (`fn(…) -> type`, `|…| -> type`): function and closure return type. -* `.` (`expr.ident`): member access. -* `..` (`..`, `expr..`, `..expr`, `expr..expr`): right-exclusive range literal. -* `..` (`..expr`): struct literal update syntax. -* `..` (`variant(x, ..)`, `struct_type { x, .. }`): “and the rest” pattern binding. -* `...` (`...expr`, `expr...expr`) *in an expression*: inclusive range expression. -* `...` (`expr...expr`) *in a pattern*: inclusive range pattern. -* `/` (`expr / expr`): arithmetic division. Overloadable (`Div`). -* `/=` (`var /= expr`): arithmetic division and assignment. Overloadable (`DivAssign`). -* `:` (`pat: type`, `ident: type`): constraints. -* `:` (`ident: expr`): struct field initializer. -* `:` (`'a: loop {…}`): loop label. -* `;`: statement and item terminator. -* `;` (`[…; len]`): part of fixed-size array syntax -* `<<` (`expr << expr`): left-shift. Overloadable (`Shl`). -* `<<=` (`var <<= expr`): left-shift and assignment. Overloadable (`ShlAssign`). -* `<` (`expr < expr`): less-than comparison. Overloadable (`PartialOrd`). -* `<=` (`var <= expr`): less-than or equal-to comparison. Overloadable (`PartialOrd`). -* `=` (`var = expr`, `ident = type`): assignment/equivalence. -* `==` (`var == expr`): equality comparison. Overloadable (`PartialEq`). -* `=>` (`pat => expr`): part of match arm syntax. -* `>` (`expr > expr`): greater-than comparison. Overloadable (`PartialOrd`). -* `>=` (`var >= expr`): greater-than or equal-to comparison. Overloadable (`PartialOrd`). -* `>>` (`expr >> expr`): right-shift. Overloadable (`Shr`). -* `>>=` (`var >>= expr`): right-shift and assignment. Overloadable (`ShrAssign`). -* `@` (`ident @ pat`): pattern binding. -* `^` (`expr ^ expr`): bitwise exclusive OR. Overloadable (`BitXor`). -* `^=` (`var ^= expr`): bitwise exclusive OR and assignment. Overloadable (`BitXorAssign`). -* `|` (`pat | pat`): pattern alternatives. -* `|` (`|…| expr`): closures. -* `|` (`expr | expr`): bitwise OR. Overloadable (`BitOr`). -* `|=` (`var |= expr`): bitwise OR and assignment. Overloadable (`BitOrAssign`). -* `||` (`expr || expr`): logical OR. -* `_`: “ignored” pattern binding. Also used to make integer-literals readable. -* `?` (`expr?`): Error propagation. - -### Non-operator Symbols - -#### Standalone Syntax - -* `'ident`: named lifetime or loop label -* `…u8`, `…i32`, `…f64`, `…usize`, *etc.*: numeric literal of specific type. -* `"…"`: string literal. -* `r"…"`, `r#"…"#`, `r##"…"##`, *etc.*: raw string literal, escape characters are not processed. -* `b"…"`: byte string literal, constructs a `[u8]` instead of a string. -* `br"…"`, `br#"…"#`, `br##"…"##`, *etc.*: raw byte string literal, combination of raw and byte string literal. -* `'…'`: character literal. -* `b'…'`: ASCII byte literal. -* `|…| expr`: closure. -* `!`: always empty bottom type for diverging functions. - -#### Path-related Syntax - -* `ident::ident`: namespace path. -* `::path`: path relative to the crate root (*i.e.* an explicitly absolute path). -* `self::path`: path relative to the current module (*i.e.* an explicitly relative path). -* `super::path`: path relative to the parent of the current module. -* `type::ident`, `::ident`: associated constants, functions, and types. -* `::…`: associated item for a type which cannot be directly named (*e.g.* `<&T>::…`, `<[T]>::…`, *etc.*). -* `trait::method(…)`: disambiguating a method call by naming the trait which defines it. -* `type::method(…)`: disambiguating a method call by naming the type for which it’s defined. -* `::method(…)`: disambiguating a method call by naming the trait *and* type. - -#### Generics - -* `path<…>` (*e.g.* `Vec`): specifies parameters to generic type *in a type*. -* `path::<…>`, `method::<…>` (*e.g.* `"42".parse::()`): specifies parameters to generic type, function, or method *in an expression*. Often referred to as *turbofish*. -* `fn ident<…> …`: define generic function. -* `struct ident<…> …`: define generic structure. -* `enum ident<…> …`: define generic enumeration. -* `impl<…> …`: define generic implementation. -* `for<…> type`: higher-ranked lifetime bounds. -* `type` (*e.g.* `Iterator`): a generic type where one or more associated types have specific assignments. - -#### Trait Bound Constraints - -* `T: U`: generic parameter `T` constrained to types that implement `U`. -* `T: 'a`: generic type `T` must outlive lifetime `'a`. When we say that a type ‘outlives’ the lifetime, we mean that it cannot transitively contain any references with lifetimes shorter than `'a`. -* `T : 'static`: The generic type `T` contains no borrowed references other than `'static` ones. -* `'b: 'a`: generic lifetime `'b` must outlive lifetime `'a`. -* `T: ?Sized`: allow generic type parameter to be a dynamically-sized type. -* `'a + trait`, `trait + trait`: compound type constraint. - -#### Macros and Attributes - -* `#[meta]`: outer attribute. -* `#![meta]`: inner attribute. -* `$ident`: macro substitution. -* `$ident:kind`: macro capture. -* `$(…)…`: macro repetition. - -#### Comments - -* `//`: line comment. -* `//!`: inner line doc comment. -* `///`: outer line doc comment. -* `/*…*/`: block comment. -* `/*!…*/`: inner block doc comment. -* `/**…*/`: outer block doc comment. - -#### Tuples - -* `()`: empty tuple (*a.k.a.* unit), both literal and type. -* `(expr)`: parenthesized expression. -* `(expr,)`: single-element tuple expression. -* `(type,)`: single-element tuple type. -* `(expr, …)`: tuple expression. -* `(type, …)`: tuple type. -* `expr(expr, …)`: function call expression. Also used to initialize tuple `struct`s and tuple `enum` variants. -* `ident!(…)`, `ident!{…}`, `ident![…]`: macro invocation. -* `expr.0`, `expr.1`, …: tuple indexing. - -#### Curly Brackets - -* `{…}`: block expression. -* `Type {…}`: `struct` literal. - -#### Square Brackets - -* `[…]`: array literal. -* `[expr; len]`: array literal containing `len` copies of `expr`. -* `[type; len]`: array type containing `len` instances of `type`. -* `expr[expr]`: collection indexing. Overloadable (`Index`, `IndexMut`). -* `expr[..]`, `expr[a..]`, `expr[..b]`, `expr[a..b]`: collection indexing pretending to be collection slicing, using `Range`, `RangeFrom`, `RangeTo`, `RangeFull` as the “index”. - -# C - Derivable Traits - -In various places in the book, we discussed the `derive` attribute that is -applied to a struct or enum. This attribute generates code that implements a -trait on the annotated type with a default implementation. In this example, the -`#[derive(Debug)]` attribute implements the `Debug` trait for the `Point` -struct: - -``` -#[derive(Debug)] -struct Point { - x: i32, - y: i32, -} -``` - -The code that the compiler generates for the implementation of `Debug` is -similar to this code: - -``` -impl ::std::fmt::Debug for Point { - fn fmt(&self, __arg_0: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - match *self { - Point { x: ref __self_0_0, y: ref __self_0_1 } => { - let mut builder = __arg_0.debug_struct("Point"); - let _ = builder.field("x", &&(*__self_0_0)); - let _ = builder.field("y", &&(*__self_0_1)); - builder.finish() - } - } - } -} -``` - -The generated code implements sensible default behavior for the `Debug` trait’s -`fmt` function: a `match` expression destructures a `Point` instance into its -field values. Then it builds up a string containing the struct’s name and each -field’s name and value. This means we’re able to use debug formatting on a -`Point` instance to see what value each field has. - -The generated code isn’t particularly easy to read because it’s only for the -compiler to consume, rather than for programmers to read! The `derive` -attribute and the default implementation of `Debug` has saved us all of the -work of writing this code for every struct or enum that we want to be able to -print using debug formatting. - -The `derive` attribute has default implementations for the following traits -provided by the standard library. If you want different behavior than what the -`derive` attribute provides, consult the standard library documentation for -each trait for the details needed for manual implementation of the traits. - -## Standard Library Traits that Can Be Derived - -The following sections list all of the traits in the standard library that can -be used with `derive`. Each section covers: - -- What operators and methods deriving this trait will enable -- What the implementation of the trait provided by `derive` does -- What implementing the trait signifies about the type -- The conditions in which you’re allowed or not allowed to implement the trait -- Examples of operations that require the trait - -### `Debug` for Programmer Output - -The `Debug` trait enables debug formatting in format strings, indicated by -adding `:?` within `{}` placeholders. - -The `Debug` trait signifies that instances of a type may be printed by -programmers in order to debug their programs by inspecting an instance of a -type at a particular point in a program’s execution. - -An example of when `Debug` is required is the `assert_eq!` macro, which prints -the values of the instances given as arguments if the equality assertion fails -so that programmers can see why the two instances weren’t equal. - -### `PartialEq` and `Eq` for Equality Comparisons - -The `PartialEq` trait signifies that instances of a type can be compared to -each other for equality, and enables use of the `==` and `!=` operators. - -Deriving `PartialEq` implements the `eq` method. When derived on structs, two -instances are equal if all fields are equal, and not equal if any fields are -not equal. When derived on enums, each variant is equal to itself and not equal -to the other variants. - -An example of when `PartialEq` is required is the `assert_eq!` macro, which -needs to be able to compare two instances of a type for equality. - -The `Eq` trait doesn’t have any methods. It only signals that for every value -of the annotated type, the value is equal to itself. The `Eq` trait can only be -applied to types that also implement `PartialEq`. An example of types that -implements `PartialEq` but that cannot implement `Eq` are floating point number -types: the implementation of floating point numbers says that two instances of -the not-a-number value, `NaN`, are not equal to each other. - -An example of when `Eq` is required is for keys in a `HashMap` so that the -`HashMap` can tell whether two keys are the same. - -### `PartialOrd` and `Ord` for Ordering Comparisons - -The `PartialOrd` trait signifies that instances of a type can be compared to -each other to see which is larger than the other for sorting purposes. A type -that implements `PartialOrd` may be used with the `<`, `>`, `<=`, and `>=` -operators. The `PartialOrd` trait can only be applied to types that also -implement `PartialEq`. - -Deriving `PartialOrd` implements the `partial_cmp` method, which returns an -`Option` that may be `None` if comparing the given values does not -produce an ordering. When derived on structs, two instances of the struct are -compared by comparing the value in each field in the order in which the fields -appear in the struct definition. When derived on enums, variants of the enum -declared earlier in the enum definition are greater than the variants listed -later. - -An example of when `PartialOrd` is required is the `gen_range` method in the -`rand` crate that generates a random value in the range specified by a low -value and a high value. - -The `Ord` trait signifies that for any two value of the annotated type, a valid -ordering exists. The `Ord` trait implements the `cmp` method, which returns an -`Ordering` rather than an `Option` because a valid ordering will -always be possible. The `Ord` trait can only be applied to types that also -implement `PartialOrd` and `Eq` (and `Eq` requires `PartialEq`). When derived -on structs and enums, `cmp` behaves the same way as the derived implementation -for `partial_cmp` does with `PartialOrd`. - -An example of when `Ord` is required is when storing values in a `BTreeSet`, -a data structure that stores data based on the sort order of the values. - -### `Clone` and `Copy` for Duplicating Values - -The `Clone` trait signifies there is a way to explicitly create a duplicate of -a value, and the duplication process might involve running arbitrary code. -Deriving `Clone` implements the `clone` method. When derived, the -implementation of `clone` for the whole type calls `clone` on each of the parts -of the type, so all of the fields or values in the type must also implement -`Clone` to derive `Clone`. - -An example of when `Clone` is required is when calling the `to_vec` method on a -slice containing instances of some type. The slice doesn’t own the instances -but the vector returned from `to_vec` will need to own its instances, so the -implementation of `to_vec` calls `clone` on each item. Thus, the type stored in -the slice must implement `Clone`. - -The `Copy` trait signifies that a value can be duplicated by only copying bits; -no other code is necessary. The `Copy` trait does not define any methods to -prevent programmers from overloading those methods violating the assumption -that no arbitrary code is being run. You can derive `Copy` on any type whose -parts all implement `Copy`. The `Copy` trait can only be applied to types that -also implement `Clone`, as a type that implements `Copy` has a trivial -implementation of `Clone`, doing the same thing as `Copy`. - -`Copy` is rarely required; when types implement `Copy`, there are optimizations -that can be applied and the code becomes nicer because you don’t have to call -`clone`. Everything possible with `Copy` can also be accomplished with `Clone`, -but the code might be slower or have to use `clone` in places. - -### `Hash` for Mapping a Value to a Value of Fixed Size - -The `Hash` trait signifies there is a way to take an instance of a type that -takes up an arbitrary amount of size and map that instance to a value of fixed -size by using a hash function. Deriving `Hash` implements the `hash` method. -When derived, the implementation of `hash` for the whole type combines the -result of calling `hash` on each of the parts of the type, so all of the fields -or values in the type must also implement `Hash` to derive `Hash`. - -An example of when `Hash` is required is for keys in a `HashMap` so that the -`HashMap` can store data efficiently. - -### `Default` for Default Values - -The `Default` trait signifies there is a way to create a default value for a -type. Deriving `Default` implements the `default` method. When derived, the -implementation of `Default` for the whole type calls the `default` method on -each of the parts of the type, so all of the fields or values in the type must -also implement `Default` to derive `Default.` - -A common use of `Default::default` is in combination with the struct update -syntax discussed in the “Creating Instances From Other Instances With Struct -Update Syntax” section in Chapter 5. You can customize a few fields of a struct -and then use the default values for the rest by using `..Default::default()`. - -An example of when `Default` is required is the `unwrap_or_default` method on -`Option` instances. If the `Option` is `None`, the `unwrap_or_default` -method will return the result of `Default::default` for the type `T` stored in -the `Option`. - -## Standard Library Traits that Can’t Be Derived - -The rest of the traits defined in the standard library can’t be implemented on -your types using `derive`. These traits don’t have a sensible default behavior -they could have, so you are required to implement them in the way that makes -sense for what you are trying to accomplish with your code. - -An example of a trait that can’t be derived is `Display`, which handles -formatting of a type for end users of your programs. You should put thought -into the appropriate way to display a type to an end user: what parts of the -type should an end user be allowed to see? What parts would they find relevant? -What format of the data would be most relevant to them? The Rust compiler -doesn’t have this insight into your application, so you must provide it. - -## Making Custom Traits Derivable - -The above list is not comprehensive, however: libraries can implement `derive` -for their own types! In this way, the list of traits you can use `derive` with -is truly open-ended. Implementing `derive` involves using a procedural macro, -which is covered in the next appendix, “Macros.” - -# D - Macros - -We’ve used macros, such as `println!`, throughout this book. This appendix will -explain: - -- What macros are and how they differ from functions -- How to define a declarative macro to do metaprogramming -- How to define a procedural macro to create custom `derive` traits - -Macros are covered in an appendix because they’re still evolving. They have -changed and will change more than the rest of the language and standard library -since Rust 1.0, so this section will likely get out of date more than the rest -of this book. The code shown here will still continue to work due to Rust’s -stability guarantees, but there may be additional capabilities or easier ways -to write macros that aren’t available at the time of this publication. - -## Macros are More Flexible and Complex than Functions - -Fundamentally, macros are a way of writing code that writes other code, which -is known as *metaprogramming*. In the previous appendix, we discussed the -`derive` attribute, which generates an implementation of various traits for -you. We’ve also used the `println!` and `vec!` macros. All of these macros -*expand* to produce more code than what you’ve written in your source code. - -Metaprogramming is useful to reduce the amount of code you have to write and -maintain, which is also one of the roles of functions. However, macros have -some additional powers that functions don’t have, as we discussed in Chapter 1. -A function signature has to declare the number and type of parameters the -function has. Macros can take a variable number of parameters: we can call -`println!("hello")` with one argument, or `println!("hello {}", name)` with two -arguments. Also, macros are expanded before the compiler interprets the meaning -of the code, so a macro can, for example, implement a trait on a given type, -whereas a function can’t because a function gets called at runtime and a trait -needs to be implemented at compile time. - -The downside to implementing a macro rather than a function is that macro -definitions are more complex than function definitions. You’re writing Rust -code that writes Rust code, and macro definitions are generally more difficult -to read, understand, and maintain than function definitions. - -Another difference between macros and functions is that macro definitions -aren’t namespaced within modules like function definitions are. In order to -prevent unexpected name clashes when using a crate, when bringing an external -crate into the scope of your project, you have to explicitly bring the macros -into the scope of your project as well with the `#[macro_use]` annotation. This -example would bring all the macros defined in the `serde` crate into the scope -of the current crate: - -``` -#[macro_use] -extern crate serde; -``` - -If `extern crate` also brought macros into scope by default, you wouldn’t be -allowed to use two crates that happened to define macros with the same name. In -practice this conflict doesn’t come up much, but the more crates you use, the -more likely it is. - -One last important difference between macros and functions: macros must be -defined or brought into scope before they’re called in a file. Unlike -functions, where we can define a function at the bottom of a file yet call it -at the top, we always have to define macros before we’re able to call them. - -## Declarative Macros with `macro_rules!` for General Metaprogramming - -The first form of macros in Rust, and the one that’s most widely used, is -called *declarative macros*. These are also sometimes referred to as *macros by -example*, *`macro_rules!` macros*, or just plain *macros*. At their core, -declarative macros allow you to write something similar to a Rust `match` -expression. As discussed in Chapter 6, `match` expressions are control -structures that take an expression, compare the resulting value of the -expression to patterns, and then choose the code specified with the matching -pattern when the program runs. Macros also have a value that is compared to -patterns that have code associated with them, but the value is the literal Rust -code passed to the macro, the patterns match the structure of that source code, -and the code associated with each pattern is the code that is generated to -replace the code passed to the macro. This all happens during compilation. - -To define a macro, you use the `macro_rules!` construct. Let’s explore how to -use `macro_rules!` by taking a look at how the `vec!` macro is defined. Chapter -8 covered how we can use the `vec!` macro to create a new vector that holds -particular values. For example, this macro creates a new vector with three -integers inside: - -``` -let v: Vec = vec![1, 2, 3]; -``` - -We can also use `vec!` to make a vector of two integers or a vector of five -string slices. Because we don’t know the number or type of values, we can’t -define a function that is able to create a new vector with the given elements -like `vec!` can. - -Let’s take a look at a slightly simplified definition of the `vec!` macro: - -``` -#[macro_export] -macro_rules! vec { - ( $( $x:expr ),* ) => { - { - let mut temp_vec = Vec::new(); - $( - temp_vec.push($x); - )* - temp_vec - } - }; -} -``` - -> Note: the actual definition of the `vec!` macro in the standard library also -> has code to pre-allocate the correct amount of memory up-front. That code -> is an optimization that we’ve chosen not to include here for simplicity. - -The `#[macro_export]` annotation indicates that this macro should be made -available when other crates import the crate in which we’re defining this -macro. Without this annotation, even if someone depending on this crate uses -the `#[macro_use]` annotation, this macro would not be brought into scope. - -Macro definitions start with `macro_rules!` and the name of the macro we’re -defining without the exclamation mark, which in this case is `vec`. This is -followed by curly brackets denoting the body of the macro definition. - -Inside the body is a structure similar to the structure of a `match` -expression. This macro definition has one arm with the pattern `( $( $x:expr -),* )`, followed by `=>` and the block of code associated with this pattern. If -this pattern matches, then the block of code will be emitted. Given that this -is the only pattern in this macro, there’s only one valid way to match; any -other will be an error. More complex macros will have more than one arm. - -The pattern syntax valid in macro definitions is different than the pattern -syntax covered in Chapter 18 because the patterns are for matching against Rust -code structure rather than values. Let’s walk through what the pieces of the -pattern used here mean; for the full macro pattern syntax, see the reference at -*https://doc.rust-lang.org/stable/reference/macros.html*. - -The `$x:expr` part of the pattern matches any Rust expression and gives the -expression the name `$x`. The `*` specifies that the pattern matches zero or -more of whatever precedes the `*`. In this case, `*` is preceded by `$(),` so -this pattern matches zero or more of whatever is inside the parentheses, -delimited by a comma. When we call this macro with `vec![1, 2, 3];`, the -pattern matches the three expressions `1`, `2`, and `3`. - -In the body of the code associated with this arm, the `$()*` part is generated -for each part that matches `$()` in the pattern, zero or more times depending -on how many times the pattern matches. The `$x` in the code associated with the -arm is replaced with each expression matched. When we call this macro with -`vec![1, 2, 3];`, the code generated that replaces this macro call will be: - -``` -let mut temp_vec = Vec::new(); -temp_vec.push(1); -temp_vec.push(2); -temp_vec.push(3); -temp_vec -``` - -We’ve defined a macro that can take any number of arguments of any type and can -generate code to create a vector containing the specified elements. - -Given that most Rust programmers will *use* macros more than *write* macros, -that’s all we’ll discuss about `macro_rules!` in this book. To learn more about -how to write macros, consult the online documentation or other resources such -as The Little Book of Rust Macros at -*https://danielkeep.github.io/tlborm/book/index.html*. - -## Procedural Macros for Custom `derive` - -The second form of macros is called *procedural macros* because they’re more -like functions (which are a type of procedure). Procedural macros accept some -Rust code as an input, operate on that code, and produce some Rust code as an -output, rather than matching against patterns and replacing the code with other -code as declarative macros do. Today, the only thing you can define procedural -macros for is to allow your traits to be implemented on a type by specifying -the trait name in a `derive` annotation. - -Let’s create a crate named `hello-world` that defines a trait named -`HelloWorld` with one associated function named `hello_world`. Rather than -making users of our crate implement the `HelloWorld` trait for each of their -types, we’d like users to be able to annotate their type with -`#[derive(HelloWorld)]` to get a default implementation of the `hello_world` -function associated with their type. The default implementation will print -`Hello world, my name is TypeName!` where `TypeName` is the name of the type on -which this trait has been defined. - -In other words, we’re going to write a crate that enables another programmer to -write code that looks like Listing A4-1 using our crate: - -Filename: src/main.rs - -``` -extern crate hello_world; -#[macro_use] -extern crate hello_world_derive; - -use hello_world::HelloWorld; - -#[derive(HelloWorld)] -struct Pancakes; - -fn main() { - Pancakes::hello_world(); -} -``` - -Listing A4-1: The code a user of our crate will be able to write when we’ve -written the procedural macro - -This code will print `Hello world, my name is Pancakes!` when we’re done. Let’s -get started! - -Let’s make a new library crate: - -``` -$ cargo new hello-world -``` - -First, we’ll define the `HelloWorld` trait and associated function: - -Filename: src/lib.rs - -``` -pub trait HelloWorld { - fn hello_world(); -} -``` - -At this point, a user of our crate could implement the trait themselves to -achieve the functionality we wanted to enable, like so: - -``` -extern crate hello_world; - -use hello_world::HelloWorld; - -struct Pancakes; - -impl HelloWorld for Pancakes { - fn hello_world() { - println!("Hello world, my name is Pancakes!"); - } -} - -fn main() { - Pancakes::hello_world(); -} -``` - -However, they would need to write out the implementation block for each type -they wanted to be able to use with `hello_world`; we’d like to make using our -trait more convenient for other programmers by saving them this work. - -Additionally, we can’t provide a default implementation for the `hello_world` -function that has the behavior we want of printing out the name of the type the -trait is implemented on: Rust doesn’t have reflection capabilities, so we can’t -look up the type’s name at runtime. We need a macro to generate code at compile -time. - -### Defining Procedural Macros Requires a Separate Crate - -The next step is to define the procedural macro. At the moment, procedural -macros need to be in their own crate. Eventually, this restriction may be -lifted, but for now, it’s required. As such, there’s a convention: for a crate -named `foo`, a custom derive procedural macro crate is called `foo-derive`. -Let’s start a new crate called `hello-world-derive` inside our `hello-world` -project: - -``` -$ cargo new hello-world-derive -``` - -We’ve chosen to create the procedural macro crate within the directory of our -`hello-world` crate because the two crates are tightly related: if we change -the trait definition in `hello-world`, we’ll have to change the implementation -of the procedural macro in `hello-world-derive` as well. The two crates will -need to be published separately, and programmers using these crates will need -to add both as dependencies and bring them both into scope. It’s possible to -have the `hello-world` crate use `hello-world-derive` as a dependency and -re-export the procedural macro code, but structuring the project this way makes -it possible for programmers to easily decide they only want to use -`hello-world` if they don’t want the `derive` functionality. - -We need to declare that the `hello-world-derive` crate is a procedural macro -crate. We also need to add dependencies on the `syn` and `quote` crates to get -useful functionality for operating on Rust code. To do these two things, add -the following to the *Cargo.toml* for `hello-world-derive`: - -Filename: hello-world-derive/Cargo.toml - -``` -[lib] -proc-macro = true - -[dependencies] -syn = "0.11.11" -quote = "0.3.15" -``` - -To start defining the procedural macro, place the code from Listing A4-2 in -*src/lib.rs* for the `hello-world-derive` crate. Note that this won’t compile -until we add a definition for the `impl_hello_world` function. We’ve split the -code into functions in this way because the code in Listing A4-2 will be the -same for almost every procedural macro crate; it’s code that makes writing a -procedural macro more convenient. What you choose to do in the place where the -`impl_hello_world` function is called will be different and depend on the -purpose of your procedural macro. - -Filename: hello-world-derive/src/lib.rs - -``` -extern crate proc_macro; -extern crate syn; -#[macro_use] -extern crate quote; - -use proc_macro::TokenStream; - -#[proc_macro_derive(HelloWorld)] -pub fn hello_world_derive(input: TokenStream) -> TokenStream { - // Construct a string representation of the type definition - let s = input.to_string(); - - // Parse the string representation - let ast = syn::parse_derive_input(&s).unwrap(); - - // Build the impl - let gen = impl_hello_world(&ast); - - // Return the generated impl - gen.parse().unwrap() -} -``` - -Listing A4-2: Code that most procedural macro crates will need to have for -processing Rust code - -We have introduced three new crates: `proc_macro`, `syn` (available from -*https://crates.io/crates/syn*), and `quote` (available from -*https://crates.io/crates/quote*). The `proc_macro` crate comes with Rust, so -we didn’t need to add that to the dependencies in *Cargo.toml*. The -`proc_macro` crate allows us to convert Rust code into a string containing that -Rust code. The `syn` crate parses Rust code from a string into a data structure -that we can perform operations on. The `quote` crate takes `syn` data -structures and turns them back into Rust code. These crates make it much -simpler to parse any sort of Rust code we might want to handle: writing a full -parser for Rust code is no simple task. - -The `hello_world_derive` function is the code that will get called when a user -of our library specifies the `#[derive(HelloWorld)]` annotation on a type -because we’ve annotated the `hello_world_derive` function here with -`proc_macro_derive` and specified the same name, `HelloWorld`. This name -matches our trait named `HelloWorld`; that’s the convention most procedural -macros follow. - -The first thing this function does is convert the `input` from a `TokenStream` -to a `String` by calling `to_string`. This `String` is a string representation -of the Rust code for which we are deriving `HelloWorld`. In the example in -Listing A4-1, `s` will have the `String` value `struct Pancakes;` because -that’s the Rust code we added the `#[derive(HelloWorld)]` annotation to. - -At the moment, the only thing you can do with a `TokenStream` is convert it to -a string. A richer API will exist in the future. - -What we really need is to be able to parse the Rust code `String` into a data -structure that we can then interpret and perform operations on. This is where -`syn` comes to play. The `parse_derive_input` function in `syn` takes a -`String` and returns a `DeriveInput` struct representing the parsed Rust code. -Here’s the relevant parts of the `DeriveInput` struct we get from parsing the -string `struct Pancakes;`: - -``` -DeriveInput { - // --snip-- - - ident: Ident( - "Pancakes" - ), - body: Struct( - Unit - ) -} -``` - -The fields of this struct show that the Rust code we’ve parsed is a unit struct -with the `ident` (identifier, meaning the name) of `Pancakes`. There are more -fields on this struct for describing all sorts of Rust code; check the `syn` -API docs for `DeriveInput` at -*https://docs.rs/syn/0.11.11/syn/struct.DeriveInput.html* for more information. - -We haven’t defined the `impl_hello_world` function; that’s where we’ll build -the new Rust code we want to include. Before we get to that, the last part of -this `hello_world_derive` function is using the `quote` crate’s `parse` -function to turn the output of the `impl_hello_world` function back into a -`TokenStream`. The returned `TokenStream` is added to the code that users of -our crate write so that when they compile their crate, they get extra -functionality we provide. - -You may have noticed that we’re calling `unwrap` to panic if the calls to the -`parse_derive_input` or `parse` functions fail because they’re unable to parse -the `TokenStream` or generate a `TokenStream`. Panicking on errors is necessary -in procedural macro code because `proc_macro_derive` functions must return -`TokenStream` rather than `Result` in order to conform to the procedural macro -API. We’ve chosen to keep this example simple by using `unwrap`; in production -code you should provide more specific error messages about what went wrong by -using `expect` or `panic!`. - -Now that we have the code to turn the annotated Rust code from a `TokenStream` -into a `String` and into a `DeriveInput` instance, let’s write the code that -will generate the code implementing the `HelloWorld` trait on the annotated -type: - -Filename: hello-world-derive/src/lib.rs - -``` -fn impl_hello_world(ast: &syn::DeriveInput) -> quote::Tokens { - let name = &ast.ident; - quote! { - impl HelloWorld for #name { - fn hello_world() { - println!("Hello, World! My name is {}", stringify!(#name)); - } - } - } -} -``` - -We are able to get an `Ident` struct instance containing the name (identifier) -of the annotated type using `ast.ident`. With the code from Listing A4-1, -`name` will be `Ident("Pancakes")`. - -The `quote!` macro from the `quote` crate lets us write up the Rust code that -we wish to return and convert it into `quote::Tokens`. The `quote!` macro lets -us use some really cool templating mechanics; we can write `#name` and `quote!` -will replace it with the value in the variable named `name`. You can even do -some repetition similar to the way regular macros work. Check out the `quote` -crate’s docs at *https://docs.rs/quote* for a thorough introduction. - -What we want to do for our procedural macro is generate an implementation of -our `HelloWorld` trait for the type the user of our crate has annotated, which -we can get by using `#name`. The trait implementation has one function, -`hello_world`, and the function body contains the functionality we want to -provide: printing `Hello, World! My name is` and then the name of the type the -user of our crate has annotated. The `stringify!` macro used here is built into -Rust. It takes a Rust expression, such as `1 + 2`, and at compile time turns -the expression into a string literal, such as `"1 + 2"`. This is different than -`format!` or `println!`, which evaluate the expression and then turn the result -into a `String`. There’s a possibility that `#name` would be an expression that -we would want to print out literally, and `stringify!` also saves an allocation -by converting `#name` to a string literal at compile time. - -At this point, `cargo build` should complete successfully in both `hello-world` -and `hello-world-derive`. Let’s hook these crates up to the code in Listing -A4-1 to see it in action! Create a new binary project in your `projects` -directory with `cargo new --bin pancakes`. We need to add both `hello-world` -and `hello-world-derive` as dependencies in the `pancakes` crate’s -*Cargo.toml*. If you’ve chosen to publish your versions of `hello-world` and -`hello-world-derive` to *https://crates.io* they would be regular dependencies; -if not, you can specify them as `path` dependencies as follows: - -``` -[dependencies] -hello_world = { path = "../hello-world" } -hello_world_derive = { path = "../hello-world/hello-world-derive" } -``` - -Put the code from Listing A4-1 into *src/main.rs*, and executing `cargo run` -should print `Hello, World! My name is Pancakes`! The implementation of the -`HelloWorld` trait from the procedural macro was included without the -`pancakes` crate needing to implement it; the `#[derive(HelloWorld)]` took care -of adding the trait implementation. - -## The Future of Macros - -In the future, we’ll be expanding both declarative and procedural macros. A -better declarative macro system will be used with the `macro` keyword, and -we’ll add more types of procedural macros, for more powerful tasks than only -`derive`. These systems are still under development at the time of publication; -please consult the online Rust documentation for the latest information. diff --git a/second-edition/nostarch/chapter01.md b/second-edition/nostarch/chapter01.md deleted file mode 100644 index 47772d23f3..0000000000 --- a/second-edition/nostarch/chapter01.md +++ /dev/null @@ -1,645 +0,0 @@ - -[TOC] - -# Getting Started - - - - -Let’s get your Rust journey started! In this chapter, we’ll discuss: - -- Installing Rust on Linux, Mac, or Windows -- Writing a program that prints “Hello, world!” -- Using `cargo`, Rust’s package manager and build system - -## Installation - -The first step to using Rust is to install it. We’ll download Rust through -`rustup`, a command-line tool for managing Rust versions and associated tools. -For this you’ll need an internet connection. - -The following steps will install the latest stable version of the Rust -compiler. The examples and output shown in this book all use stable Rust -1.21.0. Rust’s stability guarantees ensure that all of the examples in the book -that compile will continue to compile with newer versions of Rust. The output -may differ slightly between versions, as error messages and warnings are often -improved. In other words, any newer, stable version of Rust you will install -with these steps should work as expected with the content of this book. - - - -> #### Command Line Notation -> -> In this chapter and throughout the book we’ll be showing some commands used -> in the terminal. Lines that should be entered in a terminal all start with -> `$`. You don’t need to type in the `$` character, it is simply there to -> indicate the start of each command. Many tutorials use this convention: `$` -> for commands run as a regular user, and `#` for commands you should be -> running as an administrator. Lines that don’t start with `$` are typically -> showing the output of the previous command. Additionally, PowerShell specific -> examples will use `>` rather than `$`. - - - -### Installing Rustup on Linux or Mac - -If you’re on Linux or a Mac, open a terminal and enter the following command: - -``` -$ curl https://sh.rustup.rs -sSf | sh -``` - -This will download a script and start the installation of the `rustup` tool, -which installs the latest stable version of Rust. You may be prompted for your -password. If it all goes well, you’ll see this appear: - -``` -Rust is installed now. Great! -``` - -Of course, if you distrust using `curl URL | sh` to install software, you can -download, inspect, and run the script however you like. - -The installation script automatically adds Rust to your system PATH after your -next login. If you want to start using Rust right away instead of restarting -your terminal, run the following command in your shell to add Rust to your -system PATH manually: - - - - -``` -$ source $HOME/.cargo/env -``` - -Alternatively, you can add the following line to your `~/.bash_profile`: - -``` -$ export PATH="$HOME/.cargo/bin:$PATH" -``` - -Finally, you’ll need a linker of some kind. It’s likely you already have one -installed, but if you try to compile a Rust program and get errors telling you -that a linker could not be executed, you’ll need to install one. You can -install a C compiler, as that will usually come with the correct linker. Check -your platform’s documentation for how to install a C compiler. Some common Rust -packages depend on C code and will need a C compiler too, so it may be worth -installing one now regardless. - -### Installing Rustup on Windows - -On Windows, go to *https://www.rust-lang.org/en-US/install.html* and follow the -instructions for installing Rust. At some point in the installation you’ll -receive a message telling you you’ll also need the C++ build tools for Visual -Studio 2013 or later. The easiest way to acquire the build tools is to install -Build Tools for Visual Studio 2017 at -*https://www.visualstudio.com/downloads/*, found in the Other Tools and -Frameworks section. - -The rest of this book will use commands that work in both `cmd.exe` and -PowerShell. If there are specific differences, we’ll explain which to use. - -### Custom Installations Without Rustup - -If you have reasons for preferring not to use `rustup`, please see the Rust -installation page at *https://www.rust-lang.org/install.html* for other options. - -### Updating and Uninstalling - -Once you have Rust installed via `rustup`, updating to the latest version is -easy. From your shell, run the update script: - -``` -$ rustup update -``` - -To uninstall Rust and `rustup`, from your shell, run the uninstall script: - -``` -$ rustup self uninstall -``` - -### Troubleshooting - -To check whether you have Rust installed correctly, open up a shell and enter: - -``` -$ rustc --version -``` - -You should see the version number, commit hash, and commit date for the latest -stable version at the time you install in the following format: - -``` -rustc x.y.z (abcabcabc yyyy-mm-dd) -``` - -If you see this, Rust has been installed successfully! Congrats! - -If you don’t and you’re on Windows, check that Rust is in your `%PATH%` system -variable. - -If that’s all correct and Rust still isn’t working, there are a number of -places you can get help. The easiest is the #rust IRC channel on -irc.mozilla.org, which you can access through Mibbit at -*http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust*. Go to that -address, and you’ll be chatting with other Rustaceans (a silly nickname we call -ourselves) who can help you out. Other great resources include the Users forum -at *https://users.rust-lang.org/* and Stack Overflow at -*http://stackoverflow.com/questions/tagged/rust*. - -### Local Documentation - -The installer also includes a copy of the documentation locally, so you can -read it offline. Run `rustup doc` to open the local documentation in your -browser. - -Any time there’s a type or function provided by the standard library and you’re -not sure what it does or how to use it, use the API (Application Programming -Interface) documentation to find out! - -## Hello, World! - -Now that you have Rust installed, let’s write your first Rust program. It’s -traditional when learning a new language to write a little program to print the -text “Hello, world!” to the screen, so we’ll do the same here! - -> Note: This book assumes basic familiarity with the command line. Rust itself -> makes no specific demands about your editing, tooling, or where your code -> lives, so if you prefer an IDE (Integrated Development Environment) to the -> command line, feel free to use your favorite IDE. Many IDEs now have some -> degree of Rust support; check the IDE’s documentation for details. Enabling -> great IDE support has been a recent focus of the Rust team, and progress -> has been made rapidly on that front! - -### Creating a Project Directory - -First, make a directory to put your Rust code in. Rust doesn’t care where your -code lives, but for the exercises and projects in this book, we’d suggest -making a *projects* directory in your home directory and keeping all your -projects there. - -Open a terminal and enter the following commands to make a *projects* directory -and, inside that, a directory for this “Hello, world!” project: - -Linux and Mac: - -``` -$ mkdir ~/projects -$ cd ~/projects -$ mkdir hello_world -$ cd hello_world -``` - -Windows CMD: - -``` -> mkdir "%USERPROFILE%\projects" -> cd /d "%USERPROFILE%\projects" -> mkdir hello_world -> cd hello_world -``` - -Windows PowerShell: - -``` -> mkdir $env:USERPROFILE\projects -> cd $env:USERPROFILE\projects -> mkdir hello_world -> cd hello_world -``` - -### Writing and Running a Rust Program - -Next, make a new source file and call it *main.rs*---Rust files always end with -the *.rs* extension. If you’re using more than one word in your filename, use -an underscore to separate them. For example, you’d use *hello_world.rs* rather -than *helloworld.rs*. - -Now open the *main.rs* file you just created, and enter the code shown in -Listing 1-1: - -Filename: main.rs - -``` -fn main() { - println!("Hello, world!"); -} -``` - -Listing 1-1: A program that prints “Hello, world!” - -Save the file, and go back to your terminal window. On Linux or macOS, enter -the following commands to compile and run the file: - -``` -$ rustc main.rs -$ ./main -Hello, world! -``` - -On Windows, use `.\main.exe` instead of `./main`. - -``` -> rustc main.rs -> .\main.exe -Hello, world! -``` - -Regardless of your operating system, you should see the string `Hello, world!` -print to the terminal. If you don’t see this output, see the “Troubleshooting” -section earlier for ways to get help. - -If you did see `Hello, world!` printed, then congratulations! You’ve officially -written a Rust program. That makes you a Rust programmer! Welcome! - - - - -### Anatomy of a Rust Program - -Now, let’s go over what just happened in your “Hello, world!” program in -detail. Here’s the first piece of the puzzle: - -``` -fn main() { - -} -``` - -These lines define a *function* in Rust. The `main` function is special: it is -always the first code that is run for every executable Rust program. The first -line declares a function named `main` that has no parameters and returns -nothing. If there were parameters, their names would go inside the parentheses, -`(` and `)`. - -Also note that the function body is wrapped in curly brackets, `{` and `}`. -Rust requires these around all function bodies. It’s considered good style to -place the opening curly bracket on the same line as the function declaration, -with one space in between. - -> At the time of writing, an automatic formatter, `rustfmt`, is under -> development. If you’d like to stick to a standard style across Rust projects, -> `rustfmt` is a tool that will format your code in a particular style. The -> plan is to eventually include it with the standard Rust distribution, like -> `rustc`, so depending on when you read this book, you may have it already -> installed! Check the online documentation for more details. - -Inside the `main` function, we have this code: - -``` - println!("Hello, world!"); -``` - -This line does all of the work in this little program: it prints text to the -screen. There are a number of details to notice here. The first is that Rust -style is to indent with four spaces, not a tab. - -The second important detail is the `println!` call. This code is calling a Rust -*macro*. If it were calling a function instead, it would be entered as -`println` (without the `!`). We’ll discuss Rust macros in more detail in -Appendix D, but for now you just need to know that when you see a `!` that -means that you’re calling a macro instead of a normal function. - - - - -Next comes`"Hello, world!"` which is a *string*. We pass this string as an -argument to `println!` and the total effect is that the string is printed to -the screen. Easy enough! - -We end the line with a semicolon `;`, which indicates that this expression is -over, and the next one is ready to begin. Most lines of Rust code end with a -`;`. - -### Compiling and Running Are Separate Steps - -You’ve just seen how to run a newly created program, so now let’s break that -process down and examine each step. - -Before running a Rust program, you have to compile it using the Rust compiler -by entering the `rustc` command and passing it the name of your source file, -like this: - -``` -$ rustc main.rs -``` - -If you come from a C or C++ background, you’ll notice that this is similar to -`gcc` or `clang`. After compiling successfully, Rust outputs a binary -executable. - -On Linux, Mac, and PowerShell on Windows, you can see the executable by -entering the `ls` command in your shell as follows: - -``` -$ ls -main main.rs -``` - -With CMD on Windows, you’d enter: - -``` -> dir /B %= the /B option says to only show the file names =% -main.exe -main.pdb -main.rs -``` - -This shows we have two files: the source code, with the *.rs* extension, and -the executable (*main.exe* on Windows, *main* everywhere else). All that’s left -to do from here is run the *main* or *main.exe* file, like this: - -``` -$ ./main # or .\main.exe on Windows -``` - -If *main.rs* were your “Hello, world!” program, this would print `Hello, -world!` to your terminal. - -If you come from a dynamic language like Ruby, Python, or JavaScript, you may -not be used to compiling and running a program being separate steps. Rust is an -*ahead-of-time compiled* language, which means that you can compile a program, -give the executable to someone else, and they can run it even without having -Rust installed. If you give someone a `.rb`, `.py`, or `.js` file, on the other -hand, they need to have a Ruby, Python, or JavaScript implementation installed -(respectively), but you only need one command to both compile and run your -program. Everything is a tradeoff in language design. - -Just compiling with `rustc` is fine for simple programs, but as your project -grows, you’ll want to be able to manage all of the options and make it easy to -share your code. Next, we’ll introduce you to a tool called Cargo, which will -help you write real-world Rust programs. - -## Hello, Cargo! - -Cargo is Rust’s build system and package manager. Most Rustaceans will use this -tool to manage their Rust projects because Cargo takes care of a lot of tasks -for you, such as building your code, downloading the libraries your code -depends on, and building those libraries. (We call libraries your code needs -*dependencies*.) - -The simplest Rust programs, like the one we’ve written so far, don’t have any -dependencies, so if we had built the Hello World project with Cargo, it would -only be using the part of Cargo that takes care of building your code. As you -write more complex Rust programs, you’ll want to add dependencies, and if you -start the project off using Cargo, that will be a lot easier to do. - -As the vast majority of Rust projects use Cargo, the rest of this book will -assume that you’re using Cargo too. Cargo comes installed with Rust itself, if -you used the official installers as covered in the “Installation” section. If -you installed Rust through some other means, you can check if you have Cargo -installed by entering the following into your terminal: - -``` -$ cargo --version -``` - -If you see a version number, great! If you see an error like `command not -found`, then you should look at the documentation for your method of -installation to determine how to install Cargo separately. - -### Creating a Project with Cargo - -Let’s create a new project using Cargo and look at how it differs from our -original Hello World project. Navigate back to your *projects* directory (or -wherever you decided to put your code) and then on any operating system run: - -``` -$ cargo new hello_cargo --bin -$ cd hello_cargo -``` - - - - -This creates a new binary executable called `hello_cargo`. The `--bin` argument -to passed to `cargo new` makes an executable application (often just called a -*binary*), as opposed to a library. We’ve given `hello_cargo` as the name for -our project, and Cargo creates its files in a directory of the same name. - -Go into the *hello_cargo* directory and list the files, and you should see that -Cargo has generated two files and one directory for us: a *Cargo.toml* and a -*src* directory with a *main.rs* file inside. It has also initialized a new git -repository, along with a *.gitignore* file. - -> Note: Git is a common version control system. You can change `cargo new` to -> use a different version control system, or no version control system, by -> using the `--vcs` flag. Run `cargo new --help` to see the available options. - -Open up *Cargo.toml* in your text editor of choice. It should look similar to -the code in Listing 1-2: - -Filename: Cargo.toml - -``` -[package] -name = "hello_cargo" -version = "0.1.0" -authors = ["Your Name "] - -[dependencies] -``` - -Listing 1-2: Contents of *Cargo.toml* generated by `cargo new` - -This file is in the *TOML* (Tom’s Obvious, Minimal Language) format, which is -what Cargo uses as its configuration format. - -The first line, `[package]`, is a section heading that indicates that the -following statements are configuring a package. As we add more information to -this file, we’ll add other sections. - -The next three lines set the configuration information Cargo needs in order to -know that it should compile your program: the name, the version, and who wrote -it. Cargo gets your name and email information from your environment, so if -that’s not correct, go ahead and fix that and save the file. - -The last line, `[dependencies]`, is the start of a section for you to list any -of your project’s dependencies. In Rust, packages of code are referred to as -*crates*. We won’t need any other crates for this project, but we will in the -first project in Chapter 2, so we’ll use this dependencies section then. - -Now open up *src/main.rs* and take a look: - -Filename: src/main.rs - -``` -fn main() { - println!("Hello, world!"); -} -``` - -Cargo has generated a “Hello World!” for you, just like the one we wrote in -Listing 1-1! So far, the differences between our previous project and the -project generated by Cargo are that with Cargo our code goes in the *src* -directory, and we have a *Cargo.toml* configuration file in the top directory. - -Cargo expects your source files to live inside the *src* directory so that the -top-level project directory is just for READMEs, license information, -configuration files, and anything else not related to your code. In this way, -using Cargo helps you keep your projects nice and tidy. There’s a place for -everything, and everything is in its place. - -If you started a project that doesn’t use Cargo, as we did with our project in -the *hello_world* directory, you can convert it to a project that does use -Cargo by moving the project code into the *src* directory and creating an -appropriate *Cargo.toml*. - -### Building and Running a Cargo Project - -Now let’s look at what’s different about building and running your Hello World -program through Cargo! From your project directory, build your project by -entering the following commands: - -``` -$ cargo build - Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo) - Finished dev [unoptimized + debuginfo] target(s) in 2.85 secs -``` - -This creates an executable file in *target/debug/hello_cargo* (or -*target\\debug\\hello_cargo.exe* on Windows), which you can run with this -command: - -``` -$ ./target/debug/hello_cargo # or .\target\debug\hello_cargo.exe on Windows -Hello, world! -``` - -Bam! If all goes well, `Hello, world!` should print to the terminal once more. -Running `cargo build` for the first time also causes Cargo to create a new file -at the top level called *Cargo.lock*, which is used to keep track of the exact -versions of dependencies in your project. This project doesn’t have -dependencies, so the file is a bit sparse. You won’t ever need to touch this -file yourself; Cargo will manage its contents for you. - -We just built a project with `cargo build` and ran it with -`./target/debug/hello_cargo`, but we can also use `cargo run` to compile and -then run all in one go: - -``` -$ cargo run - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target/debug/hello_cargo` -Hello, world! -``` - -Notice that this time, we didn’t see the output telling us that Cargo was -compiling `hello_cargo`. Cargo figured out that the files haven’t changed, so -it just ran the binary. If you had modified your source code, Cargo would have -rebuilt the project before running it, and you would have seen output like this: - -``` -$ cargo run - Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo) - Finished dev [unoptimized + debuginfo] target(s) in 0.33 secs - Running `target/debug/hello_cargo` -Hello, world! -``` - -Finally, there’s `cargo check`. This command will quickly check your code to -make sure that it compiles, but not bother producing an executable: - -``` -$ cargo check - Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo) - Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs -``` - -Why would you not want an executable? `cargo check` is often much faster than -`cargo build`, because it skips the entire step of producing the executable. If -you’re checking your work throughout the process of writing the code, using -`cargo check` will speed things up! As such, many Rustaceans run `cargo check` -periodically as they write their program to make sure that it compiles, and -then run `cargo build` once they’re ready to give it a spin themselves. - -So to recap, using Cargo: - -- We can build a project using `cargo build` or `cargo check` -- We can build and run the project in one step with `cargo run` -- Instead of the result of the build being put in the same directory as our - code, Cargo will put it in the *target/debug* directory. - -A final advantage of using Cargo is that the commands are the same no matter -what operating system you’re on, so at this point we will no longer be -providing specific instructions for Linux and Mac versus Windows. - -### Building for Release - -When your project is finally ready for release, you can use `cargo build ---release` to compile your project with optimizations. This will create an -executable in *target/release* instead of *target/debug*. These optimizations -make your Rust code run faster, but turning them on makes your program take -longer to compile. This is why there are two different profiles: one for -development when you want to be able to rebuild quickly and often, and one for -building the final program you’ll give to a user that won’t be rebuilt -repeatedly and that will run as fast as possible. If you’re benchmarking the -running time of your code, be sure to run `cargo build --release` and benchmark -with the executable in *target/release*. - -### Cargo as Convention - -With simple projects, Cargo doesn’t provide a whole lot of value over just -using `rustc`, but it will prove its worth as you continue. With complex -projects composed of multiple crates, it’s much easier to let Cargo coordinate -the build. - -Even though the `hello_cargo` project is simple, it now uses much of the real -tooling you’ll use for the rest of your Rust career. In fact, to work on any -existing projects you can use the following commands to check out the code -using Git, change into the project directory, and build: - -``` -$ git clone someurl.com/someproject -$ cd someproject -$ cargo build -``` - -If you want to look at Cargo in more detail, check out its documentation at -*https://doc.rust-lang.org/cargo/*. - - - - -## Summary - -You’re already off to a great start on your Rust journey! In this chapter, -you’ve: - -* Installed the latest stable version of Rust -* Written a “Hello, world!” program using both `rustc` directly and using - the conventions of `cargo` - -This is a great time to build a more substantial program, to get used to -reading and writing Rust code. In the next chapter, we’ll build a guessing game -program. If you’d rather start by learning about how common programming -concepts work in Rust, see Chapter 3. diff --git a/second-edition/nostarch/chapter02.md b/second-edition/nostarch/chapter02.md deleted file mode 100644 index eccf122fa9..0000000000 --- a/second-edition/nostarch/chapter02.md +++ /dev/null @@ -1,984 +0,0 @@ - -[TOC] - -# Programming a Guessing Game - -Let’s jump into Rust by working through a hands-on project together! This -chapter introduces you to a few common Rust concepts by showing you how to use -them in a real program. You’ll learn about `let`, `match`, methods, associated -functions, using external crates, and more! The following chapters will explore -these ideas in more detail. In this chapter, you’ll practice the fundamentals. - -We’ll implement a classic beginner programming problem: a guessing game. Here’s -how it works: the program will generate a random integer between 1 and 100. It -will then prompt the player to enter a guess. After a guess is entered, the -program will indicate whether the guess is too low or too high. If the guess is -correct, the game will print a congratulatory message and exit. - -## Setting Up a New Project - -To set up a new project, go to the *projects* directory that you created in -Chapter 1 and make a new project using Cargo, like so: - -``` -$ cargo new guessing_game --bin -$ cd guessing_game -``` - -The first command, `cargo new`, takes the name of the project (`guessing_game`) -as the first argument. The `--bin` flag tells Cargo to make a binary project, -like the one in Chapter 1. The second command changes to the new project’s -directory. - -Look at the generated *Cargo.toml* file: - -Filename: Cargo.toml - -``` -[package] -name = "guessing_game" -version = "0.1.0" -authors = ["Your Name "] - -[dependencies] -``` - -If the author information that Cargo obtained from your environment is not -correct, fix that in the file and save it again. - -As you saw in Chapter 1, `cargo new` generates a “Hello, world!” program for -you. Check out the *src/main.rs* file: - -Filename: src/main.rs - -``` -fn main() { - println!("Hello, world!"); -} -``` - -Now let’s compile this “Hello, world!” program and run it in the same step -using the `cargo run` command: - -``` -$ cargo run - Compiling guessing_game v0.1.0 (file:///projects/guessing_game) - Finished dev [unoptimized + debuginfo] target(s) in 1.50 secs - Running `target/debug/guessing_game` -Hello, world! -``` - -The `run` command comes in handy when you need to rapidly iterate on a project, -as we’ll do in this game, quickly testing each iteration before moving on to -the next one. - -Reopen the *src/main.rs* file. You’ll be writing all the code in this file. - -## Processing a Guess - -The first part of the guessing game program will ask for user input, process -that input, and check that the input is in the expected form. To start, we’ll -allow the player to input a guess. Enter the code in Listing 2-1 into -*src/main.rs*. - -Filename: 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); -} -``` - -Listing 2-1: Code that gets a guess from the user and prints it - -This code contains a lot of information, so let’s go over it line by line. To -obtain user input and then print the result as output, we need to bring the -`io` (input/output) library into scope. The `io` library comes from the -standard library (which is known as `std`): - -``` -use std::io; -``` - -By default, Rust brings only a few types into the scope of every program in -the *prelude*. If a type you want to use isn’t in the -prelude, you have to bring that type into scope explicitly with a `use` -statement. Using the `std::io` library provides you with a number of useful -features, including the ability to accept user input. - -As you saw in Chapter 1, the `main` function is the entry point into the -program: - -``` -fn main() { -``` - -The `fn` syntax declares a new function, the parentheses, `()`, indicate there -are no parameters, and the curly bracket, `{`, starts the body of the function. - -As you also learned in Chapter 1, `println!` is a macro that prints a string to -the screen: - -``` -println!("Guess the number!"); - -println!("Please input your guess."); -``` - -This code is printing a prompt stating what the game is and requesting input -from the user. - -### Storing Values with Variables - -Next, we’ll create a place to store the user input, like this: - -``` -let mut guess = String::new(); -``` - -Now the program is getting interesting! There’s a lot going on in this little -line. Notice that this is a `let` statement, which is used to create a -*variable*. Here’s another example: - -``` -let foo = bar; -``` - -This line creates a new variable named `foo` and bind it to the value `bar`. In -Rust, variables are immutable by default. We’ll be discussing this concept in -detail in the “Variables and Mutability” section in Chapter 3. The following -example shows how to use `mut` before the variable name to make a variable -mutable: - -``` -let foo = 5; // immutable -let mut bar = 5; // mutable -``` - -> Note: The `//` syntax starts a comment that continues until the end of the -> line. Rust ignores everything in comments, which are discussed in more detail -> in Chapter 3. - -Now you know that `let mut guess` will introduce a mutable variable named -`guess`. On the other side of the equal sign (`=`) is the value that `guess` is -bound to, which is the result of calling `String::new`, a function that returns -a new instance of a `String`. `String` is a string -type provided by the standard library that is a growable, UTF-8 encoded bit of -text. - -The `::` syntax in the `::new` line indicates that `new` is an *associated -function* of the `String` type. An associated function is implemented on a type, -in this case `String`, rather than on a particular instance of a `String`. Some -languages call this a *static method*. - -This `new` function creates a new, empty string. You’ll find a `new` function -on many types, because it’s a common name for a function that makes a new value -of some kind. - -To summarize, the `let mut guess = String::new();` line has created a mutable -variable that is currently bound to a new, empty instance of a `String`. Whew! - -Recall that we included the input/output functionality from the standard -library with `use std::io;` on the first line of the program. Now we’ll call an -associated function, `stdin`, on `io`: - -``` -io::stdin().read_line(&mut guess) - .expect("Failed to read line"); -``` - -If we hadn’t listed the `use std::io` line at the beginning of the program, we -could have written this function call as `std::io::stdin`. The `stdin` function -returns an instance of `std::io::Stdin`, which is a -type that represents a handle to the standard input for your terminal. - -The next part of the code, `.read_line(&mut guess)`, calls the -`read_line` method on the standard input handle to -get input from the user. We’re also passing one argument to `read_line`: `&mut -guess`. - -The job of `read_line` is to take whatever the user types into standard input -and place that into a string, so it takes that string as an argument. The -string argument needs to be mutable so the method can change the string’s -content by adding the user input. - -The `&` indicates that this argument is a *reference*, which gives you a way to -let multiple parts of your code access one piece of data without needing to -copy that data into memory multiple times. References are a complex feature, -and one of Rust’s major advantages is how safe and easy it is to use -references. You don’t need to know a lot of those details to finish this -program. For now, all you need to know is that like variables, references are -immutable by default. Hence, you need to write `&mut guess` rather than -`&guess` to make it mutable. (Chapter 4 will explain references more -thoroughly.) - -### Handling Potential Failure with the `Result` Type - -We’re not quite done with this line of code. Although what we’ve discussed so -far is a single line of text, it’s only the first part of the single logical -line of code. The second part is this method: - -``` -.expect("Failed to read line"); -``` - -When you call a method with the `.foo()` syntax, it’s often wise to introduce a -newline and other whitespace to help break up long lines. We could have -written this code as: - -``` -io::stdin().read_line(&mut guess).expect("Failed to read line"); -``` - -However, one long line is difficult to read, so it’s best to divide it: two -lines for two method calls. Now let’s discuss what this line does. - -As mentioned earlier, `read_line` puts what the user types into the string -we’re passing it, but it also returns a value—in this case, an -`io::Result`. Rust has a number of types named -`Result` in its standard library: a generic `Result` -as well as specific versions for submodules, such as `io::Result`. - -The `Result` types are *enumerations*, often referred -to as *enums*. An enumeration is a type that can have a fixed set of values, -and those values are called the enum’s *variants*. Chapter 6 will cover enums -in more detail. - -For `Result`, the variants are `Ok` or `Err`. The `Ok` variant indicates the -operation was successful, and inside `Ok` is the successfully generated value. -The `Err` variant means the operation failed, and `Err` contains information -about how or why the operation failed. - -The purpose of these `Result` types is to encode error-handling information. -Values of the `Result` type, like any type, have methods defined on them. An -instance of `io::Result` has an `expect` method that -you can call. If this instance of `io::Result` is an `Err` value, `expect` will -cause the program to crash and display the message that you passed as an -argument to `expect`. If the `read_line` method returns an `Err`, it would -likely be the result of an error coming from the underlying operating system. -If this instance of `io::Result` is an `Ok` value, `expect` will take the -return value that `Ok` is holding and return just that value to you so you -can use it. In this case, that value is the number of bytes in what the user -entered into standard input. - -If you don’t call `expect`, the program will compile, but you’ll get a warning: - -``` -$ cargo build - Compiling guessing_game v0.1.0 (file:///projects/guessing_game) -warning: unused `std::result::Result` which must be used - --> src/main.rs:10:5 - | -10 | io::stdin().read_line(&mut guess); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: #[warn(unused_must_use)] on by default -``` - -Rust warns that you haven’t used the `Result` value returned from `read_line`, -indicating that the program hasn’t handled a possible error. - -The right way to suppress the warning is to actually write error handling, but -since you just want to crash this program when a problem occurs, you can use -`expect`. You’ll learn about recovering from errors in Chapter 9. - -### Printing Values with `println!` Placeholders - -Aside from the closing curly brackets, there’s only one more line to discuss in -the code added so far, which is the following: - -``` -println!("You guessed: {}", guess); -``` - -This line prints the string we saved the user’s input in. The set of curly -brackets, `{}`, is a placeholder: think of `{}` as little crab pincers that -hold a value in place. You can print more than one value using curly brackets: -the first set of curly brackets holds the first value listed after the format -string, the second set holds the second value, and so on. Printing multiple -values in one call to `println!` would look like this: - -``` -let x = 5; -let y = 10; - -println!("x = {} and y = {}", x, y); -``` - -This code would print `x = 5 and y = 10`. - -### Testing the First Part - -Let’s test the first part of the guessing game. Run it using `cargo run`: - -``` -$ cargo run - Compiling guessing_game v0.1.0 (file:///projects/guessing_game) - Finished dev [unoptimized + debuginfo] target(s) in 2.53 secs - Running `target/debug/guessing_game` -Guess the number! -Please input your guess. -6 -You guessed: 6 -``` - -At this point, the first part of the game is done: we’re getting input from the -keyboard and then printing it. - -## Generating a Secret Number - -Next, we need to generate a secret number that the user will try to guess. The -secret number should be different every time so the game is fun to play more -than once. Let’s use a random number between 1 and 100 so the game isn’t too -difficult. Rust doesn’t yet include random number functionality in its standard -library. However, the Rust team does provide a `rand` crate at *https://crates.io/crates/rand*. - - -### Using a Crate to Get More Functionality - -Remember that a crate is a package of Rust code. The project we’ve been -building is a *binary crate*, which is an executable. The `rand` crate is a -*library crate*, which contains code intended to be used in other programs. - -Cargo’s use of external crates is where it really shines. Before we can write -code that uses `rand`, we need to modify the *Cargo.toml* file to include the -`rand` crate as a dependency. Open that file now and add the following line to -the bottom beneath the `[dependencies]` section header that Cargo created for -you: - -Filename: Cargo.toml - -``` -[dependencies] - -rand = "0.3.14" -``` - -In the *Cargo.toml* file, everything that follows a header is part of a section -that continues until another section starts. The `[dependencies]` section is -where you tell Cargo which external crates your project depends on and which -versions of those crates you require. In this case, we’ll specify the `rand` -crate with the semantic version specifier `0.3.14`. Cargo understands Semantic -Versioning (sometimes called *SemVer*), which is a -standard for writing version numbers. The number `0.3.14` is actually shorthand -for `^0.3.14`, which means “any version that has a public API compatible with -version 0.3.14.” - -Now, without changing any of the code, let’s build the project, as shown in -Listing 2-2: - -``` -$ cargo build - Updating registry `https://github.com/rust-lang/crates.io-index` - Downloading rand v0.3.14 - Downloading libc v0.2.14 - Compiling libc v0.2.14 - Compiling rand v0.3.14 - Compiling guessing_game v0.1.0 (file:///projects/guessing_game) - Finished dev [unoptimized + debuginfo] target(s) in 2.53 secs -``` - -Listing 2-2: The output from running `cargo build` after adding the rand crate -as a dependency - -You may see different version numbers (but they will all be compatible with -the code, thanks to SemVer!), and the lines may be in a different order. - -Now that we have an external dependency, Cargo fetches the latest versions of -everything from the *registry*, which is a copy of data from -Crates.io at *https://crates.io*. Crates.io is where people in the Rust ecosystem post -their open source Rust projects for others to use. - - -After updating the registry, Cargo checks the `[dependencies]` section and -downloads any crates you don’t have yet. In this case, although we only listed -`rand` as a dependency, Cargo also grabbed a copy of `libc`, because `rand` -depends on `libc` to work. After downloading the crates, Rust compiles them and -then compiles the project with the dependencies available. - -If you immediately run `cargo build` again without making any changes, you -won’t get any output aside from the `Finished` line. Cargo knows it has already -downloaded and compiled the dependencies, and you haven’t changed anything -about them in your *Cargo.toml* file. Cargo also knows that you haven’t changed -anything about your code, so it doesn’t recompile that either. With nothing to -do, it simply exits. - -If you open up the *src/main.rs* file, make a trivial change, and then save it -and build again, you’ll only see two lines of output: - -``` -$ cargo build - Compiling guessing_game v0.1.0 (file:///projects/guessing_game) - Finished dev [unoptimized + debuginfo] target(s) in 2.53 secs -``` - -These lines show Cargo only updates the build with your tiny change to the -*src/main.rs* file. Your dependencies haven’t changed, so Cargo knows it can -reuse what it has already downloaded and compiled for those. It just rebuilds -your part of the code. - -#### Ensuring Reproducible Builds with the *Cargo.lock* File - -Cargo has a mechanism that ensures you can rebuild the same artifact every time -you or anyone else builds your code: Cargo will use only the versions of the -dependencies you specified until you indicate otherwise. For example, what -happens if next week version `v0.3.15` of the `rand` crate comes out and -contains an important bug fix but also contains a regression that will break -your code? - -The answer to this problem is the *Cargo.lock* file, which was created the -first time you ran `cargo build` and is now in your *guessing_game* directory. -When you build a project for the first time, Cargo figures out all the -versions of the dependencies that fit the criteria and then writes them to -the *Cargo.lock* file. When you build your project in the future, Cargo will -see that the *Cargo.lock* file exists and use the versions specified there -rather than doing all the work of figuring out versions again. This lets you -have a reproducible build automatically. In other words, your project will -remain at `0.3.14` until you explicitly upgrade, thanks to the *Cargo.lock* -file. - -#### Updating a Crate to Get a New Version - -When you *do* want to update a crate, Cargo provides another command, `update`, -which will ignore the *Cargo.lock* file and figure out all the latest versions -that fit your specifications in *Cargo.toml*. If that works, Cargo will write -those versions to the *Cargo.lock* file. - -But by default, Cargo will only look for versions larger than `0.3.0` and -smaller than `0.4.0`. If the `rand` crate has released two new versions, -`0.3.15` and `0.4.0`, you would see the following if you ran `cargo update`: - -``` -$ cargo update - Updating registry `https://github.com/rust-lang/crates.io-index` - Updating rand v0.3.14 -> v0.3.15 -``` - -At this point, you would also notice a change in your *Cargo.lock* file noting -that the version of the `rand` crate you are now using is `0.3.15`. - -If you wanted to use `rand` version `0.4.0` or any version in the `0.4.x` -series, you’d have to update the *Cargo.toml* file to look like this instead: - -``` -[dependencies] - -rand = "0.4.0" -``` - -The next time you run `cargo build`, Cargo will update the registry of crates -available and reevaluate your `rand` requirements according to the new version -you have specified. - -There’s a lot more to say about Cargo and its ecosystem which we’ll discuss in -Chapter 14, but for now, that’s all you need to know. Cargo makes it very easy -to reuse libraries, so Rustaceans are able to write smaller projects that are -assembled from a number of packages. - -### Generating a Random Number - -Now that you’ve added the `rand` crate to *Cargo.toml*, let’s start using -`rand`. The next step is to update *src/main.rs*, as shown in Listing 2-3: - -Filename: src/main.rs - -``` -extern crate rand; - -use std::io; -use rand::Rng; - -fn main() { - println!("Guess the number!"); - - let secret_number = rand::thread_rng().gen_range(1, 101); - - 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); -} -``` - -Listing 2-3: Adding code to generate a random number - -First, we add a line that lets Rust know we’ll be using the `rand` crate as an -external dependency. This also does the equivalent of calling `use rand`, so -now we can call anything in the `rand` crate by placing `rand::` before it. - -Next, we add another `use` line: `use rand::Rng`. The `Rng` trait defines -methods that random number generators implement, and this trait must be in -scope for us to use those methods. Chapter 10 will cover traits in detail. - -Also, we’re adding two more lines in the middle. The `rand::thread_rng` function -will give us the particular random number generator that we’re going to use: -one that is local to the current thread of execution and seeded by the -operating system. Next, we call the `gen_range` method on the random number -generator. This method is defined by the `Rng` trait that we brought into -scope with the `use rand::Rng` statement. The `gen_range` method takes two -numbers as arguments and generates a random number between them. It’s inclusive -on the lower bound but exclusive on the upper bound, so we need to specify `1` -and `101` to request a number between 1 and 100. - -> Note: You won’t just know which traits to use and which methods and functions -> to call from a crate. Instructions for using a crate are in each crate’s -> documentation. Another neat feature of Cargo is that you can run the `cargo -> doc --open` command, which will build documentation provided by all of your -> dependencies locally and open it in your browser. If you’re interested in -> other functionality in the `rand` crate, for example, run `cargo doc --open` -> and click `rand` in the sidebar on the left. - -The second line that we added to the code prints the secret number. This is -useful while we’re developing the program to be able to test it, but we’ll -delete it from the final version. It’s not much of a game if the program prints -the answer as soon as it starts! - -Try running the program a few times: - -``` -$ cargo run - Compiling guessing_game v0.1.0 (file:///projects/guessing_game) - Finished dev [unoptimized + debuginfo] target(s) in 2.53 secs - Running `target/debug/guessing_game` -Guess the number! -The secret number is: 7 -Please input your guess. -4 -You guessed: 4 -$ cargo run - Running `target/debug/guessing_game` -Guess the number! -The secret number is: 83 -Please input your guess. -5 -You guessed: 5 -``` - -You should get different random numbers, and they should all be numbers between -1 and 100. Great job! - -## Comparing the Guess to the Secret Number - -Now that we have user input and a random number, we can compare them. That step -is shown in Listing 2-4. Note that this code won’t compile quite yet, as we -will explain. - -Filename: src/main.rs - -``` -extern crate rand; - -use std::io; -use std::cmp::Ordering; -use rand::Rng; - -fn main() { - // ---snip--- - - println!("You guessed: {}", guess); - - match guess.cmp(&secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => println!("You win!"), - } -} -``` - -Listing 2-4: Handling the possible return values of comparing two numbers - -The first new bit here is another `use` statement, bringing a type called -`std::cmp::Ordering` into scope from the standard library. Like `Result`, -`Ordering` is another enum, but the variants for `Ordering` are `Less`, -`Greater`, and `Equal`. These are the three outcomes that are possible when you -compare two values. - -Then we add five new lines at the bottom that use the `Ordering` type. - -The `cmp` method compares two values and can be called on anything that can be -compared. It takes a reference to whatever you want to compare with: here it’s -comparing the `guess` to the `secret_number`. Then it returns a variant of the -`Ordering` enum we brought into scope with the `use` statement. We use a -`match` expression to decide what to do next based on -which variant of `Ordering` was returned from the call to `cmp` with the values -in `guess` and `secret_number`. - -A `match` expression is made up of *arms*. An arm consists of a *pattern* and -the code that should be run if the value given to the beginning of the `match` -expression fits that arm’s pattern. Rust takes the value given to `match` and -looks through each arm’s pattern in turn. The `match` construct and patterns -are powerful features in Rust that let you express a variety of situations your -code might encounter and make sure that you handle them all. These features -will be covered in detail in Chapter 6 and Chapter 18, respectively. - -Let’s walk through an example of what would happen with the `match` expression -used here. Say that the user has guessed 50 and the randomly generated secret -number this time is 38. When the code compares 50 to 38, the `cmp` method will -return `Ordering::Greater`, because 50 is greater than 38. The `match` -expression gets the `Ordering::Greater` value and starts checking each arm’s -pattern. It looks at the first arm’s pattern, `Ordering::Less`, and sees that -the value `Ordering::Greater` does not match `Ordering::Less`, so it ignores -the code in that arm and moves to the next arm. The next arm’s pattern, -`Ordering::Greater`, *does* match `Ordering::Greater`! The associated code in -that arm will execute and print `Too big!` to the screen. The `match` -expression ends because it has no need to look at the last arm in this scenario. - -However, the code in Listing 2-4 won’t compile yet. Let’s try it: - -``` -$ cargo build - 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 struct `std::string::String`, found integral variable - | - = note: expected type `&std::string::String` - = note: found type `&{integer}` - -error: aborting due to previous error -Could not compile `guessing_game`. -``` - -The core of the error states that there are *mismatched types*. Rust has a -strong, static type system. However, it also has type inference. When we wrote -`let guess = String::new()`, Rust was able to infer that `guess` should be a -`String` and didn’t make us write the type. The `secret_number`, on the other -hand, is a number type. A few number types can have a value between 1 and 100: -`i32`, a 32-bit number; `u32`, an unsigned 32-bit number; `i64`, a 64-bit -number; as well as others. Rust defaults to an `i32`, which is the type of -`secret_number` unless you add type information elsewhere that would cause Rust -to infer a different numerical type. The reason for the error is that Rust -cannot compare a string and a number type. - -Ultimately, we want to convert the `String` the program reads as input into a -real number type so we can compare it numerically to the guess. We can do that -by adding the following two lines to the `main` function body: - -Filename: src/main.rs - -``` -// --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!"), - } -} -``` - -The two new lines are: - -``` -let guess: u32 = guess.trim().parse() - .expect("Please type a number!"); -``` - -We create a variable named `guess`. But wait, doesn’t the program already have -a variable named `guess`? It does, but Rust allows us to *shadow* the previous -value of `guess` with a new one. This feature is often used in situations in -which you want to convert a value from one type to another type. Shadowing lets -us reuse the `guess` variable name rather than forcing us to create two unique -variables, like `guess_str` and `guess` for example. (Chapter 3 covers -shadowing in more detail.) - -We bind `guess` to the expression `guess.trim().parse()`. The `guess` in the -expression refers to the original `guess` that was a `String` with the input in -it. The `trim` method on a `String` instance will eliminate any whitespace at -the beginning and end. Although `u32` can contain only numerical characters, -the user must press enter to satisfy -`read_line`. When the user presses enter, a -newline character is added to the string. For example, if the user types 5 and presses enter, -`guess` looks like this: `5\n`. The `\n` represents “newline,” the result of -pressing enter. The `trim` method eliminates -`\n`, resulting in just `5`. - -The `parse` method on strings parses a string into some -kind of number. Because this method can parse a variety of number types, we -need to tell Rust the exact number type we want by using `let guess: u32`. The -colon (`:`) after `guess` tells Rust we’ll annotate the variable’s type. Rust -has a few built-in number types; the `u32` seen here is an unsigned, 32-bit -integer. It’s a good default choice for a small positive number. You’ll learn -about other number types in Chapter 3. Additionally, the `u32` annotation in -this example program and the comparison with `secret_number` means that Rust -will infer that `secret_number` should be a `u32` as well. So now the -comparison will be between two values of the same type! - -The call to `parse` could easily cause an error. If, for example, the string -contained `A👍%`, there would be no way to convert that to a number. Because it -might fail, the `parse` method returns a `Result` type, much as the `read_line` -method does (discussed earlier in “Handling Potential Failure with the Result -Type”). We’ll treat this `Result` the same way by using the `expect` method -again. If `parse` returns an `Err` `Result` variant because it couldn’t create -a number from the string, the `expect` call will crash the game and print the -message we give it. If `parse` can successfully convert the string to a number, -it will return the `Ok` variant of `Result`, and `expect` will return the -number that we want from the `Ok` value. - -Let’s run the program now! - -``` -$ cargo run - Compiling guessing_game v0.1.0 (file:///projects/guessing_game) - Finished dev [unoptimized + debuginfo] target(s) in 0.43 secs - Running `target/guessing_game` -Guess the number! -The secret number is: 58 -Please input your guess. - 76 -You guessed: 76 -Too big! -``` - -Nice! Even though spaces were added before the guess, the program still figured -out that the user guessed 76. Run the program a few times to verify the -different behavior with different kinds of input: guess the number correctly, -guess a number that is too high, and guess a number that is too low. - -We have most of the game working now, but the user can make only one guess. -Let’s change that by adding a loop! - -## Allowing Multiple Guesses with Looping - -The `loop` keyword creates an infinite loop. We’ll add that now to give users -more chances at guessing the number: - -Filename: src/main.rs - -``` -// --snip-- - - println!("The secret number is: {}", secret_number); - - loop { - println!("Please input your guess."); - - // --snip-- - - match guess.cmp(&secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => println!("You win!"), - } - } -} -``` - -As you can see, we’ve moved everything into a loop from the guess input prompt -onward. Be sure to indent the lines inside the loop another four spaces each -and run the program again. Notice that there is a new problem because the -program is doing exactly what we told it to do: ask for another guess forever! -It doesn’t seem like the user can quit! - -The user could always halt the program by using the keyboard shortcut ctrl-c. But there’s another way to escape this -insatiable monster, as mentioned in the `parse` discussion in “Comparing the -Guess to the Secret Number”: if the user enters a non-number answer, the -program will crash. The user can take advantage of that in order to quit, as -shown here: - -``` -$ cargo run - Compiling guessing_game v0.1.0 (file:///projects/guessing_game) - Finished dev [unoptimized + debuginfo] target(s) in 1.50 secs - Running `target/guessing_game` -Guess the number! -The secret number is: 59 -Please input your guess. -45 -You guessed: 45 -Too small! -Please input your guess. -60 -You guessed: 60 -Too big! -Please input your guess. -59 -You guessed: 59 -You win! -Please input your guess. -quit -thread 'main' panicked at 'Please type a number!: ParseIntError { kind: InvalidDigit }', src/libcore/result.rs:785 -note: Run with `RUST_BACKTRACE=1` for a backtrace. -error: Process didn't exit successfully: `target/debug/guess` (exit code: 101) -``` - -Typing `quit` actually quits the game, but so will any other non-number input. -However, this is suboptimal to say the least. We want the game to automatically -stop when the correct number is guessed. - -### Quitting After a Correct Guess - -Let’s program the game to quit when the user wins by adding a `break` statement: - -Filename: src/main.rs - -``` -// --snip-- - - match guess.cmp(&secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => { - println!("You win!"); - break; - } - } - } -} -``` - -Adding the `break` line after `You win!` makes the program exit the loop when -the user guesses the secret number correctly. Exiting the loop also means -exiting the program, because the loop is the last part of `main`. - -### Handling Invalid Input - -To further refine the game’s behavior, rather than crashing the program when -the user inputs a non-number, let’s make the game ignore a non-number so the -user can continue guessing. We can do that by altering the line where `guess` -is converted from a `String` to a `u32`: - -``` -let guess: u32 = match guess.trim().parse() { - Ok(num) => num, - Err(_) => continue, -}; -``` - -Switching from an `expect` call to a `match` expression is how you generally -move from crashing on an error to handling the error. Remember that `parse` -returns a `Result` type and `Result` is an enum that has the variants `Ok` or -`Err`. We’re using a `match` expression here, as we did with the `Ordering` -result of the `cmp` method. - -If `parse` is able to successfully turn the string into a number, it will -return an `Ok` value that contains the resulting number. That `Ok` value will -match the first arm’s pattern, and the `match` expression will just return the -`num` value that `parse` produced and put inside the `Ok` value. That number -will end up right where we want it in the new `guess` variable we’re creating. - -If `parse` is *not* able to turn the string into a number, it will return an -`Err` value that contains more information about the error. The `Err` value -does not match the `Ok(num)` pattern in the first `match` arm, but it does -match the `Err(_)` pattern in the second arm. The underscore, `_`, is a -catchall value; in this example, we’re saying we want to match all `Err` -values, no matter what information they have inside them. So the program will -execute the second arm’s code, `continue`, which means to go to the next -iteration of the `loop` and ask for another guess. So effectively, the program -ignores all errors that `parse` might encounter! - -Now everything in the program should work as expected. Let’s try it: - -``` -$ cargo run - Compiling guessing_game v0.1.0 (file:///projects/guessing_game) - Running `target/guessing_game` -Guess the number! -The secret number is: 61 -Please input your guess. -10 -You guessed: 10 -Too small! -Please input your guess. -99 -You guessed: 99 -Too big! -Please input your guess. -foo -Please input your guess. -61 -You guessed: 61 -You win! -``` - -Awesome! With one tiny final tweak, we will finish the guessing game. Recall -that the program is still printing the secret number. That worked well for -testing, but it ruins the game. Let’s delete the `println!` that outputs the -secret number. Listing 2-5 shows the final code: - -Filename: src/main.rs - -``` -extern crate rand; - -use std::io; -use std::cmp::Ordering; -use rand::Rng; - -fn main() { - println!("Guess the number!"); - - let secret_number = rand::thread_rng().gen_range(1, 101); - - 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; - } - } - } -} -``` - -Listing 2-5: Complete guessing game code - -## Summary - -At this point, you’ve successfully built the guessing game! Congratulations! - -This project was a hands-on way to introduce you to many new Rust concepts: -`let`, `match`, methods, associated functions, the use of external crates, and -more. In the next few chapters, you’ll learn about these concepts in more -detail. Chapter 3 covers concepts that most programming languages have, such as -variables, data types, and functions, and shows how to use them in Rust. -Chapter 4 explores ownership, a feature that makes Rust different from other -languages. Chapter 5 discusses structs and method syntax, and Chapter 6 -explains how enums work. diff --git a/second-edition/nostarch/chapter03.md b/second-edition/nostarch/chapter03.md deleted file mode 100644 index 9d86a8e50e..0000000000 --- a/second-edition/nostarch/chapter03.md +++ /dev/null @@ -1,1472 +0,0 @@ - -[TOC] - -# Common Programming Concepts - -This chapter covers concepts that appear in almost every programming language -and how they work in Rust. Many programming languages have much in common at -their core. None of the concepts presented in this chapter are unique to Rust, -but we'll discuss them in the context of Rust and explain the conventions -around using these concepts. - -Specifically, you’ll learn about variables, basic types, functions, comments, -and control flow. These foundations will be in every Rust program, and learning -them early will give you a strong core to start from. - -> ### Keywords -> -> The Rust language has a set of *keywords* that are reserved for use by -> the language only, much as in other languages. Keep in mind that you cannot -> use these words as names of variables or functions. Most of the keywords have -> special meanings, and you’ll be using them to do various tasks in your Rust -> programs; a few have no current functionality associated with them but have -> been reserved for functionality that might be added to Rust in the future. You -> can find a list of the keywords in Appendix A. - -## Variables and Mutability - -As mentioned in Chapter 2, by default variables are immutable. This is one of -many nudges Rust gives you to write your code in a way that takes advantage of -the safety and easy concurrency that Rust offers. However, you still have the -option to make your variables mutable. Let’s explore how and why Rust -encourages you to favor immutability and why sometimes you might want to opt -out. - -When a variable is immutable, once a value is bound to a name, you can’t change -that value. To illustrate this, let’s generate a new project called *variables* -in your *projects* directory by using `cargo new --bin variables`. - -Then, in your new *variables* directory, open *src/main.rs* and replace its -code with the following code that won’t compile just yet: - -Filename: src/main.rs - -``` -fn main() { - let x = 5; - println!("The value of x is: {}", x); - x = 6; - println!("The value of x is: {}", x); -} -``` - -Save and run the program using `cargo run`. You should receive an error -message, as shown in this output: - -``` -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 -``` - -This example shows how the compiler helps you find errors in your programs. -Even though compiler errors can be frustrating, they only mean your program -isn’t safely doing what you want it to do yet; they do *not* mean that you’re -not a good programmer! Experienced Rustaceans still get compiler errors. - -The error indicates that the cause of the error is that you `cannot assign twice -to immutable variable x`, because you tried to assign a second value to the -immutable `x` variable. - -It’s important that we get compile-time errors when we attempt to change a -value that we previously designated as immutable because this very situation -can lead to bugs. If one part of our code operates on the assumption that a -value will never change and another part of our code changes that value, it’s -possible that the first part of the code won’t do what it was designed to do. -The cause of this kind of bug can be difficult to track down after the fact, -especially when the second piece of code changes the value only *sometimes*. - -In Rust, the compiler guarantees that when you state that a value won’t change, -it really won’t change. That means that when you’re reading and writing code, -you don’t have to keep track of how and where a value might change. Your code -is thus easier to reason through. - -But mutability can be very useful. Variables are immutable only by default; as -you did in Chapter 2, you can make them mutable by adding `mut` in front of the -variable name. In addition to allowing this value to change, `mut` conveys -intent to future readers of the code by indicating that other parts of the code -will be changing this variable value. - -For example, let’s change *src/main.rs* to the following: - -Filename: 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); -} -``` - -When we run the program now, we get this: - -``` -$ cargo run - Compiling variables v0.1.0 (file:///projects/variables) - Finished dev [unoptimized + debuginfo] target(s) in 0.30 secs - Running `target/debug/variables` -The value of x is: 5 -The value of x is: 6 -``` - -We’re allowed to change the value that `x` binds to from `5` to `6` when `mut` -is used. In some cases, you’ll want to make a variable mutable because it makes -the code more convenient to write than if it had only immutable variables. - -There are multiple trade-offs to consider in addition to the prevention of -bugs. For example, in cases where you’re using large data structures, mutating -an instance in place may be faster than copying and returning newly allocated -instances. With smaller data structures, creating new instances and writing in -a more functional programming style may be easier to think through, so lower -performance might be a worthwhile penalty for gaining that clarity. - -### Differences Between Variables and Constants - -Being unable to change the value of a variable might have reminded you of -another programming concept that most other languages have: *constants*. Like -immutable variables, constants are values that are bound to a name and are not -allowed to change, but there are a few differences between constants and -variables. - -First, you aren’t allowed to use `mut` with constants. Constants aren’t just -immutable by default—they’re always immutable. - -You declare constants using the `const` keyword instead of the `let` keyword, -and the type of the value *must* be annotated. We’re about to cover types and -type annotations in the next section, “Data Types,” so don’t worry about the -details right now. Just know that you must always annotate the type. - -Constants can be declared in any scope, including the global scope, which makes -them useful for values that many parts of code need to know about. - -The last difference is that constants may be set only to a constant expression, -not the result of a function call or any other value that could only be -computed at runtime. - -Here’s an example of a constant declaration where the constant’s name is -`MAX_POINTS` and its value is set to 100,000. (Rust’s constant naming -convention is to use all uppercase with underscores between words): - -``` -const MAX_POINTS: u32 = 100_000; -``` - -Constants are valid for the entire time a program runs, within the scope they -were declared in, making them a useful choice for values in your application -domain that multiple parts of the program might need to know about, such as the -maximum number of points any player of a game is allowed to earn or the speed -of light. - -Naming hardcoded values used throughout your program as constants is useful in -conveying the meaning of that value to future maintainers of the code. It also -helps to have only one place in your code you would need to change if the -hardcoded value needed to be updated in the future. - -### Shadowing - -As you saw in the “Comparing the Guess to the Secret Number” section in Chapter -2, you can declare a new variable with the same name as a previous variable, -and the new variable shadows the previous variable. Rustaceans say that the -first variable is *shadowed* by the second, which means that the second -variable’s value is what appears when the variable is used. We can shadow a -variable by using the same variable’s name and repeating the use of the `let` -keyword as follows: - -Filename: src/main.rs - -``` -fn main() { - let x = 5; - - let x = x + 1; - - let x = x * 2; - - println!("The value of x is: {}", x); -} -``` - -This program first binds `x` to a value of `5`. Then it shadows `x` by -repeating `let x =`, taking the original value and adding `1` so the value of -`x` is then `6`. The third `let` statement also shadows `x`, multiplying the -previous value by `2` to give `x` a final value of `12`. When we run this -program, it will output the following: - -``` -$ cargo run - Compiling variables v0.1.0 (file:///projects/variables) - Finished dev [unoptimized + debuginfo] target(s) in 0.31 secs - Running `target/debug/variables` -The value of x is: 12 -``` - -Shadowing is different than marking a variable as `mut`, because we’ll get a -compile-time error if we accidentally try to reassign to this variable without -using the `let` keyword. By using `let`, we can perform a few transformations -on a value but have the variable be immutable after those transformations have -been completed. - -The other difference between `mut` and shadowing is that because we’re -effectively creating a new variable when we use the `let` keyword again, we can -change the type of the value but reuse the same name. For example, say our -program asks a user to show how many spaces they want between some text by -inputting space characters, but we really want to store that input as a number: - -``` -let spaces = " "; -let spaces = spaces.len(); -``` - -This construct is allowed because the first `spaces` variable is a string type -and the second `spaces` variable, which is a brand-new variable that happens to -have the same name as the first one, is a number type. Shadowing thus spares us -from having to come up with different names, such as `spaces_str` and -`spaces_num`; instead, we can reuse the simpler `spaces` name. However, if we -try to use `mut` for this, as shown here, we’ll get a compile-time error: - -``` -let mut spaces = " "; -spaces = spaces.len(); -``` - -The error says we’re not allowed to mutate a variable’s type: - -``` -error[E0308]: mismatched types - --> src/main.rs:3:14 - | -3 | spaces = spaces.len(); - | ^^^^^^^^^^^^ expected &str, found usize - | - = note: expected type `&str` - found type `usize` -``` - -Now that we’ve explored how variables work, let’s look at more data types they -can have. - -## Data Types - -Every value in Rust is of a certain *data type*, which tells Rust what kind of -data is being specified so it knows how to work with that data. We’ll look at -two data type subsets: scalar and compound. - -Keep in mind that Rust is a *statically typed* language, which means that it -must know the types of all variables at compile time. The compiler can usually -infer what type we want to use based on the value and how we use it. In cases -when many types are possible, such as when we converted a `String` to a numeric -type using `parse` in the “Comparing the Guess to the Secret Number” section in -Chapter 2, we must add a type annotation, like this: - -``` -let guess: u32 = "42".parse().expect("Not a number!"); -``` - -If we don’t add the type annotation here, Rust will display the following -error, which means the compiler needs more information from us to know which -type we want to use: - -``` -error[E0282]: type annotations needed - --> src/main.rs:2:9 - | -2 | let guess = "42".parse().expect("Not a number!"); - | ^^^^^ - | | - | cannot infer type for `_` - | consider giving `guess` a type -``` - -You’ll see different type annotations for other data types. - -### Scalar Types - -A *scalar* type represents a single value. Rust has four primary scalar types: -integers, floating-point numbers, Booleans, and characters. You may recognize -these from other programming languages. Let’s jump into how they work in Rust. - -#### Integer Types - -An *integer* is a number without a fractional component. We used one integer -type in Chapter 2, the `u32` type. This type declaration indicates that the -value it’s associated with should be an unsigned integer (signed integer types -start with `i`, instead of `u`) that takes up 32 bits of space. Table 3-1 shows -the built-in integer types in Rust. Each variant in the Signed and Unsigned -columns (for example, `i16`) can be used to declare the type of an integer -value. - -Table 3-1: Integer Types in Rust - -| Length | Signed | Unsigned | -|--------|---------|----------| -| 8-bit | `i8` | `u8` | -| 16-bit | `i16` | `u16` | -| 32-bit | `i32` | `u32` | -| 64-bit | `i64` | `u64` | -| arch | `isize` | `usize` | - -Each variant can be either signed or unsigned and has an explicit size. -*Signed* and *unsigned* refer to whether it’s possible for the number to be -negative or positive—in other words, whether the number needs to have a sign -with it (signed) or whether it will only ever be positive and can therefore be -represented without a sign (unsigned). It’s like writing numbers on paper: when -the sign matters, a number is shown with a plus sign or a minus sign; however, -when it’s safe to assume the number is positive, it’s shown with no sign. -Signed numbers are stored using two’s complement representation (if you’re -unsure what this is, you can search for it online; an explanation is outside -the scope of this book). - -Each signed variant can store numbers from -(2n - 1) to 2n - -1 - 1 inclusive, where *n* is the number of bits that variant uses. So an -`i8` can store numbers from -(27) to 27 - 1, which equals --128 to 127. Unsigned variants can store numbers from 0 to 2n - 1, -so a `u8` can store numbers from 0 to 28 - 1, which equals 0 to 255. - -Additionally, the `isize` and `usize` types depend on the kind of computer your -program is running on: 64 bits if you’re on a 64-bit architecture and 32 bits -if you’re on a 32-bit architecture. - -You can write integer literals in any of the forms shown in Table 3-2. Note -that all number literals except the byte literal allow a type suffix, such as -`57u8`, and `_` as a visual separator, such as `1_000`. - -Table 3-2: Integer Literals in Rust - -| Number literals | Example | -|------------------|---------------| -| Decimal | `98_222` | -| Hex | `0xff` | -| Octal | `0o77` | -| Binary | `0b1111_0000` | -| Byte (`u8` only) | `b'A'` | - -So how do you know which type of integer to use? If you’re unsure, Rust’s -defaults are generally good choices, and integer types default to `i32`: this -type is generally the fastest, even on 64-bit systems. The primary situation in -which you’d use `isize` or `usize` is when indexing some sort of collection. - -#### Floating-Point Types - -Rust also has two primitive types for *floating-point numbers*, which are -numbers with decimal points. Rust’s floating-point types are `f32` and `f64`, -which are 32 bits and 64 bits in size, respectively. The default type is `f64` -because on modern CPUs it’s roughly the same speed as `f32` but is capable of -more precision. - -Here’s an example that shows floating-point numbers in action: - -Filename: src/main.rs - -``` -fn main() { - let x = 2.0; // f64 - - let y: f32 = 3.0; // f32 -} -``` - -Floating-point numbers are represented according to the IEEE-754 standard. The -`f32` type is a single-precision float, and `f64` has double precision. - -#### Numeric Operations - -Rust supports the basic mathematical operations you’d expect for all of the -number types: addition, subtraction, multiplication, division, and remainder. -The following code shows how you’d use each one in a `let` statement: - -Filename: 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; - - // remainder - let remainder = 43 % 5; -} -``` - -Each expression in these statements uses a mathematical operator and evaluates -to a single value, which is then bound to a variable. Appendix B contains a -list of all operators that Rust provides. - -#### The Boolean Type - -As in most other programming languages, a Boolean type in Rust has two possible -values: `true` and `false`. The Boolean type in Rust is specified using `bool`. -For example: - -Filename: src/main.rs - -``` -fn main() { - let t = true; - - let f: bool = false; // with explicit type annotation -} -``` - -The main way to consume Boolean values is through conditionals, such as an `if` -expression. We’ll cover how `if` expressions work in Rust in the “Control Flow” -section. - -#### The Character Type - -So far we’ve worked only with numbers, but Rust supports letters too. Rust’s -`char` type is the language’s most primitive alphabetic type, and the following -code shows one way to use it. (Note that the `char` type is specified with -single quotes, as opposed to strings, which use double quotes.) - -Filename: src/main.rs - -``` -fn main() { - let c = 'z'; - let z = 'ℤ'; - let heart_eyed_cat = '😻'; -} -``` - -Rust’s `char` type represents a Unicode Scalar Value, which means it can -represent a lot more than just ASCII. Accented letters; Chinese, Japanese, and -Korean ideographs; emoji; and zero-width spaces are all valid `char` types in -Rust. Unicode Scalar Values range from `U+0000` to `U+D7FF` and `U+E000` to -`U+10FFFF` inclusive. However, a “character” isn’t really a concept in Unicode, -so your human intuition for what a “character” is may not match up with what a -`char` is in Rust. We’ll discuss this topic in detail in “Strings” in Chapter 8. - -### Compound Types - -*Compound types* can group multiple values into one type. Rust has two -primitive compound types: tuples and arrays. - -#### The Tuple Type - -A tuple is a general way of grouping together some number of other values with -a variety of types into one compound type. - -We create a tuple by writing a comma-separated list of values inside -parentheses. Each position in the tuple has a type, and the types of the -different values in the tuple don’t have to be the same. We’ve added optional -type annotations in this example: - -Filename: src/main.rs - -``` -fn main() { - let tup: (i32, f64, u8) = (500, 6.4, 1); -} -``` - -The variable `tup` binds to the entire tuple, because a tuple is considered a -single compound element. To get the individual values out of a tuple, we can -use pattern matching to destructure a tuple value, like this: - -Filename: src/main.rs - -``` -fn main() { - let tup = (500, 6.4, 1); - - let (x, y, z) = tup; - - println!("The value of y is: {}", y); -} -``` - -This program first creates a tuple and binds it to the variable `tup`. It then -uses a pattern with `let` to take `tup` and turn it into three separate -variables, `x`, `y`, and `z`. This is called *destructuring*, because it breaks -the single tuple into three parts. Finally, the program prints the value of -`y`, which is `6.4`. - -In addition to destructuring through pattern matching, we can access a tuple -element directly by using a period (`.`) followed by the index of the value we -want to access. For example: - -Filename: 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; -} -``` - -This program creates a tuple, `x`, and then makes new variables for each -element by using their index. As with most programming languages, the first -index in a tuple is 0. - -#### The Array Type - -Another way to have a collection of multiple values is with an *array*. Unlike -a tuple, every element of an array must have the same type. Arrays in Rust are -different from arrays in some other languages because arrays in Rust have a -fixed length: once declared, they cannot grow or shrink in size. - -In Rust, the values going into an array are written as a comma-separated list -inside square brackets: - -Filename: src/main.rs - -``` -fn main() { - let a = [1, 2, 3, 4, 5]; -} -``` - -Arrays are useful when you want your data allocated on the stack rather than -the heap (we will discuss the stack and the heap more in Chapter 4), or when -you want to ensure you always have a fixed number of elements. An array isn’t -as flexible as the vector type, though. A vector is a similar collection type -provided by the standard library that *is* allowed to grow or shrink in size. -If you’re unsure whether to use an array or a vector, you should probably use a -vector. Chapter 8 discusses vectors in more detail. - -An example of when you might want to use an array rather than a vector is in a -program that needs to know the names of the months of the year. It’s very -unlikely that such a program will need to add or remove months, so you can use -an array because you know it will always contain 12 items: - -``` -let months = ["January", "February", "March", "April", "May", "June", "July", - "August", "September", "October", "November", "December"]; -``` - -##### Accessing Array Elements - -An array is a single chunk of memory allocated on the stack. You can access -elements of an array using indexing, like this: - -Filename: src/main.rs - -``` -fn main() { - let a = [1, 2, 3, 4, 5]; - - let first = a[0]; - let second = a[1]; -} -``` - -In this example, the variable named `first` will get the value `1`, because -that is the value at index `[0]` in the array. The variable named `second` will -get the value `2` from index `[1]` in the array. - -##### Invalid Array Element Access - -What happens if you try to access an element of an array that is past the end -of the array? Say you change the example to the following code, which will -compile but exit with an error when it runs: - -Filename: src/main.rs - -``` -fn main() { - let a = [1, 2, 3, 4, 5]; - let index = 10; - - let element = a[index]; - - println!("The value of element is: {}", element); -} -``` - -Running this code using `cargo run` produces the following result: - -``` -$ cargo run - Compiling arrays v0.1.0 (file:///projects/arrays) - Finished dev [unoptimized + debuginfo] target(s) in 0.31 secs - Running `target/debug/arrays` -thread '
' panicked at 'index out of bounds: the len is 5 but the index is - 10', src/main.rs:6 -note: Run with `RUST_BACKTRACE=1` for a backtrace. -``` - -The compilation didn’t produce any errors, but the program resulted in a -*runtime* error and didn’t exit successfully. When you attempt to access an -element using indexing, Rust will check that the index you’ve specified is less -than the array length. If the index is greater than the length, Rust will -*panic*, which is the term Rust uses when a program exits with an error. - -This is the first example of Rust’s safety principles in action. In many -low-level languages, this kind of check is not done, and when you provide an -incorrect index, invalid memory can be accessed. Rust protects you against this -kind of error by immediately exiting instead of allowing the memory access and -continuing. Chapter 9 discusses more of Rust’s error handling. - -## Functions - -Functions are pervasive in Rust code. You’ve already seen one of the most -important functions in the language: the `main` function, which is the entry -point of many programs. You’ve also seen the `fn` keyword, which allows you to -declare new functions. - -Rust code uses *snake case* as the conventional style for function and variable -names. In snake case, all letters are lowercase and underscores separate words. -Here’s a program that contains an example function definition: - -Filename: src/main.rs - -``` -fn main() { - println!("Hello, world!"); - - another_function(); -} - -fn another_function() { - println!("Another function."); -} -``` - -Function definitions in Rust start with `fn` and have a set of parentheses -after the function name. The curly brackets tell the compiler where the -function body begins and ends. - -We can call any function we’ve defined by entering its name followed by a set -of parentheses. Because `another_function` is defined in the program, it can be -called from inside the `main` function. Note that we defined `another_function` -*after* the `main` function in the source code; we could have defined it before -as well. Rust doesn’t care where you define your functions, only that they’re -defined somewhere. - -Let’s start a new binary project named *functions* to explore functions -further. Place the `another_function` example in *src/main.rs* and run it. You -should see the following output: - -``` -$ cargo run - Compiling functions v0.1.0 (file:///projects/functions) - Finished dev [unoptimized + debuginfo] target(s) in 0.28 secs - Running `target/debug/functions` -Hello, world! -Another function. -``` - -The lines execute in the order in which they appear in the `main` function. -First, the “Hello, world!” message prints, and then `another_function` is -called and its message is printed. - -### Function Parameters - -Functions can also be defined to have *parameters*, which are special variables -that are part of a function’s signature. When a function has parameters, you -can provide it with concrete values for those parameters. Technically, the -concrete values are called *arguments*, but in casual conversation, people tend -to use the words *parameter* and *argument* interchangeably for either the -variables in a function’s definition or the concrete values passed in when you -call a function. - -The following rewritten version of `another_function` shows what parameters -look like in Rust: - -Filename: src/main.rs - -``` -fn main() { - another_function(5); -} - -fn another_function(x: i32) { - println!("The value of x is: {}", x); -} -``` - -Try running this program; you should get the following output: - -``` -$ cargo run - Compiling functions v0.1.0 (file:///projects/functions) - Finished dev [unoptimized + debuginfo] target(s) in 1.21 secs - Running `target/debug/functions` -The value of x is: 5 -``` - -The declaration of `another_function` has one parameter named `x`. The type of -`x` is specified as `i32`. When `5` is passed to `another_function`, the -`println!` macro puts `5` where the pair of curly brackets were in the format -string. - -In function signatures, you *must* declare the type of each parameter. This is -a deliberate decision in Rust’s design: requiring type annotations in function -definitions means the compiler almost never needs you to use them elsewhere in -the code to figure out what you mean. - -When you want a function to have multiple parameters, separate the parameter -declarations with commas, like this: - -Filename: src/main.rs - -``` -fn main() { - another_function(5, 6); -} - -fn another_function(x: i32, y: i32) { - println!("The value of x is: {}", x); - println!("The value of y is: {}", y); -} -``` - -This example creates a function with two parameters, both of which are `i32` -types. The function then prints the values in both of its parameters. Note that -function parameters don’t all need to be the same type, they just happen to be -in this example. - -Let’s try running this code. Replace the program currently in your *functions* -project’s *src/main.rs* file with the preceding example and run it using `cargo -run`: - -``` -$ cargo run - Compiling functions v0.1.0 (file:///projects/functions) - Finished dev [unoptimized + debuginfo] target(s) in 0.31 secs - Running `target/debug/functions` -The value of x is: 5 -The value of y is: 6 -``` - -Because we called the function with `5` as the value for `x` and `6` is passed -as the value for `y`, the two strings are printed with these values. - -### Function Bodies - -Function bodies are made up of a series of statements optionally ending in an -expression. So far, we’ve only covered functions without an ending expression, -but you have seen an expression as part of statements. Because Rust is an -expression-based language, this is an important distinction to understand. -Other languages don’t have the same distinctions, so let’s look at what -statements and expressions are and how their differences affect the bodies of -functions. - -### Statements and Expressions - -We’ve actually already used statements and expressions. *Statements* are -instructions that perform some action and do not return a value. *Expressions* -evaluate to a resulting value. Let’s look at some examples. - -Creating a variable and assigning a value to it with the `let` keyword is a -statement. In Listing 3-1, `let y = 6;` is a statement: - -Filename: src/main.rs - -``` -fn main() { - let y = 6; -} -``` - -Listing 3-1: A `main` function declaration containing one statement - -Function definitions are also statements; the entire preceding example is a -statement in itself. - -Statements do not return values. Therefore, you can’t assign a `let` statement -to another variable, as the following code tries to do; you’ll get an error: - -Filename: src/main.rs - -``` -fn main() { - let x = (let y = 6); -} -``` - -When you run this program, the error you’ll get looks like this: - -``` -$ cargo run - Compiling functions v0.1.0 (file:///projects/functions) -error: expected expression, found statement (`let`) - --> src/main.rs:2:14 - | -2 | let x = (let y = 6); - | ^^^ - | - = note: variable declaration using `let` is a statement -``` - -The `let y = 6` statement does not return a value, so there isn’t anything for -`x` to bind to. This is different from what happens in other languages, such as -C and Ruby, where the assignment returns the value of the assignment. In those -languages, you can write `x = y = 6` and have both `x` and `y` have the value -`6`; that is not the case in Rust. - -Expressions evaluate to something and make up most of the rest of the code that -you’ll write in Rust. Consider a simple math operation, such as `5 + 6`, which -is an expression that evaluates to the value `11`. Expressions can be part of -statements: in Listing 3-1, the `6` in the statement `let y = 6;` is an -expression that evaluates to the value `6`. Calling a function is an -expression. Calling a macro is an expression. The block that we use to create -new scopes, `{}`, is an expression, for example: - -Filename: src/main.rs - -``` -fn main() { - let x = 5; - - let y = { - let x = 3; - x + 1 - }; - - println!("The value of y is: {}", y); -} -``` - -This expression: - -``` -{ - let x = 3; - x + 1 -} -``` - -is a block that, in this case, evaluates to `4`. That value gets bound to `y` -as part of the `let` statement. Note the `x + 1` line without a semicolon at -the end, which is unlike most of the lines you’ve seen so far. Expressions do -not include ending semicolons. If you add a semicolon to the end of an -expression, you turn it into a statement, which will then not return a value. -Keep this in mind as you explore function return values and expressions next. - -### Functions with Return Values - -Functions can return values to the code that calls them. We don’t name return -values, but we do declare their type after an arrow (`->`). In Rust, the return -value of the function is synonymous with the value of the final expression in -the block of the body of a function. You can return early from a function by -using the `return` keyword and specifying a value, but most functions return -the last expression implicitly. Here’s an example of a function that returns a -value: - -Filename: src/main.rs - -``` -fn five() -> i32 { - 5 -} - -fn main() { - let x = five(); - - println!("The value of x is: {}", x); -} -``` - -There are no function calls, macros, or even `let` statements in the `five` -function—just the number `5` by itself. That’s a perfectly valid function in -Rust. Note that the function’s return type is specified, too, as `-> i32`. Try -running this code; the output should look like this: - -``` -$ cargo run - Compiling functions v0.1.0 (file:///projects/functions) - Finished dev [unoptimized + debuginfo] target(s) in 0.30 secs - Running `target/debug/functions` -The value of x is: 5 -``` - -The `5` in `five` is the function’s return value, which is why the return type -is `i32`. Let’s examine this in more detail. There are two important bits: -first, the line `let x = five();` shows that we’re using the return value of a -function to initialize a variable. Because the function `five` returns a `5`, -that line is the same as the following: - -``` -let x = 5; -``` - -Second, the `five` function has no parameters and defines the type of the -return value, but the body of the function is a lonely `5` with no semicolon -because it’s an expression whose value we want to return. - -Let’s look at another example: - -Filename: 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 -} -``` - -Running this code will print `The value of x is: 6`. But if we place a -semicolon at the end of the line containing `x + 1`, changing it from an -expression to a statement, we’ll get an error. - -Filename: 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; -} -``` - -Running this code produces an error, as follows: - -``` -error[E0308]: mismatched types - --> src/main.rs:7:28 - | -7 | fn plus_one(x: i32) -> i32 { - | ____________________________^ -8 | | x + 1; - | | - help: consider removing this semicolon -9 | | } - | |_^ expected i32, found () - | - = note: expected type `i32` - found type `()` -``` - -The main error message, “mismatched types,” reveals the core issue with this -code. The definition of the function `plus_one` says that it will return an -`i32`, but statements don’t evaluate to a value, which is expressed by `()`, -the empty tuple. Therefore, nothing is returned, which contradicts the function -definition and results in an error. In this output, Rust provides a message to -possibly help rectify this issue: it suggests removing the semicolon, which -would fix the error. - -## Comments - -All programmers strive to make their code easy to understand, but sometimes -extra explanation is warranted. In these cases, programmers leave notes, or -*comments*, in their source code that the compiler will ignore but people -reading the source code may find useful. - -Here’s a simple comment: - -``` -// Hello, world. -``` - -In Rust, comments must start with two slashes and continue until the end of the -line. For comments that extend beyond a single line, you’ll need to include -`//` on each line, like this: - -``` -// So we’re doing something complicated here, long enough that we need -// multiple lines of comments to do it! Whew! Hopefully, this comment will -// explain what’s going on. -``` - -Comments can also be placed at the end of lines containing code: - -Filename: src/main.rs - -``` -fn main() { - let lucky_number = 7; // I’m feeling lucky today. -} -``` - -But you’ll more often see them used in this format, with the comment on a -separate line above the code it’s annotating: - -Filename: src/main.rs - -``` -fn main() { - // I’m feeling lucky today. - let lucky_number = 7; -} -``` - -Rust also has another kind of comment, documentation comments, which we’ll -discuss in Chapter 14. - -## Control Flow - -Deciding whether or not to run some code depending on if a condition is true -and deciding to run some code repeatedly while a condition is true are basic -building blocks in most programming languages. The most common constructs that -let you control the flow of execution of Rust code are `if` expressions and -loops. - -### `if` Expressions - -An `if` expression allows you to branch your code depending on conditions. You -provide a condition and then state, “If this condition is met, run this block -of code. If the condition is not met, do not run this block of code.” - -Create a new project called *branches* in your *projects* directory to explore -the `if` expression. In the *src/main.rs* file, input the following: - -Filename: src/main.rs - -``` -fn main() { - let number = 3; - - if number < 5 { - println!("condition was true"); - } else { - println!("condition was false"); - } -} -``` - - - -All `if` expressions start with the keyword `if`, which is followed by a -condition. In this case, the condition checks whether or not the variable -`number` has a value less than 5. The block of code we want to execute if the -condition is true is placed immediately after the condition inside curly -brackets. Blocks of code associated with the conditions in `if` expressions are -sometimes called *arms*, just like the arms in `match` expressions that we -discussed in the “Comparing the Guess to the Secret Number” section of -Chapter 2. - -Optionally, we can also include an `else` expression, which we chose -to do here, to give the program an alternative block of code to execute should -the condition evaluate to false. If you don’t provide an `else` expression and -the condition is false, the program will just skip the `if` block and move on -to the next bit of code. - -Try running this code; you should see the following output: - -``` -$ cargo run - Compiling branches v0.1.0 (file:///projects/branches) - Finished dev [unoptimized + debuginfo] target(s) in 0.31 secs - Running `target/debug/branches` -condition was true -``` - -Let’s try changing the value of `number` to a value that makes the condition -`false` to see what happens: - -``` -let number = 7; -``` - -Run the program again, and look at the output: - -``` -$ cargo run - Compiling branches v0.1.0 (file:///projects/branches) - Finished dev [unoptimized + debuginfo] target(s) in 0.31 secs - Running `target/debug/branches` -condition was false -``` - -It’s also worth noting that the condition in this code *must* be a `bool`. If -the condition isn’t a `bool`, we’ll get an error. For example: - -Filename: src/main.rs - -``` -fn main() { - let number = 3; - - if number { - println!("number was three"); - } -} -``` - -The `if` condition evaluates to a value of `3` this time, and Rust throws an -error: - -``` -error[E0308]: mismatched types - --> src/main.rs:4:8 - | -4 | if number { - | ^^^^^^ expected bool, found integral variable - | - = note: expected type `bool` - found type `{integer}` -``` - -The error indicates that Rust expected a `bool` but got an integer. Unlike -languages such as Ruby and JavaScript, Rust will not automatically try to -convert non-Boolean types to a Boolean. You must be explicit and always provide -`if` with a Boolean as its condition. If we want the `if` code block to run -only when a number is not equal to `0`, for example, we can change the `if` -expression to the following: - -Filename: src/main.rs - -``` -fn main() { - let number = 3; - - if number != 0 { - println!("number was something other than zero"); - } -} -``` - -Running this code will print `number was something other than zero`. - -#### Handling Multiple Conditions with `else if` - -You can have multiple conditions by combining `if` and `else` in an `else if` -expression. For example: - -Filename: 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"); - } -} -``` - -This program has four possible paths it can take. After running it, you should -see the following output: - -``` -$ cargo run - Compiling branches v0.1.0 (file:///projects/branches) - Finished dev [unoptimized + debuginfo] target(s) in 0.31 secs - Running `target/debug/branches` -number is divisible by 3 -``` - -When this program executes, it checks each `if` expression in turn and executes -the first body for which the condition holds true. Note that even though 6 is -divisible by 2, we don’t see the output `number is divisible by 2`, nor do we -see the `number is not divisible by 4, 3, or 2` text from the `else` block. -That’s because Rust only executes the block for the first true condition, and -once it finds one, it doesn’t even check the rest. - -Using too many `else if` expressions can clutter your code, so if you have more -than one, you might want to refactor your code. Chapter 6 describes a powerful -Rust branching construct called `match` for these cases. - -#### Using `if` in a `let` Statement - -Because `if` is an expression, we can use it on the right side of a `let` -statement, as in Listing 3-2: - -Filename: src/main.rs - -``` -fn main() { - let condition = true; - let number = if condition { - 5 - } else { - 6 - }; - - println!("The value of number is: {}", number); -} -``` - -Listing 3-2: Assigning the result of an `if` expression to a variable - -The `number` variable will be bound to a value based on the outcome of the `if` -expression. Run this code to see what happens: - -``` -$ cargo run - Compiling branches v0.1.0 (file:///projects/branches) - Finished dev [unoptimized + debuginfo] target(s) in 0.30 secs - Running `target/debug/branches` -The value of number is: 5 -``` - -Remember that blocks of code evaluate to the last expression in them, and -numbers by themselves are also expressions. In this case, the value of the -whole `if` expression depends on which block of code executes. This means the -values that have the potential to be results from each arm of the `if` must be -the same type; in Listing 3-2, the results of both the `if` arm and the `else` -arm were `i32` integers. If the types are mismatched, as in the following -example, we’ll get an error: - -Filename: src/main.rs - -``` -fn main() { - let condition = true; - - let number = if condition { - 5 - } else { - "six" - }; - - println!("The value of number is: {}", number); -} -``` - -When we try to run this code, we’ll get an error. The `if` and `else` arms have -value types that are incompatible, and Rust indicates exactly where to find the -problem in the program: - -``` -error[E0308]: if and else have incompatible types - --> src/main.rs:4:18 - | -4 | let number = if condition { - | __________________^ -5 | | 5 -6 | | } else { -7 | | "six" -8 | | }; - | |_____^ expected integral variable, found &str - | - = note: expected type `{integer}` - found type `&str` -``` - -The expression in the `if` block evaluates to an integer, and the expression in -the `else` block evaluates to a string. This won’t work because variables must -have a single type. Rust needs to know at compile time what type the `number` -variable is, definitively, so it can verify at compile time that its type is -valid everywhere we use `number`. Rust wouldn’t be able to do that if the type -of `number` was only determined at runtime; the compiler would be more complex -and would make fewer guarantees about the code if it had to keep track of -multiple hypothetical types for any variable. - -### Repetition with Loops - -It’s often useful to execute a block of code more than once. For this task, -Rust provides several *loops*. A loop runs through the code inside the loop -body to the end and then starts immediately back at the beginning. To -experiment with loops, let’s make a new project called *loops*. - -Rust has three kinds of loops: `loop`, `while`, and `for`. Let’s try each one. - -#### Repeating Code with `loop` - -The `loop` keyword tells Rust to execute a block of code over and over again -forever or until you explicitly tell it to stop. - -As an example, change the *src/main.rs* file in your *loops* directory to look -like this: - -Filename: src/main.rs - -``` -fn main() { - loop { - println!("again!"); - } -} -``` - -When we run this program, we’ll see `again!` printed over and over continuously -until we stop the program manually. Most terminals support a keyboard shortcut, -ctrl-c, to halt a program that is stuck in a -continual loop. Give it a try: - -``` -$ cargo run - Compiling loops v0.1.0 (file:///projects/loops) - Finished dev [unoptimized + debuginfo] target(s) in 0.29 secs - Running `target/debug/loops` -again! -again! -again! -again! -^Cagain! -``` - -The symbol `^C` represents where you pressed ctrl-c -. You may or may not see the word `again!` printed after the `^C`, -depending on where the code was in the loop when it received the halt signal. - -Fortunately, Rust provides another, more reliable way to break out of a loop. -You can place the `break` keyword within the loop to tell the program when to -stop executing the loop. Recall that we did this in the guessing game in the -“Quitting After a Correct Guess” section of Chapter 2 to exit the -program when the user won the game by guessing the correct number. - -#### Conditional Loops with `while` - -It’s often useful for a program to evaluate a condition within a loop. While -the condition is true, the loop runs. When the condition ceases to be true, the -program calls `break`, stopping the loop. This loop type could be implemented -using a combination of `loop`, `if`, `else`, and `break`; you could try that -now in a program, if you’d like. - -However, this pattern is so common that Rust has a built-in language construct -for it, called a `while` loop. Listing 3-3 uses `while`: the program loops -three times, counting down each time, and then, after the loop, it prints -another message and exits. - -Filename: src/main.rs - -``` -fn main() { - let mut number = 3; - - while number != 0 { - println!("{}!", number); - - number = number - 1; - } - - println!("LIFTOFF!!!"); -} -``` - -Listing 3-3: Using a `while` loop to run code while a condition holds true - -This construct eliminates a lot of nesting that would be necessary if you used -`loop`, `if`, `else`, and `break`, and it’s clearer. While a condition holds -true, the code runs; otherwise, it exits the loop. - -#### Looping Through a Collection with `for` - -You could use the `while` construct to loop over the elements of a collection, -such as an array. For example, let’s look at Listing 3-4: - -Filename: 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 = index + 1; - } -} -``` - -Listing 3-4: Looping through each element of a collection using a `while` loop - -Here, the code counts up through the elements in the array. It starts at index -`0`, and then loops until it reaches the final index in the array (that is, -when `index < 5` is no longer true). Running this code will print every element -in the array: - -``` -$ cargo run - Compiling loops v0.1.0 (file:///projects/loops) - Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs - Running `target/debug/loops` -the value is: 10 -the value is: 20 -the value is: 30 -the value is: 40 -the value is: 50 -``` - -All five array values appear in the terminal, as expected. Even though `index` -will reach a value of `5` at some point, the loop stops executing before trying -to fetch a sixth value from the array. - -But this approach is error prone; we could cause the program to panic if the -index length is incorrect. It’s also slow, because the compiler adds runtime -code to perform the conditional check on every element on every iteration -through the loop. - -As a more concise alternative, you can use a `for` loop and execute some code -for each item in a collection. A `for` loop looks like this code in Listing 3-5: - -Filename: src/main.rs - -``` -fn main() { - let a = [10, 20, 30, 40, 50]; - - for element in a.iter() { - println!("the value is: {}", element); - } -} -``` - -Listing 3-5: Looping through each element of a collection using a `for` loop - -When we run this code, we’ll see the same output as in Listing 3-4. More -importantly, we’ve now increased the safety of the code and eliminated the -chance of bugs that might result from going beyond the end of the array or not -going far enough and missing some items. - -For example, in the code in Listing 3-4, if you removed an item from the `a` -array but forgot to update the condition to `while index < 4`, the code would -panic. Using the `for` loop, you wouldn’t need to remember to change any other -code if you changed the number of values in the array. - -The safety and conciseness of `for` loops make them the most commonly used loop -construct in Rust. Even in situations in which you want to run some code a -certain number of times, as in the countdown example that used a `while` loop -in Listing 3-3, most Rustaceans would use a `for` loop. The way to do that -would be to use a `Range`, which is a type provided by the standard library -that generates all numbers in sequence starting from one number and ending -before another number. - -Here’s what the countdown would look like using a `for` loop and another method -we’ve not yet talked about, `rev`, to reverse the range: - -Filename: src/main.rs - -``` -fn main() { - for number in (1..4).rev() { - println!("{}!", number); - } - println!("LIFTOFF!!!"); -} -``` - -This code is a bit nicer, isn’t it? - -## Summary - -You made it! That was a sizable chapter: you learned about variables, scalar -and compound data types, functions, comments, `if` expressions, and loops! If -you want to practice with the concepts discussed in this chapter, try building -programs to do the following: - -* Convert temperatures between Fahrenheit and Celsius. -* Generate the nth Fibonacci number. -* Print the lyrics to the Christmas carol “The Twelve Days of Christmas,” -taking advantage of the repetition in the song. - -When you’re ready to move on, we’ll talk about a concept in Rust that *doesn’t* -commonly exist in other programming languages: ownership. diff --git a/second-edition/nostarch/chapter04.md b/second-edition/nostarch/chapter04.md deleted file mode 100644 index e5cccae7a0..0000000000 --- a/second-edition/nostarch/chapter04.md +++ /dev/null @@ -1,1244 +0,0 @@ - -[TOC] - -# Understanding Ownership - -Ownership is Rust’s most unique feature, and it enables Rust to make memory -safety guarantees without needing a garbage collector. Therefore, it’s -important to understand how ownership works in Rust. In this chapter, we’ll -talk about ownership as well as several related features: borrowing, slices, -and how Rust lays data out in memory. - -## What Is Ownership? - -Rust’s central feature is *ownership*. Although the feature is straightforward -to explain, it has deep implications for the rest of the language. - -All programs have to manage the way they use a computer’s memory while running. -Some languages have garbage collection that constantly looks for no longer used -memory as the program runs; in other languages, the programmer must explicitly -allocate and free the memory. Rust uses a third approach: memory is managed -through a system of ownership with a set of rules that the compiler checks at -compile time. None of the ownership features slow down your program while it's -running. - -Because ownership is a new concept for many programmers, it does take some time -to get used to. The good news is that the more experienced you become with Rust -and the rules of the ownership system, the more you’ll be able to naturally -develop code that is safe and efficient. Keep at it! - -When you understand ownership, you’ll have a solid foundation for understanding -the features that make Rust unique. In this chapter, you’ll learn ownership by -working through some examples that focus on a very common data structure: -strings. - - - -### The Stack and the Heap - -In many programming languages, you don’t have to think about the stack and -the heap very often. But in a systems programming language like Rust, whether -a value is on the stack or the heap has more of an effect on how the language -behaves and why you have to make certain decisions. Parts of ownership will -be described in relation to the stack and the heap later in this chapter, so -here is a brief explanation in preparation. - -Both the stack and the heap are parts of memory that is available to your code -to use at runtime, but they are structured in different ways. The stack stores -values in the order it gets them and removes the values in the opposite order. -This is referred to as *last in, first out*. Think of a stack of plates: when -you add more plates, you put them on top of the pile, and when you need a -plate, you take one off the top. Adding or removing plates from the middle or -bottom wouldn’t work as well! Adding data is called *pushing onto the stack*, -and removing data is called *popping off the stack*. - -The stack is fast because of the way it accesses the data: it never has to -search for a place to put new data or a place to get data from because that -place is always the top. Another property that makes the stack fast is that -all data on the stack must take up a known, fixed size. - -Data with a size unknown at compile time or a size that might change can be -stored on the heap instead. The heap is less organized: when you put data on -the heap, you ask for some amount of space. The operating system finds an -empty spot somewhere in the heap that is big enough, marks it as being in -use, and returns a *pointer*, which is the address of that location. This -process is called *allocating on the heap*, sometimes abbreviated as just -“allocating.” Pushing values onto the stack is not considered allocating. -Because the pointer is a known, fixed size, you can store the pointer on the -stack, but when you want the actual data, you have to follow the pointer. - -Think of being seated at a restaurant. When you enter, you state the number of -people in your group, and the staff finds an empty table that fits everyone -and leads you there. If someone in your group comes late, they can ask where -you’ve been seated to find you. - -Accessing data in the heap is slower than accessing data on the stack because -you have to follow a pointer to get there. Contemporary processors are faster -if they jump around less in memory. Continuing the analogy, consider a server -at a restaurant taking orders from many tables. It’s most efficient to get -all the orders at one table before moving on to the next table. Taking an -order from table A, then an order from table B, then one from A again, and -then one from B again would be a much slower process. By the same token, a -processor can do its job better if it works on data that’s close to other -data (as it is on the stack) rather than farther away (as it can be on the -heap). Allocating a large amount of space on the heap can also take time. - -When your code calls a function, the values passed into the function -(including, potentially, pointers to data on the heap) and the function’s -local variables get pushed onto the stack. When the function is over, those -values get popped off the stack. - -Keeping track of what parts of code are using what data on the heap, -minimizing the amount of duplicate data on the heap, and cleaning up unused -data on the heap so you don’t run out of space are all problems that ownership -addresses. Once you understand ownership, you won’t need to think about the -stack and the heap very often, but knowing that managing heap data is why -ownership exists can help explain why it works the way it does. - - - -### Ownership Rules - -First, let’s take a look at the ownership rules. Keep these rules in mind as we -work through the examples that illustrate them: - -> 1. Each value in Rust has a variable that’s called its *owner*. -> 2. There can only be one owner at a time. -> 3. When the owner goes out of scope, the value will be dropped. - -### Variable Scope - -We’ve walked through an example of a Rust program already in Chapter 2. Now -that we’re past basic syntax, we won’t include all the `fn main() {` code in -examples, so if you’re following along, you’ll have to put the following -examples inside a `main` function manually. As a result, our examples will be a -bit more concise, letting us focus on the actual details rather than -boilerplate code. - -As a first example of ownership, we’ll look at the *scope* of some variables. A -scope is the range within a program for which an item is valid. Let’s say we -have a variable that looks like this: - -``` -let s = "hello"; -``` - -The variable `s` refers to a string literal, where the value of the string is -hardcoded into the text of our program. The variable is valid from the point at -which it’s declared until the end of the current *scope*. Listing 4-1 has -comments annotating where the variable `s` is valid: - -``` -{ // s is not valid here, 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 -``` - -Listing 4-1: A variable and the scope in which it is valid - -In other words, there are two important points in time here: - -* When `s` comes *into scope*, it is valid. -* It remains valid until it goes *out of scope*. - -At this point, the relationship between scopes and when variables are valid is -similar to that in other programming languages. Now we’ll build on top of this -understanding by introducing the `String` type. - -### The `String` Type - -To illustrate the rules of ownership, we need a data type that is more complex -than the ones we covered in the “Data Types” section of Chapter 3. The types -covered previously are all stored on the stack and popped off the stack when -their scope is over, but we want to look at data that is stored on the heap and -explore how Rust knows when to clean up that data. - -We’ll use `String` as the example here and concentrate on the parts of `String` -that relate to ownership. These aspects also apply to other complex data types -provided by the standard library and that you create. We’ll discuss `String` in -more depth in Chapter 8. - -We’ve already seen string literals, where a string value is hardcoded into our -program. String literals are convenient, but they aren’t suitable for every -situation in which we may want to use text. One reason is that they’re -immutable. Another is that not every string value can be known when we write -our code: for example, what if we want to take user input and store it? For -these situations, Rust has a second string type, `String`. This type is -allocated on the heap and as such is able to store an amount of text that is -unknown to us at compile time. You can create a `String` from a string literal -using the `from` function, like so: - -``` -let s = String::from("hello"); -``` - -The double colon (`::`) is an operator that allows us to namespace this -particular `from` function under the `String` type rather than using some sort -of name like `string_from`. We’ll discuss this syntax more in the “Method -Syntax” section of Chapter 5 and when we talk about namespacing with modules in -“Module Definitions” in Chapter 7. - -This kind of string *can* be mutated: - -``` -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!` -``` - -So, what’s the difference here? Why can `String` be mutated but literals -cannot? The difference is how these two types deal with memory. - -### Memory and Allocation - -In the case of a string literal, we know the contents at compile time, so the -text is hardcoded directly into the final executable. This is why string -literals are fast and efficient. But these properties only come from the string -literal’s immutability. Unfortunately, we can’t put a blob of memory into the -binary for each piece of text whose size is unknown at compile time and whose -size might change while running the program. - -With the `String` type, in order to support a mutable, growable piece of text, -we need to allocate an amount of memory on the heap, unknown at compile time, -to hold the contents. This means: - -* The memory must be requested from the operating system at runtime. -* We need a way of returning this memory to the operating system when we’re - done with our `String`. - -That first part is done by us: when we call `String::from`, its implementation -requests the memory it needs. This is pretty much universal in programming -languages. - -However, the second part is different. In languages with a *garbage collector -(GC)*, the GC keeps track and cleans up memory that isn’t being used anymore, -and we don’t need to think about it. Without a GC, it’s our responsibility to -identify when memory is no longer being used and call code to explicitly return -it, just as we did to request it. Doing this correctly has historically been a -difficult programming problem. If we forget, we’ll waste memory. If we do it -too early, we’ll have an invalid variable. If we do it twice, that’s a bug too. -We need to pair exactly one `allocate` with exactly one `free`. - -Rust takes a different path: the memory is automatically returned once the -variable that owns it goes out of scope. Here’s a version of our scope example -from Listing 4-1 using a `String` instead of a string literal: - -``` -{ - 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 -``` - -There is a natural point at which we can return the memory our `String` needs -to the operating system: when `s` goes out of scope. When a variable goes out -of scope, Rust calls a special function for us. This function is called `drop`, -and it’s where the author of `String` can put the code to return the memory. -Rust calls `drop` automatically at the closing `}`. - -> Note: In C++, this pattern of deallocating resources at the end of an item’s -> lifetime is sometimes called *Resource Acquisition Is Initialization (RAII)*. -> The `drop` function in Rust will be familiar to you if you’ve used RAII -> patterns. - -This pattern has a profound impact on the way Rust code is written. It may seem -simple right now, but the behavior of code can be unexpected in more -complicated situations when we want to have multiple variables use the data -we’ve allocated on the heap. Let’s explore some of those situations now. - -#### Ways Variables and Data Interact: Move - -Multiple variables can interact with the same data in different ways in Rust. -Let’s look at an example using an integer in Listing 4-2: - -``` -let x = 5; -let y = x; -``` - -Listing 4-2: Assigning the integer value of variable `x` to `y` - -We can probably guess what this is doing: “bind the value `5` to `x`; then make -a copy of the value in `x` and bind it to `y`.” We now have two variables, `x` -and `y`, and both equal `5`. This is indeed what is happening, because integers -are simple values with a known, fixed size, and these two `5` values are pushed -onto the stack. - -Now let’s look at the `String` version: - -``` -let s1 = String::from("hello"); -let s2 = s1; -``` - -This looks very similar to the previous code, so we might assume that the way -it works would be the same: that is, the second line would make a copy of the -value in `s1` and bind it to `s2`. But this isn’t quite what happens. - -Take a look at Figure 4-1 to see what is happening to `String` under the -covers. A `String` is made up of three parts, shown on the left: a pointer to -the memory that holds the contents of the string, a length, and a capacity. -This group of data is stored on the stack. On the right is the memory on the -heap that holds the contents. - -String in memory - -Figure 4-1: Representation in memory of a `String` holding the value `"hello"` -bound to `s1` - -The length is how much memory, in bytes, the contents of the `String` is -currently using. The capacity is the total amount of memory, in bytes, that the -`String` has received from the operating system. The difference between length -and capacity matters, but not in this context, so for now, it’s fine to ignore -the capacity. - -When we assign `s1` to `s2`, the `String` data is copied, meaning we copy the -pointer, the length, and the capacity that are on the stack. We do not copy the -data on the heap that the pointer refers to. In other words, the data -representation in memory looks like Figure 4-2. - -s1 and s2 pointing to the same value - -Figure 4-2: Representation in memory of the variable `s2` that has a copy of -the pointer, length, and capacity of `s1` - -The representation does *not* look like Figure 4-3, which is what memory would -look like if Rust instead copied the heap data as well. If Rust did this, the -operation `s2 = s1` could be very expensive in terms of runtime performance if -the data on the heap were large. - -s1 and s2 to two places - -Figure 4-3: Another possibility for what `s2 = s1` might do if Rust copied the -heap data as well - -Earlier, we said that when a variable goes out of scope, Rust automatically -calls the `drop` function and cleans up the heap memory for that variable. But -Figure 4-2 shows both data pointers pointing to the same location. This is a -problem: when `s2` and `s1` go out of scope, they will both try to free the -same memory. This is known as a *double free* error and is one of the memory -safety bugs we mentioned previously. Freeing memory twice can lead to memory -corruption, which can potentially lead to security vulnerabilities. - -To ensure memory safety, there’s one more detail to what happens in this -situation in Rust. Instead of trying to copy the allocated memory, Rust -considers `s1` to no longer be valid and, therefore, Rust doesn’t need to free -anything when `s1` goes out of scope. Check out what happens when you try to -use `s1` after `s2` is created; it won’t work: - -``` -let s1 = String::from("hello"); -let s2 = s1; - -println!("{}, world!", s1); -``` - -You’ll get an error like this because Rust prevents you from using the -invalidated reference: - -``` -error[E0382]: use of moved value: `s1` - --> src/main.rs:5:28 - | -3 | let s2 = s1; - | -- value moved here -4 | -5 | println!("{}, world!", s1); - | ^^ value used here after move - | - = note: move occurs because `s1` has type `std::string::String`, which does - not implement the `Copy` trait -``` - -If you’ve heard the terms *shallow copy* and *deep copy* while working with -other languages, the concept of copying the pointer, length, and capacity -without copying the data probably sounds like making a shallow copy. But -because Rust also invalidates the first variable, instead of being called a -shallow copy, it’s known as a *move*. Here we would read this by saying that -`s1` was *moved* into `s2`. So what actually happens is shown in Figure 4-4. - -s1 moved to s2 - -Figure 4-4: Representation in memory after `s1` has been invalidated - -That solves our problem! With only `s2` valid, when it goes out of scope, it -alone will free the memory, and we’re done. - -In addition, there’s a design choice that’s implied by this: Rust will never -automatically create “deep” copies of your data. Therefore, any *automatic* -copying can be assumed to be inexpensive in terms of runtime performance. - -#### Ways Variables and Data Interact: Clone - -If we *do* want to deeply copy the heap data of the `String`, not just the -stack data, we can use a common method called `clone`. We’ll discuss method -syntax in Chapter 5, but because methods are a common feature in many -programming languages, you’ve probably seen them before. - -Here’s an example of the `clone` method in action: - -``` -let s1 = String::from("hello"); -let s2 = s1.clone(); - -println!("s1 = {}, s2 = {}", s1, s2); -``` - -This works just fine and explicitly produces the behavior shown in Figure 4-3, -where the heap data *does* get copied. - -When you see a call to `clone`, you know that some arbitrary code is being -executed and that code may be expensive. It’s a visual indicator that something -different is going on. - -#### Stack-Only Data: Copy - -There’s another wrinkle we haven’t talked about yet. This code using integers, -part of which was shown earlier in Listing 4-2, works and is valid: - -``` -let x = 5; -let y = x; - -println!("x = {}, y = {}", x, y); -``` - -But this code seems to contradict what we just learned: we don’t have a call to -`clone`, but `x` is still valid and wasn’t moved into `y`. - -The reason is that types such as integers that have a known size at compile -time are stored entirely on the stack, so copies of the actual values are quick -to make. That means there’s no reason we would want to prevent `x` from being -valid after we create the variable `y`. In other words, there’s no difference -between deep and shallow copying here, so calling `clone` wouldn’t do anything -different from the usual shallow copying and we can leave it out. - -Rust has a special annotation called the `Copy` trait that we can place on -types like integers that are stored on the stack (we’ll talk more about traits -in Chapter 10). If a type has the `Copy` trait, an older variable is still -usable after assignment. Rust won’t let us annotate a type with the `Copy` -trait if the type, or any of its parts, has implemented the `Drop` trait. If -the type needs something special to happen when the value goes out of scope and -we add the `Copy` annotation to that type, we’ll get a compile time error. To -learn about how to add the `Copy` annotation to your type, see “Derivable -Traits” in Appendix C. - -So what types are `Copy`? You can check the documentation for the given type to -be sure, but as a general rule, any group of simple scalar values can be -`Copy`, and nothing that requires allocation or is some form of resource is -`Copy`. Here are some of the types that are `Copy`: - -* All the integer types, such as `u32`. -* The Boolean type, `bool`, with values `true` and `false`. -* All the floating point types, such as `f64`. -* The character type, `char`. -* Tuples, but only if they contain types that are also `Copy`. For example, - `(i32, i32)` is `Copy`, but `(i32, String)` is not. - -### Ownership and Functions - -The semantics for passing a value to a function are similar to those for -assigning a value to a variable. Passing a variable to a function will move or -copy, just as assignment does. Listing 4-3 has an example with some annotations -showing where variables go into and out of scope: - -Filename: 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); // x would move into the function, - // but i32 is Copy, so it’s okay to still - // use x afterward - -} // Here, x goes out of scope, then s. But 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. -``` - -Listing 4-3: Functions with ownership and scope annotated - -If we tried to use `s` after the call to `takes_ownership`, Rust would throw a -compile time error. These static checks protect us from mistakes. Try adding -code to `main` that uses `s` and `x` to see where you can use them and where -the ownership rules prevent you from doing so. - -### Return Values and Scope - -Returning values can also transfer ownership. Listing 4-4 is an example with -similar annotations to those in Listing 4-3: - -Filename: 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 goes out of scope but 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("hello"); // some_string comes into scope - - some_string // some_string is returned and - // moves out to the calling - // function. -} - -// takes_and_gives_back will take a String and return one. -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 -} -``` - -Listing 4-4: Transferring ownership of return values - -The ownership of a variable follows the same pattern every time: assigning a -value to another variable moves it. When a variable that includes data on the -heap goes out of scope, the value will be cleaned up by `drop` unless the data -has been moved to be owned by another variable. - -Taking ownership and then returning ownership with every function is a bit -tedious. What if we want to let a function use a value but not take ownership? -It’s quite annoying that anything we pass in also needs to be passed back if we -want to use it again, in addition to any data resulting from the body of the -function that we might want to return as well. - -It’s possible to return multiple values using a tuple, as shown in Listing 4-5: - -Filename: src/main.rs - -``` -fn main() { - let s1 = String::from("hello"); - - let (s2, len) = calculate_length(s1); - - println!("The length of '{}' is {}.", s2, len); -} - -fn calculate_length(s: String) -> (String, usize) { - let length = s.len(); // len() returns the length of a String - - (s, length) -} -``` - -Listing 4-5: Returning ownership of parameters - -But this is too much ceremony and a lot of work for a concept that should be -common. Luckily for us, Rust has a feature for this concept, called -*references*. - -## References and Borrowing - -The issue with the tuple code in Listing 4-5 is that we have to return the -`String` to the calling function so we can still use the `String` after the -call to `calculate_length`, because the `String` was moved into -`calculate_length`. - -Here is how you would define and use a `calculate_length` function that has a -reference to an object as a parameter instead of taking ownership of the -value: - -Filename: src/main.rs - -``` -fn main() { - let s1 = String::from("hello"); - - let len = calculate_length(&s1); - - println!("The length of '{}' is {}.", s1, len); -} - -fn calculate_length(s: &String) -> usize { - s.len() -} -``` - -First, notice that all the tuple code in the variable declaration and the -function return value is gone. Second, note that we pass `&s1` into -`calculate_length` and, in its definition, we take `&String` rather than -`String`. - -These ampersands are *references*, and they allow you to refer to some value -without taking ownership of it. Figure 4-5 shows a diagram. - -&String s pointing at String s1 - -Figure 4-5: A diagram of `&String s` pointing at `String s1` - -> Note: The opposite of referencing by using `&` is *dereferencing*, which is -> accomplished with the dereference operator, `*`. We’ll see some uses of the -> dereference operator in Chapter 8 and discuss details of dereferencing in -> Chapter 15. - -Let’s take a closer look at the function call here: - -``` -let s1 = String::from("hello"); - -let len = calculate_length(&s1); -``` - -The `&s1` syntax lets us create a reference that *refers* to the value of `s1` -but does not own it. Because it does not own it, the value it points to will -not be dropped when the reference goes out of scope. - -Likewise, the signature of the function uses `&` to indicate that the type of -the parameter `s` is a reference. Let’s add some explanatory annotations: - -``` -fn calculate_length(s: &String) -> usize { // s is a reference to a String - s.len() -} // Here, s goes out of scope. But because it does not have ownership of what - // it refers to, nothing happens. -``` - -The scope in which the variable `s` is valid is the same as any function -parameter’s scope, but we don’t drop what the reference points to when it goes -out of scope because we don’t have ownership. When functions have references as -parameters instead of the actual values, we won’t need to return the values in -order to give back ownership, because we never had ownership. - -We call having references as function parameters *borrowing*. As in real life, -if a person owns something, you can borrow it from them. When you’re done, you -have to give it back. - -So what happens if we try to modify something we’re borrowing? Try the code in -Listing 4-6. Spoiler alert: it doesn’t work! - -Filename: src/main.rs - -``` -fn main() { - let s = String::from("hello"); - - change(&s); -} - -fn change(some_string: &String) { - some_string.push_str(", world"); -} -``` - -Listing 4-6: Attempting to modify a borrowed value - -Here’s the error: - -``` -error[E0596]: cannot borrow immutable borrowed content `*some_string` as mutable - --> error.rs:8:5 - | -7 | fn change(some_string: &String) { - | ------- use `&mut String` here to make mutable -8 | some_string.push_str(", world"); - | ^^^^^^^^^^^ cannot borrow as mutable -``` - -Just as variables are immutable by default, so are references. We’re not -allowed to modify something we have a reference to. - -### Mutable References - -We can fix the error in the code from Listing 4-6 with just a small tweak: - -Filename: 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"); -} -``` - -First, we had to change `s` to be `mut`. Then we had to create a mutable -reference with `&mut s` and accept a mutable reference with `some_string: &mut -String`. - -But mutable references have one big restriction: you can only have one mutable -reference to a particular piece of data in a particular scope. This code will -fail: - -Filename: src/main.rs - -``` -let mut s = String::from("hello"); - -let r1 = &mut s; -let r2 = &mut s; -``` - -Here’s the error: - -``` -error[E0499]: cannot borrow `s` as mutable more than once at a time - --> borrow_twice.rs:5:19 - | -4 | let r1 = &mut s; - | - first mutable borrow occurs here -5 | let r2 = &mut s; - | ^ second mutable borrow occurs here -6 | } - | - first borrow ends here -``` - -This restriction allows for mutation but in a very controlled fashion. It’s -something that new Rustaceans struggle with, because most languages let you -mutate whenever you’d like. - -The benefit of having this restriction is that Rust can prevent data races at -compile time. A *data race* is similar to a race condition and happens when -these three behaviors occur: - -* Two or more pointers access the same data at the same time. -* At least one of the pointers is being used to write to the data. -* There’s no mechanism being used to synchronize access to the data. - -Data races cause undefined behavior and can be difficult to diagnose and fix -when you’re trying to track them down at runtime; Rust prevents this problem -from happening because it won’t even compile code with data races! - -As always, we can use curly brackets to create a new scope, allowing for -multiple mutable references, just not *simultaneous* ones: - -``` -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; -``` - -A similar rule exists for combining mutable and immutable references. This code -results in an error: - -``` -let mut s = String::from("hello"); - -let r1 = &s; // no problem -let r2 = &s; // no problem -let r3 = &mut s; // BIG PROBLEM -``` - -Here’s the error: - -``` -error[E0502]: cannot borrow `s` as mutable because it is also borrowed as -immutable - --> borrow_thrice.rs:6:19 - | -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 | } - | - immutable borrow ends here -``` - -Whew! We *also* cannot have a mutable reference while we have an immutable one. -Users of an immutable reference don’t expect the values to suddenly change out -from under them! However, multiple immutable references are okay because no one -who is just reading the data has the ability to affect anyone else’s reading of -the data. - -Even though these errors may be frustrating at times, remember that it’s the -Rust compiler pointing out a potential bug early (at compile time rather than -at runtime) and showing you exactly where the problem is. Then you don’t have -to track down why your data isn’t what you thought it was. - -### Dangling References - -In languages with pointers, it’s easy to erroneously create a *dangling -pointer*, a pointer that references a location in memory that may have been -given to someone else, by freeing some memory while preserving a pointer to -that memory. In Rust, by contrast, the compiler guarantees that references will -never be dangling references: if you have a reference to some data, the -compiler will ensure that the data will not go out of scope before the -reference to the data does. - -Let’s try to create a dangling reference, which Rust will prevent with a -compile-time error: - -Filename: src/main.rs - -``` -fn main() { - let reference_to_nothing = dangle(); -} - -fn dangle() -> &String { - let s = String::from("hello"); - - &s -} -``` - -Here’s the error: - -``` -error[E0106]: missing lifetime specifier - --> dangle.rs:5:16 - | -5 | fn dangle() -> &String { - | ^ expected 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 giving it a 'static lifetime -``` - -This error message refers to a feature we haven’t covered yet: *lifetimes*. -We’ll discuss lifetimes in detail in Chapter 10. But, if you disregard the -parts about lifetimes, the message does contain the key to why this code is a -problem: - -``` -this function's return type contains a borrowed value, but there is no value -for it to be borrowed from. -``` - -Let’s take a closer look at exactly what’s happening at each stage of our -`dangle` code: - -``` -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. Its memory goes away. - // Danger! -``` - -Because `s` is created inside `dangle`, when the code of `dangle` is finished, -`s` will be deallocated. But we tried to return a reference to it. That means -this reference would be pointing to an invalid `String` That’s no good! Rust -won’t let us do this. - -The solution here is to return the `String` directly: - -``` -fn no_dangle() -> String { - let s = String::from("hello"); - - s -} -``` - -This works without any problems. Ownership is moved out, and nothing is -deallocated. - -### The Rules of References - -Let’s recap what we’ve discussed about references: - -* At any given time, you can have *either* (but not both of) one mutable - reference or any number of immutable references. -* References must always be valid. - -Next, we’ll look at a different kind of reference: slices. - -## The Slice Type - -Another data type that does not have ownership is the *slice*. Slices let you -reference a contiguous sequence of elements in a collection rather than the -whole collection. - -Here’s a small programming problem: write a function that takes a string and -returns the first word it finds in that string. If the function doesn’t find a -space in the string, the whole string must be one word, so the entire string -should be returned. - -Let’s think about the signature of this function: - -``` -fn first_word(s: &String) -> ? -``` - -This function, `first_word`, has a `&String` as a parameter. We don’t want -ownership, so this is fine. But what should we return? We don’t really have a -way to talk about *part* of a string. However, we could return the index of the -end of the word. Let’s try that, as shown in Listing 4-7: - -Filename: 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() -} -``` - -Listing 4-7: The `first_word` function that returns a byte index value into the -`String` parameter - -Because we need to go through the `String` element by element and check whether -a value is a space, we’ll convert our `String` to an array of bytes using the -`as_bytes` method: - -``` -let bytes = s.as_bytes(); -``` - -Next, we create an iterator over the array of bytes using the `iter` method: - -``` -for (i, &item) in bytes.iter().enumerate() { -``` - -We’ll discuss iterators in more detail in Chapter 13. For now, know that `iter` -is a method that returns each element in a collection and that `enumerate` -wraps the result of `iter` and returns each element as part of a tuple instead. -The first element of the tuple returned from `enumerate` is the index, and the -second element is a reference to the element. This is a bit more convenient -than calculating the index ourselves. - -Because the `enumerate` method returns a tuple, we can use patterns to -destructure that tuple, just like everywhere else in Rust. So in the `for` -loop, we specify a pattern that has `i` for the index in the tuple and `&item` -for the single byte in the tuple. Because we get a reference to the element -from `.iter().enumerate()`, we use `&` in the pattern. - -Inside the `for` loop, we search for the byte that represents the space by -using the byte literal syntax. If we find a space, we return the position. -Otherwise, we return the length of the string by using `s.len()`: - -``` - if item == b' ' { - return i; - } -} -s.len() -``` - -We now have a way to find out the index of the end of the first word in the -string, but there’s a problem. We’re returning a `usize` on its own, but it’s -only a meaningful number in the context of the `&String`. In other words, -because it’s a separate value from the `String`, there’s no guarantee that it -will still be valid in the future. Consider the program in Listing 4-8 that -uses the `first_word` function from Listing 4-7: - -Filename: src/main.rs - -``` -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 there's no more string that - // we could meaningfully use the value 5 with. word is now totally invalid! -} -``` - -Listing 4-8: Storing the result from calling the `first_word` function and then -changing the `String` contents - -This program compiles without any errors and would also do so if we used `word` -after calling `s.clear()`. Because `word` isn’t connected to the state of `s` -at all, `word` still contains the value `5`. We could use that value `5` with -the variable `s` to try to extract the first word out, but this would be a bug -because the contents of `s` have changed since we saved `5` in `word`. - -Having to worry about the index in `word` getting out of sync with the data in -`s` is tedious and error prone! Managing these indices is even more brittle if -we write a `second_word` function. Its signature would have to look like this: - -``` -fn second_word(s: &String) -> (usize, usize) { -``` - -Now we’re tracking a starting *and* an ending index, and we have even more -values that were calculated from data in a particular state but aren’t tied to -that state at all. We now have three unrelated variables floating around that -need to be kept in sync. - -Luckily, Rust has a solution to this problem: string slices. - -### String Slices - -A *string slice* is a reference to part of a `String`, and it looks like this: - -``` -let s = String::from("hello world"); - -let hello = &s[0..5]; -let world = &s[6..11]; -``` - -This is similar to taking a reference to the whole `String` but with the extra -`[0..5]` bit. Rather than a reference to the entire `String`, it’s a reference -to a portion of the `String`. The `start..end` syntax is a range that begins at -`start` and continues up to, but not including, `end`. - -We can create slices using a range within brackets by specifying -`[starting_index..ending_index]`, where `starting_index` is the first position -in the slice and `ending_index` is one more than the last position in the -slice. Internally, the slice data structure stores the starting position and -the length of the slice, which corresponds to `ending_index` minus -`starting_index`. So in the case of `let world = &s[6..11];`, `world` would be -a slice that contains a pointer to the 6th byte of `s` and a length value of 5. - -Figure 4-6 shows this in a diagram. - -world containing a pointer to the 6th byte of String s and a length 5 - -Figure 4-6: String slice referring to part of a `String` - -With Rust’s `..` range syntax, if you want to start at the first index (zero), -you can drop the value before the two periods. In other words, these are equal: - -``` -let s = String::from("hello"); - -let slice = &s[0..2]; -let slice = &s[..2]; -``` - -By the same token, if your slice includes the last byte of the `String`, you -can drop the trailing number. That means these are equal: - -``` -let s = String::from("hello"); - -let len = s.len(); - -let slice = &s[3..len]; -let slice = &s[3..]; -``` - -You can also drop both values to take a slice of the entire string. So these -are equal: - -``` -let s = String::from("hello"); - -let len = s.len(); - -let slice = &s[0..len]; -let slice = &s[..]; -``` - -> Note: String slice range indices must occur at valid UTF-8 character -> boundaries. If you attempt to create a string slice in the middle of a -> multibyte character, your program will exit with an error. For the purposes -> of introducing string slices, we are assuming ASCII only in this section; a -> more thorough discussion of UTF-8 handling is in the “Strings” section of -> Chapter 8. - -With all this information in mind, let’s rewrite `first_word` to return a -slice. The type that signifies “string slice” is written as `&str`: - -Filename: 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[..] -} -``` - -We get the index for the end of the word in the same way as we did in Listing -4-7, by looking for the first occurrence of a space. When we find a space, we -return a string slice using the start of the string and the index of the space -as the starting and ending indices. - -Now when we call `first_word`, we get back a single value that is tied to the -underlying data. The value is made up of a reference to the starting point of -the slice and the number of elements in the slice. - -Returning a slice would also work for a `second_word` function: - -``` -fn second_word(s: &String) -> &str { -``` - -We now have a straightforward API that’s much harder to mess up, because the -compiler will ensure the references into the `String` remain valid. Remember -the bug in the program in Listing 4-8, when we got the index to the end of the -first word but then cleared the string so our index was invalid? That code was -logically incorrect but didn’t show any immediate errors. The problems would -show up later if we kept trying to use the first word index with an emptied -string. Slices make this bug impossible and let us know we have a problem with -our code much sooner. Using the slice version of `first_word` will throw a -compile time error: - -Filename: src/main.rs - -``` -fn main() { - let mut s = String::from("hello world"); - - let word = first_word(&s); - - s.clear(); // Error! -} -``` - -Here’s the compiler error: - -``` -error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable - --> src/main.rs:6:5 - | -4 | let word = first_word(&s); - | - immutable borrow occurs here -5 | -6 | s.clear(); // Error! - | ^ mutable borrow occurs here -7 | } - | - immutable borrow ends here -``` - -Recall from the borrowing rules that if we have an immutable reference to -something, we cannot also take a mutable reference. Because `clear` needs to -truncate the `String`, it tries to take a mutable reference, which fails. Not -only has Rust made our API easier to use, but it has also eliminated an entire -class of errors at compile time! - -#### String Literals Are Slices - -Recall that we talked about string literals being stored inside the binary. Now -that we know about slices, we can properly understand string literals: - -``` -let s = "Hello, world!"; -``` - -The type of `s` here is `&str`: it’s a slice pointing to that specific point of -the binary. This is also why string literals are immutable; `&str` is an -immutable reference. - -#### String Slices as Parameters - -Knowing that you can take slices of literals and `String`s leads us to one more -improvement on `first_word`, and that’s its signature: - -``` -fn first_word(s: &String) -> &str { -``` - -A more experienced Rustacean would write the following line instead because it -allows us to use the same function on both `String`s and `&str`s: - -``` -fn first_word(s: &str) -> &str { -``` - -If we have a string slice, we can pass that directly. If we have a `String`, we -can pass a slice of the entire `String`. Defining a function to take a string -slice instead of a reference to a `String` makes our API more general and useful -without losing any functionality: - -Filename: src/main.rs - -``` -fn main() { - let my_string = String::from("hello world"); - - // first_word works on slices of `String`s - let word = first_word(&my_string[..]); - - let my_string_literal = "hello world"; - - // first_word works on slices of string literals - 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); -} -``` - -### Other Slices - -String slices, as you might imagine, are specific to strings. But there’s a -more general slice type, too. Consider this array: - -``` -let a = [1, 2, 3, 4, 5]; -``` - -Just as we might want to refer to a part of a string, we might want to refer -to part of an array. We’d do so like this: - -``` -let a = [1, 2, 3, 4, 5]; - -let slice = &a[1..3]; -``` - -This slice has the type `&[i32]`. It works the same way as string slices do, by -storing a reference to the first element and a length. You’ll use this kind of -slice for all sorts of other collections. We’ll discuss these collections in -detail when we talk about vectors in Chapter 8. - -## Summary - -The concepts of ownership, borrowing, and slices ensure memory safety in Rust -programs at compile time. The Rust language gives you control over your memory -usage in the same way as other systems programming languages, but having the -owner of data automatically clean up that data when the owner goes out of scope -means you don’t have to write and debug extra code to get this control. - -Ownership affects how lots of other parts of Rust work, so we’ll talk about -these concepts further throughout the rest of the book. Let’s move on to -Chapter 5 and look at grouping pieces of data together in a `struct`. diff --git a/second-edition/nostarch/chapter05.md b/second-edition/nostarch/chapter05.md deleted file mode 100644 index c171681355..0000000000 --- a/second-edition/nostarch/chapter05.md +++ /dev/null @@ -1,859 +0,0 @@ - -[TOC] - -# Using Structs to Structure Related Data - -A *struct*, or *structure*, is a custom data type that lets you name and -package together multiple related values that make up a meaningful group. If -you’re familiar with an object-oriented language, a *struct* is like an -object’s data attributes. In this chapter, we’ll compare and contrast tuples -with structs, demonstrate how to use structs, and discuss how to define methods -and associated functions to specify behavior associated with a struct’s data. -Structs and enums (discussed in Chapter 6) are the building blocks for creating -new types in your program’s domain to take full advantage of Rust’s compile -time type checking. - -## Defining and Instantiating Structs - -Structs are similar to tuples, which were discussed in Chapter 3. Like tuples, -the pieces of a struct can be different types. Unlike with tuples, you’ll name -each piece of data so it’s clear what the values mean. As a result of these -names, structs are more flexible than tuples: you don’t have to rely on the -order of the data to specify or access the values of an instance. - -To define a struct, we enter the keyword `struct` and name the entire struct. A -struct’s name should describe the significance of the pieces of data being -grouped together. Then, inside curly brackets, we define the names and types of -the pieces of data, which we call *fields*. For example, Listing 5-1 shows a -struct that stores information about a user account: - -``` -struct User { - username: String, - email: String, - sign_in_count: u64, - active: bool, -} -``` - -Listing 5-1: A `User` struct definition - -To use a struct after we’ve defined it, we create an *instance* of that struct -by specifying concrete values for each of the fields. We create an instance by -stating the name of the struct and then add curly brackets containing `key: -value` pairs, where the keys are the names of the fields and the values are the -data we want to store in those fields. We don’t have to specify the fields in -the same order in which we declared them in the struct. In other words, the -struct definition is like a general template for the type, and instances fill -in that template with particular data to create values of the type. For -example, we can declare a particular user as shown in Listing 5-2: - -``` -# struct User { -# username: String, -# email: String, -# sign_in_count: u64, -# active: bool, -# } -# -let user1 = User { - email: String::from("someone@example.com"), - username: String::from("someusername123"), - active: true, - sign_in_count: 1, -}; -``` - -Listing 5-2: Creating an instance of the `User` struct - -To get a specific value from a struct, we can use dot notation. If we wanted -just this user’s email address, we could use `user1.email` wherever we wanted -to use this value. If the instance is mutable, we can change a value by using -the dot notation and assigning into a particular field. Listing 5-3 shows how -to change the value in the `email` field of a mutable `User` instance: - -``` -# struct User { -# username: String, -# email: String, -# sign_in_count: u64, -# active: bool, -# } -# -let mut user1 = User { - email: String::from("someone@example.com"), - username: String::from("someusername123"), - active: true, - sign_in_count: 1, -}; - -user1.email = String::from("anotheremail@example.com"); -``` - -Listing 5-3: Changing the value in the `email` field of a `User` instance - -Note that the entire instance must be mutable; Rust doesn’t allow us to mark -only certain fields as mutable. - -As with any expression, we can construct a new instance of the struct as the -last expression in the function body to implicitly return that new instance. -Listing 5-4 shows a `build_user` function that returns a `User` instance with -the given email and username. The `active` field gets the value of `true`, and -the `sign_in_count` gets a value of `1`. - -``` -# struct User { -# username: String, -# email: String, -# sign_in_count: u64, -# active: bool, -# } -# -fn build_user(email: String, username: String) -> User { - User { - email: email, - username: username, - active: true, - sign_in_count: 1, - } -} -``` - -Listing 5-4: A `build_user` function that takes an email and username and -returns a `User` instance - -It makes sense to name the function parameters with the same name as the struct -fields, but having to repeat the `email` and `username` field names and -variables is a bit tedious. If the struct had more fields, repeating each name -would get even more annoying. Luckily, there’s a convenient shorthand! - -### Using the Field Init Shorthand when Variables and Fields Have the Same Name - -Because the parameter names and the struct field names are exactly the same in -Listing 5-4, we can use the *field init shorthand* syntax to rewrite -`build_user` so that it behaves exactly the same but doesn’t have the -repetition of `email` and `username` as shown in Listing 5-5. - -``` -# struct User { -# username: String, -# email: String, -# sign_in_count: u64, -# active: bool, -# } -# -fn build_user(email: String, username: String) -> User { - User { - email, - username, - active: true, - sign_in_count: 1, - } -} -``` - -Listing 5-5: A `build_user` function that uses field init shorthand because the -`email` and `username` parameters have the same name as struct fields - -Here, we’re creating a new instance of the `User` struct, which has a field -named `email`. We want to set the `email` field’s value to the value in the -`email` parameter of the `build_user` function. Because the `email` field and -the `email` parameter have the same name, we only need to write `email` rather -than `email: email`. - -### Creating Instances From Other Instances With Struct Update Syntax - -It’s often useful to create a new instance of a struct that uses most of an old -instance’s values but changes some. You’ll do this using *struct update syntax*. - -First, Listing 5-6 shows how we create a new `User` instance in `user2` without -the update syntax. We set new values for `email` and `username` but otherwise -use the same values from `user1` that we created in Listing 5-2: - -``` -# struct User { -# username: String, -# email: String, -# sign_in_count: u64, -# active: bool, -# } -# -# let user1 = User { -# email: String::from("someone@example.com"), -# username: String::from("someusername123"), -# active: true, -# sign_in_count: 1, -# }; -# -let user2 = User { - email: String::from("another@example.com"), - username: String::from("anotherusername567"), - active: user1.active, - sign_in_count: user1.sign_in_count, -}; -``` - -Listing 5-6: Creating a new `User` instance using some of the values from -`user1` - -Using struct update syntax, we can achieve the same effect with less code, as -shown in Listing 5-7. The syntax `..` specifies that the remaining fields not -explicitly set should have the same value as the fields in the given instance. - -``` -# struct User { -# username: String, -# email: String, -# sign_in_count: u64, -# active: bool, -# } -# -# let user1 = User { -# email: String::from("someone@example.com"), -# username: String::from("someusername123"), -# active: true, -# sign_in_count: 1, -# }; -# -let user2 = User { - email: String::from("another@example.com"), - username: String::from("anotherusername567"), - ..user1 -}; -``` - -Listing 5-7: Using struct update syntax to set new `email` and `username` -values for a `User` instance but use the rest of the values from the fields of -the instance in the `user1` variable - -The code in Listing 5-7 also creates an instance in `user2` that has a -different value for `email` and `username` but has the same values for the -`active` and `sign_in_count` fields from `user1`. - -### Tuple Structs without Named Fields to Create Different Types - -You can also define structs that look similar to tuples, called *tuple -structs*. Tuple structs have the added meaning the struct name provides but -don’t have names associated with their fields; rather, they just have the types -of the fields. Tuple structs are useful when you want to give the whole tuple a -name and make the tuple be a different type than other tuples, and naming each -field as in a regular struct would be verbose or redundant. - -To define a tuple struct start with the `struct` keyword and the struct name -followed by the types in the tuple. For example, here are definitions and -usages of two tuple structs named `Color` and `Point`: - -``` -struct Color(i32, i32, i32); -struct Point(i32, i32, i32); - -let black = Color(0, 0, 0); -let origin = Point(0, 0, 0); -``` - -Note that the `black` and `origin` values are different types, because they’re -instances of different tuple structs. Each struct you define is its own type, -even though the fields within the struct have the same types. For example, a -function that takes a parameter of type `Color` cannot take a `Point` as an -argument, even though both types are made up of three `i32` values. Otherwise, -tuple struct instances behave like tuples: you can destructure them into their -individual pieces, you can use a `.` followed by the index to access an -individual value, and so on. - -### Unit-Like Structs Without Any Fields - -You can also define structs that don’t have any fields! These are called -*unit-like structs* because they behave similarly to `()`, the unit type. -Unit-like structs can be useful in situations in which you need to implement a -trait on some type but don’t have any data that you want to store in the type -itself. We’ll discuss traits in Chapter 10. - -> ### Ownership of Struct Data -> -> In the `User` struct definition in Listing 5-1, we used the owned `String` -> type rather than the `&str` string slice type. This is a deliberate choice -> because we want instances of this struct to own all of its data and for that -> data to be valid for as long as the entire struct is valid. -> -> It’s possible for structs to store references to data owned by something else, -> but to do so requires the use of *lifetimes*, a Rust feature that we’ll -> discuss in Chapter 10. Lifetimes ensure that the data referenced by a struct -> is valid for as long as the struct is. Let’s say you try to store a reference -> in a struct without specifying lifetimes, like this, which won’t work: -> -> Filename: src/main.rs -> -> ```rust,ignore -> struct User { -> username: &str, -> email: &str, -> sign_in_count: u64, -> active: bool, -> } -> -> fn main() { -> let user1 = User { -> email: "someone@example.com", -> username: "someusername123", -> active: true, -> sign_in_count: 1, -> }; -> } -> ``` -> -> The compiler will complain that it needs lifetime specifiers: -> -> ```text -> errorE0106: missing lifetime specifier -> --> -> | -> 2 | username: &str, -> | ^ expected lifetime parameter -> -> errorE0106: missing lifetime specifier -> --> -> | -> 3 | email: &str, -> | ^ expected lifetime parameter -> ``` -> -> In Chapter 10, we’ll discuss how to fix these errors so you can store -> references in structs, but for now, we’ll fix errors like these using owned -> types like `String` instead of references like `&str`. - -## An Example Program Using Structs - -To understand when we might want to use structs, let’s write a program that -calculates the area of a rectangle. We’ll start with single variables, and then -refactor the program until we’re using structs instead. - -Let’s make a new binary project with Cargo called *rectangles* that will take -the width and height of a rectangle specified in pixels and calculate the area -of the rectangle. Listing 5-8 shows a short program with one way of doing -exactly that in our project’s *src/main.rs*: - -Filename: src/main.rs - -``` -fn main() { - let width1 = 30; - let height1 = 50; - - println!( - "The area of the rectangle is {} square pixels.", - area(width1, height1) - ); -} - -fn area(width: u32, height: u32) -> u32 { - width * height -} -``` - -Listing 5-8: Calculating the area of a rectangle specified by separate width -and height variables - -Now, run this program using `cargo run`: - -``` -The area of the rectangle is 1500 square pixels. -``` - -Even though Listing 5-8 works and figures out the area of the rectangle by -calling the `area` function with each dimension, we can do better. The width -and the height are related to each other because together they describe one -rectangle. - -The issue with this code is evident in the signature of `area`: - -``` -fn area(width: u32, height: u32) -> u32 { -``` - -The `area` function is supposed to calculate the area of one rectangle, but the -function we wrote has two parameters. The parameters are related, but that’s -not expressed anywhere in our program. It would be more readable and more -manageable to group width and height together. We’ve already discussed one way -we might do that in “The Tuple Type” section of Chapter 3: by using tuples. - -### Refactoring with Tuples - -Listing 5-9 shows another version of our program that uses tuples: - -Filename: 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 -} -``` - -Listing 5-9: Specifying the width and height of the rectangle with a tuple - -In one way, this program is better. Tuples let us add a bit of structure, and -we’re now passing just one argument. But in another way, this version is less -clear: tuples don’t name their elements, so our calculation has become more -confusing because we have to index into the parts of the tuple. - -It doesn’t matter if we mix up width and height for the area calculation, but -if we want to draw the rectangle on the screen, it would matter! We would have -to keep in mind that `width` is the tuple index `0` and `height` is the tuple -index `1`. If someone else worked on this code, they would have to figure this -out and keep it in mind as well. It would be easy to forget or mix up these -values and cause errors, because we haven’t conveyed the meaning of our data in -our code. - -### Refactoring with Structs: Adding More Meaning - -We use structs to add meaning by labeling the data. We can transform the tuple -we’re using into a data type with a name for the whole as well as names for the -parts, as shown in Listing 5-10: - -Filename: 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 -} -``` - -Listing 5-10: Defining a `Rectangle` struct - -Here we’ve defined a struct and named it `Rectangle`. Inside the curly -brackets, we defined the fields as `width` and `height`, both of which have -type `u32`. Then in `main`, we created a particular instance of `Rectangle` -that has a width of 30 and a height of 50. - -Our `area` function is now defined with one parameter, which we’ve named -`rectangle`, whose type is an immutable borrow of a struct `Rectangle` -instance. As mentioned in Chapter 4, we want to borrow the struct rather than -take ownership of it. This way, `main` retains its ownership and can continue -using `rect1`, which is the reason we use the `&` in the function signature and -where we call the function. - -The `area` function accesses the `width` and `height` fields of the `Rectangle` -instance. Our function signature for `area` now says exactly what we mean: -calculate the area of `Rectangle`, using its `width` and `height` fields. This -conveys that the width and height are related to each other, and it gives -descriptive names to the values rather than using the tuple index values of `0` -and `1`. This is a win for clarity. - -### Adding Useful Functionality with Derived Traits - -It’d be nice to be able to print an instance of `Rectangle` while we’re -debugging our program and see the values for all its fields. Listing 5-11 tries -using the `println!` macro as we have used in previous chapters. This won’t -work, however: - -Filename: src/main.rs - -``` -struct Rectangle { - width: u32, - height: u32, -} - -fn main() { - let rect1 = Rectangle { width: 30, height: 50 }; - - println!("rect1 is {}", rect1); -} -``` - -Listing 5-11: Attempting to print a `Rectangle` instance - -When we run this code, we get an error with this core message: - -``` -error[E0277]: the trait bound `Rectangle: std::fmt::Display` is not satisfied -``` - -The `println!` macro can do many kinds of formatting, and by default, curly -brackets tell `println!` to use formatting known as `Display`: output intended -for direct end user consumption. The primitive types we’ve seen so far -implement `Display` by default, because there’s only one way you’d want to show -a `1` or any other primitive type to a user. But with structs, the way -`println!` should format the output is less clear because there are more -display possibilities: Do you want commas or not? Do you want to print the -curly brackets? Should all the fields be shown? Due to this ambiguity, Rust -doesn’t try to guess what we want, and structs don’t have a provided -implementation of `Display`. - -If we continue reading the errors, we’ll find this helpful note: - -``` -`Rectangle` cannot be formatted with the default formatter; try using -`:?` instead if you are using a format string -``` - -Let’s try it! The `println!` macro call will now look like `println!("rect1 is -{:?}", rect1);`. Putting the specifier `:?` inside the curly brackets tells -`println!` we want to use an output format called `Debug`. `Debug` is a trait -that enables us to print our struct in a way that is useful for developers so -we can see its value while we’re debugging our code. - -Run the code with this change. Drat! We still get an error: - -``` -error[E0277]: the trait bound `Rectangle: std::fmt::Debug` is not satisfied -``` - -But again, the compiler gives us a helpful note: - -``` -`Rectangle` cannot be formatted using `:?`; if it is defined in your -crate, add `#[derive(Debug)]` or manually implement it -``` - -Rust *does* include functionality to print out debugging information, but we -have to explicitly opt in to make that functionality available for our struct. -To do that, we add the annotation `#[derive(Debug)]` just before the struct -definition, as shown in Listing 5-12: - -Filename: src/main.rs - -``` -#[derive(Debug)] -struct Rectangle { - width: u32, - height: u32, -} - -fn main() { - let rect1 = Rectangle { width: 30, height: 50 }; - - println!("rect1 is {:?}", rect1); -} -``` - -Listing 5-12: Adding the annotation to derive the `Debug` trait and printing -the `Rectangle` instance using debug formatting - -Now when we run the program, we won’t get any errors, and we’ll see the -following output: - -``` -rect1 is Rectangle { width: 30, height: 50 } -``` - -Nice! It’s not the prettiest output, but it shows the values of all the fields -for this instance, which would definitely help during debugging. When we have -larger structs, it’s useful to have output that’s a bit easier to read; in -those cases, we can use `{:#?}` instead of `{:?}` in the `println!` string. -When we use the `{:#?}` style in the example, the output will look like this: - -``` -rect1 is Rectangle { - width: 30, - height: 50 -} -``` - -Rust has provided a number of traits for us to use with the `derive` annotation -that can add useful behavior to our custom types. Those traits and their -behaviors are listed in Appendix C, “Derivable Traits.” We’ll cover how to -implement these traits with custom behavior as well as how to create your own -traits in Chapter 10. - -Our `area` function is very specific: it only computes the area of rectangles. -It would be helpful to tie this behavior more closely to our `Rectangle` -struct, because it won’t work with any other type. Let’s look at how we can -continue to refactor this code by turning the `area` function into an `area` -*method* defined on our `Rectangle` type. - -## Method Syntax - -*Methods* are similar to functions: they’re declared with the `fn` keyword and -their name, they can have parameters and a return value, and they contain some -code that is run when they’re called from somewhere else. However, methods are -different from functions in that they’re defined within the context of a struct -(or an enum or a trait object, which we cover in Chapters 6 and 17, -respectively), and their first parameter is always `self`, which represents the -instance of the struct the method is being called on. - -### Defining Methods - -Let’s change the `area` function that has a `Rectangle` instance as a parameter -and instead make an `area` method defined on the `Rectangle` struct, as shown -in Listing 5-13: - -Filename: 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() - ); -} -``` - -Listing 5-13: Defining an `area` method on the `Rectangle` struct - -To define the function within the context of `Rectangle`, we start an `impl` -(implementation) block. Then we move the `area` function within the `impl` -curly brackets and change the first (and in this case, only) parameter to be -`self` in the signature and everywhere within the body. In `main`, where we -called the `area` function and passed `rect1` as an argument, we can instead -use *method syntax* to call the `area` method on our `Rectangle` instance. -The method syntax goes after an instance: we add a dot followed by the method -name, parentheses, and any arguments. - -In the signature for `area`, we use `&self` instead of `rectangle: &Rectangle` -because Rust knows the type of `self` is `Rectangle` due to this method’s being -inside the `impl Rectangle` context. Note that we still need to use the `&` -before `self`, just as we did in `&Rectangle`. Methods can take ownership of -`self`, borrow `self` immutably as we’ve done here, or borrow `self` mutably, -just as they can any other parameter. - -We’ve chosen `&self` here for the same reason we used `&Rectangle` in the -function version: we don’t want to take ownership, and we just want to read the -data in the struct, not write to it. If we wanted to change the instance that -we’ve called the method on as part of what the method does, we’d use `&mut -self` as the first parameter. Having a method that takes ownership of the -instance by using just `self` as the first parameter is rare; this technique is -usually used when the method transforms `self` into something else and you want -to prevent the caller from using the original instance after the transformation. - -The main benefit of using methods instead of functions, in addition to using -method syntax and not having to repeat the type of `self` in every method’s -signature, is for organization. We’ve put all the things we can do with an -instance of a type in one `impl` block rather than making future users of our -code search for capabilities of `Rectangle` in various places in the library we -provide. - -> ### Where’s the `->` Operator? -> -> In C and C++, two different operators are used for calling methods: you use -> `.` if you’re calling a method on the object directly and `->` if you’re -> calling the method on a pointer to the object and need to dereference the -> pointer first. In other words, if `object` is a pointer, -> `object->something()` is similar to `(*object).something()`. -> -> Rust doesn’t have an equivalent to the `->` operator; instead, Rust has a -> feature called *automatic referencing and dereferencing*. Calling methods is -> one of the few places in Rust that has this behavior. -> -> Here’s how it works: when you call a method with `object.something()`, Rust -> automatically adds in `&`, `&mut`, or `*` so `object` matches the signature of -> the method. In other words, the following are the same: -> -> ```rust -> # #derive(Debug,Copy,Clone) -> # struct Point { -> # x: f64, -> # y: f64, -> # } -> # -> # impl Point { -> # fn distance(&self, other: &Point) -> f64 { -> # let x_squared = f64::powi(other.x - self.x, 2); -> # let y_squared = f64::powi(other.y - self.y, 2); -> # -> # f64::sqrt(x_squared + y_squared) -> # } -> # } -> # let p1 = Point { x: 0.0, y: 0.0 }; -> # let p2 = Point { x: 5.0, y: 6.5 }; -> p1.distance(&p2); -> (&p1).distance(&p2); -> ``` -> -> The first one looks much cleaner. This automatic referencing behavior works -> because methods have a clear receiver—the type of `self`. Given the receiver -> and name of a method, Rust can figure out definitively whether the method is -> reading (`&self`), mutating (`&mut self`), or consuming (`self`). The fact -> that Rust makes borrowing implicit for method receivers is a big part of -> making ownership ergonomic in practice. - -### Methods with More Parameters - -Let’s practice using methods by implementing a second method on the `Rectangle` -struct. This time, we want an instance of `Rectangle` to take another instance -of `Rectangle` and return `true` if the second `Rectangle` can fit completely -within `self`; otherwise it should return `false`. That is, we want to be able -to write the program shown in Listing 5-14, once we’ve defined the `can_hold` -method: - -Filename: 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)); -} -``` - -Listing 5-14: Using the as-yet-unwritten `can_hold` method - -And the expected output would look like the following, because both dimensions -of `rect2` are smaller than the dimensions of `rect1` but `rect3` is wider than -`rect1`: - -``` -Can rect1 hold rect2? true -Can rect1 hold rect3? false -``` - -We know we want to define a method, so it will be within the `impl Rectangle` -block. The method name will be `can_hold`, and it will take an immutable borrow -of another `Rectangle` as a parameter. We can tell what the type of the -parameter will be by looking at the code that calls the method: -`rect1.can_hold(&rect2)` passes in `&rect2`, which is an immutable borrow to -`rect2`, an instance of `Rectangle`. This makes sense because we only need to -read `rect2` (rather than write, which would mean we’d need a mutable borrow), -and we want `main` to retain ownership of `rect2` so we can use it again after -calling the `can_hold` method. The return value of `can_hold` will be a -Boolean, and the implementation will check whether the width and height of -`self` are both greater than the width and height of the other `Rectangle`, -respectively. Let’s add the new `can_hold` method to the `impl` block from -Listing 5-13, shown in Listing 5-15: - -Filename: src/main.rs - -``` -# #[derive(Debug)] -# struct Rectangle { -# width: u32, -# height: u32, -# } -# -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 - } -} -``` - -Listing 5-15: Implementing the `can_hold` method on `Rectangle` that takes -another `Rectangle` instance as a parameter - -When we run this code with the `main` function in Listing 5-14, we’ll get our -desired output. Methods can take multiple parameters that we add to the -signature after the `self` parameter, and those parameters work just like -parameters in functions. - -### Associated Functions - -Another useful feature of `impl` blocks is that we’re allowed to define -functions within `impl` blocks that *don’t* take `self` as a parameter. These -are called *associated functions* because they’re associated with the struct. -They’re still functions, not methods, because they don’t have an instance of -the struct to work with. You’ve already used the `String::from` associated -function. - -Associated functions are often used for constructors that will return a new -instance of the struct. For example, we could provide an associated function -that would have one dimension parameter and use that as both width and height, -thus making it easier to create a square `Rectangle` rather than having to -specify the same value twice: - -Filename: src/main.rs - -``` -# #[derive(Debug)] -# struct Rectangle { -# width: u32, -# height: u32, -# } -# -impl Rectangle { - fn square(size: u32) -> Rectangle { - Rectangle { width: size, height: size } - } -} -``` - -To call this associated function, we use the `::` syntax with the struct name; -`let sq = Rectangle::square(3);` is an example. This function is namespaced by -the struct: the `::` syntax is used for both associated functions and -namespaces created by modules. We’ll discuss modules in Chapter 7. - -### Multiple `impl` Blocks - -Each struct is allowed to have multiple `impl` blocks. For example, Listing -5-15 is equivalent to the code shown in Listing 5-16, which has each method -in its own `impl` block: - -``` -# #[derive(Debug)] -# struct Rectangle { -# width: u32, -# height: u32, -# } -# -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 - } -} -``` - -Listing 5-16: Rewriting Listing 5-15 using multiple `impl` blocks - -There’s no reason to separate these methods into multiple `impl` blocks here, -but this is valid syntax. We’ll see a case in which multiple `impl` blocks are -useful in Chapter 10 where we discuss generic types and traits. - -## Summary - -Structs let you create custom types that are meaningful for your domain. By -using structs, you can keep associated pieces of data connected to each other -and name each piece to make your code clear. Methods let you specify the -behavior that instances of your structs have, and associated functions let you -namespace functionality that is particular to your struct without having an -instance available. - -But structs aren’t the only way you can create custom types: let’s turn to -Rust’s enum feature to add another tool to your toolbox. diff --git a/second-edition/nostarch/chapter06.md b/second-edition/nostarch/chapter06.md deleted file mode 100644 index acf4bffe94..0000000000 --- a/second-edition/nostarch/chapter06.md +++ /dev/null @@ -1,753 +0,0 @@ - -[TOC] - -# Enums and Pattern Matching - -In this chapter we’ll look at *enumerations*, also referred to as *enums*. -Enums allow you to define a type by enumerating its possible values. First, -we’ll define and use an enum to show how an enum can encode meaning along with -data. Next, we’ll explore a particularly useful enum, called `Option`, which -expresses that a value can be either something or nothing. Then we’ll look at -how pattern matching in the `match` expression makes it easy to run different -code for different values of an enum. Finally, we’ll cover how the `if let` -construct is another convenient and concise idiom available to you to handle -enums in your code. - -Enums are a feature in many languages, but their capabilities differ in each -language. Rust’s enums are most similar to *algebraic data types* in functional -languages, such as F#, OCaml, and Haskell. - -## Defining an Enum - -Let’s look at a situation we might want to express in code and see why enums -are useful and more appropriate than structs in this case. Say we need to work -with IP addresses. Currently, two major standards are used for IP addresses: -version four and version six. These are the only possibilities for an IP -address that our program will come across: we can *enumerate* all possible -values, which is where enumeration gets its name. - -Any IP address can be either a version four or a version six address, but not -both at the same time. That property of IP addresses makes the enum data -structure appropriate, because enum values can only be one of the variants. -Both version four and version six addresses are still fundamentally IP -addresses, so they should be treated as the same type when the code is handling -situations that apply to any kind of IP address. - -We can express this concept in code by defining an `IpAddrKind` enumeration and -listing the possible kinds an IP address can be, `V4` and `V6`. These are known -as the *variants* of the enum: - -``` -enum IpAddrKind { - V4, - V6, -} -``` - -`IpAddrKind` is now a custom data type that we can use elsewhere in our code. - -### Enum Values - -We can create instances of each of the two variants of `IpAddrKind` like this: - -``` -let four = IpAddrKind::V4; -let six = IpAddrKind::V6; -``` - -Note that the variants of the enum are namespaced under its identifier, and we -use a double colon to separate the two. The reason this is useful is that now -both values `IpAddrKind::V4` and `IpAddrKind::V6` are of the same type: -`IpAddrKind`. We can then, for instance, define a function that takes any -`IpAddrKind`: - -``` -fn route(ip_type: IpAddrKind) { } -``` - -And we can call this function with either variant: - -``` -route(IpAddrKind::V4); -route(IpAddrKind::V6); -``` - -Using enums has even more advantages. Thinking more about our IP address type, -at the moment we don’t have a way to store the actual IP address *data*; we -only know what *kind* it is. Given that you just learned about structs in -Chapter 5, you might tackle this problem as shown in Listing 6-1: - -``` -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"), -}; -``` - -Listing 6-1: Storing the data and `IpAddrKind` variant of an IP address using a -`struct` - -Here, we’ve defined a struct `IpAddr` that has two fields: a `kind` field that -is of type `IpAddrKind` (the enum we defined previously) and an `address` field -of type `String`. We have two instances of this struct. The first, `home`, has -the value `IpAddrKind::V4` as its `kind` with associated address data of -`127.0.0.1`. The second instance, `loopback`, has the other variant of -`IpAddrKind` as its `kind` value, `V6`, and has address `::1` associated with -it. We’ve used a struct to bundle the `kind` and `address` values together, so -now the variant is associated with the value. - -We can represent the same concept in a more concise way using just an enum, -rather than an enum inside a struct, by putting data directly into each enum -variant. This new definition of the `IpAddr` enum says that both `V4` and `V6` -variants will have associated `String` values: - -``` -enum IpAddr { - V4(String), - V6(String), -} - -let home = IpAddr::V4(String::from("127.0.0.1")); - -let loopback = IpAddr::V6(String::from("::1")); -``` - -We attach data to each variant of the enum directly, so there is no need for an -extra struct. - -There’s another advantage to using an enum rather than a struct: each variant -can have different types and amounts of associated data. Version four type IP -addresses will always have four numeric components that will have values -between 0 and 255. If we wanted to store `V4` addresses as four `u8` values but -still express `V6` addresses as one `String` value, we wouldn’t be able to with -a struct. Enums handle this case with ease: - -``` -enum IpAddr { - V4(u8, u8, u8, u8), - V6(String), -} - -let home = IpAddr::V4(127, 0, 0, 1); - -let loopback = IpAddr::V6(String::from("::1")); -``` - -We’ve shown several different ways to define data structures to store version -four and version six IP addresses. However, as it turns out, wanting to store -IP addresses and encode which kind they are is so common that the standard -library has a definition we can use! Let’s look at how the standard library -defines `IpAddr`: it has the exact enum and variants that we’ve defined and -used, but it embeds the address data inside the variants in the form of two -different structs, which are defined differently for each variant: - -``` -struct Ipv4Addr { - // --snip-- -} - -struct Ipv6Addr { - // --snip-- -} - -enum IpAddr { - V4(Ipv4Addr), - V6(Ipv6Addr), -} -``` - -This code illustrates that you can put any kind of data inside an enum variant: -strings, numeric types, or structs, for example. You can even include another -enum! Also, standard library types are often not much more complicated than -what you might come up with. - -Note that even though the standard library contains a definition for `IpAddr`, -we can still create and use our own definition without conflict because we -haven’t brought the standard library’s definition into our scope. We’ll talk -more about bringing types into scope in Chapter 7. - -Let’s look at another example of an enum in Listing 6-2: this one has a wide -variety of types embedded in its variants: - -``` -enum Message { - Quit, - Move { x: i32, y: i32 }, - Write(String), - ChangeColor(i32, i32, i32), -} -``` - -Listing 6-2: A `Message` enum whose variants each store different amounts and -types of values - -This enum has four variants with different types: - -* `Quit` has no data associated with it at all. -* `Move` includes an anonymous struct inside it. -* `Write` includes a single `String`. -* `ChangeColor` includes three `i32` values. - -Defining an enum with variants like the ones in Listing 6-2 is similar to -defining different kinds of struct definitions, except the enum doesn’t use the -`struct` keyword and all the variants are grouped together under the `Message` -type. The following structs could hold the same data that the preceding enum -variants hold: - -``` -struct QuitMessage; // unit struct -struct MoveMessage { - x: i32, - y: i32, -} -struct WriteMessage(String); // tuple struct -struct ChangeColorMessage(i32, i32, i32); // tuple struct -``` - -But if we used the different structs, which each have their own type, we -couldn’t as easily define a function to take any of these kinds of messages as -we could with the `Message` enum defined in Listing 6-2, which is a single type. - -There is one more similarity between enums and structs: just as we’re able to -define methods on structs using `impl`, we’re also able to define methods on -enums. Here’s a method named `call` that we could define on our `Message` enum: - -``` -impl Message { - fn call(&self) { - // method body would be defined here - } -} - -let m = Message::Write(String::from("hello")); -m.call(); -``` - -The body of the method would use `self` to get the value that we called the -method on. In this example, we’ve created a variable `m` that has the value -`Message::Write(String::from("hello"))`, and that is what `self` will be in the -body of the `call` method when `m.call()` runs. - -Let’s look at another enum in the standard library that is very common and -useful: `Option`. - -### The `Option` Enum and Its Advantages Over Null Values - -In the previous section, we looked at how the `IpAddr` enum let us use Rust’s -type system to encode more information than just the data into our program. -This section explores a case study of `Option`, which is another enum defined -by the standard library. The `Option` type is used in many places because it -encodes the very common scenario in which a value could be something or it -could be nothing. Expressing this concept in terms of the type system means the -compiler can check whether you’ve handled all the cases you should be handling; -this functionality can prevent bugs that are extremely common in other -programming languages. - -Programming language design is often thought of in terms of which features you -include, but the features you exclude are important too. Rust doesn’t have the -null feature that many other languages have. *Null* is a value that means there -is no value there. In languages with null, variables can always be in one of -two states: null or not-null. - -In his 2009 presentation “Null References: The Billion Dollar Mistake,” Tony -Hoare, the inventor of null, has this to say: - -> I call it my billion-dollar mistake. At that time, I was designing the first -> comprehensive type system for references in an object-oriented language. My -> goal was to ensure that all use of references should be absolutely safe, with -> checking performed automatically by the compiler. But I couldn’t resist the -> temptation to put in a null reference, simply because it was so easy to -> implement. This has led to innumerable errors, vulnerabilities, and system -> crashes, which have probably caused a billion dollars of pain and damage in -> the last forty years. - -The problem with null values is that if you try to use a null value as a -not-null value, you’ll get an error of some kind. Because this null or not-null -property is pervasive, it’s extremely easy to make this kind of error. - -However, the concept that null is trying to express is still a useful one: a -null is a value that is currently invalid or absent for some reason. - -The problem isn’t really with the concept but with the particular -implementation. As such, Rust does not have nulls, but it does have an enum -that can encode the concept of a value being present or absent. This enum is -`Option`, and it is defined by the standard library as follows: - -``` -enum Option { - Some(T), - None, -} -``` - -The `Option` enum is so useful that it’s even included in the prelude; you -don’t need to bring it into scope explicitly. In addition, so are its variants: -you can use `Some` and `None` directly without the `Option::` prefix. The -`Option` enum is still just a regular enum, and `Some(T)` and `None` are -still variants of type `Option`. - -The `` syntax is a feature of Rust we haven’t talked about yet. It’s a -generic type parameter, and we’ll cover generics in more detail in Chapter 10. -For now, all you need to know is that `` means the `Some` variant of the -`Option` enum can hold one piece of data of any type. Here are some examples of -using `Option` values to hold number types and string types: - -``` -let some_number = Some(5); -let some_string = Some("a string"); - -let absent_number: Option = None; -``` - -If we use `None` rather than `Some`, we need to tell Rust what type of -`Option` we have, because the compiler can’t infer the type that the `Some` -variant will hold by looking only at a `None` value. - -When we have a `Some` value, we know that a value is present and the value is -held within the `Some`. When we have a `None` value, in some sense, it means -the same thing as null: we don’t have a valid value. So why is having -`Option` any better than having null? - -In short, because `Option` and `T` (where `T` can be any type) are different -types, the compiler won’t let us use an `Option` value as if it were -definitely a valid value. For example, this code won’t compile because it’s -trying to add an `i8` to an `Option`: - -``` -let x: i8 = 5; -let y: Option = Some(5); - -let sum = x + y; -``` - -If we run this code, we get an error message like this: - -``` -error[E0277]: the trait bound `i8: std::ops::Add>` is -not satisfied - --> - | -5 | let sum = x + y; - | ^ no implementation for `i8 + std::option::Option` - | -``` - -Intense! In effect, this error message means that Rust doesn’t understand how -to add an `i8` and an `Option`, because they’re different types. When we -have a value of a type like `i8` in Rust, the compiler will ensure that we -always have a valid value. We can proceed confidently without having to check -for null before using that value. Only when we have an `Option` (or -whatever type of value we’re working with) do we have to worry about possibly -not having a value, and the compiler will make sure we handle that case before -using the value. - -In other words, you have to convert an `Option` to a `T` before you can -perform `T` operations with it. Generally, this helps catch one of the most -common issues with null: assuming that something isn’t null when it actually -is. - -Not having to worry about incorrectly assuming a not-null value helps you to be -more confident in your code. In order to have a value that can possibly be -null, you must explicitly opt in by making the type of that value `Option`. -Then, when you use that value, you are required to explicitly handle the case -when the value is null. Everywhere that a value has a type that isn’t an -`Option`, you *can* safely assume that the value isn’t null. This was a -deliberate design decision for Rust to limit null’s pervasiveness and increase -the safety of Rust code. - -So, how do you get the `T` value out of a `Some` variant when you have a value -of type `Option` so you can use that value? The `Option` enum has a large -number of methods that are useful in a variety of situations; you can check -them out in its documentation. Becoming familiar with the methods on -`Option` will be extremely useful in your journey with Rust. - -In general, in order to use an `Option` value, you want to have code that -will handle each variant. You want some code that will run only when you have a -`Some(T)` value, and this code is allowed to use the inner `T`. You want some -other code to run if you have a `None` value, and that code doesn’t have a `T` -value available. The `match` expression is a control flow construct that does -just this when used with enums: it will run different code depending on which -variant of the enum it has, and that code can use the data inside the matching -value. - -## The `match` Control Flow Operator - -Rust has an extremely powerful control flow operator called `match` that allows -you to compare a value against a series of patterns and then execute code based -on which pattern matches. Patterns can be made up of literal values, variable -names, wildcards, and many other things; Chapter 18 covers all the different -kinds of patterns and what they do. The power of `match` comes from the -expressiveness of the patterns and the fact that the compiler confirms that all -possible cases are handled. - -Think of a `match` expression as being like a coin-sorting machine: coins slide -down a track with variously sized holes along it, and each coin falls through -the first hole it encounters that it fits into. In the same way, values go -through each pattern in a `match`, and at the first pattern the value “fits,” -the value falls into the associated code block to be used during execution. - -Because we just mentioned coins, let’s use them as an example using `match`! We -can write a function that can take an unknown United States coin and, in a -similar way as the counting machine, determine which coin it is and return its -value in cents, as shown here in Listing 6-3: - -``` -enum Coin { - Penny, - Nickel, - Dime, - Quarter, -} - -fn value_in_cents(coin: Coin) -> u32 { - match coin { - Coin::Penny => 1, - Coin::Nickel => 5, - Coin::Dime => 10, - Coin::Quarter => 25, - } -} -``` - -Listing 6-3: An enum and a `match` expression that has the variants of the enum -as its patterns - -Let’s break down the `match` in the `value_in_cents` function. First, we list -the `match` keyword followed by an expression, which in this case is the value -`coin`. This seems very similar to an expression used with `if`, but there’s a -big difference: with `if`, the expression needs to return a Boolean value, but -here, it can be any type. The type of `coin` in this example is the `Coin` enum -that we defined on line 1. - -Next are the `match` arms. An arm has two parts: a pattern and some code. The -first arm here has a pattern that is the value `Coin::Penny` and then the `=>` -operator that separates the pattern and the code to run. The code in this case -is just the value `1`. Each arm is separated from the next with a comma. - -When the `match` expression executes, it compares the resulting value against -the pattern of each arm, in order. If a pattern matches the value, the code -associated with that pattern is executed. If that pattern doesn’t match the -value, execution continues to the next arm, much as in a coin-sorting machine. -We can have as many arms as we need: in Listing 6-3, our `match` has four arms. - -The code associated with each arm is an expression, and the resulting value of -the expression in the matching arm is the value that gets returned for the -entire `match` expression. - -Curly brackets typically aren’t used if the match arm code is short, as it is -in Listing 6-3 where each arm just returns a value. If you want to run multiple -lines of code in a match arm, you can use curly brackets. For example, the -following code would print “Lucky penny!” every time the method was called with -a `Coin::Penny` but would still return the last value of the block, `1`: - -``` -fn value_in_cents(coin: Coin) -> u32 { - match coin { - Coin::Penny => { - println!("Lucky penny!"); - 1 - }, - Coin::Nickel => 5, - Coin::Dime => 10, - Coin::Quarter => 25, - } -} -``` - -### Patterns that Bind to Values - -Another useful feature of match arms is that they can bind to the parts of the -values that match the pattern. This is how we can extract values out of enum -variants. - -As an example, let’s change one of our enum variants to hold data inside it. -From 1999 through 2008, the United States minted quarters with different -designs for each of the 50 states on one side. No other coins got state -designs, so only quarters have this extra value. We can add this information to -our `enum` by changing the `Quarter` variant to include a `UsState` value stored -inside it, which we’ve done here in Listing 6-4: - -``` -#[derive(Debug)] // So we can inspect the state in a minute -enum UsState { - Alabama, - Alaska, - // --snip-- -} - -enum Coin { - Penny, - Nickel, - Dime, - Quarter(UsState), -} -``` - -Listing 6-4: A `Coin` enum in which the `Quarter` variant also holds a -`UsState` value - -Let’s imagine that a friend of ours is trying to collect all 50 state quarters. -While we sort our loose change by coin type, we’ll also call out the name of -the state associated with each quarter so if it’s one our friend doesn’t have, -they can add it to their collection. - -In the match expression for this code, we add a variable called `state` to the -pattern that matches values of the variant `Coin::Quarter`. When a -`Coin::Quarter` matches, the `state` variable will bind to the value of that -quarter’s state. Then we can use `state` in the code for that arm, like so: - -``` -fn value_in_cents(coin: Coin) -> u32 { - match coin { - Coin::Penny => 1, - Coin::Nickel => 5, - Coin::Dime => 10, - Coin::Quarter(state) => { - println!("State quarter from {:?}!", state); - 25 - }, - } -} -``` - -If we were to call `value_in_cents(Coin::Quarter(UsState::Alaska))`, `coin` -would be `Coin::Quarter(UsState::Alaska)`. When we compare that value with each -of the match arms, none of them match until we reach `Coin::Quarter(state)`. At -that point, the binding for `state` will be the value `UsState::Alaska`. We can -then use that binding in the `println!` expression, thus getting the inner -state value out of the `Coin` enum variant for `Quarter`. - -### Matching with `Option` - -In the previous section, we wanted to get the inner `T` value out of the `Some` -case when using `Option`; we can also handle `Option` using `match` as we -did with the `Coin` enum! Instead of comparing coins, we’ll compare the -variants of `Option`, but the way that the `match` expression works remains -the same. - -Let’s say we want to write a function that takes an `Option` and, if -there’s a value inside, adds 1 to that value. If there isn’t a value inside, -the function should return the `None` value and not attempt to perform any -operations. - -This function is very easy to write, thanks to `match`, and will look like -Listing 6-5: - -``` -fn plus_one(x: Option) -> Option { - match x { - None => None, - Some(i) => Some(i + 1), - } -} - -let five = Some(5); -let six = plus_one(five); -let none = plus_one(None); -``` - -Listing 6-5: A function that uses a `match` expression on an `Option` - -Let’s examine the first execution of `plus_one` in more detail. When we call -`plus_one(five)`, the variable `x` in the body of `plus_one` will have the -value `Some(5)`. We then compare that against each match arm. - -``` -None => None, -``` - -The `Some(5)` value doesn’t match the pattern `None`, so we continue to the -next arm. - -``` -Some(i) => Some(i + 1), -``` - -Does `Some(5)` match `Some(i)`? Why yes it does! We have the same variant. The -`i` binds to the value contained in `Some`, so `i` takes the value `5`. The -code in the match arm is then executed, so we add 1 to the value of `i` and -create a new `Some` value with our total `6` inside. - -Now let’s consider the second call of `plus_one` in Listing 6-5, where `x` is -`None`. We enter the `match` and compare to the first arm. - -``` -None => None, -``` - -It matches! There’s no value to add to, so the program stops and returns the -`None` value on the right side of `=>`. Because the first arm matched, no other -arms are compared. - -Combining `match` and enums is useful in many situations. You’ll see this -pattern a lot in Rust code: `match` against an enum, bind a variable to the -data inside, and then execute code based on it. It’s a bit tricky at first, but -once you get used to it, you’ll wish you had it in all languages. It’s -consistently a user favorite. - -### Matches Are Exhaustive - -There’s one other aspect of `match` we need to discuss. Consider this version -of our `plus_one` function that has a bug and won’t compile: - -``` -fn plus_one(x: Option) -> Option { - match x { - Some(i) => Some(i + 1), - } -} -``` - -We didn’t handle the `None` case, so this code will cause a bug. Luckily, it’s -a bug Rust knows how to catch. If we try to compile this code, we’ll get this -error: - -``` -error[E0004]: non-exhaustive patterns: `None` not covered - --> - | -6 | match x { - | ^ pattern `None` not covered -``` - -Rust knows that we didn’t cover every possible case and even knows which -pattern we forgot! Matches in Rust are *exhaustive*: we must exhaust every last -possibility in order for the code to be valid. Especially in the case of -`Option`, when Rust prevents us from forgetting to explicitly handle the -`None` case, it protects us from assuming that we have a value when we might -have null, thus making the billion-dollar mistake discussed earlier. - -### The `_` Placeholder - -Rust also has a pattern we can use when we don’t want to list all possible -values. For example, a `u8` can have valid values of 0 through 255. If we only -care about the values 1, 3, 5, and 7, we don’t want to have to list out 0, 2, -4, 6, 8, 9 all the way up to 255. Fortunately, we don’t have to: we can use the -special pattern `_` instead: - -``` -let some_u8_value = 0u8; -match some_u8_value { - 1 => println!("one"), - 3 => println!("three"), - 5 => println!("five"), - 7 => println!("seven"), - _ => (), -} -``` - -The `_` pattern will match any value. By putting it after our other arms, the -`_` will match all the possible cases that aren’t specified before it. The `()` -is just the unit value, so nothing will happen in the `_` case. As a result, we -can say that we want to do nothing for all the possible values that we don’t -list before the `_` placeholder. - -However, the `match` expression can be a bit wordy in a situation in which we -only care about *one* of the cases. For this situation, Rust provides `if let`. - -## Concise Control Flow with `if let` - -The `if let` syntax lets you combine `if` and `let` into a less verbose way to -handle values that match one pattern while ignoring the rest. Consider the -program in Listing 6-6 that matches on an `Option` value but only wants to -execute code if the value is 3: - -``` -let some_u8_value = Some(0u8); -match some_u8_value { - Some(3) => println!("three"), - _ => (), -} -``` - -Listing 6-6: A `match` that only cares about executing code when the value is -`Some(3)` - -We want to do something with the `Some(3)` match but do nothing with any other -`Some` value or the `None` value. To satisfy the `match` expression, we -have to add `_ => ()` after processing just one variant, which is a lot of -boilerplate code to add. - -Instead, we could write this in a shorter way using `if let`. The following -code behaves the same as the `match` in Listing 6-6: - -``` -if let Some(3) = some_u8_value { - println!("three"); -} -``` - -The syntax `if let` takes a pattern and an expression separated by an `=`. It -works the same way as a `match`, where the expression is given to the `match` -and the pattern is its first arm. - -Using `if let` means you have less typing, less indentation, and less -boilerplate code. However, you lose the exhaustive checking that `match` -enforces. Choosing between `match` and `if let` depends on what you’re doing in -your particular situation and whether gaining conciseness is an appropriate -trade-off for losing exhaustive checking. - -In other words, you can think of `if let` as syntax sugar for a `match` that -runs code when the value matches one pattern and then ignores all other values. - -We can include an `else` with an `if let`. The block of code that goes with the -`else` is the same as the block of code that would go with the `_` case in the -`match` expression that is equivalent to the `if let` and `else`. Recall the -`Coin` enum definition in Listing 6-4, where the `Quarter` variant also held a -`UsState` value. If we wanted to count all non-quarter coins we see while also -announcing the state of the quarters, we could do that with a `match` -expression like this: - -``` -let mut count = 0; -match coin { - Coin::Quarter(state) => println!("State quarter from {:?}!", state), - _ => count += 1, -} -``` - -Or we could use an `if let` and `else` expression like this: - -``` -let mut count = 0; -if let Coin::Quarter(state) = coin { - println!("State quarter from {:?}!", state); -} else { - count += 1; -} -``` - -If you have a situation in which your program has logic that is too verbose to -express using a `match`, remember that `if let` is in your Rust toolbox as well. - -## Summary - -We’ve now covered how to use enums to create custom types that can be one of a -set of enumerated values. We’ve shown how the standard library’s `Option` -type helps you use the type system to prevent errors. When enum values have -data inside them, you can use `match` or `if let` to extract and use those -values, depending on how many cases you need to handle. - -Your Rust programs can now express concepts in your domain using structs and -enums. Creating custom types to use in your API ensures type safety: the -compiler will make certain your functions get only values of the type each -function expects. - -In order to provide a well-organized API to your users that is straightforward -to use and only exposes exactly what your users will need, let’s now turn to -Rust’s modules. diff --git a/second-edition/nostarch/chapter07.md b/second-edition/nostarch/chapter07.md deleted file mode 100644 index 7be64e7930..0000000000 --- a/second-edition/nostarch/chapter07.md +++ /dev/null @@ -1,1069 +0,0 @@ - -[TOC] - -# Using Modules to Reuse and Organize Code - -When you start writing programs in Rust, your code might live solely in the -`main` function. As your code grows, you’ll eventually move functionality into -other functions for reuse and better organization. By splitting your code into -smaller chunks, you make each chunk easier to understand on its own. But what -happens if you have too many functions? Rust has a module system that enables -the reuse of code in an organized fashion. - -In the same way that you extract lines of code into a function, you can extract -functions (and other code, like structs and enums) into different modules. A -*module* is a namespace that contains definitions of functions or types, and -you can choose whether those definitions are visible outside their module -(public) or not (private). Here’s an overview of how modules work: - -* The `mod` keyword declares a new module. Code within the module appears - either immediately following this declaration within curly brackets or in - another file. -* By default, functions, types, constants, and modules are private. The `pub` - keyword makes an item public and therefore visible outside its namespace. -* The `use` keyword brings modules, or the definitions inside modules, into - scope so it’s easier to refer to them. - -We’ll look at each of these parts to see how they fit into the whole. - -## `mod` and the Filesystem - -We’ll start our module example by making a new project with Cargo, but instead -of creating a binary crate, we’ll make a library crate: a project that other -people can pull into their projects as a dependency. For example, the `rand` -crate discussed in Chapter 2 is a library crate that we used as a dependency in -the guessing game project. - -We’ll create a skeleton of a library that provides some general networking -functionality; we’ll concentrate on the organization of the modules and -functions, but we won’t worry about what code goes in the function bodies. -We’ll call our library `communicator`. To create a library, pass the `--lib` -option instead of `--bin`: - -``` -$ cargo new communicator --lib -$ cd communicator -``` - -Notice that Cargo generated *src/lib.rs* instead of *src/main.rs*. Inside -*src/lib.rs* we’ll find the following: - -Filename: src/lib.rs - -``` -#[cfg(test)] -mod tests { - #[test] - fn it_works() { - assert_eq!(2 + 2, 4); - } -} -``` - -Cargo creates an example test to help us get our library started, rather than -the “Hello, world!” binary that we get when we use the `--bin` option. We’ll -look at the `#[]` and `mod tests` syntax in the “Using `super` to Access a -Parent Module” section later in this chapter, but for now, leave this code at -the bottom of *src/lib.rs*. - -Because we don’t have a *src/main.rs* file, there’s nothing for Cargo to -execute with the `cargo run` command. Therefore, we’ll use the `cargo build` -command to compile our library crate’s code. - -We’ll look at different options for organizing your library’s code that will be -suitable in a variety of situations, depending on the intent of the code. - -### Module Definitions - -For our `communicator` networking library, we’ll first define a module named -`network` that contains the definition of a function called `connect`. Every -module definition in Rust starts with the `mod` keyword. Add this code to the -beginning of the *src/lib.rs* file, above the test code: - -Filename: src/lib.rs - -``` -mod network { - fn connect() { - } -} -``` - -After the `mod` keyword, we put the name of the module, `network`, and then a -block of code in curly brackets. Everything inside this block is inside the -namespace `network`. In this case, we have a single function, `connect`. If we -wanted to call this function from code outside the `network` module, we -would need to specify the module and use the namespace syntax `::` like so: -`network::connect()`. - -We can also have multiple modules, side by side, in the same *src/lib.rs* file. -For example, to also have a `client` module that has a function named -`connect`, we can add it as shown in Listing 7-1: - -Filename: src/lib.rs - -``` -mod network { - fn connect() { - } -} - -mod client { - fn connect() { - } -} -``` - -Listing 7-1: The `network` module and the `client` module defined side by side -in *src/lib.rs* - -Now we have a `network::connect` function and a `client::connect` function. -These can have completely different functionality, and the function names do -not conflict with each other because they’re in different modules. - -In this case, because we’re building a library, the file that serves as the -entry point for building our library is *src/lib.rs*. However, in respect to -creating modules, there’s nothing special about *src/lib.rs*. We could also -create modules in *src/main.rs* for a binary crate in the same way as we’re -creating modules in *src/lib.rs* for the library crate. In fact, we can put -modules inside of modules, which can be useful as your modules grow to keep -related functionality organized together and separate functionality apart. The -way you choose to organize your code depends on how you think about the -relationship between the parts of your code. For instance, the `client` code -and its `connect` function might make more sense to users of our library if -they were inside the `network` namespace instead, as in Listing 7-2: - -Filename: src/lib.rs - -``` -mod network { - fn connect() { - } - - mod client { - fn connect() { - } - } -} -``` - -Listing 7-2: Moving the `client` module inside the `network` module - -In your *src/lib.rs* file, replace the existing `mod network` and `mod client` -definitions with the ones in Listing 7-2, which have the `client` module as an -inner module of `network`. The functions `network::connect` and -`network::client::connect` are both named `connect`, but they don’t conflict -with each other because they’re in different namespaces. - -In this way, modules form a hierarchy. The contents of *src/lib.rs* are at the -topmost level, and the submodules are at lower levels. Here’s what the -organization of our example in Listing 7-1 looks like when thought of as a -hierarchy: - -``` -communicator - ├── network - └── client -``` - -And here’s the hierarchy corresponding to the example in Listing 7-2: - -``` -communicator - └── network - └── client -``` - -The hierarchy shows that in Listing 7-2, `client` is a child of the `network` -module rather than a sibling. More complicated projects can have many modules, -and they’ll need to be organized logically in order for you to keep track of -them. What “logically” means in your project is up to you and depends on how -you and your library’s users think about your project’s domain. Use the -techniques shown here to create side-by-side modules and nested modules in -whatever structure you would like. - -### Moving Modules to Other Files - -Modules form a hierarchical structure, much like another structure in computing -that you’re used to: filesystems! We can use Rust’s module system along with -multiple files to split up Rust projects so not everything lives in -*src/lib.rs* or *src/main.rs*. For this example, let’s start with the code in -Listing 7-3: - -Filename: src/lib.rs - -``` -mod client { - fn connect() { - } -} - -mod network { - fn connect() { - } - - mod server { - fn connect() { - } - } -} -``` - -Listing 7-3: Three modules, `client`, `network`, and `network::server`, all -defined in *src/lib.rs* - -The file *src/lib.rs* has this module hierarchy: - -``` -communicator - ├── client - └── network - └── server -``` - -If these modules had many functions, and those functions were becoming lengthy, -it would be difficult to scroll through this file to find the code we wanted to -work with. Because the functions are nested inside one or more `mod` blocks, -the lines of code inside the functions will start getting lengthy as well. -These would be good reasons to separate the `client`, `network`, and `server` -modules from *src/lib.rs* and place them into their own files. - -First, let’s replace the `client` module code with only the declaration of the -`client` module so that *src/lib.rs* looks like code shown in Listing 7-4: - -Filename: src/lib.rs - -``` -mod client; - -mod network { - fn connect() { - } - - mod server { - fn connect() { - } - } -} -``` - -Listing 7-4: Extracting the contents of the `client` module but leaving the -declaration in *src/lib.rs* - -We’re still *declaring* the `client` module here, but by replacing the block -with a semicolon, we’re telling Rust to look in another location for the code -defined within the scope of the `client` module. In other words, the line `mod -client;` means this: - -``` -mod client { - // contents of client.rs -} -``` - -Now we need to create the external file with that module name. Create a -*client.rs* file in your *src/* directory and open it. Then enter the -following, which is the `connect` function in the `client` module that we -removed in the previous step: - -Filename: src/client.rs - -``` -fn connect() { -} -``` - -Note that we don’t need a `mod` declaration in this file because we already -declared the `client` module with `mod` in *src/lib.rs*. This file just -provides the *contents* of the `client` module. If we put a `mod client` here, -we’d be giving the `client` module its own submodule named `client`! - -Rust only knows to look in *src/lib.rs* by default. If we want to add more -files to our project, we need to tell Rust in *src/lib.rs* to look in other -files; this is why `mod client` needs to be defined in *src/lib.rs* and can’t -be defined in *src/client.rs*. - -Now the project should compile successfully, although you’ll get a few -warnings. Remember to use `cargo build` instead of `cargo run` because we have -a library crate rather than a binary crate: - -``` -$ cargo build - Compiling communicator v0.1.0 (file:///projects/communicator) -warning: function is never used: `connect` - --> src/client.rs:1:1 - | -1 | / fn connect() { -2 | | } - | |_^ - | - = note: #[warn(dead_code)] on by default - -warning: function is never used: `connect` - --> src/lib.rs:4:5 - | -4 | / fn connect() { -5 | | } - | |_____^ - -warning: function is never used: `connect` - --> src/lib.rs:8:9 - | -8 | / fn connect() { -9 | | } - | |_________^ -``` - -These warnings tell us that we have functions that are never used. Don’t worry -about these warnings for now; we’ll address them later in this chapter in the -“Controlling Visibility with `pub`” section. The good news is that they’re just -warnings; our project built successfully! - -Next, let’s extract the `network` module into its own file using the same -pattern. In *src/lib.rs*, delete the body of the `network` module and add a -semicolon to the declaration, like so: - -Filename: src/lib.rs - -``` -mod client; - -mod network; -``` - -Then create a new *src/network.rs* file and enter the following: - -Filename: src/network.rs - -``` -fn connect() { -} - -mod server { - fn connect() { - } -} -``` - -Notice that we still have a `mod` declaration within this module file; this is -because we still want `server` to be a submodule of `network`. - -Run `cargo build` again. Success! We have one more module to extract: `server`. -Because it’s a submodule—that is, a module within a module—our current tactic -of extracting a module into a file named after that module won’t work. We’ll -try anyway so you can see the error. First, change *src/network.rs* to have -`mod server;` instead of the `server` module’s contents: - -Filename: src/network.rs - -``` -fn connect() { -} - -mod server; -``` - -Then create a *src/server.rs* file and enter the contents of the `server` -module that we extracted: - -Filename: src/server.rs - -``` -fn connect() { -} -``` - -When we try to `cargo build`, we’ll get the error shown in Listing 7-5: - -``` -$ cargo build - Compiling communicator v0.1.0 (file:///projects/communicator) -error: cannot declare a new module at this location - --> src/network.rs:4:5 - | -4 | mod server; - | ^^^^^^ - | -note: maybe move this module `src/network.rs` to its own directory via `src/network/mod.rs` - --> src/network.rs:4:5 - | -4 | mod server; - | ^^^^^^ -note: ... or maybe `use` the module `server` instead of possibly redeclaring it - --> src/network.rs:4:5 - | -4 | mod server; - | ^^^^^^ -``` - -Listing 7-5: Error when trying to extract the `server` submodule into -*src/server.rs* - -The error says we `cannot declare a new module at this location` and is -pointing to the `mod server;` line in *src/network.rs*. So *src/network.rs* is -different than *src/lib.rs* somehow: keep reading to understand why. - -The note in the middle of Listing 7-5 is actually very helpful because it -points out something we haven’t yet talked about doing: - -``` -note: maybe move this module `network` to its own directory via -`network/mod.rs` -``` - -Instead of continuing to follow the same file-naming pattern we used -previously, we can do what the note suggests: - -1. Make a new *directory* named *network*, the parent module’s name. -2. Move the *src/network.rs* file into the new *network* directory and - rename it *src/network/mod.rs*. -3. Move the submodule file *src/server.rs* into the *network* directory. - -Here are commands to carry out these steps: - -``` -$ mkdir src/network -$ mv src/network.rs src/network/mod.rs -$ mv src/server.rs src/network -``` - -Now when we try to run `cargo build`, compilation will work (we’ll still have -warnings though). Our module layout still looks exactly the same as it did when -we had all the code in *src/lib.rs* in Listing 7-3: - -``` -communicator - ├── client - └── network - └── server -``` - -The corresponding file layout now looks like this: - -``` -└── src - ├── client.rs - ├── lib.rs - └── network - ├── mod.rs - └── server.rs -``` - -So when we wanted to extract the `network::server` module, why did we have to -also change the *src/network.rs* file to the *src/network/mod.rs* file and put -the code for `network::server` in the *network* directory in -*src/network/server.rs*? Why couldn’t we just extract the `network::server` -module into *src/server.rs*? The reason is that Rust wouldn’t be able to -recognize that `server` was supposed to be a submodule of `network` if the -*server.rs* file was in the *src* directory. To clarify Rust’s behavior here, -let’s consider a different example with the following module hierarchy, where -all the definitions are in *src/lib.rs*: - -``` -communicator - ├── client - └── network - └── client -``` - -In this example, we have three modules again: `client`, `network`, and -`network::client`. Following the same steps we did earlier for extracting -modules into files, we would create *src/client.rs* for the `client` module. -For the `network` module, we would create *src/network.rs*. But we wouldn’t be -able to extract the `network::client` module into a *src/client.rs* file -because that already exists for the top-level `client` module! If we could put -the code for *both* the `client` and `network::client` modules in the -*src/client.rs* file, Rust wouldn’t have any way to know whether the code was -for `client` or for `network::client`. - -Therefore, in order to extract a file for the `network::client` submodule of -the `network` module, we needed to create a directory for the `network` module -instead of a *src/network.rs* file. The code that is in the `network` module -then goes into the *src/network/mod.rs* file, and the submodule -`network::client` can have its own *src/network/client.rs* file. Now the -top-level *src/client.rs* is unambiguously the code that belongs to the -`client` module. - -### Rules of Module Filesystems - -Let’s summarize the rules of modules with regard to files: - -* If a module named `foo` has no submodules, you should put the declarations - for `foo` in a file named *foo.rs*. -* If a module named `foo` does have submodules, you should put the declarations - for `foo` in a file named *foo/mod.rs*. - -These rules apply recursively, so if a module named `foo` has a submodule named -`bar` and `bar` does not have submodules, you should have the following files -in your *src* directory: - -``` -└── foo - ├── bar.rs (contains the declarations in `foo::bar`) - └── mod.rs (contains the declarations in `foo`, including `mod bar`) -``` - -The modules should be declared in their parent module’s file using the `mod` -keyword. - -Next, we’ll talk about the `pub` keyword and get rid of those warnings! - -## Controlling Visibility with `pub` - -We resolved the error messages shown in Listing 7-5 by moving the `network` and -`network::server` code into the *src/network/mod.rs* and -*src/network/server.rs* files, respectively. At that point, `cargo build` was -able to build our project, but we still get warning messages about the -`client::connect`, `network::connect`, and `network::server::connect` functions -not being used. - -So why are we receiving these warnings? After all, we’re building a library -with functions that are intended to be used by our *users*, not necessarily by -us within our own project, so it shouldn’t matter that these `connect` -functions go unused. The point of creating them is that they will be used by -another project, not our own. - -To understand why this program invokes these warnings, let’s try using the -`connect` library from another project, calling it externally. To do that, -we’ll create a binary crate in the same directory as our library crate by -making a *src/main.rs* file containing this code: - -Filename: src/main.rs - -``` -extern crate communicator; - -fn main() { - communicator::client::connect(); -} -``` - -We use the `extern crate` command to bring the `communicator` library crate -into scope. Our package now contains *two* crates. Cargo treats *src/main.rs* -as the root file of a binary crate, which is separate from the existing library -crate whose root file is *src/lib.rs*. This pattern is quite common for -executable projects: most functionality is in a library crate, and the binary -crate uses that library crate. As a result, other programs can also use the -library crate, and it’s a nice separation of concerns. - -From the point of view of a crate outside the `communicator` library looking -in, all the modules we’ve been creating are within a module that has the same -name as the crate, `communicator`. We call the top-level module of a crate the -*root module*. - -Also note that even if we’re using an external crate within a submodule of our -project, the `extern crate` should go in our root module (so in *src/main.rs* -or *src/lib.rs*). Then, in our submodules, we can refer to items from external -crates as if the items are top-level modules. - -Right now, our binary crate just calls our library’s `connect` function from -the `client` module. However, invoking `cargo build` will now give us an error -after the warnings: - -``` -error[E0603]: module `client` is private - --> src/main.rs:4:5 - | -4 | communicator::client::connect(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -``` - -Ah ha! This error tells us that the `client` module is private, which is the -crux of the warnings. It’s also the first time we’ve run into the concepts of -*public* and *private* in the context of Rust. The default state of all code in -Rust is private: no one else is allowed to use the code. If you don’t use a -private function within your program, because your program is the only code -allowed to use that function, Rust will warn you that the function has gone -unused. - -After you specify that a function such as `client::connect` is public, not only -will your call to that function from your binary crate be allowed, but also the -warning that the function is unused will go away. Marking a function as public -lets Rust know that the function will be used by code outside of your program. -Rust considers the theoretical external usage that’s now possible as the -function “being used.” Thus, when a function is marked public, Rust will not -require that it be used in your program and will stop warning that the function -is unused. - -### Making a Function Public - -To tell Rust to make a function public, we add the `pub` keyword to the start -of the declaration. We’ll focus on fixing the warning that indicates -`client::connect` has gone unused for now, as well as the `` module `client` is -private `` error from our binary crate. Modify *src/lib.rs* to make the -`client` module public, like so: - -Filename: src/lib.rs - -``` -pub mod client; - -mod network; -``` - -The `pub` keyword is placed right before `mod`. Let’s try building again: - -``` -error[E0603]: function `connect` is private - --> src/main.rs:4:5 - | -4 | communicator::client::connect(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -``` - -Hooray! We have a different error! Yes, different error messages are a cause -for celebration. The new error shows `` function `connect` is private ``, so -let’s edit *src/client.rs* to make `client::connect` public too: - -Filename: src/client.rs - -``` -pub fn connect() { -} -``` - -Now run `cargo build` again: - -``` -warning: function is never used: `connect` - --> src/network/mod.rs:1:1 - | -1 | / fn connect() { -2 | | } - | |_^ - | - = note: #[warn(dead_code)] on by default - -warning: function is never used: `connect` - --> src/network/server.rs:1:1 - | -1 | / fn connect() { -2 | | } - | |_^ -``` - -The code compiled, and the warning that `client::connect` is not being used is -gone! - -Unused code warnings don’t always indicate that an item in your code needs to -be made public: if you *didn’t* want these functions to be part of your public -API, unused code warnings could be alerting you to code you no longer need that -you can safely delete. They could also be alerting you to a bug if you had just -accidentally removed all places within your library where this function is -called. - -But in this case, we *do* want the other two functions to be part of our -crate’s public API, so let’s mark them as `pub` as well to get rid of the -remaining warnings. Modify *src/network/mod.rs* to look like the following: - -Filename: src/network/mod.rs - -``` -pub fn connect() { -} - -mod server; -``` - -Then compile the code: - -``` -warning: function is never used: `connect` - --> src/network/mod.rs:1:1 - | -1 | / pub fn connect() { -2 | | } - | |_^ - | - = note: #[warn(dead_code)] on by default - -warning: function is never used: `connect` - --> src/network/server.rs:1:1 - | -1 | / fn connect() { -2 | | } - | |_^ -``` - -Hmmm, we’re still getting an unused function warning, even though -`network::connect` is set to `pub`. The reason is that the function is public -within the module, but the `network` module that the function resides in is not -public. We’re working from the interior of the library out this time, whereas -with `client::connect` we worked from the outside in. We need to change -*src/lib.rs* to make `network` public too, like so: - -Filename: src/lib.rs - -``` -pub mod client; - -pub mod network; -``` - -Now when we compile, that warning is gone: - -``` -warning: function is never used: `connect` - --> src/network/server.rs:1:1 - | -1 | / fn connect() { -2 | | } - | |_^ - | - = note: #[warn(dead_code)] on by default -``` - -Only one warning is left—try to fix this one on your own! - -### Privacy Rules - -Overall, these are the rules for item visibility: - -- If an item is public, it can be accessed through any of its parent modules. -- If an item is private, it can be accessed only by its immediate parent - module and any of the parent’s child modules. - -### Privacy Examples - -Let’s look at a few more privacy examples to get some practice. Create a new -library project and enter the code in Listing 7-6 into your new project’s -*src/lib.rs*: - -Filename: src/lib.rs - -``` -mod outermost { - pub fn middle_function() {} - - fn middle_secret_function() {} - - mod inside { - pub fn inner_function() {} - - fn secret_function() {} - } -} - -fn try_me() { - outermost::middle_function(); - outermost::middle_secret_function(); - outermost::inside::inner_function(); - outermost::inside::secret_function(); -} -``` - -Listing 7-6: Examples of private and public functions, some of which are -incorrect - -Before you try to compile this code, make a guess about which lines in the -`try_me` function will have errors. Then, try compiling the code to see whether -you were right—and read on for the discussion of the errors! - -#### Looking at the Errors - -The `try_me` function is in the root module of our project. The module named -`outermost` is private, but the second privacy rule states that the `try_me` -function is allowed to access the `outermost` module because `outermost` is in -the current (root) module, as is `try_me`. - -The call to `outermost::middle_function` will work because `middle_function` is -public and `try_me` is accessing `middle_function` through its parent module -`outermost`. We determined in the previous paragraph that this module is -accessible. - -The call to `outermost::middle_secret_function` will cause a compilation error. -Because `middle_secret_function` is private, the second rule applies. The root -module is neither the current module of `middle_secret_function` (`outermost` -is), nor is it a child module of the current module of `middle_secret_function`. - -The module named `inside` is private and has no child modules, so it can be -accessed only by its current module `outermost`. That means the `try_me` -function is not allowed to call `outermost::inside::inner_function` or -`outermost::inside::secret_function`. - -#### Fixing the Errors - -Here are some suggestions for changing the code in an attempt to fix the -errors. Make a guess as to whether it will fix the errors before you try each -one. Then compile the code to see whether or not you’re right, using the -privacy rules to understand why. Feel free to design more experiments and try -them out! - -* What if the `inside` module were public? -* What if `outermost` were public and `inside` were private? -* What if, in the body of `inner_function`, you called - `::outermost::middle_secret_function()`? (The two colons at the beginning mean - that we want to refer to the modules starting from the root module.) - -Next, let’s talk about bringing items into scope with the `use` keyword. - -## Referring to Names in Different Modules - -We’ve covered how to call functions defined within a module using the module -name as part of the call, as in the call to the `nested_modules` function shown -here in Listing 7-7: - -Filename: src/main.rs - -``` -pub mod a { - pub mod series { - pub mod of { - pub fn nested_modules() {} - } - } -} - -fn main() { - a::series::of::nested_modules(); -} -``` - -Listing 7-7: Calling a function by fully specifying its enclosing module’s path - -As you can see, referring to the fully qualified name can get quite lengthy. -Fortunately, Rust has a keyword to make these calls more concise. - -### Bringing Names into Scope with the `use` Keyword - -Rust’s `use` keyword shortens lengthy function calls by bringing the modules of -the function you want to call into scope. Here’s an example of bringing the -`a::series::of` module into a binary crate’s root scope: - -Filename: src/main.rs - -``` -pub mod a { - pub mod series { - pub mod of { - pub fn nested_modules() {} - } - } -} - -use a::series::of; - -fn main() { - of::nested_modules(); -} -``` - -The line `use a::series::of;` means that rather than using the full -`a::series::of` path wherever we want to refer to the `of` module, we can use -`of`. - -The `use` keyword brings only what we’ve specified into scope: it does not -bring children of modules into scope. That’s why we still have to use -`of::nested_modules` when we want to call the `nested_modules` function. - -We could have chosen to bring the function into scope by instead specifying the -function in the `use` as follows: - -``` -pub mod a { - pub mod series { - pub mod of { - pub fn nested_modules() {} - } - } -} - -use a::series::of::nested_modules; - -fn main() { - nested_modules(); -} -``` - -Doing so allows us to exclude all the modules and reference the function -directly. - -Because enums also form a sort of namespace like modules, we can bring an -enum’s variants into scope with `use` as well. For any kind of `use` statement, -if you’re bringing multiple items from one namespace into scope, you can list -them using curly brackets and commas in the last position, like so: - -``` -enum TrafficLight { - Red, - Yellow, - Green, -} - -use TrafficLight::{Red, Yellow}; - -fn main() { - let red = Red; - let yellow = Yellow; - let green = TrafficLight::Green; -} -``` - -We’re still specifying the `TrafficLight` namespace for the `Green` variant -because we didn’t include `Green` in the `use` statement. - -### Bringing All Names into Scope with a Glob - -To bring all the items in a namespace into scope at once, we can use the `*` -syntax, which is called the *glob operator*. This example brings all the -variants of an enum into scope without having to list each specifically: - -``` -enum TrafficLight { - Red, - Yellow, - Green, -} - -use TrafficLight::*; - -fn main() { - let red = Red; - let yellow = Yellow; - let green = Green; -} -``` - -The `*` will bring into scope all the visible items in the `TrafficLight` -namespace. You should use globs sparingly: they are convenient, but a glob -might also pull in more items than you expected and cause naming conflicts. - -### Using `super` to Access a Parent Module - -As you saw at the beginning of this chapter, when you create a library crate, -Cargo makes a `tests` module for you. Let’s go into more detail about that now. -In your `communicator` project, open *src/lib.rs*: - -Filename: src/lib.rs - -``` -pub mod client; - -pub mod network; - -#[cfg(test)] -mod tests { - #[test] - fn it_works() { - assert_eq!(2 + 2, 4); - } -} -``` - -Chapter 11 explains more about testing, but parts of this example should make -sense now: we have a module named `tests` that lives next to our other modules -and contains one function named `it_works`. Even though there are special -annotations, the `tests` module is just another module! So our module hierarchy -looks like this: - -``` -communicator - ├── client - ├── network - | └── client - └── tests -``` - -Tests are for exercising the code within our library, so let’s try to call our -`client::connect` function from this `it_works` function, even though we won’t -be checking any functionality right now. This won’t work yet: - -Filename: src/lib.rs - -``` -#[cfg(test)] -mod tests { - #[test] - fn it_works() { - client::connect(); - } -} -``` - -Run the tests by invoking the `cargo test` command: - -``` -$ cargo test - Compiling communicator v0.1.0 (file:///projects/communicator) -error[E0433]: failed to resolve. Use of undeclared type or module `client` - --> src/lib.rs:9:9 - | -9 | client::connect(); - | ^^^^^^ Use of undeclared type or module `client` -``` - -The compilation failed, but why? We don’t need to place `communicator::` in -front of the function, as we did in *src/main.rs*, because we are definitely -within the `communicator` library crate here. The reason is that paths are -always relative to the current module, which here is `tests`. The only -exception is in a `use` statement, where paths are relative to the crate root -by default. Our `tests` module needs the `client` module in its scope! - -So how do we get back up one module in the module hierarchy to call the -`client::connect` function in the `tests` module? In the `tests` module, we can -either use leading colons to let Rust know that we want to start from the root -and list the whole path, like this: - -``` -::client::connect(); -``` - -Or, we can use `super` to move up one module in the hierarchy from our current -module, like this: - -``` -super::client::connect(); -``` - -These two options don’t look that different in this example, but if you’re -deeper in a module hierarchy, starting from the root every time would make your -code lengthy. In those cases, using `super` to get from the current module to -sibling modules is a good shortcut. Plus, if you’ve specified the path from the -root in many places in your code and then rearrange your modules by moving a -subtree to another place, you’ll end up needing to update the path in several -places, which would be tedious. - -It would also be annoying to have to type `super::` in each test, but you’ve -already seen the tool for that solution: `use`! The `super::` functionality -changes the path you give to `use` so it is relative to the parent module -instead of to the root module. - -For these reasons, in the `tests` module especially, `use super::something` is -usually the best solution. So now our test looks like this: - -Filename: src/lib.rs - -``` -#[cfg(test)] -mod tests { - use super::client; - - #[test] - fn it_works() { - client::connect(); - } -} -``` - -When we run `cargo test` again, the test will pass, and the first part of the -test result output will be the following: - -``` -$ cargo test - Compiling communicator v0.1.0 (file:///projects/communicator) - Running target/debug/communicator-92007ddb5330fa5a - -running 1 test -test tests::it_works ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out -``` - -## Summary - -Now you know some new techniques for organizing your code! Use these techniques -to group related functionality together, keep files from becoming too long, and -present a tidy public API to your library users. - -Next, we’ll look at some collection data structures in the standard library -that you can use in your nice, neat code. diff --git a/second-edition/nostarch/chapter08.md b/second-edition/nostarch/chapter08.md deleted file mode 100644 index c824e9045b..0000000000 --- a/second-edition/nostarch/chapter08.md +++ /dev/null @@ -1,1046 +0,0 @@ - -[TOC] - -# Common Collections - -Rust’s standard library includes a number of very useful data structures called -*collections*. Most other data types represent one specific value, but -collections can contain multiple values. Unlike the built-in array and tuple -types, the data these collections point to is stored on the heap, which means -the amount of data does not need to be known at compile time and can grow or -shrink as the program runs. Each kind of collection has different capabilities -and costs, and choosing an appropriate one for your current situation is a -skill you’ll develop over time. In this chapter, we’ll discuss three -collections that are used very often in Rust programs: - -* A *vector* allows you to store a variable number of values next to each other. -* A *string* is a collection of characters. We’ve mentioned the `String` type - previously, but in this chapter we’ll talk about it in depth. -* A *hash map* allows you to associate a value with a particular key. It’s a - particular implementation of the more general data structure called a *map*. - -To learn about the other kinds of collections provided by the standard library, -see the documentation at *https://doc.rust-lang.org/stable/std/collections/*. - -We’ll discuss how to create and update vectors, strings, and hash maps, as well -as what makes each special. - -## Storing Lists of Values with Vectors - -The first collection type we’ll look at is `Vec`, also known as a *vector*. -Vectors allow you to store more than one value in a single data structure that -puts all the values next to each other in memory. Vectors can only store values -of the same type. They are useful when you have a list of items, such as the -lines of text in a file or the prices of items in a shopping cart. - -### Creating a New Vector - -To create a new, empty vector, we can call the `Vec::new` function, as shown in -Listing 8-1: - -``` -let v: Vec = Vec::new(); -``` - -Listing 8-1: Creating a new, empty vector to hold values of type `i32` - -Note that we added a type annotation here. Because we aren’t inserting any -values into this vector, Rust doesn’t know what kind of elements we intend to -store. This is an important point. Vectors are implemented using generics; -we’ll cover how to use generics with your own types in Chapter 10. For now, -know that the `Vec` type provided by the standard library can hold any type, -and when a specific vector holds a specific type, the type is specified within -angle brackets. In Listing 8-1, we’ve told Rust that the `Vec` in `v` will -hold elements of the `i32` type. - -In more realistic code, Rust can often infer the type of value you want to -store once you insert values, so you rarely need to do this type annotation. -It’s more common to create a `Vec` that has initial values, and Rust -provides the `vec!` macro for convenience. The macro will create a new vector -that holds the values you give it. Listing 8-2 creates a new `Vec` that -holds the values `1`, `2`, and `3`: - -``` -let v = vec![1, 2, 3]; -``` - -Listing 8-2: Creating a new vector containing values - -Because we’ve given initial `i32` values, Rust can infer that the type of `v` -is `Vec`, and the type annotation isn’t necessary. Next, we’ll look at how -to modify a vector. - -### Updating a Vector - -To create a vector and then add elements to it, we can use the `push` method, -as shown in Listing 8-3: - -``` -let mut v = Vec::new(); - -v.push(5); -v.push(6); -v.push(7); -v.push(8); -``` - -Listing 8-3: Using the `push` method to add values to a vector - -As with any variable, if we want to be able to change its value, we need to -make it mutable using the `mut` keyword, as discussed in Chapter 3. The numbers -we place inside are all of type `i32`, and Rust infers this from the data, so -we don’t need the `Vec` annotation. - -### Dropping a Vector Drops Its Elements - -Like any other `struct`, a vector is freed when it goes out of scope, as -annotated in Listing 8-4: - -``` -{ - let v = vec![1, 2, 3, 4]; - - // do stuff with v - -} // <- v goes out of scope and is freed here -``` - -Listing 8-4: Showing where the vector and its elements are dropped - -When the vector gets dropped, all of its contents are also dropped, meaning -those integers it holds will be cleaned up. This may seem like a -straightforward point but can get a bit more complicated when you start to -introduce references to the elements of the vector. Let’s tackle that next! - -### Reading Elements of Vectors - -Now that you know how to create, update, and destroy vectors, knowing how to -read their contents is a good next step. There are two ways to reference a -value stored in a vector. In the examples, we’ve annotated the types of the -values that are returned from these functions for extra clarity. - -Listing 8-5 shows both methods of accessing a value in a vector, either with -indexing syntax or the `get` method: - -``` -let v = vec![1, 2, 3, 4, 5]; - -let third: &i32 = &v[2]; -let third: Option<&i32> = v.get(2); -``` - -Listing 8-5: Using indexing syntax or the `get` method to access an item in a -vector - -Note two details here. First, we use the index value of `2` to get the third -element: vectors are indexed by number, starting at zero. Second, the two ways -to get the third element are by using `&` and `[]`, which gives us a reference, -or by using the `get` method with the index passed as an argument, which gives -us an `Option<&T>`. - -Rust has two ways to reference an element so you can choose how the program -behaves when you try to use an index value that the vector doesn’t have an -element for. As an example, let’s see what a program will do if it has a vector -that holds five elements and then tries to access an element at index 100, as -shown in Listing 8-6: - -``` -let v = vec![1, 2, 3, 4, 5]; - -let does_not_exist = &v[100]; -let does_not_exist = v.get(100); -``` - -Listing 8-6: Attempting to access the element at index 100 in a vector -containing five elements - -When we run this code, the first `[]` method will cause the program to panic -because it references a nonexistent element. This method is best used when you -want your program to crash if there’s an attempt to access an element past the -end of the vector. - -When the `get` method is passed an index that is outside the vector, it returns -`None` without panicking. You would use this method if accessing an element -beyond the range of the vector happens occasionally under normal circumstances. -Your code will then have logic to handle having either `Some(&element)` or -`None`, as discussed in Chapter 6. For example, the index could be coming from -a person entering a number. If they accidentally enter a number that’s too -large and the program gets a `None` value, you could tell the user how many -items are in the current vector and give them another chance to enter a valid -value. That would be more user-friendly than crashing the program due to a typo! - -When the program has a valid reference, the borrow checker enforces the -ownership and borrowing rules (covered in Chapter 4) to ensure this reference -and any other references to the contents of the vector remain valid. Recall the -rule that states you can’t have mutable and immutable references in the same -scope. That rule applies in Listing 8-7, where we hold an immutable reference to -the first element in a vector and try to add an element to the end, which won’t -work: - -``` -let mut v = vec![1, 2, 3, 4, 5]; - -let first = &v[0]; - -v.push(6); -``` - -Listing 8-7: Attempting to add an element to a vector while holding a reference -to an item - -Compiling this code will result in this error: - -``` -error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable - --> - | -4 | let first = &v[0]; - | - immutable borrow occurs here -5 | -6 | v.push(6); - | ^ mutable borrow occurs here -7 | -8 | } - | - immutable borrow ends here -``` - -The code in Listing 8-7 might look like it should work: why should a reference -to the first element care about what changes at the end of the vector? This -error is due to the way vectors work: adding a new element onto the end of the -vector might require allocating new memory and copying the old elements to the -new space, if there isn’t enough room to put all the elements next to each -other where the vector currently is. In that case, the reference to the first -element would be pointing to deallocated memory. The borrowing rules prevent -programs from ending up in that situation. - -> Note: For more on the implementation details of the `Vec` type, see “The -> Rustonomicon” at https://doc.rust-lang.org/stable/nomicon/vec.html. - -### Iterating over the Values in a Vector - -If we want to access each element in a vector in turn, we can iterate through -all of the elements rather than use indexes to access one at a time. Listing -8-8 shows how to use a `for` loop to get immutable references to each element -in a vector of `i32` values and print them: - -``` -let v = vec![100, 32, 57]; -for i in &v { - println!("{}", i); -} -``` - -Listing 8-8: Printing each element in a vector by iterating over the elements -using a `for` loop - -We can also iterate over mutable references to each element in a mutable vector -in order to make changes to all the elements. The `for` loop in Listing 8-9 -will add `50` to each element: - -``` -let mut v = vec![100, 32, 57]; -for i in &mut v { - *i += 50; -} -``` - -Listing 8-9: Iterating over mutable references to elements in a vector - -To change the value that the mutable reference refers to, we have to use the -dereference operator (`*`) to get to the value in `i` before we can use the -`+=` operator . - -### Using an Enum to Store Multiple Types - -At the beginning of this chapter, we said that vectors can only store values -that are the same type. This can be inconvenient; there are definitely use -cases for needing to store a list of items of different types. Fortunately, the -variants of an enum are defined under the same enum type, so when we need to -store elements of a different type in a vector, we can define and use an enum! - -For example, say we want to get values from a row in a spreadsheet in which -some of the columns in the row contain integers, some floating-point numbers, -and some strings. We can define an enum whose variants will hold the different -value types, and then all the enum variants will be considered the same type: -that of the enum. Then we can create a vector that holds that enum and so, -ultimately, holds different types. We’ve demonstrated this in Listing 8-10: - -``` -enum SpreadsheetCell { - Int(i32), - Float(f64), - Text(String), -} - -let row = vec![ - SpreadsheetCell::Int(3), - SpreadsheetCell::Text(String::from("blue")), - SpreadsheetCell::Float(10.12), -]; -``` - -Listing 8-10: Defining an `enum` to store values of different types in one -vector - -Rust needs to know what types will be in the vector at compile time so it knows -exactly how much memory on the heap will be needed to store each element. A -secondary advantage is that we can be explicit about what types are allowed in -this vector. If Rust allowed a vector to hold any type, there would be a chance -that one or more of the types would cause errors with the operations performed -on the elements of the vector. Using an enum plus a `match` expression means -that Rust will ensure at compile time that every possible case is handled, as -discussed in Chapter 6. - -When you’re writing a program, if you don’t know the exhaustive set of types -the program will get at runtime to store in a vector, the enum technique won’t -work. Instead, you can use a trait object, which we’ll cover in Chapter 17. - -Now that we’ve discussed some of the most common ways to use vectors, be sure -to review the API documentation for all the many useful methods defined on -`Vec` by the standard library. For example, in addition to `push`, a `pop` -method removes and returns the last element. Let’s move on to the next -collection type: `String`! - -## Storing UTF-8 Encoded Text with Strings - -We talked about strings in Chapter 4, but we’ll look at them in more depth now. -New Rustaceans commonly get stuck on strings due to a combination of three -reasons: Rust’s propensity for exposing possible errors, strings being a more -complicated data structure than many programmers give them credit for, and -UTF-8. These factors combine in a way that can seem difficult when you’re -coming from other programming languages. - -It’s useful to discuss strings in the context of collections because strings -are implemented as a collection of bytes, plus some methods to provide useful -functionality when those bytes are interpreted as text. In this section, we’ll -talk about the operations on `String` that every collection type has, such as -creating, updating, and reading. We’ll also discuss the ways in which `String` -is different from the other collections, namely how indexing into a `String` is -complicated by the differences between how people and computers interpret -`String` data. - -### What Is a String? - -We’ll first define what we mean by the term *string*. Rust has only one string -type in the core language, which is the string slice `str` that is usually seen -in its borrowed form `&str`. In Chapter 4, we talked about *string slices*, -which are references to some UTF-8 encoded string data stored elsewhere. String -literals, for example, are stored in the binary output of the program and are -therefore string slices. - -The `String` type, which is provided by Rust’s standard library rather than -coded into the core language, is a growable, mutable, owned, UTF-8 encoded -string type. When Rustaceans refer to “strings” in Rust, they usually mean the -`String` and the string slice `&str` types, not just one of those types. -Although this section is largely about `String`, both types are used heavily in -Rust’s standard library, and both `String` and string slices are UTF-8 encoded. - -Rust’s standard library also includes a number of other string types, such as -`OsString`, `OsStr`, `CString`, and `CStr`. Library crates can provide even -more options for storing string data. See how those names all end in `String` -or `Str`? They refer to owned and borrowed variants, just like the `String` and -`str` types you’ve seen previously. These string types can store text in -different encodings or be represented in memory in a different way, for -example. We won’t discuss these other string types in this chapter; see their -API documentation for more about how to use them and when each is appropriate. - -### Creating a New String - -Many of the same operations available with `Vec` are available with `String` -as well, starting with the `new` function to create a string, shown in Listing -8-11: - -``` -let mut s = String::new(); -``` - -Listing 8-11: Creating a new, empty `String` - -This line creates a new empty string called `s`, which we can then load data -into. Often, we’ll have some initial data that we want to start the string -with. For that, we use the `to_string` method, which is available on any type -that implements the `Display` trait, as string literals do. Listing 8-12 shows -two examples: - -``` -let data = "initial contents"; - -let s = data.to_string(); - -// the method also works on a literal directly: -let s = "initial contents".to_string(); -``` - -Listing 8-12: Using the `to_string` method to create a `String` from a string -literal - -This code creates a string containing `initial contents`. - -We can also use the function `String::from` to create a `String` from a string -literal. The code in Listing 8-13 is equivalent to the code from Listing 8-12 -that uses `to_string`: - -``` -let s = String::from("initial contents"); -``` - -Listing 8-13: Using the `String::from` function to create a `String` from a -string literal - -Because strings are used for so many things, we can use many different generic -APIs for strings, providing us with a lot of options. Some of them can seem -redundant, but they all have their place! In this case, `String::from` and -`to_string` do the same thing, so which you choose is a matter of style. - -Remember that strings are UTF-8 encoded, so we can include any properly encoded -data in them, as shown in Listing 8-14: - -``` -let hello = String::from("السلام عليكم"); -let hello = String::from("Dobrý den"); -let hello = String::from("Hello"); -let hello = String::from("שָׁלוֹם"); -let hello = String::from("नमस्ते"); -let hello = String::from("こんにちは"); -let hello = String::from("안녕하세요"); -let hello = String::from("你好"); -let hello = String::from("Olá"); -let hello = String::from("Здравствуйте"); -let hello = String::from("Hola"); -``` - -Listing 8-14: Storing greetings in different languages in strings - -All of these are valid `String` values. - -### Updating a String - -A `String` can grow in size and its contents can change, just like the contents -of a `Vec`, if you push more data into it. In addition, you can conveniently -use the `+` operator or the `format!` macro to concatenate `String` values. - -#### Appending to a String with `push_str` and `push` - -We can grow a `String` by using the `push_str` method to append a string slice, -as shown in Listing 8-15: - -``` -let mut s = String::from("foo"); -s.push_str("bar"); -``` - -Listing 8-15: Appending a string slice to a `String` using the `push_str` method - -After these two lines, `s` will contain `foobar`. The `push_str` method takes a -string slice because we don’t necessarily want to take ownership of the -parameter. For example, the code in Listing 8-16 shows that it would be -unfortunate if we weren’t able to use `s2` after appending its contents to `s1`: - -``` -let mut s1 = String::from("foo"); -let s2 = "bar"; -s1.push_str(s2); -println!("s2 is {}", s2); -``` - -Listing 8-16: Using a string slice after appending its contents to a `String` - -If the `push_str` method took ownership of `s2`, we wouldn’t be able to print -its value on the last line. However, this code works as we’d expect! - -The `push` method takes a single character as a parameter and adds it to the -`String`. Listing 8-17 shows code that adds the letter l to a `String` using -the `push` method: - -``` -let mut s = String::from("lo"); -s.push('l'); -``` - -Listing 8-17: Adding one character to a `String` value using `push` - -As a result of this code, `s` will contain `lol`. - -#### Concatenation with the `+` Operator or the `format!` Macro - -Often, you’ll want to combine two existing strings. One way is to use the `+` -operator, as shown in Listing 8-18: - -``` -let s1 = String::from("Hello, "); -let s2 = String::from("world!"); -let s3 = s1 + &s2; // Note s1 has been moved here and can no longer be used -``` - -Listing 8-18: Using the `+` operator to combine two `String` values into a new -`String` value - -The string `s3` will contain `Hello, world!` as a result of this code. The -reason `s1` is no longer valid after the addition and the reason we used a -reference to `s2` has to do with the signature of the method that gets called -when we use the `+` operator. The `+` operator uses the `add` method, whose -signature looks something like this: - -``` -fn add(self, s: &str) -> String { -``` - -This isn’t the exact signature that’s in the standard library: in the standard -library, `add` is defined using generics. Here, we’re looking at the signature -of `add` with concrete types substituted for the generic ones, which is what -happens when we call this method with `String` values. We’ll discuss generics -in Chapter 10. This signature gives us the clues we need to understand the -tricky bits of the `+` operator. - -First, `s2` has an `&`, meaning that we’re adding a *reference* of the second -string to the first string because of the `s` parameter in the `add` function: -we can only add a `&str` to a `String`; we can’t add two `String` values -together. But wait—the type of `&s2` is `&String`, not `&str`, as specified in -the second parameter to `add`. So why does Listing 8-18 compile? - -The reason we’re able to use `&s2` in the call to `add` is that the compiler -can *coerce* the `&String` argument into a `&str`. When we call the `add` -method, Rust uses a *deref coercion*, which here turns `&s2` into `&s2[..]`. -We’ll discuss deref coercion in more depth in Chapter 15. Because `add` does -not take ownership of the `s` parameter, `s2` will still be a valid `String` -after this operation. - -Second, we can see in the signature that `add` takes ownership of `self`, -because `self` does *not* have an `&`. This means `s1` in Listing 8-18 will be -moved into the `add` call and no longer be valid after that. So although `let -s3 = s1 + &s2;` looks like it will copy both strings and create a new one, this -statement actually takes ownership of `s1`, appends a copy of the contents of -`s2`, and then returns ownership of the result. In other words, it looks like -it’s making a lot of copies but isn’t; the implementation is more efficient -than copying. - -If we need to concatenate multiple strings, the behavior of the `+` operator -gets unwieldy: - -``` -let s1 = String::from("tic"); -let s2 = String::from("tac"); -let s3 = String::from("toe"); - -let s = s1 + "-" + &s2 + "-" + &s3; -``` - -At this point, `s` will be `tic-tac-toe`. With all of the `+` and `"` -characters, it’s difficult to see what’s going on. For more complicated string -combining, we can use the `format!` macro: - -``` -let s1 = String::from("tic"); -let s2 = String::from("tac"); -let s3 = String::from("toe"); - -let s = format!("{}-{}-{}", s1, s2, s3); -``` - -This code also sets `s` to `tic-tac-toe`. The `format!` macro works in the same -way as `println!`, but instead of printing the output to the screen, it returns -a `String` with the contents. The version of the code using `format!` is much -easier to read and doesn’t take ownership of any of its parameters. - -### Indexing into Strings - -In many other programming languages, accessing individual characters in a -string by referencing them by index is a valid and common operation. However, -if you try to access parts of a `String` using indexing syntax in Rust, you’ll -get an error. Consider the invalid code in Listing 8-19: - -``` -let s1 = String::from("hello"); -let h = s1[0]; -``` - -Listing 8-19: Attempting to use indexing syntax with a String - -This code will result in the following error: - -``` -error[E0277]: the trait bound `std::string::String: std::ops::Index<{integer}>` is not satisfied - --> - | -3 | let h = s1[0]; - | ^^^^^ the type `std::string::String` cannot be indexed by `{integer}` - | - = help: the trait `std::ops::Index<{integer}>` is not implemented for `std::string::String` -``` - -The error and the note tell the story: Rust strings don’t support indexing. But -why not? To answer that question, we need to discuss how Rust stores strings in -memory. - -#### Internal Representation - -A `String` is a wrapper over a `Vec`. Let’s look at some of our properly -encoded UTF-8 example strings from Listing 8-14. First, this one: - -``` -let len = String::from("Hola").len(); -``` - -In this case, `len` will be 4, which means the vector storing the string “Hola” -is 4 bytes long. Each of these letters takes 1 byte when encoded in UTF-8. But -what about the following line? (Note that this line begins with the capital -Cyrillic letter Ze, not the Arabic number 3.) - -``` -let len = String::from("Здравствуйте").len(); -``` - -Asked how long the string is, you might say 12. However, Rust’s answer is 24: -that’s the number of bytes it takes to encode “Здравствуйте” in UTF-8, because -each Unicode scalar value takes 2 bytes of storage. Therefore, an index into -the string’s bytes will not always correlate to a valid Unicode scalar value. -To demonstrate, consider this invalid Rust code: - -``` -let hello = "Здравствуйте"; -let answer = &hello[0]; -``` - -What should the value of `answer` be? Should it be `З`, the first letter? When -encoded in UTF-8, the first byte of `З` is `208` and the second is `151`, so -`answer` should in fact be `208`, but `208` is not a valid character on its -own. Returning `208` is likely not what a user would want if they asked for the -first letter of this string; however, that’s the only data that Rust has at -byte index 0. Users generally don’t want the byte value returned, even if the -string contains only Latin letters: if `&"hello"[0]` were valid code that -returned the byte value, it would return `104`, not `h`. To avoid returning an -unexpected value and causing bugs that might not be discovered immediately, -Rust doesn’t compile this code at all and prevents misunderstandings early in -the development process. - -#### Bytes and Scalar Values and Grapheme Clusters! Oh My! - -Another point about UTF-8 is that there are actually three relevant ways to -look at strings from Rust’s perspective: as bytes, scalar values, and grapheme -clusters (the closest thing to what we would call *letters*). - -If we look at the Hindi word “नमस्ते” written in the Devanagari script, it is -stored as a vector of `u8` values that looks like this: - -``` -[224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164, -224, 165, 135] -``` - -That’s 18 bytes and is how computers ultimately store this data. If we look at -them as Unicode scalar values, which are what Rust’s `char` type is, those -bytes look like this: - -``` -['न', 'म', 'स', '्', 'त', 'े'] -``` - -There are six `char` values here, but the fourth and sixth are not letters: -they’re diacritics that don’t make sense on their own. Finally, if we look at -them as grapheme clusters, we’d get what a person would call the four letters -that make up the Hindi word: - -``` -["न", "म", "स्", "ते"] -``` - -Rust provides different ways of interpreting the raw string data that computers -store so that each program can choose the interpretation it needs, no matter -what human language the data is in. - -A final reason Rust doesn’t allow us to index into a `String` to get a -character is that indexing operations are expected to always take constant time -(O(1)). But it isn’t possible to guarantee that performance with a `String`, -because Rust would have to walk through the contents from the beginning to the -index to determine how many valid characters there were. - -### Slicing Strings - -Indexing into a string is often a bad idea because it’s not clear what the -return type of the string-indexing operation should be: a byte value, a -character, a grapheme cluster, or a string slice. Therefore, Rust asks you to -be more specific if you really need to use indices to create string slices. To -be more specific in your indexing and indicate that you want a string slice, -rather than indexing using `[]` with a single number, you can use `[]` with a -range to create a string slice containing particular bytes: - -``` -let hello = "Здравствуйте"; - -let s = &hello[0..4]; -``` - -Here, `s` will be a `&str` that contains the first 4 bytes of the string. -Earlier, we mentioned that each of these characters was 2 bytes, which means -`s` will be `Зд`. - -What would happen if we used `&hello[0..1]`? The answer: Rust would panic at -runtime in the same way as if an invalid index were accessed in a vector: - -``` -thread 'main' panicked at 'byte index 1 is not a char boundary; it is inside 'З' (bytes 0..2) of `Здравствуйте`', src/libcore/str/mod.rs:2188:4 -``` - -You should use ranges to create string slices with caution, because doing so -can crash your program. - -### Methods for Iterating Over Strings - -Fortunately, you can access elements in a string in other ways. - -If you need to perform operations on individual Unicode scalar values, the best -way to do so is to use the `chars` method. Calling `chars` on “नमस्ते” separates -out and returns six values of type `char`, and you can iterate over the result -in order to access each element: - -``` -for c in "नमस्ते".chars() { - println!("{}", c); -} -``` - -This code will print the following: - -``` -न -म -स -् -त -े -``` - -The `bytes` method returns each raw byte, which might be appropriate for your -domain: - -``` -for b in "नमस्ते".bytes() { - println!("{}", b); -} -``` - -This code will print the 18 bytes that make up this `String`: - -``` -224 -164 -// --snip-- -165 -135 -``` - -But be sure to remember that valid Unicode scalar values may be made up of more -than 1 byte. - -Getting grapheme clusters from strings is complex, so this functionality is not -provided by the standard library. Crates are available on -crates.io at *https://crates.io* if this is the functionality you need. - -### Strings Are Not So Simple - -To summarize, strings are complicated. Different programming languages make -different choices about how to present this complexity to the programmer. Rust -has chosen to make the correct handling of `String` data the default behavior -for all Rust programs, which means programmers have to put more thought into -handling UTF-8 data upfront. This trade-off exposes more of the complexity of -strings than is apparent in other programming languages, but it prevents you -from having to handle errors involving non-ASCII characters later in your -development life cycle. - -Let’s switch to something a bit less complex: hash maps! - -## Storing Keys with Associated Values in Hash Maps - -The last of our common collections is the *hash map*. The type `HashMap` -stores a mapping of keys of type `K` to values of type `V`. It does this via a -*hashing function*, which determines how it places these keys and values into -memory. Many programming languages support this kind of data structure, but -they often use a different name, such as hash, map, object, hash table, or -associative array, just to name a few. - -Hash maps are useful when you want to look up data not by using an index, as -you can with vectors, but by using a key that can be of any type. For example, -in a game, you could keep track of each team’s score in a hash map in which -each key is a team’s name and the values are each team’s score. Given a team -name, you can retrieve its score. - -We’ll go over the basic API of hash maps in this section, but many more goodies -are hiding in the functions defined on `HashMap` by the standard library. -As always, check the standard library documentation for more information. - -### Creating a New Hash Map - -You can create an empty hash map with `new` and add elements with `insert`. In -Listing 8-20, we’re keeping track of the scores of two teams whose names are -Blue and Yellow. The Blue team starts with 10 points, and the Yellow team -starts with 50: - -``` -use std::collections::HashMap; - -let mut scores = HashMap::new(); - -scores.insert(String::from("Blue"), 10); -scores.insert(String::from("Yellow"), 50); -``` - -Listing 8-20: Creating a new hash map and inserting some keys and values - -Note that we need to first `use` the `HashMap` from the collections portion of -the standard library. Of our three common collections, this one is the least -often used, so it’s not included in the features brought into scope -automatically in the prelude. Hash maps also have less support from the -standard library; there’s no built-in macro to construct them, for example. - -Just like vectors, hash maps store their data on the heap. This `HashMap` has -keys of type `String` and values of type `i32`. Like vectors, hash maps are -homogeneous: all of the keys must have the same type, and all of the values -must have the same type. - -Another way of constructing a hash map is by using the `collect` method on a -vector of tuples, where each tuple consists of a key and its value. The -`collect` method gathers data into a number of collection types, including -`HashMap`. For example, if we had the team names and initial scores in two -separate vectors, we could use the `zip` method to create a vector of tuples -where “Blue” is paired with 10, and so forth. Then we could use the `collect` -method to turn that vector of tuples into a hash map, as shown in Listing 8-21: - -``` -use std::collections::HashMap; - -let teams = vec![String::from("Blue"), String::from("Yellow")]; -let initial_scores = vec![10, 50]; - -let scores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collect(); -``` - -Listing 8-21: Creating a hash map from a list of teams and a list of scores - -The type annotation `HashMap<_, _>` is needed here because it’s possible to -`collect` into many different data structures and Rust doesn’t know which you -want unless you specify. For the parameters for the key and value types, -however, we use underscores, and Rust can infer the types that the hash map -contains based on the types of the data in the vectors. - -### Hash Maps and Ownership - -For types that implement the `Copy` trait, like `i32`, the values are copied -into the hash map. For owned values like `String`, the values will be moved and -the hash map will be the owner of those values, as demonstrated in Listing 8-22: - -``` -use std::collections::HashMap; - -let field_name = String::from("Favorite color"); -let field_value = String::from("Blue"); - -let mut map = HashMap::new(); -map.insert(field_name, field_value); -// field_name and field_value are invalid at this point, try using them and -// see what compiler error you get! -``` - -Listing 8-22: Showing that keys and values are owned by the hash map once -they’re inserted - -We aren’t able to use the variables `field_name` and `field_value` after -they’ve been moved into the hash map with the call to `insert`. - -If we insert references to values into the hash map, the values won’t be moved -into the hash map. The values that the references point to must be valid for at -least as long as the hash map is valid. We’ll talk more about these issues in -the “Validating References with Lifetimes” section in Chapter 10. - -### Accessing Values in a Hash Map - -We can get a value out of the hash map by providing its key to the `get` -method, as shown in Listing 8-23: - -``` -use std::collections::HashMap; - -let mut scores = HashMap::new(); - -scores.insert(String::from("Blue"), 10); -scores.insert(String::from("Yellow"), 50); - -let team_name = String::from("Blue"); -let score = scores.get(&team_name); -``` - -Listing 8-23: Accessing the score for the Blue team stored in the hash map - -Here, `score` will have the value that’s associated with the Blue team, and the -result will be `Some(&10)`. The result is wrapped in `Some` because `get` -returns an `Option<&V>`; if there’s no value for that key in the hash map, -`get` will return `None`. The program will need to handle the `Option` in one -of the ways that we covered in Chapter 6. - -We can iterate over each key/value pair in a hash map in a similar manner as we -do with vectors, using a `for` loop: - -``` -use std::collections::HashMap; - -let mut scores = HashMap::new(); - -scores.insert(String::from("Blue"), 10); -scores.insert(String::from("Yellow"), 50); - -for (key, value) in &scores { - println!("{}: {}", key, value); -} -``` - -This code will print each pair in an arbitrary order: - -``` -Yellow: 50 -Blue: 10 -``` - -### Updating a Hash Map - -Although the number of keys and values is growable, each key can only have one -value associated with it at a time. When you want to change the data in a hash -map, you have to decide how to handle the case when a key already has a value -assigned. You could replace the old value with the new value, completely -disregarding the old value. You could keep the old value and ignore the new -value, only adding the new value if the key *doesn’t* already have a value. Or -you could combine the old value and the new value. Let’s look at how to do each -of these! - -#### Overwriting a Value - -If we insert a key and a value into a hash map and then insert that same key -with a different value, the value associated with that key will be replaced. -Even though the code in Listing 8-24 calls `insert` twice, the hash map will -only contain one key/value pair because we’re inserting the value for the Blue -team’s key both times: - -``` -use std::collections::HashMap; - -let mut scores = HashMap::new(); - -scores.insert(String::from("Blue"), 10); -scores.insert(String::from("Blue"), 25); - -println!("{:?}", scores); -``` - -Listing 8-24: Replacing a value stored with a particular key - -This code will print `{"Blue": 25}`. The original value of `10` has been -overwritten. - -#### Only Inserting a Value If the Key Has No Value - -It’s common to check whether a particular key has a value and, if it doesn’t, -insert a value for it. Hash maps have a special API for this called `entry` -that takes the key you want to check as a parameter. The return value of the -`entry` function is an enum called `Entry` that represents a value that might -or might not exist. Let’s say we want to check whether the key for the Yellow -team has a value associated with it. If it doesn’t, we want to insert the value -50, and the same for the Blue team. Using the `entry` API, the code looks like -Listing 8-25: - -``` -use std::collections::HashMap; - -let mut scores = HashMap::new(); -scores.insert(String::from("Blue"), 10); - -scores.entry(String::from("Yellow")).or_insert(50); -scores.entry(String::from("Blue")).or_insert(50); - -println!("{:?}", scores); -``` - -Listing 8-25: Using the `entry` method to only insert if the key does not -already have a value - -The `or_insert` method on `Entry` is defined to return a mutable reference to -the value for the corresponding `Entry` key if that key exists, and if not, -inserts the parameter as the new value for this key and returns a mutable -reference to the new value. This technique is much cleaner than writing the -logic ourselves and, in addition, plays more nicely with the borrow checker. - -Running the code in Listing 8-25 will print `{"Yellow": 50, "Blue": 10}`. The -first call to `entry` will insert the key for the Yellow team with the value -`50` because the Yellow team doesn’t have a value already. The second call to -`entry` will not change the hash map because the Blue team already has the -value `10`. - -#### Updating a Value Based on the Old Value - -Another common use case for hash maps is to look up a key’s value and then -update it based on the old value. For instance, Listing 8-26 shows code that -counts how many times each word appears in some text. We use a hash map with -the words as keys and increment the value to keep track of how many times we’ve -seen that word. If it’s the first time we’ve seen a word, we’ll first insert -the value `0`: - -``` -use std::collections::HashMap; - -let text = "hello world wonderful world"; - -let mut map = HashMap::new(); - -for word in text.split_whitespace() { - let count = map.entry(word).or_insert(0); - *count += 1; -} - -println!("{:?}", map); -``` - -Listing 8-26: Counting occurrences of words using a hash map that stores words -and counts - -This code will print `{"world": 2, "hello": 1, "wonderful": 1}`. The -`or_insert` method actually returns a mutable reference (`&mut V`) to the value -for this key. Here we store that mutable reference in the `count` variable, so -in order to assign to that value, we must first dereference `count` using the -asterisk (`*`). The mutable reference goes out of scope at the end of the `for` -loop, so all of these changes are safe and allowed by the borrowing rules. - -### Hashing Functions - -By default, `HashMap` uses a cryptographically secure hashing function that can -provide resistance to Denial of Service (DoS) attacks. This is not the fastest -hashing algorithm available, but the trade-off for better security that comes -with the drop in performance is worth it. If you profile your code and find -that the default hash function is too slow for your purposes, you can switch to -another function by specifying a different *hasher*. A hasher is a type that -implements the `BuildHasher` trait. We’ll talk about traits and how to -implement them in Chapter 10. You don’t necessarily have to implement your own -hasher from scratch; crates.io at *https://crates.io* has libraries shared by -other Rust users that provide hashers implementing many common hashing -algorithms. - -## Summary - -Vectors, strings, and hash maps will provide a large amount of functionality -necessary in programs when you need to store, access, and modify data. Here are -some exercises you should now be equipped to solve: - -* Given a list of integers, use a vector and return the mean (the average - value), median (when sorted, the value in the middle position), and mode (the - value that occurs most often; a hash map will be helpful here) of the list. -* Convert strings to pig latin. The first consonant of each word is moved to - the end of the word and “ay” is added, so “first” becomes “irst-fay.” Words - that start with a vowel have “hay” added to the end instead (“apple” becomes - “apple-hay”). Keep in mind the details about UTF-8 encoding! -* Using a hash map and vectors, create a text interface to allow a user to add - employee names to a department in a company. For example, “Add Sally to - Engineering” or “Add Amir to Sales.” Then let the user retrieve a list of all - people in a department or all people in the company by department, sorted - alphabetically. - -The standard library API documentation describes methods that vectors, strings, -and hash maps have that will be helpful for these exercises! - -We’re getting into more complex programs in which operations can fail, so, it’s -a perfect time to discuss error handling. We’ll do that next! diff --git a/second-edition/nostarch/chapter09.md b/second-edition/nostarch/chapter09.md deleted file mode 100644 index cc0823df69..0000000000 --- a/second-edition/nostarch/chapter09.md +++ /dev/null @@ -1,938 +0,0 @@ - -[TOC] - -# Error Handling - -Rust’s commitment to reliability extends to error handling. Errors are a fact -of life in software, so Rust has a number of features for handling situations -in which something goes wrong. In many cases, Rust requires you to acknowledge -the possibility of an error and take some action before your code will compile. -This requirement makes your program more robust by ensuring that you’ll -discover errors and handle them appropriately before you’ve deployed your code -to production! - -Rust groups errors into two major categories: *recoverable* and *unrecoverable* -errors. For a recoverable error, such as a file not found error, it’s -reasonable to report the problem to the user and retry the operation. -Unrecoverable errors are always symptoms of bugs, like trying to access a -location beyond the end of an array. - -Most languages don’t distinguish between these two kinds of errors and handle -both in the same way, using mechanisms such as exceptions. Rust doesn’t have -exceptions. Instead, it has the type `Result` for recoverable errors and -the `panic!` macro that stops execution when the program encounters an -unrecoverable error. This chapter covers calling `panic!` first and then talks -about returning `Result` values. Additionally, we’ll explore -considerations when deciding whether to try to recover from an error or to stop -execution. - -## Unrecoverable Errors with `panic!` - -Sometimes, bad things happen in your code, and there’s nothing you can do about -it. In these cases, Rust has the `panic!` macro. When the `panic!` macro -executes, your program will print a failure message, unwind and clean up the -stack, and then quit. This most commonly occurs when a bug of some kind has -been detected and it’s not clear to the programmer how to handle the error. - -> ### Unwinding the Stack or Aborting in Response to a Panic -> -> By default, when a panic occurs, the program starts *unwinding*, which -> means Rust walks back up the stack and cleans up the data from each function -> it encounters. But this walking back and cleanup is a lot of work. The -> alternative is to immediately *abort*, which ends the program without -> cleaning up. Memory that the program was using will then need to be cleaned -> up by the operating system. If in your project you need to make the resulting -> binary as small as possible, you can switch from unwinding to aborting upon a -> panic by adding `panic = 'abort'` to the appropriate `[profile]` sections in -> your *Cargo.toml* file. For example, if you want to abort on panic in release -> mode, add this: -> -> ``` -> [profile.release] -> panic = 'abort' -> ``` - -Let’s try calling `panic!` in a simple program: - -Filename: src/main.rs - -``` -fn main() { - panic!("crash and burn"); -} -``` - -When you run the program, you’ll see something like this: - -``` -$ cargo run - Compiling panic v0.1.0 (file:///projects/panic) - Finished dev [unoptimized + debuginfo] target(s) in 0.25 secs - Running `target/debug/panic` -thread 'main' panicked at 'crash and burn', src/main.rs:2:4 -note: Run with `RUST_BACKTRACE=1` for a backtrace. -``` - -The call to `panic!` causes the error message contained in the last three -lines. The first line shows our panic message and the place in our source code -where the panic occurred: *src/main.rs:2:4* indicates that it’s the second -line, fourth character of our *src/main.rs* file. - -In this case, the line indicated is part of our code, and if we go to that -line, we see the `panic!` macro call. In other cases, the `panic!` call might -be in code that our code calls, and the filename and line number reported by -the error message will be someone else’s code where the `panic!` macro is -called, not the line of our code that eventually led to the `panic!` call. We -can use the backtrace of the functions the `panic!` call came from to figure -out the part of our code that is causing the problem. We’ll discuss what a -backtrace is in more detail next. - -### Using a `panic!` Backtrace - -Let’s look at another example to see what it’s like when a `panic!` call comes -from a library because of a bug in our code instead of from our code calling -the macro directly. Listing 9-1 has some code that attempts to access an -element by index in a vector: - -Filename: src/main.rs - -``` -fn main() { - let v = vec![1, 2, 3]; - - v[99]; -} -``` - -Listing 9-1: Attempting to access an element beyond the end of a vector, which -will cause a `panic!` - -Here, we’re attempting to access the hundredth element of our vector (which is -at index 99 because indexing starts at zero), but it has only three elements. -In this situation, Rust will panic. Using `[]` is supposed to return an -element, but if you pass an invalid index, there’s no element that Rust could -return here that would be correct. - -Other languages, like C, will attempt to give you exactly what you asked for in -this situation, even though it isn’t what you want: you’ll get whatever is at -the location in memory that would correspond to that element in the vector, -even though the memory doesn’t belong to the vector. This is called a *buffer -overread* and can lead to security vulnerabilities if an attacker is able to -manipulate the index in such a way as to read data they shouldn’t be allowed to -that is stored after the array. - -To protect your program from this sort of vulnerability, if you try to read an -element at an index that doesn’t exist, Rust will stop execution and refuse to -continue. Let’s try it and see: - -``` -$ cargo run - Compiling panic v0.1.0 (file:///projects/panic) - Finished dev [unoptimized + debuginfo] target(s) in 0.27 secs - Running `target/debug/panic` -thread 'main' panicked at 'index out of bounds: the len is 3 but the index is -99', /checkout/src/liballoc/vec.rs:1555:10 -note: Run with `RUST_BACKTRACE=1` for a backtrace. -``` - -This error points at a file we didn’t write, *vec.rs*. That’s the -implementation of `Vec` in the standard library. The code that gets run when -we use `[]` on our vector `v` is in *vec.rs*, and that is where the `panic!` is -actually happening. - -The next note line tells us that we can set the `RUST_BACKTRACE` environment -variable to get a backtrace of exactly what happened to cause the error. A -*backtrace* is a list of all the functions that have been called to get to this -point. Backtraces in Rust work as they do in other languages: the key to -reading the backtrace is to start from the top and read until you see files you -wrote. That’s the spot where the problem originated. The lines above the lines -mentioning your files are code that your code called; the lines below are code -that called your code. These lines might include core Rust code, standard -library code, or crates that you’re using. Let’s try getting a backtrace by -setting the `RUST_BACKTRACE` environment variable to any value except 0. -Listing 9-2 shows output similar to what you’ll see: - -``` -$ RUST_BACKTRACE=1 cargo run - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target/debug/panic` -thread 'main' panicked at 'index out of bounds: the len is 3 but the index is -99', /checkout/src/liballoc/vec.rs:1555:10 -stack backtrace: - 0: std::sys::imp::backtrace::tracing::imp::unwind_backtrace - at /checkout/src/libstd/sys/unix/backtrace/tracing/gcc_s.rs:49 - 1: std::sys_common::backtrace::_print - at /checkout/src/libstd/sys_common/backtrace.rs:71 - 2: std::panicking::default_hook::{{closure}} - at /checkout/src/libstd/sys_common/backtrace.rs:60 - at /checkout/src/libstd/panicking.rs:381 - 3: std::panicking::default_hook - at /checkout/src/libstd/panicking.rs:397 - 4: std::panicking::rust_panic_with_hook - at /checkout/src/libstd/panicking.rs:611 - 5: std::panicking::begin_panic - at /checkout/src/libstd/panicking.rs:572 - 6: std::panicking::begin_panic_fmt - at /checkout/src/libstd/panicking.rs:522 - 7: rust_begin_unwind - at /checkout/src/libstd/panicking.rs:498 - 8: core::panicking::panic_fmt - at /checkout/src/libcore/panicking.rs:71 - 9: core::panicking::panic_bounds_check - at /checkout/src/libcore/panicking.rs:58 - 10: as core::ops::index::Index>::index - at /checkout/src/liballoc/vec.rs:1555 - 11: panic::main - at src/main.rs:4 - 12: __rust_maybe_catch_panic - at /checkout/src/libpanic_unwind/lib.rs:99 - 13: std::rt::lang_start - at /checkout/src/libstd/panicking.rs:459 - at /checkout/src/libstd/panic.rs:361 - at /checkout/src/libstd/rt.rs:61 - 14: main - 15: __libc_start_main - 16: -``` - -Listing 9-2: The backtrace generated by a call to `panic!` displayed when the -environment variable `RUST_BACKTRACE` is set - -That’s a lot of output! The exact output you see might be different depending -on your operating system and Rust version. In order to get backtraces with this -information, debug symbols must be enabled. Debug symbols are enabled by -default when using `cargo build` or `cargo run` without the `--release` flag, -as we have here. - -In the output in Listing 9-2, line 11 of the backtrace points to the line in -our project that’s causing the problem: line 4 of *src/main.rs*. If we don’t -want our program to panic, the location pointed to by the first line mentioning -a file we wrote is where we should start investigating. In Listing 9-1, where -we deliberately wrote code that would panic in order to demonstrate how to use -backtraces, the way to fix the panic is to not request an element at index 99 -from a vector that only contains 3 items. When your code panics in the future, -you’ll need to figure out what action the code is taking with what values to -cause the panic and what the code should do instead. - -We’ll come back to `panic!` and when we should and should not use `panic!` to -handle error conditions in the “To `panic!` or Not to `panic!`” section later -in this chapter. Next, we’ll look at how to recover from an error using -`Result`. - -## Recoverable Errors with `Result` - -Most errors aren’t serious enough to require the program to stop entirely. -Sometimes, when a function fails, it’s for a reason that you can easily -interpret and respond to. For example, if you try to open a file and that -operation fails because the file doesn’t exist, you might want to create the -file instead of terminating the process. - -Recall from “Handling Potential Failure with the `Result` Type” in Chapter 2 -that the `Result` enum is defined as having two variants, `Ok` and `Err`, as -follows: - -``` -enum Result { - Ok(T), - Err(E), -} -``` - -The `T` and `E` are generic type parameters: we’ll discuss generics in more -detail in Chapter 10. What you need to know right now is that `T` represents -the type of the value that will be returned in a success case within the `Ok` -variant, and `E` represents the type of the error that will be returned in a -failure case within the `Err` variant. Because `Result` has these generic type -parameters, we can use the `Result` type and the functions that the standard -library has defined on it in many different situations where the successful -value and error value we want to return may differ. - -Let’s call a function that returns a `Result` value because the function could -fail. In Listing 9-3 we try to open a file: - -Filename: src/main.rs - -``` -use std::fs::File; - -fn main() { - let f = File::open("hello.txt"); -} -``` - -Listing 9-3: Opening a file - -How do we know `File::open` returns a `Result`? We could look at the standard -library API documentation, or we could ask the compiler! If we give `f` a type -annotation that we know is *not* the return type of the function and then try -to compile the code, the compiler will tell us that the types don’t match. The -error message will then tell us what the type of `f` *is*. Let’s try it! We -know that the return type of `File::open` isn’t of type `u32`, so let’s change -the `let f` statement to this: - -``` -let f: u32 = File::open("hello.txt"); -``` - -Attempting to compile now gives us the following output: - -``` -error[E0308]: mismatched types - --> src/main.rs:4:18 - | -4 | let f: u32 = File::open("hello.txt"); - | ^^^^^^^^^^^^^^^^^^^^^^^ expected u32, found enum -`std::result::Result` - | - = note: expected type `u32` - found type `std::result::Result` -``` - -This tells us the return type of the `File::open` function is a `Result`. -The generic parameter `T` has been filled in here with the type of the success -value, `std::fs::File`, which is a file handle. The type of `E` used in the -error value is `std::io::Error`. - -This return type means the call to `File::open` might succeed and return a file -handle that we can read from or write to. The function call also might fail: -for example, the file might not exist, or we might not have permission to -access the file. The `File::open` function needs to have a way to tell us -whether it succeeded or failed and at the same time give us either the file -handle or error information. This information is exactly what the `Result` enum -conveys. - -In the case where `File::open` succeeds, the value in the variable `f` will be -an instance of `Ok` that contains a file handle. In the case where it fails, -the value in `f` will be an instance of `Err` that contains more information -about the kind of error that happened. - -We need to add to the code in Listing 9-3 to take different actions depending -on the value `File::open` returns. Listing 9-4 shows one way to handle the -`Result` using a basic tool, the `match` expression that we discussed in -Chapter 6. - -Filename: src/main.rs - -``` -use std::fs::File; - -fn main() { - let f = File::open("hello.txt"); - - let f = match f { - Ok(file) => file, - Err(error) => { - panic!("There was a problem opening the file: {:?}", error) - }, - }; -} -``` - -Listing 9-4: Using a `match` expression to handle the `Result` variants that -might be returned - -Note that, like the `Option` enum, the `Result` enum and its variants have been -imported in the prelude, so we don’t need to specify `Result::` before the `Ok` -and `Err` variants in the `match` arms. - -Here we tell Rust that when the result is `Ok`, return the inner `file` value -out of the `Ok` variant, and we then assign that file handle value to the -variable `f`. After the `match`, we can use the file handle for reading or -writing. - -The other arm of the `match` handles the case where we get an `Err` value from -`File::open`. In this example, we’ve chosen to call the `panic!` macro. If -there’s no file named *hello.txt* in our current directory and we run this -code, we’ll see the following output from the `panic!` macro: - -``` -thread 'main' panicked at 'There was a problem opening the file: Error { repr: -Os { code: 2, message: "No such file or directory" } }', src/main.rs:9:12 -``` - -As usual, this output tells us exactly what has gone wrong. - -### Matching on Different Errors - -The code in Listing 9-4 will `panic!` no matter why `File::open` failed. What -we want to do instead is take different actions for different failure reasons: -if `File::open` failed because the file doesn’t exist, we want to create the -file and return the handle to the new file. If `File::open` failed for any -other reason—for example, because we didn’t have permission to open the file—we -still want the code to `panic!` in the same way as it did in Listing 9-4. Look -at Listing 9-5, which adds another arm to the `match`: - -Filename: src/main.rs - - - -``` -use std::fs::File; -use std::io::ErrorKind; - -fn main() { - let f = File::open("hello.txt"); - - let f = match f { - Ok(file) => file, - Err(ref error) if error.kind() == ErrorKind::NotFound => { - match File::create("hello.txt") { - Ok(fc) => fc, - Err(e) => { - panic!( - "Tried to create file but there was a problem: {:?}", - e - ) - }, - } - }, - Err(error) => { - panic!( - "There was a problem opening the file: {:?}", - error - ) - }, - }; -} -``` - -Listing 9-5: Handling different kinds of errors in different ways - -The type of the value that `File::open` returns inside the `Err` variant is -`io::Error`, which is a struct provided by the standard library. This struct -has a method `kind` that we can call to get an `io::ErrorKind` value. The enum -`io::ErrorKind` is provided by the standard library and has variants -representing the different kinds of errors that might result from an `io` -operation. The variant we want to use is `ErrorKind::NotFound`, which indicates -the file we’re trying to open doesn’t exist yet. - -The condition `if error.kind() == ErrorKind::NotFound` is called a *match -guard*: it’s an extra condition on a `match` arm that further refines the arm’s -pattern. This condition must be true for that arm’s code to be run; otherwise, -the pattern matching will move on to consider the next arm in the `match`. The -`ref` in the pattern is needed so `error` is not moved into the guard condition -but is merely referenced by it. The reason you use `ref` to create a reference -in a pattern instead of `&` will be covered in detail in Chapter 18. In short, -in the context of a pattern, `&` matches a reference and gives you its value, -but `ref` matches a value and gives you a reference to it. - -The condition we want to check in the match guard is whether the value returned -by `error.kind()` is the `NotFound` variant of the `ErrorKind` enum. If it is, -we try to create the file with `File::create`. However, because `File::create` -could also fail, we need to add an inner `match` statement as well. When the -file can’t be opened, a different error message will be printed. The last arm -of the outer `match` stays the same so the program panics on any error besides -the missing file error. - -### Shortcuts for Panic on Error: `unwrap` and `expect` - -Using `match` works well enough, but it can be a bit verbose and doesn’t always -communicate intent well. The `Result` type has many helper methods -defined on it to do various tasks. One of those methods, called `unwrap`, is a -shortcut method that is implemented just like the `match` statement we wrote in -Listing 9-4. If the `Result` value is the `Ok` variant, `unwrap` will return -the value inside the `Ok`. If the `Result` is the `Err` variant, `unwrap` will -call the `panic!` macro for us. Here is an example of `unwrap` in action: - -Filename: src/main.rs - -``` -use std::fs::File; - -fn main() { - let f = File::open("hello.txt").unwrap(); -} -``` - -If we run this code without a *hello.txt* file, we’ll see an error message from -the `panic!` call that the `unwrap` method makes: - -``` -thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error { -repr: Os { code: 2, message: "No such file or directory" } }', -src/libcore/result.rs:906:4 -``` - -Another method, `expect`, which is similar to `unwrap`, lets us also choose the -`panic!` error message. Using `expect` instead of `unwrap` and providing good -error messages can convey your intent and make tracking down the source of a -panic easier. The syntax of `expect` looks like this: - -Filename: src/main.rs - -``` -use std::fs::File; - -fn main() { - let f = File::open("hello.txt").expect("Failed to open hello.txt"); -} -``` - -We use `expect` in the same way as `unwrap`: to return the file handle or call -the `panic!` macro. The error message used by `expect` in its call to `panic!` -will be the parameter that we pass to `expect`, rather than the default -`panic!` message that `unwrap` uses. Here’s what it looks like: - -``` -thread 'main' panicked at 'Failed to open hello.txt: Error { repr: Os { code: -2, message: "No such file or directory" } }', src/libcore/result.rs:906:4 -``` - -Because this error message starts with the text we specified, `Failed to open -hello.txt`, it will be easier to find where in the code this error message is -coming from. If we use `unwrap` in multiple places, it can take more time to -figure out exactly which `unwrap` is causing the panic because all `unwrap` -calls that panic print the same message. - -### Propagating Errors - -When you’re writing a function whose implementation calls something that might -fail, instead of handling the error within this function, you can return the -error to the calling code so that it can decide what to do. This is known as -*propagating* the error and gives more control to the calling code, where there -might be more information or logic that dictates how the error should be -handled than what you have available in the context of your code. - -For example, Listing 9-6 shows a function that reads a username from a file. If -the file doesn’t exist or can’t be read, this function will return those errors -to the code that called this function: - -Filename: src/main.rs - -``` -use std::io; -use std::io::Read; -use std::fs::File; - -fn read_username_from_file() -> Result { - let f = File::open("hello.txt"); - - let mut f = match f { - Ok(file) => file, - Err(e) => return Err(e), - }; - - let mut s = String::new(); - - match f.read_to_string(&mut s) { - Ok(_) => Ok(s), - Err(e) => Err(e), - } -} -``` - -Listing 9-6: A function that returns errors to the calling code using `match` - -Let’s look at the return type of the function first: `Result`. This means the function is returning a value of the type -`Result` where the generic parameter `T` has been filled in with the -concrete type `String`, and the generic type `E` has been filled in with the -concrete type `io::Error`. If this function succeeds without any problems, the -code that calls this function will receive an `Ok` value that holds a -`String`—the username that this function read from the file. If this function -encounters any problems, the code that calls this function will receive an -`Err` value that holds an instance of `io::Error` that contains more -information about what the problems were. We chose `io::Error` as the return -type of this function because that happens to be the type of the error value -returned from both of the operations we’re calling in this function’s body that -might fail: the `File::open` function and the `read_to_string` method. - -The body of the function starts by calling the `File::open` function. Then we -handle the `Result` value returned with a `match` similar to the `match` in -Listing 9-4, only instead of calling `panic!` in the `Err` case, we return -early from this function and pass the error value from `File::open` back to the -calling code as this function’s error value. If `File::open` succeeds, we store -the file handle in the variable `f` and continue. - -Then we create a new `String` in variable `s` and call the `read_to_string` -method on the file handle in `f` to read the contents of the file into `s`. The -`read_to_string` method also returns a `Result` because it might fail, even -though `File::open` succeeded. So we need another `match` to handle that -`Result`: if `read_to_string` succeeds, then our function has succeeded, and we -return the username from the file that’s now in `s` wrapped in an `Ok`. If -`read_to_string` fails, we return the error value in the same way that we -returned the error value in the `match` that handled the return value of -`File::open`. However, we don’t need to explicitly say `return`, because this -is the last expression in the function. - -The code that calls this code will then handle getting either an `Ok` value -that contains a username or an `Err` value that contains an `io::Error`. We -don’t know what the calling code will do with those values. If the calling code -gets an `Err` value, it could call `panic!` and crash the program, use a -default username, or look up the username from somewhere other than a file, for -example. We don’t have enough information on what the calling code is actually -trying to do, so we propagate all the success or error information upward for -it to handle appropriately. - -This pattern of propagating errors is so common in Rust that Rust provides the -question mark operator `?` to make this easier. - -#### A Shortcut for Propagating Errors: the `?` Operator - -Listing 9-7 shows an implementation of `read_username_from_file` that has the -same functionality as it had in Listing 9-6, but this implementation uses the -question mark operator: - -Filename: src/main.rs - -``` -use std::io; -use std::io::Read; -use std::fs::File; - -fn read_username_from_file() -> Result { - let mut f = File::open("hello.txt")?; - let mut s = String::new(); - f.read_to_string(&mut s)?; - Ok(s) -} -``` - -Listing 9-7: A function that returns errors to the calling code using `?` - -The `?` placed after a `Result` value is defined to work in almost the same way -as the `match` expressions we defined to handle the `Result` values in Listing -9-6. If the value of the `Result` is an `Ok`, the value inside the `Ok` will -get returned from this expression, and the program will continue. If the value -is an `Err`, the value inside the `Err` will be returned from the whole -function as if we had used the `return` keyword so the error value gets -propagated to the calling code. - -There is a difference between what the `match` expression from Listing 9-6 and -`?` do: error values used with `?` go through the `from` function, defined in -the `From` trait in the standard library, which is used to convert errors from -one type into another. When `?` calls the `from` function, the error type -received is converted into the error type defined in the return type of the -current function. This is useful when a function returns one error type to -represent all the ways a function might fail, even if parts might fail for many -different reasons. As long as each error type implements the `from` function to -define how to convert itself to the returned error type, `?` takes care of the -conversion automatically. - -In the context of Listing 9-7, the `?` at the end of the `File::open` call will -return the value inside an `Ok` to the variable `f`. If an error occurs, `?` -will return early out of the whole function and give any `Err` value to the -calling code. The same thing applies to the `?` at the end of the -`read_to_string` call. - -The `?` operator eliminates a lot of boilerplate and makes this function’s -implementation simpler. We could even shorten this code further by chaining -method calls immediately after the `?`, as shown in Listing 9-8: - -Filename: src/main.rs - -``` -use std::io; -use std::io::Read; -use std::fs::File; - -fn read_username_from_file() -> Result { - let mut s = String::new(); - - File::open("hello.txt")?.read_to_string(&mut s)?; - - Ok(s) -} -``` - -Listing 9-8: Chaining method calls after `?` - -We’ve moved the creation of the new `String` in `s` to the beginning of the -function; that part hasn’t changed. Instead of creating a variable `f`, we’ve -chained the call to `read_to_string` directly onto the result of -`File::open("hello.txt")?`. We still have a `?` at the end of the -`read_to_string` call, and we still return an `Ok` value containing the -username in `s` when both `File::open` and `read_to_string` succeed rather than -returning errors. The functionality is again the same as in Listing 9-6 and -Listing 9-7; this is just a different, more ergonomic way to write it. - -#### The `?` Operator Can Only Be Used in Functions That Return `Result` - -The `?` operator can only be used in functions that have a return type of -`Result`, because it is defined to work in the same way as the `match` -expression we defined in Listing 9-6. The part of the `match` that requires a -return type of `Result` is `return Err(e)`, so the return type of the function -must be a `Result` to be compatible with this `return`. - -Let’s look at what happens if we use `?` in the `main` function, which you’ll -recall has a return type of `()`: - -``` -use std::fs::File; - -fn main() { - let f = File::open("hello.txt")?; -} -``` - -When we compile this code, we get the following error message: - -``` -error[E0277]: the trait bound `(): std::ops::Try` is not satisfied - --> src/main.rs:4:13 - | -4 | let f = File::open("hello.txt")?; - | ------------------------ - | | - | the `?` operator can only be used in a function that returns - `Result` (or another type that implements `std::ops::Try`) - | in this macro invocation - | - = help: the trait `std::ops::Try` is not implemented for `()` - = note: required by `std::ops::Try::from_error` -``` - -This error points out that we’re only allowed to use `?` in a function that -returns `Result`. In functions that don’t return `Result`, when you call other -functions that return `Result`, you’ll need to use a `match` or one of the -`Result` methods to handle the `Result` instead of using `?` to potentially -propagate the error to the calling code. - -Now that we’ve discussed the details of calling `panic!` or returning `Result`, -let’s return to the topic of how to decide which is appropriate to use in which -cases. - -## To `panic!` or Not to `panic!` - -So how do you decide when you should call `panic!` and when you should return -`Result`? When code panics, there’s no way to recover. You could call `panic!` -for any error situation, whether there’s a possible way to recover or not, but -then you’re making the decision on behalf of the code calling your code that a -situation is unrecoverable. When you choose to return a `Result` value, you -give the calling code options rather than making the decision for it. The -calling code could choose to attempt to recover in a way that’s appropriate for -its situation, or it could decide that an `Err` value in this case is -unrecoverable, so it can call `panic!` and turn your recoverable error into an -unrecoverable one. Therefore, returning `Result` is a good default choice when -you’re defining a function that might fail. - -In rare situations, it’s more appropriate to write code that panics instead of -returning a `Result`. Let’s explore why it’s appropriate to panic in examples, -prototype code, and tests. Then we’ll discuss situations in which the compiler -can’t tell that failure is impossible, but you as a human can. The chapter will -conclude with some general guidelines on how to decide whether to panic in -library code. - -### Examples, Prototype Code, and Tests - -When you’re writing an example to illustrate some concept, having robust -error-handling code in the example as well can make the example less clear. In -examples, it’s understood that a call to a method like `unwrap` that could -panic is meant as a placeholder for the way you’d want your application to -handle errors, which can differ based on what the rest of your code is doing. - -Similarly, the `unwrap` and `expect` methods are very handy when prototyping, -before you’re ready to decide how to handle errors. They leave clear markers in -your code for when you’re ready to make your program more robust. - -If a method call fails in a test, you’d want the whole test to fail, even if -that method isn’t the functionality under test. Because `panic!` is how a test -is marked as a failure, calling `unwrap` or `expect` is exactly what should -happen. - -### Cases in Which You Have More Information Than the Compiler - -It would also be appropriate to call `unwrap` when you have some other logic -that ensures the `Result` will have an `Ok` value, but the logic isn’t -something the compiler understands. You’ll still have a `Result` value that you -need to handle: whatever operation you’re calling still has the possibility of -failing in general, even though it’s logically impossible in your particular -situation. If you can ensure by manually inspecting the code that you’ll never -have an `Err` variant, it’s perfectly acceptable to call `unwrap`. Here’s an -example: - -``` -use std::net::IpAddr; - -let home: IpAddr = "127.0.0.1".parse().unwrap(); -``` - -We’re creating an `IpAddr` instance by parsing a hardcoded string. We can see -that `127.0.0.1` is a valid IP address, so it’s acceptable to use `unwrap` -here. However, having a hardcoded, valid string doesn’t change the return type -of the `parse` method: we still get a `Result` value, and the compiler will -still make us handle the `Result` as if the `Err` variant is a possibility -because the compiler isn’t smart enough to see that this string is always a -valid IP address. If the IP address string came from a user rather than being -hardcoded into the program and therefore *did* have a possibility of failure, -we’d definitely want to handle the `Result` in a more robust way instead. - -### Guidelines for Error Handling - -It’s advisable to have your code panic when it’s possible that your code -could end up in a bad state. In this context, a *bad state* is when some -assumption, guarantee, contract, or invariant has been broken, such as when -invalid values, contradictory values, or missing values are passed to your -code—plus one or more of the following: - -* The bad state is not something that’s *expected* to happen occasionally. -* Your code after this point needs to rely on not being in this bad state. -* There’s not a good way to encode this information in the types you use. - -If someone calls your code and passes in values that don’t make sense, the best -choice might be to call `panic!` and alert the person using your library to the -bug in their code so they can fix it during development. Similarly, `panic!` is -often appropriate if you’re calling external code that is out of your control -and it returns an invalid state that you have no way of fixing. - -When a bad state is reached, but it’s expected to happen no matter how well you -write your code, it’s still more appropriate to return a `Result` rather than -to make a `panic!` call. Examples include a parser being given malformed data -or an HTTP request returning a status that indicates you have hit a rate limit. -In these cases, you should indicate that failure is an expected possibility by -returning a `Result` to propagate these bad states upward so the calling code -can decide how to handle the problem. To call `panic!` wouldn’t be the best way -to handle these cases. - -When your code performs operations on values, your code should verify the -values are valid first and panic if the values aren’t valid. This is mostly for -safety reasons: attempting to operate on invalid data can expose your code to -vulnerabilities. This is the main reason the standard library will call -`panic!` if you attempt an out-of-bounds memory access: trying to access memory -that doesn’t belong to the current data structure is a common security problem. -Functions often have *contracts*: their behavior is only guaranteed if the -inputs meet particular requirements. Panicking when the contract is violated -makes sense because a contract violation always indicates a caller-side bug and -it’s not a kind of error you want the calling code to have to explicitly -handle. In fact, there’s no reasonable way for calling code to recover; the -calling *programmers* need to fix the code. Contracts for a function, -especially when a violation will cause a panic, should be explained in the API -documentation for the function. - -However, having lots of error checks in all of your functions would be verbose -and annoying. Fortunately, you can use Rust’s type system (and thus the type -checking the compiler does) to do many of the checks for you. If your function -has a particular type as a parameter, you can proceed with your code’s logic -knowing that the compiler has already ensured you have a valid value. For -example, if you have a type rather than an `Option`, your program expects to -have *something* rather than *nothing*. Your code then doesn’t have to handle -two cases for the `Some` and `None` variants: it will only have one case for -definitely having a value. Code trying to pass nothing to your function won’t -even compile, so your function doesn’t have to check for that case at runtime. -Another example is using an unsigned integer type such as `u32`, which ensures -the parameter is never negative. - -Let’s take the idea of using Rust’s type system to ensure we have a valid value -one step further and look at creating a custom type for validation. Recall the -guessing game in Chapter 2 in which our code asked the user to guess a number -between 1 and 100. We never validated that the user’s guess was between those -numbers before checking it against our secret number; we only validated that -the guess was positive. In this case, the consequences were not very dire: our -output of “Too high” or “Too low” would still be correct. But it would be a -useful enhancement to guide the user toward valid guesses and have different -behavior when a user guesses a number that’s out of range versus when a user -types, for example, letters instead. - -One way to do this would be to parse the guess as an `i32` instead of only a -`u32` to allow potentially negative numbers, and then add a check for the -number being in range, like so: - -``` -loop { - // --snip-- - - let guess: i32 = match guess.trim().parse() { - Ok(num) => num, - Err(_) => continue, - }; - - if guess < 1 || guess > 100 { - println!("The secret number will be between 1 and 100."); - continue; - } - - match guess.cmp(&secret_number) { - // --snip-- -} -``` - -The `if` expression checks whether our value is out of range, tells the user -about the problem, and calls `continue` to start the next iteration of the loop -and ask for another guess. After the `if` expression, we can proceed with the -comparisons between `guess` and the secret number knowing that `guess` is -between 1 and 100. - -However, this is not an ideal solution: if it was absolutely critical that the -program only operated on values between 1 and 100, and it had many functions -with this requirement, having a check like this in every function would be -tedious (and might impact performance). - -Instead, we can make a new type and put the validations in a function to create -an instance of the type rather than repeating the validations everywhere. That -way, it’s safe for functions to use the new type in their signatures and -confidently use the values they receive. Listing 9-9 shows one way to define a -`Guess` type that will only create an instance of `Guess` if the `new` function -receives a value between 1 and 100: - -``` -pub struct Guess { - value: u32, -} - -impl Guess { - pub fn new(value: u32) -> Guess { - if value < 1 || value > 100 { - panic!("Guess value must be between 1 and 100, got {}.", value); - } - - Guess { - value - } - } - - pub fn value(&self) -> u32 { - self.value - } -} -``` - -Listing 9-9: A `Guess` type that will only continue with values between 1 and -100 - -First, we define a struct named `Guess` that has a field named `value` that -holds a `u32`. This is where the number will be stored. - -Then we implement an associated function named `new` on `Guess` that creates -instances of `Guess` values. The `new` function is defined to have one -parameter named `value` of type `u32` and to return a `Guess`. The code in the -body of the `new` function tests `value` to make sure it’s between 1 and 100. -If `value` doesn’t pass this test, we make a `panic!` call, which will alert -the programmer who is writing the calling code that they have a bug they need -to fix, because creating a `Guess` with a `value` outside this range would -violate the contract that `Guess::new` is relying on. The conditions in which -`Guess::new` might panic should be discussed in its public-facing API -documentation; we’ll cover documentation conventions indicating the possibility -of a `panic!` in the API documentation that you create in Chapter 14. If -`value` does pass the test, we create a new `Guess` with its `value` field set -to the `value` parameter and return the `Guess`. - -Next, we implement a method named `value` that borrows `self`, doesn’t have any -other parameters, and returns a `u32`. This kind of method is sometimes called -a *getter*, because its purpose is to get some data from its fields and return -it. This public method is necessary because the `value` field of the `Guess` -struct is private. It’s important that the `value` field be private so code -using the `Guess` struct is not allowed to set `value` directly: code outside -the module *must* use the `Guess::new` function to create an instance of -`Guess`, thereby ensuring there’s no way for a `Guess` to have a `value` that -hasn’t been checked by the conditions in the `Guess::new` function. - -A function that has a parameter or returns only numbers between 1 and 100 could -then declare in its signature that it takes or returns a `Guess` rather than a -`u32` and wouldn’t need to do any additional checks in its body. - -## Summary - -Rust’s error handling features are designed to help you write more robust code. -The `panic!` macro signals that your program is in a state it can’t handle and -lets you tell the process to stop instead of trying to proceed with invalid or -incorrect values. The `Result` enum uses Rust’s type system to indicate that -operations might fail in a way that your code could recover from. You can use -`Result` to tell code that calls your code that it needs to handle potential -success or failure as well. Using `panic!` and `Result` in the appropriate -situations will make your code more reliable in the face of inevitable problems. - -Now that you’ve seen useful ways that the standard library uses generics with -the `Option` and `Result` enums, we’ll talk about how generics work and how you -can use them in your code. - diff --git a/second-edition/nostarch/chapter10.md b/second-edition/nostarch/chapter10.md deleted file mode 100644 index 6ad017e2f4..0000000000 --- a/second-edition/nostarch/chapter10.md +++ /dev/null @@ -1,1881 +0,0 @@ - -[TOC] - -# Generic Types, Traits, and Lifetimes - -Every programming language has tools for effectively handling the duplication -of concepts. In Rust, one such tool is *generics*. Generics are abstract -stand-ins for concrete types or other properties. When we’re writing code, we -can express the behavior of generics or how they relate to other generics -without knowing what will be in their place when compiling and running the code. - -Similar to the way a function takes parameters with unknown values to run the -same code on multiple concrete values, functions can take parameters of some -generic type instead of a concrete type, like `i32` or `String`. In fact, we’ve -already used generics in Chapter 6 with `Option`, Chapter 8 with `Vec` -and `HashMap`, and Chapter 9 with `Result`. In this chapter, you’ll -explore how to define your own types, functions, and methods with generics! - -First, we’ll review how to extract a function to reduce code duplication. Next, -we’ll use the same technique to make a generic function from two functions that -only differ in the types of their parameters. We’ll also explain how to use -generic types in struct and enum definitions. - -Then you’ll learn how to use *traits* to define behavior in a generic way. You -can then combine traits with generic types to constrain a generic type to only -those types that have a particular behavior, as opposed to just any type. - -Finally, we’ll discuss *lifetimes*, a variety of generics that give the -compiler information about how references relate to each other. Lifetimes allow -us to borrow values in many situations while still enabling the compiler to -check that the references are valid. - -## Removing Duplication by Extracting a Function - -Before diving into generics syntax, let’s first look at how to remove -duplication that doesn’t involve generic types by extracting a function. Then -we’ll apply this technique to extract a generic function! In the same way that -you recognize duplicated code to extract into a function, you’ll start to -recognize duplicated code that can use generics. - -Consider a short program that finds the largest number in a list, as shown in -Listing 10-1: - -Filename: src/main.rs - -``` -fn main() { - let number_list = vec![34, 50, 25, 100, 65]; - - let mut largest = number_list[0]; - - for number in number_list { - if number > largest { - largest = number; - } - } - - println!("The largest number is {}", largest); -} -``` - -Listing 10-1: Code to find the largest number in a list of numbers - -This code stores a list of integers in the variable `number_list` and places -the first number in the list in a variable named `largest`. Then it iterates -through all the numbers in the list, and if the current number is greater than -the number stored in `largest`, it replaces the number in that variable. -However, if the current number is less than the largest number seen so far, the -variable doesn’t change and the code moves on to the next number in the list. -After considering all the numbers in the list, `largest` should hold the -largest number, which in this case is 100. - -To find the largest number in two different lists of numbers, we can duplicate -the code in Listing 10-1 and use the same logic at two different places in the -program, as shown in Listing 10-2: - -Filename: src/main.rs - -``` -fn main() { - let number_list = vec![34, 50, 25, 100, 65]; - - let mut largest = number_list[0]; - - for number in number_list { - if number > largest { - largest = number; - } - } - - println!("The largest number is {}", largest); - - let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8]; - - let mut largest = number_list[0]; - - for number in number_list { - if number > largest { - largest = number; - } - } - - println!("The largest number is {}", largest); -} -``` - -Listing 10-2: Code to find the largest number in *two* lists of numbers - -Although this code works, duplicating code is tedious and error prone. We also -have to update the code in multiple places to change it. - -To eliminate this duplication, we can create an abstraction by defining a -function that operates on any list of integers given to it in a parameter. This -solution makes our code clearer and lets us express the concept of finding the -largest number in a list abstractly. - -In Listing 10-3, we extracted the code that finds the largest number into a -function named `largest`. Unlike the code in Listing 10-1, which can find the -largest number in only one particular list, this program can find the largest -number in two different lists: - -Filename: src/main.rs - -``` -fn largest(list: &[i32]) -> i32 { - let mut largest = list[0]; - - for &item in list.iter() { - if item > largest { - largest = item; - } - } - - largest -} - -fn main() { - let number_list = vec![34, 50, 25, 100, 65]; - - let result = largest(&number_list); - println!("The largest number is {}", result); - - let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8]; - - let result = largest(&number_list); - println!("The largest number is {}", result); -} -``` - -Listing 10-3: Abstracted code to find the largest number in two lists - -The `largest` function has a parameter called `list`, which represents any -concrete slice of `i32` values that we might pass into the function. As a -result, when we call the function, the code runs on the specific values that we -pass in. - -In sum, here are the steps we took to change the code from Listing 10-2 to -Listing 10-3: - -1. Identify duplicate code. -2. Extract the duplicate code into the body of the function, and specify the - inputs and return values of that code in the function signature. -3. Update the two instances of duplicated code to call the function instead. - -Next, we’ll use these same steps with generics to reduce code duplication in -different ways. In the same way that the function body can operate on an -abstract `list` instead of specific values, generics allow code to operate on -abstract types. - -For example, say we had two functions: one that finds the largest item in a -slice of `i32` values and one that finds the largest item in a slice of `char` -values. How would we eliminate that duplication? Let’s find out! - -## Generic Data Types - -We can use generics to create definitions for items like function signatures or -structs, which we can then use with many different concrete data types. Let’s -first look at how to define functions, structs, enums, and methods using -generics. Then we’ll discuss how generics affect code performance. - -### In Function Definitions - -When defining a function that uses generics, we place the generics in the -signature of the function where we would usually specify the data types of the -parameters and return value. Doing so makes our code more flexible and provides -more functionality to callers of our function while preventing code duplication. - -Continuing with our `largest` function, Listing 10-4 shows two functions that -both find the largest value in a slice: - -Filename: src/main.rs - -``` -fn largest_i32(list: &[i32]) -> i32 { - let mut largest = list[0]; - - for &item in list.iter() { - if item > largest { - largest = item; - } - } - - largest -} - -fn largest_char(list: &[char]) -> char { - let mut largest = list[0]; - - for &item in list.iter() { - if item > largest { - largest = item; - } - } - - largest -} - -fn main() { - let number_list = vec![34, 50, 25, 100, 65]; - - let result = largest_i32(&number_list); - println!("The largest number is {}", result); - - let char_list = vec!['y', 'm', 'a', 'q']; - - let result = largest_char(&char_list); - println!("The largest char is {}", result); -} -``` - -Listing 10-4: Two functions that differ only in their names and the types in -their signatures - -The `largest_i32` function is the one we extracted in Listing 10-3 that finds -the largest `i32` in a slice. The `largest_char` function finds the largest -`char` in a slice. The function bodies have the same code, so let’s eliminate -the duplication by introducing a generic type parameter in a single function. - -To parameterize the types in the new function we’ll define, we need to name the -type parameter, just like we do for the value parameters to a function. You can -use any identifier as a type parameter name. But we’ll use `T` because, by -convention, parameter names in Rust are short, often just a letter, and Rust’s -type naming convention is CamelCase. Short for “type,” `T` is the default -choice of most Rust programmers. - -When we use a parameter in the body of the function, we have to declare the -parameter name in the signature so that the compiler knows what that name -means. Similarly, when we use a type parameter name in a function signature, we -have to declare the type parameter name before we use it. To define the generic -`largest` function, place type name declarations inside angle brackets (`<>`) -between the name of the function and the parameter list, like this: - -``` -fn largest(list: &[T]) -> T { -``` - -We read this definition as: the function `largest` is generic over some type -`T`. This function has one parameter named `list`, which is a slice of values -of type `T`. The `largest` function will return a value of the same type `T`. - -Listing 10-5 shows the combined `largest` function definition using the generic -data type in its signature. The listing also shows how we can call the function -with either a slice of `i32` values or `char` values. Note that this code won’t -compile yet, but we’ll fix it later in this chapter. - -Filename: src/main.rs - -``` -fn largest(list: &[T]) -> T { - let mut largest = list[0]; - - for &item in list.iter() { - if item > largest { - largest = item; - } - } - - largest -} - -fn main() { - let number_list = vec![34, 50, 25, 100, 65]; - - let result = largest(&number_list); - println!("The largest number is {}", result); - - let char_list = vec!['y', 'm', 'a', 'q']; - - let result = largest(&char_list); - println!("The largest char is {}", result); -} -``` - -Listing 10-5: A definition of the `largest` function that uses generic type -parameters but doesn’t compile yet - -If we compile this code right now, we’ll get this error: - -``` -error[E0369]: binary operation `>` cannot be applied to type `T` - --> src/main.rs:5:12 - | -5 | if item > largest { - | ^^^^^^^^^^^^^^ - | - = note: an implementation of `std::cmp::PartialOrd` might be missing for `T` -``` - -The note mentions `std::cmp::PartialOrd`, which is a *trait*. We’ll talk about -traits in the next section. For now, this error states that the body of -`largest` won’t work for all possible types that `T` could be. Because we want -to compare values of type `T` in the body, we can only use types whose values -can be ordered. To enable comparisons, the standard library has the -`std::cmp::PartialOrd` trait that you can implement on types (see Appendix C, -“Derivable Traits,” for more on this trait). You’ll learn how to specify that a -generic type has a particular trait in the “Trait Bounds” section, but let’s -first explore other ways of using generic type parameters. - -### In Struct Definitions - -We can also define structs to use a generic type parameter in one or more -fields using the `<>` syntax. Listing 10-6 shows how to define a `Point` -struct to hold `x` and `y` coordinate values of any type: - -Filename: src/main.rs - -``` -struct Point { - x: T, - y: T, -} - -fn main() { - let integer = Point { x: 5, y: 10 }; - let float = Point { x: 1.0, y: 4.0 }; -} -``` - -Listing 10-6: A `Point` struct that holds `x` and `y` values of type `T` - -The syntax for using generics in struct definitions is similar to that used in -function definitions. First, we declare the name of the type parameter inside -angle brackets just after the name of the struct. Then we can use the generic -type in the struct definition where we would otherwise specify concrete data -types. - -Note that because we’ve only used one generic type to define `Point`, this -says that the `Point` struct is generic over some type `T`, and the fields -`x` and `y` are *both* that same type, whatever that type may be. This means -that if we create an instance of a `Point` that has values of different -types, as in Listing 10-7, our code won’t compile: - -Filename: src/main.rs - -``` -struct Point { - x: T, - y: T, -} - -fn main() { - let wont_work = Point { x: 5, y: 4.0 }; -} -``` - -Listing 10-7: The fields `x` and `y` must be the same type because both have -the same generic data type `T` - -In this example, when we assign the integer value `5` to `x`, we let the -compiler know that the generic type `T` will be an integer for this instance of -`Point`. Then when we specify `4.0` for `y`, which we’ve defined to have the -same type as `x`, we’ll get a type mismatch error like this: - -``` -error[E0308]: mismatched types - --> src/main.rs:7:38 - | -7 | let wont_work = Point { x: 5, y: 4.0 }; - | ^^^ expected integral variable, found -floating-point variable - | - = note: expected type `{integer}` - found type `{float}` -``` - -To define a `Point` struct where `x` and `y` are both generics but could have -different types, we can use multiple generic type parameters. For example, in -Listing 10-8, we can change the definition of `Point` to be generic over types -`T` and `U` where `x` is of type `T` and `y` is of type `U`: - -Filename: src/main.rs - -``` -struct Point { - x: T, - y: U, -} - -fn main() { - let both_integer = Point { x: 5, y: 10 }; - let both_float = Point { x: 1.0, y: 4.0 }; - let integer_and_float = Point { x: 5, y: 4.0 }; -} -``` - -Listing 10-8: A `Point` generic over two types so that `x` and `y` can be -values of different types - -Now all the instances of `Point` shown are allowed! You can use as many generic -type parameters in a definition as you want, but using more than a few makes -your code hard to read. When you need lots of generic types in your code, it -could indicate that your code needs restructuring into smaller pieces. - -### In Enum Definitions - -As we did with structs, we can define enums to hold generic data types in their -variants. Let’s take another look at the `Option` enum that the standard -library provides that we used in Chapter 6: - -``` -enum Option { - Some(T), - None, -} -``` - -This definition should now make more sense to you. As you can see, `Option` -is an enum that is generic over type `T` and has two variants: `Some`, which -holds one value of type `T`, and a `None` variant that doesn’t hold any value. -By using the `Option` enum, we can express the abstract concept of having an -optional value, and because `Option` is generic, we can use this abstraction -no matter what the type of the optional value is. - -Enums can use multiple generic types as well. The definition of the `Result` -enum that we used in Chapter 9 is one example: - -``` -enum Result { - Ok(T), - Err(E), -} -``` - -The `Result` enum is generic over two types, `T` and `E`, and has two variants: -`Ok`, which holds a value of type `T`, and `Err`, which holds a value of type -`E`. This definition makes it convenient to use the `Result` enum anywhere we -have an operation that might succeed (return a value of some type `T`) or fail -(return an error of some type `E`). In fact, this is what we used to open a -file in Listing 9-3 where `T` was filled in with the type `std::fs::File` when -the file was opened successfully and `E` was filled in with the type -`std::io::Error` when there were problems opening the file. - -When you recognize situations in your code with multiple struct or enum -definitions that differ only in the types of the values they hold, you can -avoid duplication by using generic types instead. - -### In Method Definitions - -As we did in Chapter 5, we can implement methods on structs and enums that have -generic types in their definitions. Listing 10-9 shows the `Point` struct we -defined in Listing 10-6 with a method named `x` implemented on it: - -Filename: src/main.rs - -``` -struct Point { - x: T, - y: T, -} - -impl Point { - fn x(&self) -> &T { - &self.x - } -} - -fn main() { - let p = Point { x: 5, y: 10 }; - - println!("p.x = {}", p.x()); -} -``` - -Listing 10-9: Implementing a method named `x` on the `Point` struct that -will return a reference to the `x` field of type `T` - -Here, we’ve defined a method named `x` on `Point` that returns a reference -to the data in the field `x`. - -Note that we have to declare `T` just after `impl` so we can use it to specify -that we’re implementing methods on the type `Point`. By declaring `T` as a -generic type after `impl`, Rust can identify that the type in the angle -brackets in `Point` is a generic type rather than a concrete type. - -We could, for example, implement methods only on `Point` instances rather -than on `Point` instances with any generic type. In Listing 10-10 we use the -concrete type `f32`, meaning we don’t declare any types after `impl`: - -``` -impl Point { - fn distance_from_origin(&self) -> f32 { - (self.x.powi(2) + self.y.powi(2)).sqrt() - } -} -``` - -Listing 10-10: An `impl` block that only applies to a struct with a particular -concrete type for the generic type parameter `T` - -This code means the type `Point` will have a method named -`distance_from_origin`, and other instances of `Point` where `T` is not of -type `f32` will not have this method defined. The method measures how far our -point is from the point at coordinates (0.0, 0.0) and uses mathematical -operations that are only available for floating point types. - -Generic type parameters in a struct definition aren’t always the same as those -you use in that struct’s method signatures. For example, Listing 10-11 defines -the method `mixup` on the `Point` struct from Listing 10-8. The method -takes another `Point` as a parameter, which might have different types than the -`self` `Point` we’re calling `mixup` on. The method creates a new `Point` -instance with the `x` value from the `self` `Point` (of type `T`) and the `y` -value from the passed-in `Point` (of type `W`): - -Filename: src/main.rs - -``` -struct Point { - x: T, - y: U, -} - -impl Point { - fn mixup(self, other: Point) -> Point { - Point { - x: self.x, - y: other.y, - } - } -} - -fn main() { - let p1 = Point { x: 5, y: 10.4 }; - let p2 = Point { x: "Hello", y: 'c'}; - - let p3 = p1.mixup(p2); - - println!("p3.x = {}, p3.y = {}", p3.x, p3.y); -} -``` - -Listing 10-11: Methods that use different generic types than their struct’s -definition - -In `main`, we’ve defined a `Point` that has an `i32` for `x` (with value `5`) -and an `f64` for `y` (with value `10.4`). The `p2` variable is a `Point` struct -that has a string slice for `x` (with value `"Hello"`) and a `char` for `y` -(with value `c`). Calling `mixup` on `p1` with the argument `p2` gives us `p3`, -which will have an `i32` for `x`, because `x` came from `p1`. The `p3` variable -will have a `char` for `y`, because `y` came from `p2`. The `println!` macro -call will print `p3.x = 5, p3.y = c`. - -The purpose of this example is to demonstrate a situation in which some generic -parameters are declared with `impl` and some are declared with the method -definition. Here, the generic parameters `T` and `U` are declared after `impl`, -because they go with the struct definition. The generic parameters `V` and `W` -are declared after `fn mixup`, because they’re only relevant to the method. - -### Performance of Code Using Generics - -You might be wondering whether there is a runtime cost when you’re using -generic type parameters. The good news is that Rust implements generics in such -a way that your code doesn’t run any slower using generic types than it would -with concrete types. - -Rust accomplishes this by performing monomorphization of the code that is using -generics at compile time. *Monomorphization* is the process of turning generic -code into specific code by filling in the concrete types that are used when -compiled. - -In this process, the compiler does the opposite of the steps we used to create -the generic function in Listing 10-5: the compiler looks at all the places -where generic code is called and generates code for the concrete types the -generic code is called with. - -Let’s look at how this works with an example that uses the standard library’s -`Option` enum: - -``` -let integer = Some(5); -let float = Some(5.0); -``` - -When Rust compiles this code, it performs monomorphization. During that -process, the compiler reads the values that have been used in the instances of -`Option` and identifies two kinds of `Option`: one is `i32` and the other -is `f64`. As such, it expands the generic definition of `Option` into -`Option_i32` and `Option_f64`, thereby replacing the generic definition with -the specific ones. - -The monomorphized version of the code looks like the following. The generic -`Option` is replaced with the specific definitions created by the compiler: - -Filename: src/main.rs - -``` -enum Option_i32 { - Some(i32), - None, -} - -enum Option_f64 { - Some(f64), - None, -} - -fn main() { - let integer = Option_i32::Some(5); - let float = Option_f64::Some(5.0); -} -``` - -Because Rust compiles generic code into code that specifies the type in each -instance, we pay no runtime cost for using generics. When the code runs, it -performs just like it would if we had duplicated each definition by hand. The -process of monomorphization makes Rust’s generics extremely efficient at -runtime. - -## Traits: Defining Shared Behavior - -A *trait* tells the Rust compiler about functionality a particular type has and -can share with other types. We can use traits to define shared behavior in an -abstract way. We can use trait bounds to specify that a generic can be any type -that has certain behavior. - -> Note: Traits are similar to a feature often called *interfaces* in other -> languages, although with some differences. - -### Defining a Trait - -A type’s behavior consists of the methods we can call on that type. Different -types share the same behavior if we can call the same methods on all of those -types. Trait definitions are a way to group method signatures together to -define a set of behaviors necessary to accomplish some purpose. - -For example, let’s say we have multiple structs that hold various kinds and -amounts of text: a `NewsArticle` struct that holds a news story filed in a -particular location and a `Tweet` that can have at most 280 characters along -with metadata that indicates whether it was a new tweet, a retweet, or a reply -to another tweet. - -We want to make a media aggregator library that can display summaries of data -that might be stored in a `NewsArticle` or `Tweet` instance. To do this, we -need a summary from each type, and we need to request that summary by calling a -`summarize` method on an instance. Listing 10-12 shows the definition of a -`Summary` trait that expresses this behavior: - -Filename: src/lib.rs - -``` -pub trait Summary { - fn summarize(&self) -> String; -} -``` - -Listing 10-12: Definition of a `Summary` trait that consists of the behavior -provided by a `summarize` method - -Here, we declare a trait using the `trait` keyword and then the trait’s name, -which is `Summary` in this case. Inside the curly brackets we declare the -method signatures that describe the behaviors of the types that implement this -trait, which in this case is `fn summarize(&self) -> String`. - -After the method signature, instead of providing an implementation within curly -brackets, we use a semicolon. Each type implementing this trait must provide -its own custom behavior for the body of the method. The compiler will enforce -that any type that has the `Summary` trait will have the method `summarize` -defined with this signature exactly. - -A trait can have multiple methods in its body: the method signatures are listed -one per line and each line ends in a semicolon. - -### Implementing a Trait on a Type - -Now that we’ve defined the desired behavior using the `Summary` trait, we can -implement it on the types in our media aggregator. Listing 10-13 shows an -implementation of the `Summary` trait on the `NewsArticle` struct that uses the -headline, the author, and the location to create the return value of -`summarize`. For the `Tweet` struct, we define `summarize` as the username -followed by the entire text of the tweet, assuming that tweet content is -already limited to 280 characters. - -Filename: src/lib.rs - -``` -pub struct NewsArticle { - pub headline: String, - pub location: String, - pub author: String, - pub content: String, -} - -impl Summary for NewsArticle { - fn summarize(&self) -> String { - format!("{}, by {} ({})", self.headline, self.author, self.location) - } -} - -pub struct Tweet { - pub username: String, - pub content: String, - pub reply: bool, - pub retweet: bool, -} - -impl Summary for Tweet { - fn summarize(&self) -> String { - format!("{}: {}", self.username, self.content) - } -} -``` - -Listing 10-13: Implementing the `Summary` trait on the `NewsArticle` and -`Tweet` types - -Implementing a trait on a type is similar to implementing regular methods. The -difference is that after `impl`, we put the trait name that we want to -implement, then use the `for` keyword, and then specify the name of the type we -want to implement the trait for. Within the `impl` block, we put the method -signatures that the trait definition has defined. Instead of adding a semicolon -after each signature, we use curly brackets and fill in the method body with -the specific behavior that we want the methods of the trait to have for the -particular type. - -After implementing the trait, we can call the methods on instances of -`NewsArticle` and `Tweet` in the same way we call regular methods, like this: - -``` -let tweet = Tweet { - username: String::from("horse_ebooks"), - content: String::from("of course, as you probably already know, people"), - reply: false, - retweet: false, -}; - -println!("1 new tweet: {}", tweet.summarize()); -``` - -This code prints `1 new tweet: horse_ebooks: of course, as you probably already -know, people`. - -Note that because we defined the `Summary` trait and the `NewsArticle` and -`Tweet` types in the same *lib.rs* in Listing 10-13, they’re all in the same -scope. Let’s say this *lib.rs* is for a crate we’ve called `aggregator`, and -someone else wants to use our crate’s functionality to implement the `Summary` -trait on a struct defined within their library’s scope. They would need to -import the trait into their scope first. They would do so by specifying `use -aggregator::Summary;`, which then enables them to implement `Summary` for their -type. The `Summary` trait would also need to be a public trait for another -crate to implement it, which it is because we put the `pub` keyword before -`trait` in Listing 10-12. - -One restriction to note with trait implementations is that we can implement a -trait on a type only if either the trait or the type is local to your crate. -For example, we can implement standard library traits like `Display` on a -custom type like `Tweet` as part of our `aggregator` crate functionality, -because the type `Tweet` is local to our `aggregator` crate. We can also -implement `Summary` on `Vec` in our `aggregator` crate, because the -trait `Summary` is local to our `aggregator` crate. - -But we can’t implement external traits on external types. For example, we can’t -implement the `Display` trait on `Vec` within our `aggregator` crate, -because `Display` and `Vec` are defined in the standard library and aren’t -local to our `aggregator` crate. This restriction is part of a property of -programs called *coherence*, and more specifically the *orphan rule*, so named -because the parent type is not present. This rule ensures that other people’s -code can’t break your code and vice versa. Without the rule, two crates could -implement the same trait for the same type, and Rust wouldn’t know which -implementation to use. - -### Default Implementations - -Sometimes it’s useful to have default behavior for some or all of the methods -in a trait instead of requiring implementations for all methods on every type. -Then, as we implement the trait on a particular type, we can keep or override -each method’s default behavior. - -Listing 10-14 shows how to specify a default string for the `summarize` method -of the `Summary` trait instead of only defining the method signature, like we -did in Listing 10-12: - -Filename: src/lib.rs - -``` -pub trait Summary { - fn summarize(&self) -> String { - String::from("(Read more...)") - } -} -``` - -Listing 10-14: Definition of a `Summary` trait with a default implementation of -the `summarize` method - -To use a default implementation to summarize instances of `NewsArticle` instead -of defining a custom implementation, we specify an empty `impl` block with -`impl Summary for NewsArticle {}`. - -Even though we’re no longer defining the `summarize` method on `NewsArticle` -directly, we’ve provided a default implementation and specified that -`NewsArticle` implements the `Summary` trait. As a result, we can still call -the `summarize` method on an instance of `NewsArticle`, like this: - -``` -let article = NewsArticle { - headline: String::from("Penguins win the Stanley Cup Championship!"), - location: String::from("Pittsburgh, PA, USA"), - author: String::from("Iceburgh"), - content: String::from("The Pittsburgh Penguins once again are the best - hockey team in the NHL."), -}; - -println!("New article available! {}", article.summarize()); -``` - -This code prints `New article available! (Read more...)`. - -Creating a default implementation for `summarize` doesn’t require us to change -anything about the implementation of `Summary` on `Tweet` in Listing 10-13. The -reason is that the syntax for overriding a default implementation is the same -as the syntax for implementing a trait method that doesn’t have a default -implementation. - -Default implementations can call other methods in the same trait, even if those -other methods don’t have a default implementation. In this way, a trait can -provide a lot of useful functionality and only require implementors to specify -a small part of it. For example, we could define the `Summary` trait to have a -`summarize_author` method whose implementation is required, and then define a -`summarize` method that has a default implementation that calls the -`summarize_author` method: - -``` -pub trait Summary { - fn summarize_author(&self) -> String; - - fn summarize(&self) -> String { - format!("(Read more from {}...)", self.summarize_author()) - } -} -``` - -To use this version of `Summary`, we only need to define `summarize_author` -when we implement the trait on a type: - -``` -impl Summary for Tweet { - fn summarize_author(&self) -> String { - format!("@{}", self.username) - } -} -``` - -After we define `summarize_author`, we can call `summarize` on instances of the -`Tweet` struct, and the default implementation of `summarize` will call the -definition of `summarize_author` that we’ve provided. Because we’ve implemented -`summarize_author`, the `Summary` trait has given us the behavior of the -`summarize` method without requiring us to write any more code. - -``` -let tweet = Tweet { - username: String::from("horse_ebooks"), - content: String::from("of course, as you probably already know, people"), - reply: false, - retweet: false, -}; - -println!("1 new tweet: {}", tweet.summarize()); -``` - -This code prints `1 new tweet: (Read more from @horse_ebooks...)`. - -Note that it isn’t possible to call the default implementation from an -overriding implementation of that same method. - -### Trait Bounds - -Now that you know how to define traits and implement those traits on types, we -can explore how to use traits with generic type parameters. We can use *trait -bounds* to constrain generic types to ensure the type will be limited to those -that implement a particular trait and behavior. - -For example, in Listing 10-13, we implemented the `Summary` trait on the types -`NewsArticle` and `Tweet`. We can define a function `notify` that calls the -`summarize` method on its parameter `item`, which is of the generic type `T`. -To be able to call `summarize` on `item` without getting an error telling us -that the generic type `T` doesn’t implement the method `summarize`, we can use -trait bounds on `T` to specify that `item` must be of a type that implements -the `Summary` trait: - -``` -pub fn notify(item: T) { - println!("Breaking news! {}", item.summarize()); -} -``` - -We place trait bounds with the declaration of the generic type parameter, after -a colon and inside angle brackets. Because of the trait bound on `T`, we can -call `notify` and pass in any instance of `NewsArticle` or `Tweet`. Code that -calls the function with any other type, like a `String` or an `i32`, won’t -compile, because those types don’t implement `Summary`. - -We can specify multiple trait bounds on a generic type using the `+` syntax. -For example, to use display formatting on the type `T` in a function as well as -the `summarize` method, we can use `T: Summary + Display` to say `T` can be any -type that implements `Summary` and `Display`. - -However, there are downsides to using too many trait bounds. Each generic has -its own trait bounds; so functions with multiple generic type parameters can -have lots of trait bound information between a function’s name and its -parameter list, making the function signature hard to read. For this reason, -Rust has alternate syntax for specifying trait bounds inside a `where` clause -after the function signature. So instead of writing this: - -``` -fn some_function(t: T, u: U) -> i32 { -``` - -we can use a `where` clause, like this: - -``` -fn some_function(t: T, u: U) -> i32 - where T: Display + Clone, - U: Clone + Debug -{ -``` - -This function’s signature is less cluttered in that the function name, -parameter list, and return type are close together, similar to a function -without lots of trait bounds. - -### Fixing the `largest` Function with Trait Bounds - -Now that you know how to specify the behavior you want to use using the generic -type parameter’s bounds, let’s return to Listing 10-5 to fix the definition of -the `largest` function that uses a generic type parameter! Last time we tried -to run that code, we received this error: - -``` -error[E0369]: binary operation `>` cannot be applied to type `T` - --> src/main.rs:5:12 - | -5 | if item > largest { - | ^^^^^^^^^^^^^^ - | - = note: an implementation of `std::cmp::PartialOrd` might be missing for `T` -``` - -In the body of `largest` we wanted to compare two values of type `T` using the -greater-than (`>`) operator. Because that operator is defined as a default -method on the standard library trait `std::cmp::PartialOrd`, we need to specify -`PartialOrd` in the trait bounds for `T` so the `largest` function can work on -slices of any type that we can compare. We don’t need to bring `PartialOrd` -into scope because it’s in the prelude. Change the signature of `largest` to -look like this: - -``` -fn largest(list: &[T]) -> T { -``` - -This time when we compile the code, we get a different set of errors: - -``` -error[E0508]: cannot move out of type `[T]`, a non-copy slice - --> src/main.rs:2:23 - | -2 | let mut largest = list[0]; - | ^^^^^^^ - | | - | cannot move out of here - | help: consider using a reference instead: `&list[0]` - -error[E0507]: cannot move out of borrowed content - --> src/main.rs:4:9 - | -4 | for &item in list.iter() { - | ^---- - | || - | |hint: to prevent move, use `ref item` or `ref mut item` - | cannot move out of borrowed content -``` - -The key line in this error is `cannot move out of type [T], a non-copy slice`. -With our non-generic versions of the `largest` function, we were only trying to -find the largest `i32` or `char`. As discussed in “Stack-Only Data: Copy” -section in Chapter 4, types like `i32` and `char` that have a known size can be -stored on the stack, so they implement the `Copy` trait. But when we made the -`largest` function generic, the `list` parameter could have types in it that -don’t implement the `Copy` trait. Consequently, we wouldn’t be able to move the -value out of `list[0]` and into the `largest` variable, resulting in this error. - -To call this code with only those types that implement the `Copy` trait, we can -add `Copy` to the trait bounds of `T`! Listing 10-15 shows the complete code of -a generic `largest` function that will compile as long as the types of the -values in the slice that we pass into the function implement the `PartialOrd` -*and* `Copy` traits, like `i32` and `char` do: - -Filename: src/main.rs - -``` -fn largest(list: &[T]) -> T { - let mut largest = list[0]; - - for &item in list.iter() { - if item > largest { - largest = item; - } - } - - largest -} - -fn main() { - let number_list = vec![34, 50, 25, 100, 65]; - - let result = largest(&number_list); - println!("The largest number is {}", result); - - let char_list = vec!['y', 'm', 'a', 'q']; - - let result = largest(&char_list); - println!("The largest char is {}", result); -} -``` - -Listing 10-15: A working definition of the `largest` function that works on any -generic type that implements the `PartialOrd` and `Copy` traits - -If we don’t want to restrict the `largest` function to the types that implement -the `Copy` trait, we could specify that `T` has the trait bound `Clone` instead -of `Copy`. Then we could clone each value in the slice when we want the -`largest` function to have ownership. Using the `clone` function means we’re -potentially making more heap allocations in the case of types that own heap -data like `String`, and heap allocations can be slow if we’re working with -large amounts of data. - -Another way we could implement `largest` is for the function to return a -reference to a `T` value in the slice. If we change the return type to `&T` -instead of `T`, thereby changing the body of the function to return a -reference, we wouldn’t need the `Clone` or `Copy` trait bounds and we could -avoid heap allocations. Try implementing these alternate solutions on your own! - -### Using Trait Bounds to Conditionally Implement Methods - -By using a trait bound with an `impl` block that uses generic type parameters, -we can implement methods conditionally for types that implement the specified -traits. For example, the type `Pair` in Listing 10-16 always implements the -`new` function. But `Pair` only implements the `cmp_display` method if its -inner type `T` implements the `PartialOrd` trait that enables comparison *and* -the `Display` trait that enables printing: - -``` -use std::fmt::Display; - -struct Pair { - x: T, - y: T, -} - -impl Pair { - fn new(x: T, y: T) -> Self { - Self { - x, - y, - } - } -} - -impl Pair { - fn cmp_display(&self) { - if self.x >= self.y { - println!("The largest member is x = {}", self.x); - } else { - println!("The largest member is y = {}", self.y); - } - } -} -``` - -Listing 10-16: Conditionally implement methods on a generic type depending on -trait bounds - -We can also conditionally implement a trait for any type that implements -another trait. Implementations of a trait on any type that satisfies the trait -bounds are called *blanket implementations* and are extensively used in the -Rust standard library. For example, the standard library implements the -`ToString` trait on any type that implements the `Display` trait. The `impl` -block in the standard library looks similar to this code: - -``` -impl ToString for T { - // --snip-- -} -``` - -Because the standard library has this blanket implementation, we can call the -`to_string` method defined by the `ToString` trait on any type that implements -the `Display` trait. For example, we can turn integers into their corresponding -`String` values like this because integers implement `Display`: - -``` -let s = 3.to_string(); -``` - -Blanket implementations appear in the documentation for the trait in the -“Implementors” section. - -Traits and trait bounds let us write code that uses generic type parameters to -reduce duplication but also specify to the compiler that we want the generic -type to have particular behavior. The compiler can then use the trait bound -information to check that all the concrete types used with our code provide the -correct behavior. In dynamically typed languages, we would get an error at -runtime if we called a method on a type that the type didn’t implement. But -Rust moves these errors to compile time so we’re forced to fix the problems -before our code is even able to run. Additionally, we don’t have to write code -that checks for behavior at runtime because we’ve already checked at compile -time. Doing so improves performance without having to give up the flexibility -of generics. - -Another kind of generic that we’ve already been using is called *lifetimes*. -Rather than ensuring that a type has the behavior we want, lifetimes ensure -that references are valid as long as we need them to be. Let’s look at how -lifetimes do that. - -## Validating References with Lifetimes - -One detail we didn’t discuss in the “References and Borrowing” section in -Chapter 4 is that every reference in Rust has a *lifetime*, which is the scope -for which that reference is valid. Most of the time lifetimes are implicit and -inferred, just like most of the time types are inferred. We must annotate types -when multiple types are possible. In a similar way, we must annotate lifetimes -when the lifetimes of references could be related in a few different ways. Rust -requires us to annotate the relationships using generic lifetime parameters to -ensure the actual references used at runtime will definitely be valid. - -The concept of lifetimes is somewhat different from tools in other programming -languages, arguably making lifetimes Rust’s most distinctive feature. Although -we won’t cover lifetimes in their entirety in this chapter, we’ll discuss -common ways you might encounter lifetime syntax so you can become familiar with -the concepts. See the “Advanced Lifetimes” section in Chapter 19 for more -detailed information. - -### Lifetimes Prevent Dangling References - -The main aim of lifetimes is to prevent dangling references, which cause a -program to reference data other than the data it’s intended to reference. -Consider the program in Listing 10-17, which has an outer scope and an inner -scope: - -``` -{ - let r; - - { - let x = 5; - r = &x; - } - - println!("r: {}", r); -} -``` - -Listing 10-17: An attempt to use a reference whose value has gone out of scope - -> Note: The example in Listing 10-17 and the next few examples declare -> variables without giving them an initial value, so the variable name exists -> in the outer scope. At first glance, this might appear to be in conflict with -> Rust having no null values. However, if we try to use a variable before -> giving it a value, we’ll get a compile time error, which shows that Rust -> indeed does not allow null values. - -The outer scope declares a variable named `r` with no initial value, and the -inner scope declares a variable named `x` with the initial value of `5`. Inside -the inner scope, we attempt to set the value of `r` as a reference to `x`. Then -the inner scope ends, and we attempt to print the value in `r`. This code won’t -compile because the value `r` is referring to has gone out of scope before we -try to use it. Here is the error message: - -``` -error[E0597]: `x` does not live long enough - --> src/main.rs:7:5 - | -6 | r = &x; - | - borrow occurs here -7 | } - | ^ `x` dropped here while still borrowed -... -10 | } - | - borrowed value needs to live until here -``` - -The variable `x` doesn’t “live long enough.” The reason is that `x` will be out -of scope when the inner scope ends on line 7. But `r` is still valid for the -outer scope; because its scope is larger, we say that it “lives longer.” If -Rust allowed this code to work, `r` would be referencing memory that was -deallocated when `x` went out of scope, and anything we tried to do with `r` -wouldn’t work correctly. So how does Rust determine that this code is invalid? -It uses a borrow checker. - -### The Borrow Checker - -The Rust compiler has a *borrow checker* that compares scopes to determine that -all borrows are valid. Listing 10-18 shows the same code as Listing 10-17 but -with annotations showing the lifetimes of the variables: - -``` -{ - let r; // ---------+-- 'a - // | - { // | - let x = 5; // -+-- 'b | - r = &x; // | | - } // -+ | - // | - println!("r: {}", r); // | -} // ---------+ -``` - -Listing 10-18: Annotations of the lifetimes of `r` and `x`, named `'a` and -`'b`, respectively - -Here, we’ve annotated the lifetime of `r` with `'a` and the lifetime of `x` -with `'b`. As you can see, the inner `'b` block is much smaller than the outer -`'a` lifetime block. At compile time, Rust compares the size of the two -lifetimes and sees that `r` has a lifetime of `'a` but that it refers to memory -with a lifetime of `'b`. The program is rejected because `'b` is shorter than -`'a`: the subject of the reference doesn’t live as long as the reference. - -Listing 10-19 fixes the code so it doesn’t have a dangling reference and -compiles without any errors: - -``` -{ - let x = 5; // ----------+-- 'b - // | - let r = &x; // --+-- 'a | - // | | - println!("r: {}", r); // | | - // --+ | -} // ----------+ -``` - -Listing 10-19: A valid reference because the data has a longer lifetime than -the reference - -Here, `x` has the lifetime `'b`, which in this case is larger than `'a`. This -means `r` can reference `x` because Rust knows that the reference in `r` will -always be valid while `x` is valid. - -Now that you know where the lifetimes of references are and how Rust analyzes -lifetimes to ensure references will always be valid, let’s explore generic -lifetimes of parameters and return values in the context of functions. - -### Generic Lifetimes in Functions - -Let’s write a function that returns the longer of two string slices. This -function will take two string slices and return a string slice. After we’ve -implemented the `longest` function, the code in Listing 10-20 should print `The -longest string is abcd`: - -Filename: src/main.rs - -``` -fn main() { - let string1 = String::from("abcd"); - let string2 = "xyz"; - - let result = longest(string1.as_str(), string2); - println!("The longest string is {}", result); -} -``` - -Listing 10-20: A `main` function that calls the `longest` function to find the -longer of two string slices - -Note that we want the function to take string slices, which are references, -because we don’t want the `longest` function to take ownership of its -parameters. We want to allow the function to accept slices of a `String` (the -type stored in the variable `string1`) as well as string literals (which is -what variable `string2` contains). - -Refer to the “String Slices as Parameters” section in Chapter 4 for more -discussion about why the parameters we use in Listing 10-20 are the ones we -want. - -If we try to implement the `longest` function as shown in Listing 10-21, it -won’t compile: - -Filename: src/main.rs - -``` -fn longest(x: &str, y: &str) -> &str { - if x.len() > y.len() { - x - } else { - y - } -} -``` - -Listing 10-21: An implementation of the `longest` function that returns the -longer of two string slices but does not yet compile - -Instead, we get the following error that talks about lifetimes: - -``` -error[E0106]: missing lifetime specifier - --> src/main.rs:1:33 - | -1 | fn longest(x: &str, y: &str) -> &str { - | ^ expected lifetime parameter - | - = help: this function's return type contains a borrowed value, but the -signature does not say whether it is borrowed from `x` or `y` -``` - -The help text reveals that the return type needs a generic lifetime parameter -on it because Rust can’t tell whether the reference being returned refers to -`x` or `y`. Actually, we don’t know either, because the `if` block in the body -of this function returns a reference to `x` and the `else` block returns a -reference to `y`! - -When we’re defining this function, we don’t know the concrete values that will -be passed into this function, so we don’t know whether the `if` case or the -`else` case will execute. We also don’t know the concrete lifetimes of the -references that will be passed in, so we can’t look at the scopes like we did -in Listings 10-18 and 10-19 to determine that the reference we return will -always be valid. The borrow checker can’t determine this either, because it -doesn’t know how the lifetimes of `x` and `y` relate to the lifetime of the -return value. To fix this error, we’ll add generic lifetime parameters that -define the relationship between the references so the borrow checker can -perform its analysis. - -### Lifetime Annotation Syntax - -Lifetime annotations don’t change how long any of the references live. Just -like functions can accept any type when the signature specifies a generic type -parameter, functions can accept references with any lifetime by specifying a -generic lifetime parameter. Lifetime annotations describe the relationships of -the lifetimes of multiple references to each other without affecting the -lifetimes. - -Lifetime annotations have a slightly unusual syntax: the names of lifetime -parameters must start with an apostrophe `'` and are usually all lowercase and -very short, like generic types. Most people use the name `'a`. We place -lifetime parameter annotations after the `&` of a reference, using a space to -separate the annotation from the reference’s type. - -Here are some examples: a reference to an `i32` without a lifetime parameter, a -reference to an `i32` that has a lifetime parameter named `'a`, and a mutable -reference to an `i32` that also has the lifetime `'a`: - -``` -&i32 // a reference -&'a i32 // a reference with an explicit lifetime -&'a mut i32 // a mutable reference with an explicit lifetime -``` - -One lifetime annotation by itself doesn’t have much meaning because the -annotations are meant to tell Rust how generic lifetime parameters of multiple -references relate to each other. For example, let’s say we have a function with -the parameter `first` that is a reference to an `i32` with lifetime `'a`. The -function also has another parameter named `second` that is another reference to -an `i32` that also has the lifetime `'a`. The lifetime annotations indicate -that the references `first` and `second` must both live as long as that generic -lifetime. - -### Lifetime Annotations in Function Signatures - -Now let’s examine lifetime annotations in the context of the `longest` -function. As with generic type parameters, we need to declare generic lifetime -parameters inside angle brackets between the function name and the parameter -list. The constraint we want to express in this signature is that all the -references in the parameters and the return value must have the same lifetime. -We’ll name the lifetime `'a`, and then add it to each reference, as shown in -Listing 10-22: - -Filename: src/main.rs - -``` -fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { - if x.len() > y.len() { - x - } else { - y - } -} -``` - -Listing 10-22: The `longest` function definition specifying that all the -references in the signature must have the same lifetime `'a` - -This code should compile and produce the result we want when we use it with the -`main` function in Listing 10-20. - -The function signature now tells Rust that for some lifetime `'a`, the function -takes two parameters, both of which are string slices that live at least as -long as lifetime `'a`. The function signature also tells Rust that the string -slice returned from the function will live at least as long as lifetime `'a`. -These constraints are what we want Rust to enforce. - -As discussed earlier, by specifying the lifetime parameters in this function -signature, we’re not changing the lifetimes of any values passed in or -returned. Instead, we’re specifying that the borrow checker should reject any -values that don’t adhere to these constraints. Note that the `longest` function -doesn’t need to know exactly how long `x` and `y` will live, only that some -scope can be substituted for `'a` that will satisfy this signature. - -When annotating lifetimes in functions, the annotations go in the function -signature, not in the function body. Rust can analyze the code within the -function without any help. However, when a function has references to or from -code outside that function, it becomes almost impossible for Rust to figure out -the lifetimes of the parameters or return values on its own. The lifetimes -might be different each time the function is called. This is why we need to -annotate the lifetimes manually. - -When we pass concrete references to `longest`, the concrete lifetime that is -substituted for `'a` is the part of the scope of `x` that overlaps with the -scope of `y`. In other words, the generic lifetime `'a` will get the concrete -lifetime that is equal to the smaller of the lifetimes of `x` and `y`. Because -we’ve annotated the returned reference with the same lifetime parameter `'a`, -the returned reference will also be valid for the length of the smaller of the -lifetimes of `x` and `y`. - -Let’s look at how the lifetime annotations restrict the `longest` function by -passing in references that have different concrete lifetimes. Listing 10-23 is -a straightforward example: - -Filename: src/main.rs - -``` -fn main() { - let string1 = String::from("long string is long"); - - { - let string2 = String::from("xyz"); - let result = longest(string1.as_str(), string2.as_str()); - println!("The longest string is {}", result); - } -} -``` - -Listing 10-23: Using the `longest` function with references to `String` values -that have different concrete lifetimes - -In this example, `string1` is valid until the end of the outer scope, `string2` -is valid until the end of the inner scope, and `result` references something -that is valid until the end of the inner scope. Run this code, and you’ll see -that the borrow checker approves of this code; it will compile and print `The -longest string is long string is long`. - -Next, let’s try an example that shows that the lifetime of the reference in -`result` must be the smaller lifetime of the two arguments. We’ll move the -declaration of the `result` variable outside the inner scope but leave the -assignment of the value to the `result` variable inside the scope with -`string2`. Then we’ll move the `println!` that uses `result` outside the inner -scope, after the inner scope has ended. The code in Listing 10-24 will not -compile: - -Filename: src/main.rs - -``` -fn main() { - let string1 = String::from("long string is long"); - let result; - { - let string2 = String::from("xyz"); - result = longest(string1.as_str(), string2.as_str()); - } - println!("The longest string is {}", result); -} -``` - -Listing 10-24: Attempting to use `result` after `string2` has gone out of -scope; the code won’t compile - -When we try to compile this code, we’ll get this error: - -``` -error[E0597]: `string2` does not live long enough - --> src/main.rs:15:5 - | -14 | result = longest(string1.as_str(), string2.as_str()); - | ------- borrow occurs here -15 | } - | ^ `string2` dropped here while still borrowed -16 | println!("The longest string is {}", result); -17 | } - | - borrowed value needs to live until here -``` - -The error shows that for `result` to be valid for the `println!` statement, -`string2` would need to be valid until the end of the outer scope. Rust knows -this because we annotated the lifetimes of the function parameters and return -values using the same lifetime parameter `'a`. - -As humans, we can look at this code and see that `string1` is longer than -`string2`, and therefore `result` will contain a reference to `string1`. -Because `string1` has not gone out of scope yet, a reference to `string1` will -still be valid for the `println!` statement. However, the compiler can’t see -that the reference is valid in this case. We’ve told Rust that the lifetime of -the reference returned by the `longest` function is the same as the smaller of -the lifetimes of the references passed in. Therefore, the borrow checker -disallows the code in Listing 10-24 as possibly having an invalid reference. - -Try designing more experiments that vary the values and lifetimes of the -references passed in to the `longest` function and how the returned reference -is used. Make hypotheses about whether or not your experiments will pass the -borrow checker before you compile; then check to see if you’re right! - -### Thinking in Terms of Lifetimes - -The way in which you need to specify lifetime parameters depends on what your -function is doing. For example, if we changed the implementation of the -`longest` function to always return the first parameter rather than the longest -string slice, we wouldn’t need to specify a lifetime on the `y` parameter. The -following code will compile: - -Filename: src/main.rs - -``` -fn longest<'a>(x: &'a str, y: &str) -> &'a str { - x -} -``` - -In this example, we’ve specified a lifetime parameter `'a` for the parameter -`x` and the return type, but not for the parameter `y`, because the lifetime of -`y` does not have any relationship with the lifetime of `x` or the return value. - -When returning a reference from a function, the lifetime parameter for the -return type needs to match the lifetime parameter for one of the parameters. If -the reference returned does *not* refer to one of the parameters, it must refer -to a value created within this function, which would be a dangling reference -because the value will go out of scope at the end of the function. Consider -this attempted implementation of the `longest` function that won’t compile: - -Filename: src/main.rs - -``` -fn longest<'a>(x: &str, y: &str) -> &'a str { - let result = String::from("really long string"); - result.as_str() -} -``` - -Here, even though we’ve specified a lifetime parameter `'a` for the return -type, this implementation will fail to compile because the return value -lifetime is not related to the lifetime of the parameters at all. Here is the -error message we get: - -``` -error[E0597]: `result` does not live long enough - --> src/main.rs:3:5 - | -3 | result.as_str() - | ^^^^^^ does not live long enough -4 | } - | - borrowed value only lives until here - | -note: borrowed value must be valid for the lifetime 'a as defined on the -function body at 1:1... - --> src/main.rs:1:1 - | -1 | / fn longest<'a>(x: &str, y: &str) -> &'a str { -2 | | let result = String::from("really long string"); -3 | | result.as_str() -4 | | } - | |_^ -``` - -The problem is that `result` goes out of scope and gets cleaned up at the end -of the `longest` function. We’re also trying to return a reference to `result` -from the function. There is no way we can specify lifetime parameters that -would change the dangling reference, and Rust won’t let us create a dangling -reference. In this case, the best fix would be to return an owned data type -rather than a reference so the calling function is then responsible for -cleaning up the value. - -Ultimately, lifetime syntax is about connecting the lifetimes of various -parameters and return values of functions. Once they’re connected, Rust has -enough information to allow memory-safe operations and disallow operations that -would create dangling pointers or otherwise violate memory safety. - -### Lifetime Annotations in Struct Definitions - -So far, we’ve only defined structs to hold owned types. It’s possible for -structs to hold references, but in that case we would need to add a lifetime -annotation on every reference in the struct’s definition. Listing 10-25 has a -struct named `ImportantExcerpt` that holds a string slice: - -Filename: src/main.rs - -``` -struct ImportantExcerpt<'a> { - part: &'a str, -} - -fn main() { - let novel = String::from("Call me Ishmael. Some years ago..."); - let first_sentence = novel.split('.') - .next() - .expect("Could not find a '.'"); - let i = ImportantExcerpt { part: first_sentence }; -} -``` - -Listing 10-25: A struct that holds a reference, so its definition needs a -lifetime annotation - -This struct has one field, `part`, that holds a string slice, which is a -reference. As with generic data types, we declare the name of the generic -lifetime parameter inside angle brackets after the name of the struct so we can -use the lifetime parameter in the body of the struct definition. This -annotation means an instance of `ImportantExcerpt` can’t outlive the reference -it holds in its `part` field. - -The `main` function here creates an instance of the `ImportantExcerpt` struct -that holds a reference to the first sentence of the `String` owned by the -variable `novel`. The data in `novel` exists before the `ImportantExcerpt` -instance is created. In addition, `novel` doesn’t go out of scope until after -the `ImportantExcerpt` goes out of scope, so the reference in the -`ImportantExcerpt` instance is valid. - -### Lifetime Elision - -You’ve learned that every reference has a lifetime and that you need to specify -lifetime parameters for functions or structs that use references. However, in -Chapter 4 we had a function in the “String Slices” section, which is shown again -in Listing 10-26, that compiled without lifetime annotations: - -Filename: src/lib.rs - -``` -fn first_word(s: &str) -> &str { - let bytes = s.as_bytes(); - - for (i, &item) in bytes.iter().enumerate() { - if item == b' ' { - return &s[0..i]; - } - } - - &s[..] -} -``` - -Listing 10-26: A function we defined in Chapter 4 that compiled without -lifetime annotations, even though the parameter and return type are references - -The reason this function compiles without lifetime annotations is historical: -in early versions (pre-1.0) of Rust, this code wouldn’t have compiled because -every reference needed an explicit lifetime. At that time, the function -signature would have been written like this: - -``` -fn first_word<'a>(s: &'a str) -> &'a str { -``` - -After writing a lot of Rust code, the Rust team found that Rust programmers -were entering the same lifetime annotations repeatedly in particular -situations. These situations were predictable and followed a few deterministic -patterns. The developers programmed these patterns into the compiler’s code so -the borrow checker could infer the lifetimes in these situations and not need -explicit annotations. - -This piece of Rust history is relevant because it’s possible that more -deterministic patterns will emerge and be added to the compiler. In the future, -even fewer lifetime annotations might be required. - -The patterns programmed into Rust’s analysis of references are called the -*lifetime elision rules*. These aren’t rules for programmers to follow; they’re -a set of particular cases that the compiler will consider, and if your code -fits these cases, you don’t need to write the lifetimes explicitly. - -The elision rules don’t provide full inference. If Rust deterministically -applies the rules but there is still ambiguity as to what lifetimes the -references have, the compiler won’t guess what the lifetime of the remaining -references should be. In this case, instead of guessing, the compiler will give -you an error that you can resolve by adding the lifetime annotations that -specify how the references relate to each other. - -Lifetimes on function or method parameters are called *input lifetimes*, and -lifetimes on return values are called *output lifetimes*. - -The compiler uses three rules to figure out what lifetimes references have when -there aren’t explicit annotations. The first rule applies to input lifetimes, -and the second and third rules apply to output lifetimes. If the compiler gets -to the end of the three rules and there are still references for which it can’t -figure out lifetimes, the compiler will stop with an error. - -The first rule is that each parameter that is a reference gets its own lifetime -parameter. In other words, a function with one parameter gets one lifetime -parameter: `fn foo<'a>(x: &'a i32)`; a function with two parameters gets two -separate lifetime parameters: `fn foo<'a, 'b>(x: &'a i32, y: &'b i32)`; and so -on. - -The second rule is if there is exactly one input lifetime parameter, that -lifetime is assigned to all output lifetime parameters: `fn foo<'a>(x: &'a i32) --> &'a i32`. - -The third rule is if there are multiple input lifetime parameters, but one of -them is `&self` or `&mut self` because this is a method, the lifetime of `self` -is assigned to all output lifetime parameters. This third rule makes methods -much nicer to read and write because fewer symbols are necessary. - -Let’s pretend we’re the compiler. We’ll apply these rules to figure out what -the lifetimes of the references in the signature of the `first_word` function -in Listing 10-26 are. The signature starts without any lifetimes associated -with the references: - -``` -fn first_word(s: &str) -> &str { -``` - -Then the compiler applies the first rule, which specifies that each parameter -gets its own lifetime. We’ll call it `'a` as usual, so now the signature is: - -``` -fn first_word<'a>(s: &'a str) -> &str { -``` - -The second rule applies because there is exactly one input lifetime. The second -rule specifies that the lifetime of the one input parameter gets assigned to -the output lifetime, so the signature is now this: - -``` -fn first_word<'a>(s: &'a str) -> &'a str { -``` - -Now all the references in this function signature have lifetimes, and the -compiler can continue its analysis without needing the programmer to annotate -the lifetimes in this function signature. - -Let’s look at another example, this time using the `longest` function that had -no lifetime parameters when we started working with it in Listing 10-21: - -``` -fn longest(x: &str, y: &str) -> &str { -``` - -Let’s apply the first rule: each parameter gets its own lifetime. This time we -have two parameters instead of one, so we have two lifetimes: - -``` -fn longest<'a, 'b>(x: &'a str, y: &'b str) -> &str { -``` - -You can see that the second rule doesn’t apply because there is more than one -input lifetime. The third rule doesn’t apply either, because `longest` is a -function rather than a method, so none of the parameters are `self`. After -working through all three rules, we still haven’t figured out what the return -type’s lifetime is. This is why we got an error trying to compile the code in -Listing 10-21: the compiler worked through the lifetime elision rules but still -couldn’t figure out all the lifetimes of the references in the signature. - -Because the third rule really only applies in method signatures, we’ll look at -lifetimes in that context next to see why the third rule means we don’t have to -annotate lifetimes in method signatures very often. - -### Lifetime Annotations in Method Definitions - -When we implement methods on a struct with lifetimes, we use the same syntax as -that of generic type parameters shown in Listing 10-11. Where we declare and -use the lifetime parameters depends on whether they’re related to the struct -fields or the method parameters and return values. - -Lifetime names for struct fields always need to be declared after the `impl` -keyword and then used after the struct’s name, because those lifetimes are part -of the struct’s type. - -In method signatures inside the `impl` block, references might be tied to the -lifetime of references in the struct’s fields, or they might be independent. In -addition, the lifetime elision rules often make it so that lifetime annotations -aren’t necessary in method signatures. Let’s look at some examples using the -struct named `ImportantExcerpt` that we defined in Listing 10-25. - -First, we’ll use a method named `level` whose only parameter is a reference to -`self` and whose return value is an `i32`, which is not a reference to anything: - -``` -impl<'a> ImportantExcerpt<'a> { - fn level(&self) -> i32 { - 3 - } -} -``` - -The lifetime parameter declaration after `impl` and use after the type name is -required, but we’re not required to annotate the lifetime of the reference to -`self` because of the first elision rule. - -Here is an example where the third lifetime elision rule applies: - -``` -impl<'a> ImportantExcerpt<'a> { - fn announce_and_return_part(&self, announcement: &str) -> &str { - println!("Attention please: {}", announcement); - self.part - } -} -``` - -There are two input lifetimes, so Rust applies the first lifetime elision rule -and gives both `&self` and `announcement` their own lifetimes. Then, because -one of the parameters is `&self`, the return type gets the lifetime of `&self`, -and all lifetimes have been accounted for. - -### The Static Lifetime - -One special lifetime we need to discuss is `'static`, which denotes the entire -duration of the program. All string literals have the `'static` lifetime, which -we can annotate as follows: `let s: &'static str = "I have a static lifetime.";` - -The text of this string is stored directly in the binary of your program, which -is always available. Therefore, the lifetime of all string literals is -`'static`. - -You might see suggestions to use the `'static` lifetime in error messages. But -before specifying `'static` as the lifetime for a reference, think about -whether the reference you have actually lives the entire lifetime of your -program or not. You might consider whether you want it to live that long, even -if it could. Most of the time, the problem results from attempting to create a -dangling reference or a mismatch of the available lifetimes. In such cases, the -solution is fixing those problems, not specifying the `'static` lifetime. - -## Generic Type Parameters, Trait Bounds, and Lifetimes Together - -Let’s briefly look at the syntax of specifying generic type parameters, trait -bounds, and lifetimes all in one function! - -``` -use std::fmt::Display; - -fn longest_with_an_announcement<'a, T>(x: &'a str, y: &'a str, ann: T) -> &'a -str - where T: Display -{ - println!("Announcement! {}", ann); - if x.len() > y.len() { - x - } else { - y - } -} -``` - -This is the `longest` function from Listing 10-22 that returns the longer of -two string slices. But now it has an extra parameter named `ann` of the generic -type `T`, which can be filled in by any type that implements the `Display` -trait as specified by the `where` clause. This extra parameter will be printed -before the function compares the lengths of the string slices, which is why the -`Display` trait bound is necessary. Because lifetimes are a type of generic, -the declarations of the lifetime parameter `'a` and the generic type parameter -`T` go in the same list inside the angle brackets after the function name. - -## Summary - -We covered a lot in this chapter! Now that you know about generic type -parameters, traits and trait bounds, and generic lifetime parameters, you’re -ready to write code without repetition yet works in many different situations. -Generic type parameters let you apply the code to different types. Traits and -trait bounds ensure that even though the types are generic, they’ll have the -behavior the code needs. You learned how to use lifetime annotations to ensure -that this flexible code won’t have any dangling references. And all of this -analysis happens at compile time, which doesn’t affect runtime performance! - -Believe it or not, there is much more to learn on the topics we discussed in -this chapter: Chapter 17 discusses trait objects, which are another way to use -traits. Chapter 19 covers more complex scenarios involving lifetime annotations -as well as some advanced type system features. But in the next chapter, you’ll -learn how to write tests in Rust so you can make sure your code is working the -way it should. diff --git a/second-edition/nostarch/chapter11.md b/second-edition/nostarch/chapter11.md deleted file mode 100644 index b05c05ea80..0000000000 --- a/second-edition/nostarch/chapter11.md +++ /dev/null @@ -1,1442 +0,0 @@ - -[TOC] - -# Writing Automated Tests - -In his 1972 essay “The Humble Programmer,” Edsger W. Dijkstra said that -“Program testing can be a very effective way to show the presence of bugs, but -it is hopelessly inadequate for showing their absence.” That doesn’t mean we -shouldn’t try to test as much as we can! - -Correctness in our programs is the extent to which our code does what we intend -it to do. Rust is designed with a high degree of concern about the correctness -of programs, but correctness is complex and not easy to prove. Rust’s type -system shoulders a huge part of this burden, but the type system cannot catch -every kind of incorrectness. As such, Rust includes support for writing -automated software tests within the language. - -As an example, say we write a function called `add_two` that adds 2 to whatever -number is passed to it. This function’s signature accepts an integer as a -parameter and returns an integer as a result. When we implement and compile -that function, Rust does all the type checking and borrow checking that you’ve -learned so far to ensure that, for instance, we aren’t passing a `String` value -or an invalid reference to this function. But Rust *can’t* check that this -function will do precisely what we intend, which is return the parameter plus 2 -rather than, say, the parameter plus 10 or the parameter minus 50! That’s where -tests come in. - -We can write tests that assert, for example, that when we pass `3` to the -`add_two` function, the returned value is `5`. We can run these tests whenever -we make changes to our code to make sure any existing correct behavior has not -changed. - -Testing is a complex skill: although we can’t cover every detail about how to -write good tests in one chapter, we’ll discuss the mechanics of Rust’s testing -facilities. We’ll talk about the annotations and macros available to you when -writing your tests, the default behavior and options provided for running your -tests, and how to organize tests into unit tests and integration tests. - -## How to Write Tests - -Tests are Rust functions that verify that the non-test code is functioning in -the expected manner. The bodies of test functions typically perform these three -actions: - -1. Set up any needed data or state. -2. Run the code you want to test. -3. Assert the results are what you expect. - -Let’s look at the features Rust provides specifically for writing tests that -take these actions, which include the `test` attribute, a few macros, and the -`should_panic` attribute. - -### The Anatomy of a Test Function - -At its simplest, a test in Rust is a function that’s annotated with the `test` -attribute. Attributes are metadata about pieces of Rust code; one example is -the `derive` attribute we used with structs in Chapter 5. To change a function -into a test function, add `#[test]` on the line before `fn`. When you run your -tests with the `cargo test` command, Rust builds a test runner binary that runs -the functions annotated with the `test` attribute and reports on whether each -test function passes or fails. - -In Chapter 7, we saw that when we make a new library project with Cargo, a test -module with a test function in it is automatically generated for us. This -module helps you start writing your tests so you don’t have to look up the -exact structure and syntax of test functions every time you start a new -project. You can add as many additional test functions and as many test modules -as you want! - -We’ll explore some aspects of how tests work by experimenting with the template -test generated for us without actually testing any code. Then we’ll write some -real-world tests that call some code that we’ve written and assert that its -behavior is correct. - -Let’s create a new library project called `adder`: - -``` -$ cargo new adder --lib - Created library `adder` project -$ cd adder -``` - -The contents of the *src/lib.rs* file in your `adder` library should look like -Listing 11-1: - -Filename: src/lib.rs - -``` -#[cfg(test)] -mod tests { - #[test] - fn it_works() { - assert_eq!(2 + 2, 4); - } -} -``` - -Listing 11-1: The test module and function generated automatically by `cargo -new` - -For now, let’s ignore the top two lines and focus on the function to see how it -works. Note the `#[test]` annotation before the `fn` line: this attribute -indicates this is a test function, so the test runner knows to treat this -function as a test. We could also have non-test functions in the `tests` module -to help set up common scenarios or perform common operations, so we need to -indicate which functions are tests by using the `#[test]` attribute. - -The function body uses the `assert_eq!` macro to assert that 2 + 2 equals 4. -This assertion serves as an example of the format for a typical test. Let’s run -it to see that this test passes. - -The `cargo test` command runs all tests in our project, as shown in Listing -11-2: - -``` -$ cargo test - Compiling adder v0.1.0 (file:///projects/adder) - Finished dev [unoptimized + debuginfo] target(s) in 0.22 secs - Running target/debug/deps/adder-ce99bcc2479f4607 - -running 1 test -test tests::it_works ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out - - Doc-tests adder - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out -``` - -Listing 11-2: The output from running the automatically generated test - -Cargo compiled and ran the test. After the `Compiling`, `Finished`, and -`Running` lines is the line `running 1 test`. The next line shows the name -of the generated test function, called `it_works`, and the result of running -that test, `ok`. The overall summary of running the tests appears next. The -text `test result: ok.` means that all the tests passed, and the portion that -reads `1 passed; 0 failed` totals the number of tests that passed or failed. - -Because we don’t have any tests we’ve marked as ignored, the summary shows `0 -ignored`. We also haven’t filtered the tests being run, so the end of the -summary shows `0 filtered out`. We’ll talk about ignoring and filtering out -tests in the next section, “Controlling How Tests Are Run.” - -The `0 measured` statistic is for benchmark tests that measure performance. -Benchmark tests are, as of this writing, only available in nightly Rust. See -the documentation about benchmark tests at -*https://doc.rust-lang.org/nightly/unstable-book/library-features/test.html* to -learn more. - -The next part of the test output, which starts with `Doc-tests adder`, is for -the results of any documentation tests. We don’t have any documentation tests -yet, but Rust can compile any code examples that appear in our API -documentation. This feature helps us keep our docs and our code in sync! We’ll -discuss how to write documentation tests in the “Documentation Comments” -section of Chapter 14. For now, we’ll ignore the `Doc-tests` output. - -Let’s change the name of our test to see how that changes the test output. -Change the `it_works` function to a different name, such as `exploration`, like -so: - -Filename: src/lib.rs - -``` -#[cfg(test)] -mod tests { - #[test] - fn exploration() { - assert_eq!(2 + 2, 4); - } -} -``` - -Then run `cargo test` again. The output now shows `exploration` instead of -`it_works`: - -``` -running 1 test -test tests::exploration ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out -``` - -Let’s add another test, but this time we’ll make a test that fails! Tests fail -when something in the test function panics. Each test is run in a new thread, -and when the main thread sees that a test thread has died, the test is marked -as failed. We talked about the simplest way to cause a panic in Chapter 9, -which is to call the `panic!` macro. Enter the new test, `another`, so your -*src/lib.rs* file looks like Listing 11-3: - -Filename: src/lib.rs - -``` -#[cfg(test)] -mod tests { - #[test] - fn exploration() { - assert_eq!(2 + 2, 4); - } - - #[test] - fn another() { - panic!("Make this test fail"); - } -} -``` - -Listing 11-3: Adding a second test that will fail because we call the `panic!` -macro - -Run the tests again using `cargo test`. The output should look like Listing -11-4, which shows that our `exploration` test passed and `another` failed: - -``` -running 2 tests -test tests::exploration ... ok -test tests::another ... FAILED - -failures: - ----- tests::another stdout ---- - thread 'tests::another' panicked at 'Make this test fail', src/lib.rs:10:8 -note: Run with `RUST_BACKTRACE=1` for a backtrace. - -failures: - tests::another - -test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out - -error: test failed -``` - -Listing 11-4: Test results when one test passes and one test fails - -Instead of `ok`, the line `test tests::another` shows `FAILED`. Two new -sections appear between the individual results and the summary: the first -section displays the detailed reason for each test failure. In this case, -`another` failed because it `panicked at 'Make this test fail'`, which happened -on line 10 in the *src/lib.rs* file. The next section lists just the names of -all the failing tests, which is useful when there are lots of tests and lots of -detailed failing test output. We can use the name of a failing test to run just -that test to more easily debug it; we’ll talk more about ways to run tests in -the “Controlling How Tests Are Run” section. - -The summary line displays at the end: overall, our test result is `FAILED`. -We had one test pass and one test fail. - -Now that you’ve seen what the test results look like in different scenarios, -let’s look at some macros other than `panic!` that are useful in tests. - -### Checking Results with the `assert!` Macro - -The `assert!` macro, provided by the standard library, is useful when you want -to ensure that some condition in a test evaluates to `true`. We give the -`assert!` macro an argument that evaluates to a Boolean. If the value is -`true`, `assert!` does nothing and the test passes. If the value is `false`, -the `assert!` macro calls the `panic!` macro, which causes the test to fail. -Using the `assert!` macro helps us check that our code is functioning in the -way we intend. - -In Chapter 5, Listing 5-15, we used a `Rectangle` struct and a `can_hold` -method, which are repeated here in Listing 11-5. Let’s put this code in the -*src/lib.rs* file and write some tests for it using the `assert!` macro. - -Filename: src/lib.rs - -``` -#[derive(Debug)] -pub struct Rectangle { - length: u32, - width: u32, -} - -impl Rectangle { - pub fn can_hold(&self, other: &Rectangle) -> bool { - self.length > other.length && self.width > other.width - } -} -``` - -Listing 11-5: Using the `Rectangle` struct and its `can_hold` method from -Chapter 5 - -The `can_hold` method returns a Boolean, which means it’s a perfect use case -for the `assert!` macro. In Listing 11-6, we write a test that exercises the -`can_hold` method by creating a `Rectangle` instance that has a length of 8 and -a width of 7 and asserting that it can hold another `Rectangle` instance that -has a length of 5 and a width of 1: - -Filename: src/lib.rs - -``` -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn larger_can_hold_smaller() { - let larger = Rectangle { length: 8, width: 7 }; - let smaller = Rectangle { length: 5, width: 1 }; - - assert!(larger.can_hold(&smaller)); - } -} -``` - -Listing 11-6: A test for `can_hold` that checks whether a larger rectangle can -indeed hold a smaller rectangle - -Note that we’ve added a new line inside the `tests` module: `use super::*;`. -The `tests` module is a regular module that follows the usual visibility rules -we covered in Chapter 7 in the “Privacy Rules” section. Because the `tests` -module is an inner module, we need to bring the code under test in the outer -module into the scope of the inner module. We use a glob here so anything we -define in the outer module is available to this `tests` module. - -We’ve named our test `larger_can_hold_smaller`, and we’ve created the two -`Rectangle` instances that we need. Then we called the `assert!` macro and -passed it the result of calling `larger.can_hold(&smaller)`. This expression -is supposed to return `true`, so our test should pass. Let’s find out! - -``` -running 1 test -test tests::larger_can_hold_smaller ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out -``` - -It does pass! Let’s add another test, this time asserting that a smaller -rectangle cannot hold a larger rectangle: - -Filename: src/lib.rs - -``` -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn larger_can_hold_smaller() { - // --snip-- - } - - #[test] - fn smaller_cannot_hold_larger() { - let larger = Rectangle { length: 8, width: 7 }; - let smaller = Rectangle { length: 5, width: 1 }; - - assert!(!smaller.can_hold(&larger)); - } -} -``` - -Because the correct result of the `can_hold` function in this case is `false`, -we need to negate that result before we pass it to the `assert!` macro. As a -result, our test will pass if `can_hold` returns `false`: - -``` -running 2 tests -test tests::smaller_cannot_hold_larger ... ok -test tests::larger_can_hold_smaller ... ok - -test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out -``` - -Two tests that pass! Now let’s see what happens to our test results when we -introduce a bug in our code. Let’s change the implementation of the `can_hold` -method by replacing the greater-than sign with a less-than sign when it -compares the lengths: - -``` -// --snip-- - -impl Rectangle { - pub fn can_hold(&self, other: &Rectangle) -> bool { - self.length < other.length && self.width > other.width - } -} -``` - -Running the tests now produces the following: - -``` -running 2 tests -test tests::smaller_cannot_hold_larger ... ok -test tests::larger_can_hold_smaller ... FAILED - -failures: - ----- tests::larger_can_hold_smaller stdout ---- - thread 'tests::larger_can_hold_smaller' panicked at 'assertion failed: - larger.can_hold(&smaller)', src/lib.rs:22:8 -note: Run with `RUST_BACKTRACE=1` for a backtrace. - -failures: - tests::larger_can_hold_smaller - -test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out -``` - -Our tests caught the bug! Because `larger.length` is 8 and `smaller.length` is -5, the comparison of the lengths in `can_hold` now returns `false`: 8 is not -less than 5. - -### Testing Equality with the `assert_eq!` and `assert_ne!` Macros - -A common way to test functionality is to compare the result of the code under -test to the value you expect the code to return to make sure they’re equal. You -could do this using the `assert!` macro and passing it an expression using the -`==` operator. However, this is such a common test that the standard library -provides a pair of macros—`assert_eq!` and `assert_ne!`—to perform this test -more conveniently. These macros compare two arguments for equality or -inequality, respectively. They’ll also print the two values if the assertion -fails, which makes it easier to see *why* the test failed; conversely, the -`assert!` macro only indicates that it got a `false` value for the `==` -expression, not the values that lead to the `false` value. - -In Listing 11-7, we write a function named `add_two` that adds `2` to its -parameter and returns the result. Then we test this function using the -`assert_eq!` macro. - -Filename: src/lib.rs - -``` -pub fn add_two(a: i32) -> i32 { - a + 2 -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn it_adds_two() { - assert_eq!(4, add_two(2)); - } -} -``` - -Listing 11-7: Testing the function `add_two` using the `assert_eq!` macro - -Let’s check that it passes! - -``` -running 1 test -test tests::it_adds_two ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out -``` - -The first argument we gave to the `assert_eq!` macro, `4`, is equal to the -result of calling `add_two(2)`. The line for this test is `test -tests::it_adds_two ... ok`, and the `ok` text indicates that our test passed! - -Let’s introduce a bug into our code to see what it looks like when a test that -uses `assert_eq!` fails. Change the implementation of the `add_two` function to -instead add `3`: - -``` -pub fn add_two(a: i32) -> i32 { - a + 3 -} -``` - -Run the tests again: - -``` -running 1 test -test tests::it_adds_two ... FAILED - -failures: - ----- tests::it_adds_two stdout ---- - thread 'tests::it_adds_two' panicked at 'assertion failed: `(left == right)` - left: `4`, - right: `5`', src/lib.rs:11:8 -note: Run with `RUST_BACKTRACE=1` for a backtrace. - -failures: - tests::it_adds_two - -test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out -``` - -Our test caught the bug! The `it_adds_two` test failed, displaying the message -`` assertion failed: `(left == right)` `` and showing that `left` was `4` and -`right` was `5`. This message is useful and helps us start debugging: it means -the `left` argument to `assert_eq!` was `4` but the `right` argument, where we -had `add_two(2)`, was `5`. - -Note that in some languages and test frameworks, the parameters to the -functions that assert two values are equal are called `expected` and `actual`, -and the order in which we specify the arguments matters. However, in Rust, -they’re called `left` and `right`, and the order in which we specify the value -we expect and the value that the code under test produces doesn’t matter. We -could write the assertion in this test as `assert_eq!(add_two(2), 4)`, which -would result in a failure message that displays `` assertion failed: `(left == -right)` `` and that `left` was `5` and `right` was `4`. - -The `assert_ne!` macro will pass if the two values we give it are not equal and -fail if they’re equal. This macro is most useful for cases when we’re not sure -what a value *will* be, but we know what the value definitely *won’t* be if our -code is functioning as we intend. For example, if we’re testing a function that -is guaranteed to change its input in some way, but the way in which the input -is changed depends on the day of the week that we run our tests, the best thing -to assert might be that the output of the function is not equal to the input. - -Under the surface, the `assert_eq!` and `assert_ne!` macros use the operators -`==` and `!=`, respectively. When the assertions fail, these macros print their -arguments using debug formatting, which means the values being compared must -implement the `PartialEq` and `Debug` traits. All the primitive types and most -of the standard library types implement these traits. For structs and enums -that you define, you’ll need to implement `PartialEq` to assert that values of -those types are equal or not equal. You’ll need to implement `Debug` to print -the values when the assertion fails. Because both traits are derivable traits, -as mentioned in Listing 5-12 in Chapter 5, this is usually as straightforward -as adding the `#[derive(PartialEq, Debug)]` annotation to your struct or enum -definition. See Appendix C, “Derivable Traits,” for more details about these -and other derivable traits. - -### Adding Custom Failure Messages - -You can also add a custom message to be printed with the failure message as -optional arguments to the `assert!`, `assert_eq!`, and `assert_ne!` macros. Any -arguments specified after the one required argument to `assert!` or the two -required arguments to `assert_eq!` and `assert_ne!` are passed along to the -`format!` macro (discussed in Chapter 8 in the “Concatenation with the `+` -Operator or the `format!` Macro” section), so you can pass a format string that -contains `{}` placeholders and values to go in those placeholders. Custom -messages are useful to document what an assertion means; when a test fails, -you’ll have a better idea of what the problem is with the code. - -For example, let’s say we have a function that greets people by name and we -want to test that the name we pass into the function appears in the output: - -Filename: src/lib.rs - -``` -pub fn greeting(name: &str) -> String { - format!("Hello {}!", name) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn greeting_contains_name() { - let result = greeting("Carol"); - assert!(result.contains("Carol")); - } -} -``` - -The requirements for this program haven’t been agreed upon yet, and we’re -pretty sure the `Hello` text at the beginning of the greeting will change. We -decided we don’t want to have to update the test when the requirements change, -so instead of checking for exact equality to the value returned from the -`greeting` function, we’ll just assert that the output contains the text of the -input parameter. - -Let’s introduce a bug into this code by changing `greeting` to not include -`name` to see what this test failure looks like: - -``` -pub fn greeting(name: &str) -> String { - String::from("Hello!") -} -``` - -Running this test produces the following: - -``` -running 1 test -test tests::greeting_contains_name ... FAILED - -failures: - ----- tests::greeting_contains_name stdout ---- - thread 'tests::greeting_contains_name' panicked at 'assertion failed: -result.contains("Carol")', src/lib.rs:12:8 -note: Run with `RUST_BACKTRACE=1` for a backtrace. - -failures: - tests::greeting_contains_name -``` - -This result just indicates that the assertion failed and which line the -assertion is on. A more useful failure message in this case would print the -value we got from the `greeting` function. Let’s change the test function, -giving it a custom failure message made from a format string with a placeholder -filled in with the actual value we got from the `greeting` function: - -``` -#[test] -fn greeting_contains_name() { - let result = greeting("Carol"); - assert!( - result.contains("Carol"), - "Greeting did not contain name, value was `{}`", result - ); -} -``` - -Now when we run the test, we’ll get a more informative error message: - -``` ----- tests::greeting_contains_name stdout ---- - thread 'tests::greeting_contains_name' panicked at 'Greeting did not -contain name, value was `Hello!`', src/lib.rs:12:8 -note: Run with `RUST_BACKTRACE=1` for a backtrace. -``` - -We can see the value we actually got in the test output, which would help us -debug what happened instead of what we were expecting to happen. - -### Checking for Panics with `should_panic` - -In addition to checking that our code returns the correct values we expect, -it’s also important to check that our code handles error conditions as we -expect. For example, consider the `Guess` type that we created in Chapter 9, -Listing 9-9. Other code that uses `Guess` depends on the guarantee that `Guess` -instances will contain only values between 1 and 100. We can write a test that -ensures that attempting to create a `Guess` instance with a value outside that -range panics. - -We do this by adding another attribute, `should_panic`, to our test function. -This attribute makes a test pass if the code inside the function panics; the -test will fail if the code inside the function doesn’t panic. - -Listing 11-8 shows a test that checks that the error conditions of `Guess::new` -happen when we expect them to: - -Filename: src/lib.rs - -``` -pub struct Guess { - value: u32, -} - -impl Guess { - pub fn new(value: u32) -> Guess { - if value < 1 || value > 100 { - panic!("Guess value must be between 1 and 100, got {}.", value); - } - - Guess { - value - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - #[should_panic] - fn greater_than_100() { - Guess::new(200); - } -} -``` - -Listing 11-8: Testing that a condition will cause a `panic!` - -We place the `#[should_panic]` attribute after the `#[test]` attribute and -before the test function it applies to. Let’s look at the result when this test -passes: - -``` -running 1 test -test tests::greater_than_100 ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out -``` - -Looks good! Now let’s introduce a bug in our code by removing the condition -that the `new` function will panic if the value is greater than 100: - -``` -// --snip-- - -impl Guess { - pub fn new(value: u32) -> Guess { - if value < 1 { - panic!("Guess value must be between 1 and 100, got {}.", value); - } - - Guess { - value - } - } -} -``` - -When we run the test in Listing 11-8, it will fail: - -``` -running 1 test -test tests::greater_than_100 ... FAILED - -failures: - -failures: - tests::greater_than_100 - -test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out -``` - -We don’t get a very helpful message in this case, but when we look at the test -function, we see that it’s annotated with `#[should_panic]`. The failure we got -means that the code in the test function did not cause a panic. - -Tests that use `should_panic` can be imprecise because they only indicate that -the code has caused some panic. A `should_panic` test would pass even if the -test panics for a different reason than the one we were expecting to happen. To -make `should_panic` tests more precise, we can add an optional `expected` -parameter to the `should_panic` attribute. The test harness will make sure that -the failure message contains the provided text. For example, consider the -modified code for `Guess` in Listing 11-9 where the `new` function panics with -different messages depending on whether the value is too small or too large: - -Filename: src/lib.rs - -``` -// --snip-- - -impl Guess { - pub fn new(value: u32) -> Guess { - if value < 1 { - panic!("Guess value must be greater than or equal to 1, got {}.", - value); - } else if value > 100 { - panic!("Guess value must be less than or equal to 100, got {}.", - value); - } - - Guess { - value - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - #[should_panic(expected = "Guess value must be less than or equal to 100")] - fn greater_than_100() { - Guess::new(200); - } -} -``` - -Listing 11-9: Testing that a condition will cause a `panic!` with a particular -panic message - -This test will pass because the value we put in the `should_panic` attribute’s -`expected` parameter is a substring of the message that the `Guess::new` -function panics with. We could have specified the entire panic message that we -expect, which in this case would be `Guess value must be less than or equal to -100, got 200.` What you choose to specify in the expected parameter for -`should_panic` depends on how much of the panic message is unique or dynamic -and how precise you want your test to be. In this case, a substring of the -panic message is enough to ensure that the code in the test function executes -the `else if value > 100` case. - -To see what happens when a `should_panic` test with an `expected` message -fails, let’s again introduce a bug into our code by swapping the bodies of the -`if value < 1` and the `else if value > 100` blocks: - -``` -if value < 1 { - panic!("Guess value must be less than or equal to 100, got {}.", value); -} else if value > 100 { - panic!("Guess value must be greater than or equal to 1, got {}.", value); -} -``` - -This time when we run the `should_panic` test, it will fail: - -``` -running 1 test -test tests::greater_than_100 ... FAILED - -failures: - ----- tests::greater_than_100 stdout ---- - thread 'tests::greater_than_100' panicked at 'Guess value must be -greater than or equal to 1, got 200.', src/lib.rs:11:12 -note: Run with `RUST_BACKTRACE=1` for a backtrace. -note: Panic did not include expected string 'Guess value must be less than or -equal to 100' - -failures: - tests::greater_than_100 - -test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out -``` - -The failure message indicates that this test did indeed panic as we expected, -but the panic message did not include the expected string `'Guess value must be -less than or equal to 100'`. The panic message that we did get in this case was -`Guess value must be greater than or equal to 1, got 200.` Now we can start -figuring out where our bug is! - -Now that you know several ways to write tests, let’s look at what is happening -when we run our tests and explore the different options we can use with `cargo -test`. - -## Controlling How Tests Are Run - -Just as `cargo run` compiles your code and then runs the resulting binary, -`cargo test` compiles your code in test mode and runs the resulting test -binary. You can specify command line options to change the default behavior of -`cargo test`. For example, the default behavior of the binary produced by -`cargo test` is to run all the tests in parallel and capture output generated -during test runs, preventing the output from being displayed and making it -easier to read the output related to the test results. - -Some command line options go to `cargo test`, and some go to the resulting test -binary. To separate these two types of arguments, you list the arguments that -go to `cargo test` followed by the separator `--` and then the ones that go to -the test binary. Running `cargo test --help` displays the options you can use -with `cargo test`, and running `cargo test -- --help` displays the options you -can use after the separator `--`. - -### Running Tests in Parallel or Consecutively - -When you run multiple tests, by default they run in parallel using threads. -This means the tests will finish running faster so you can get feedback quicker -on whether or not your code is working. Because the tests are running at the -same time, make sure your tests don’t depend on each other or on any shared -state, including a shared environment, such as the current working directory or -environment variables. - -For example, say each of your tests runs some code that creates a file on disk -named *test-output.txt* and writes some data to that file. Then each test reads -the data in that file and asserts that the file contains a particular value, -which is different in each test. Because the tests run at the same time, one -test might overwrite the file between when another test writes and reads the -file. The second test will then fail, not because the code is incorrect but -because the tests have interfered with each other while running in parallel. -One solution is to make sure each test writes to a different file; another -solution is to run the tests one at a time. - -If you don’t want to run the tests in parallel or if you want more fine-grained -control over the number of threads used, you can send the `--test-threads` flag -and the number of threads you want to use to the test binary. Take a look at -the following example: - -``` -$ cargo test -- --test-threads=1 -``` - -We set the number of test threads to `1`, telling the program not to use any -parallelism. Running the tests using one thread will take longer than running -them in parallel, but the tests won’t interfere with each other if they share -state. - -### Showing Function Output - -By default, if a test passes, Rust’s test library captures anything printed to -standard output. For example, if we call `println!` in a test and the test -passes, we won’t see the `println!` output in the terminal; we’ll see only the -line that indicates the test passed. If a test fails, we’ll see whatever was -printed to standard output with the rest of the failure message. - -As an example, Listing 11-10 has a silly function that prints the value of its -parameter and returns 10, as well as a test that passes and a test that fails. - -Filename: src/lib.rs - -``` -fn prints_and_returns_10(a: i32) -> i32 { - println!("I got the value {}", a); - 10 -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn this_test_will_pass() { - let value = prints_and_returns_10(4); - assert_eq!(10, value); - } - - #[test] - fn this_test_will_fail() { - let value = prints_and_returns_10(8); - assert_eq!(5, value); - } -} -``` - -Listing 11-10: Tests for a function that calls `println!` - -When we run these tests with `cargo test`, we’ll see the following output: - -``` -running 2 tests -test tests::this_test_will_pass ... ok -test tests::this_test_will_fail ... FAILED - -failures: - ----- tests::this_test_will_fail stdout ---- - I got the value 8 -thread 'tests::this_test_will_fail' panicked at 'assertion failed: `(left == right)` - left: `5`, - right: `10`', src/lib.rs:19:8 -note: Run with `RUST_BACKTRACE=1` for a backtrace. - -failures: - tests::this_test_will_fail - -test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out -``` - -Note that nowhere in this output do we see `I got the value 4`, which is what -is printed when the test that passes runs. That output has been captured. The -output from the test that failed, `I got the value 8`, appears in the section -of the test summary output, which also shows the cause of the test failure. - -If we want to see printed values for passing tests as well, we can disable the -output capture behavior by using the `--nocapture` flag: - -``` -$ cargo test -- --nocapture -``` - -When we run the tests in Listing 11-10 again with the `--nocapture` flag, we -see the following output: - -``` -running 2 tests -I got the value 4 -I got the value 8 -test tests::this_test_will_pass ... ok -thread 'tests::this_test_will_fail' panicked at 'assertion failed: `(left == right)` - left: `5`, - right: `10`', src/lib.rs:19:8 -note: Run with `RUST_BACKTRACE=1` for a backtrace. -test tests::this_test_will_fail ... FAILED - -failures: - -failures: - tests::this_test_will_fail - -test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out -``` - -Note that the output for the tests and the test results are interleaved; the -reason is that the tests are running in parallel, as we talked about in the -previous section. Try using the `--test-threads=1` option and the `--nocapture` -flag, and see what the output looks like then! - -### Running a Subset of Tests by Name - -Sometimes, running a full test suite can take a long time. If you’re working on -code in a particular area, you might want to run only the tests pertaining to -that code. You can choose which tests to run by passing `cargo test` the name -or names of the test(s) you want to run as an argument. - -To demonstrate how to run a subset of tests, we’ll create three tests for our -`add_two` function, as shown in Listing 11-11, and choose which ones to run: - -Filename: src/lib.rs - -``` -pub fn add_two(a: i32) -> i32 { - a + 2 -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn add_two_and_two() { - assert_eq!(4, add_two(2)); - } - - #[test] - fn add_three_and_two() { - assert_eq!(5, add_two(3)); - } - - #[test] - fn one_hundred() { - assert_eq!(102, add_two(100)); - } -} -``` - -Listing 11-11: Three tests with three different names - -If we run the tests without passing any arguments, as we saw earlier, all the -tests will run in parallel: - -``` -running 3 tests -test tests::add_two_and_two ... ok -test tests::add_three_and_two ... ok -test tests::one_hundred ... ok - -test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out -``` - -#### Running Single Tests - -We can pass the name of any test function to `cargo test` to run only that test: - -``` -$ cargo test one_hundred - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running target/debug/deps/adder-06a75b4a1f2515e9 - -running 1 test -test tests::one_hundred ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out -``` - -Only the test with the name `one_hundred` ran; the other two tests didn’t match -that name. The test output lets us know we had more tests than what this -command ran by displaying `2 filtered out` at the end of the summary line. - -We can’t specify the names of multiple tests in this way; only the first value -given to `cargo test` will be used. But there is a way to run multiple tests. - -#### Filtering to Run Multiple Tests - -We can specify part of a test name, and any test whose name matches that value -will be run. For example, because two of our tests’ names contain `add`, we can -run those two by running `cargo test add`: - -``` -$ cargo test add - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running target/debug/deps/adder-06a75b4a1f2515e9 - -running 2 tests -test tests::add_two_and_two ... ok -test tests::add_three_and_two ... ok - -test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out -``` - -This command ran all tests with `add` in the name and filtered out the test -named `one_hundred`. Also note that the module in which tests appear becomes -part of the test’s name, so we can run all the tests in a module by filtering -on the module’s name. - -### Ignoring Some Tests Unless Specifically Requested - -Sometimes a few specific tests can be very time-consuming to execute, so you -might want to exclude them during most runs of `cargo test`. Rather than -listing as arguments all tests you do want to run, you can instead annotate the -time-consuming tests using the `ignore` attribute to exclude them, as shown -here: - -Filename: src/lib.rs - -``` -#[test] -fn it_works() { - assert_eq!(2 + 2, 4); -} - -#[test] -#[ignore] -fn expensive_test() { - // code that takes an hour to run -} -``` - -After `#[test]` we add the `#[ignore]` line to the test we want to exclude. Now -when we run our tests, `it_works` runs, but `expensive_test` doesn’t: - -``` -$ cargo test - Compiling adder v0.1.0 (file:///projects/adder) - Finished dev [unoptimized + debuginfo] target(s) in 0.24 secs - Running target/debug/deps/adder-ce99bcc2479f4607 - -running 2 tests -test expensive_test ... ignored -test it_works ... ok - -test result: ok. 1 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out -``` - -The `expensive_test` function is listed as `ignored`. If we want to run only -the ignored tests, we can use `cargo test -- --ignored`: - -``` -$ cargo test -- --ignored - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running target/debug/deps/adder-ce99bcc2479f4607 - -running 1 test -test expensive_test ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out -``` - -By controlling which tests run, you can make sure your `cargo test` results -will be fast. When you’re at a point where it makes sense to check the results -of the `ignored` tests and you have time to wait for the results, you can run -`cargo test -- --ignored` instead. - -## Test Organization - -As mentioned at the start of the chapter, testing is a complex discipline, and -different people use different terminology and organization. The Rust community -thinks about tests in terms of two main categories: *unit tests* and -*integration tests*. Unit tests are small and more focused, testing one module -in isolation at a time, and can test private interfaces. Integration tests are -entirely external to your library and use your code in the same way any other -external code would, using only the public interface and potentially exercising -multiple modules per test. - -Writing both kinds of tests is important to ensure that the pieces of your -library are doing what you expect them to separately and together. - -### Unit Tests - -The purpose of unit tests is to test each unit of code in isolation from the -rest of the code to quickly pinpoint where code is and isn’t working as -expected. You’ll put unit tests in the *src* directory in each file with the -code that they’re testing. The convention is to create a module named `tests` -in each file to contain the test functions and to annotate the module with -`cfg(test)`. - -#### The Tests Module and `#[cfg(test)]` - -The `#[cfg(test)]` annotation on the tests module tells Rust to compile and run -the test code only when you run `cargo test`, not when you run `cargo build`. -This saves compile time when you only want to build the library and saves space -in the resulting compiled artifact because the tests are not included. You’ll -see that because integration tests go in a different directory, they don’t need -the `#[cfg(test)]` annotation. However, because unit tests go in the same files -as the code, you’ll use `#[cfg(test)]` to specify that they shouldn’t be -included in the compiled result. - -Recall that when we generated the new `adder` project in the first section of -this chapter, Cargo generated this code for us: - -Filename: src/lib.rs - -``` -#[cfg(test)] -mod tests { - #[test] - fn it_works() { - assert_eq!(2 + 2, 4); - } -} -``` - -This code is the automatically generated test module. The attribute `cfg` -stands for *configuration* and tells Rust that the following item should only -be included given a certain configuration option. In this case, the -configuration option is `test`, which is provided by Rust for compiling and -running tests. By using the `cfg` attribute, Cargo compiles our test code only -if we actively run the tests with `cargo test`. This includes any helper -functions that might be within this module, in addition to the functions -annotated with `#[test]`. - -#### Testing Private Functions - -There’s debate within the testing community about whether or not private -functions should be tested directly, and other languages make it difficult or -impossible to test private functions. Regardless of which testing ideology you -adhere to, Rust’s privacy rules do allow you to test private functions. -Consider the code in Listing 11-12 with the private function `internal_adder`: - -Filename: src/lib.rs - -``` -pub fn add_two(a: i32) -> i32 { - internal_adder(a, 2) -} - -fn internal_adder(a: i32, b: i32) -> i32 { - a + b -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn internal() { - assert_eq!(4, internal_adder(2, 2)); - } -} -``` - -Listing 11-12: Testing a private function - -Note that the `internal_adder` function is not marked as `pub`, but because -tests are just Rust code and the `tests` module is just another module, you can -import and call `internal_adder` in a test just fine. If you don’t think -private functions should be tested, there’s nothing in Rust that will compel -you to do so. - -### Integration Tests - -In Rust, integration tests are entirely external to your library. They use your -library in the same way any other code would, which means they can only call -functions that are part of your library’s public API. Their purpose is to test -whether many parts of your library work together correctly. Units of code that -work correctly on their own could have problems when integrated, so test -coverage of the integrated code is important as well. To create integration -tests, you first need a *tests* directory. - -#### The *tests* Directory - -We create a *tests* directory at the top level of our project directory, next -to *src*. Cargo knows to look for integration test files in this directory. We -can then make as many test files as we want to in this directory, and Cargo -will compile each of the files as an individual crate. - -Let’s create an integration test. With the code in Listing 11-12 still in the -*src/lib.rs* file, make a *tests* directory, create a new file named -*tests/integration_test.rs*, and enter the code in Listing 11-13: - -Filename: tests/integration_test.rs - -``` -extern crate adder; - -#[test] -fn it_adds_two() { - assert_eq!(4, adder::add_two(2)); -} -``` - -Listing 11-13: An integration test of a function in the `adder` crate - -We’ve added `extern crate adder` at the top of the code, which we didn’t need -in the unit tests. The reason is that each test in the `tests` directory is a -separate crate, so we need to import our library into each of them. - -We don’t need to annotate any code in *tests/integration_test.rs* with -`#[cfg(test)]`. Cargo treats the `tests` directory specially and compiles files -in this directory only when we run `cargo test`. Run `cargo test` now: - -``` -$ cargo test - Compiling adder v0.1.0 (file:///projects/adder) - Finished dev [unoptimized + debuginfo] target(s) in 0.31 secs - Running target/debug/deps/adder-abcabcabc - -running 1 test -test tests::internal ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out - - Running target/debug/deps/integration_test-ce99bcc2479f4607 - -running 1 test -test it_adds_two ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out - - Doc-tests adder - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out -``` - -The three sections of output include the unit tests, the integration test, and -the doc tests. The first section for the unit tests is the same as we’ve been -seeing: one line for each unit test (one named `internal` that we added in -Listing 11-12) and then a summary line for the unit tests. - -The integration tests section starts with the line `Running -target/debug/deps/integration-test-ce99bcc2479f4607` (the hash at the end of -your output will be different). Next, there is a line for each test function in -that integration test and a summary line for the results of the integration -test just before the `Doc-tests adder` section starts. - -Similarly to how adding more unit test functions adds more result lines to the -unit tests section, adding more test functions to the integration test file -adds more result lines to this integration test file’s section. Each -integration test file has its own section, so if we add more files in the -*tests* directory, there will be more integration test sections. - -We can still run a particular integration test function by specifying the test -function’s name as an argument to `cargo test`. To run all the tests in a -particular integration test file, use the `--test` argument of `cargo test` -followed by the name of the file: - -``` -$ cargo test --test integration_test - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running target/debug/integration_test-952a27e0126bb565 - -running 1 test -test it_adds_two ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out -``` - -This command runs only the tests in the *tests/integration_test.rs* file. - -#### Submodules in Integration Tests - -As you add more integration tests, you might want to make more than one file in -the *tests* directory to help organize them; for example, you can group the -test functions by the functionality they’re testing. As mentioned earlier, each -file in the *tests* directory is compiled as its own separate crate. - -Treating each integration test file as its own crate is useful to create -separate scopes that are more like the way end users will be using your crate. -However, this means files in the *tests* directory don’t share the same -behavior as files in *src* do, as you learned in Chapter 7 regarding how to -separate code into modules and files. - -The different behavior of files in the *tests* directory is most noticeable -when you have a set of helper functions that would be useful in multiple -integration test files and you try to follow the steps in the “Moving Modules -to Other Files” section of Chapter 7 to extract them into a common module. For -example, if we create *tests/common.rs* and place a function named `setup` in -it, we can add some code to `setup` that we want to call from multiple test -functions in multiple test files: - -Filename: tests/common.rs - -``` -pub fn setup() { - // setup code specific to your library's tests would go here -} -``` - -When we run the tests again, we’ll see a new section in the test output for the -*common.rs* file, even though this file doesn’t contain any test functions nor -did we call the `setup` function from anywhere: - -``` -running 1 test -test tests::internal ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out - - Running target/debug/deps/common-b8b07b6f1be2db70 - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out - - Running target/debug/deps/integration_test-d993c68b431d39df - -running 1 test -test it_adds_two ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out - - Doc-tests adder - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out -``` - -Having `common` appear in the test results with `running 0 tests` displayed for -it is not what we wanted. We just wanted to share some code with the other -integration test files. - -To avoid having `common` appear in the test output, instead of creating -*tests/common.rs*, we’ll create *tests/common/mod.rs*. In the “Rules of Module -Filesystems” section of Chapter 7, we used the naming convention -*module_name/mod.rs* for files of modules that have submodules. We don’t have -submodules for `common` here, but naming the file this way tells Rust not to -treat the `common` module as an integration test file. When we move the `setup` -function code into *tests/common/mod.rs* and delete the *tests/common.rs* file, -the section in the test output will no longer appear. Files in subdirectories -of the *tests* directory don’t get compiled as separate crates or have sections -in the test output. - -After we’ve created *tests/common/mod.rs*, we can use it from any of the -integration test files as a module. Here’s an example of calling the `setup` -function from the `it_adds_two` test in *tests/integration_test.rs*: - -Filename: tests/integration_test.rs - -``` -extern crate adder; - -mod common; - -#[test] -fn it_adds_two() { - common::setup(); - assert_eq!(4, adder::add_two(2)); -} -``` - -Note that the `mod common;` declaration is the same as the module declarations -we demonstrated in Listing 7-4. Then in the test function, we can call the -`common::setup()` function. - -#### Integration Tests for Binary Crates - -If our project is a binary crate that only contains a *src/main.rs* file and -doesn’t have a *src/lib.rs* file, we can’t create integration tests in the -*tests* directory and use `extern crate` to import functions defined in the -*src/main.rs* file. Only library crates expose functions that other crates can -call and use; binary crates are meant to be run on their own. - -This is one of the reasons Rust projects that provide a binary have a -straightforward *src/main.rs* file that calls logic that lives in the -*src/lib.rs* file. Using that structure, integration tests *can* test the -library crate by using `extern crate` to exercise the important functionality. -If the important functionality works, the small amount of code in the -*src/main.rs* file will work as well, and that small amount of code doesn’t -need to be tested. - -## Summary - -Rust’s testing features provide a way to specify how code should function to -ensure it continues to work as you expect, even as you make changes. Unit tests -exercise different parts of a library separately and can test private -implementation details. Integration tests check that many parts of the library -work together correctly, and they use the library’s public API to test the code -in the same way external code will use it. Even though Rust’s type system and -ownership rules help prevent some kinds of bugs, tests are still important to -reduce logic bugs having to do with how your code is expected to behave. - -Let’s combine the knowledge you learned in this chapter and in previous -chapters to work on a project! diff --git a/second-edition/nostarch/chapter12.md b/second-edition/nostarch/chapter12.md deleted file mode 100644 index a8e5b0b168..0000000000 --- a/second-edition/nostarch/chapter12.md +++ /dev/null @@ -1,1688 +0,0 @@ - -[TOC] - -# An I/O Project: Building a Command Line Program - -This chapter is a recap of the many skills you’ve learned so far and an -exploration of a few more standard library features. We’ll build a command line -tool that interacts with file and command line input/output to practice some of -the Rust concepts you now have under your belt. - -Rust’s speed, safety, single binary output, and cross-platform support make it -an ideal language for creating command line tools, so for our project, we’ll -make our own version of the classic command line tool `grep` (**g**lobally -search a **r**egular **e**xpression and **p**rint). In the simplest use case, -`grep` searches a specified file for a specified string. To do so, `grep` takes -as its arguments a filename and a string. Then it reads the file, finds lines -in that file that contain the string argument, and prints those lines. - -Along the way, we’ll show how to make our command line tool use features of the -terminal that many command line tools use. We’ll read the value of an -environment variable to allow the user to configure the behavior of our tool. -We’ll also print to the standard error console stream (`stderr`) instead of -standard output (`stdout`), so, for example, the user can redirect successful -output to a file while still seeing error messages onscreen. - -One Rust community member, Andrew Gallant, has already created a fully -featured, very fast version of `grep`, called `ripgrep`. By comparison, our -version of `grep` will be fairly simple, but this chapter will give you some of -the background knowledge you need to understand a real-world project such as -`ripgrep`. - -Our `grep` project will combine a number of concepts you’ve learned so far: - -* Organizing code (using what you learned in modules, Chapter 7) -* Using vectors and strings (collections, Chapter 8) -* Handling errors (Chapter 9) -* Using traits and lifetimes where appropriate (Chapter 10) -* Writing tests (Chapter 11) - -We’ll also briefly introduce closures, iterators, and trait objects, which -Chapters 13 and 17 will cover in detail. - -## Accepting Command Line Arguments - -Let’s create a new project with, as always, `cargo new`. We’ll call our project -`minigrep` to distinguish it from the `grep` tool that you might already have -on your system. - -``` -$ cargo new --bin minigrep - Created binary (application) `minigrep` project -$ cd minigrep -``` - -The first task is to make `minigrep` accept its two command line arguments: the -filename and a string to search for. That is, we want to be able to run our -program with `cargo run`, a string to search for, and a path to a file to -search in, like so: - -``` -$ cargo run searchstring example-filename.txt -``` - -Right now, the program generated by `cargo new` cannot process arguments we -give it. Some existing libraries on Crates.io at *https://crates.io/* can help -with writing a program that accepts command line arguments, but because you’re -just learning this concept, let’s implement this capability ourselves. - -### Reading the Argument Values - -To enable `minigrep` to read the values of command line arguments we pass to -it, we’ll need a function provided in Rust’s standard library, which is -`std::env::args`. This function returns an *iterator* of the command line -arguments that were given to `minigrep`. We haven’t discussed iterators yet -(we’ll cover them fully in Chapter 13), but for now, you only need to know two -details about iterators: iterators produce a series of values, and we can call -the `collect` method on an iterator to turn it into a collection, such as a -vector, containing all the elements the iterator produces. - -Use the code in Listing 12-1 to allow your `minigrep` program to read any -command line arguments passed to it and then collect the values into a vector: - -Filename: src/main.rs - -``` -use std::env; - -fn main() { - let args: Vec = env::args().collect(); - println!("{:?}", args); -} -``` - -Listing 12-1: Collecting the command line arguments into a vector and printing -them - -First, we bring the `std::env` module into scope with a `use` statement so we -can use its `args` function. Notice that the `std::env::args` function is -nested in two levels of modules. As we discussed in Chapter 7, in cases where -the desired function is nested in more than one module, it’s conventional to -bring the parent module into scope rather than the function. By doing so, we -can easily use other functions from `std::env`. It’s also less ambiguous than -adding `use std::env::args` and then calling the function with just `args`, -because `args` might easily be mistaken for a function that’s defined in the -current module. - -> ### The `args` Function and Invalid Unicode -> -> Note that `std::env::args` will panic if any argument contains invalid -> Unicode. If your program needs to accept arguments containing invalid -> Unicode, use `std::env::args_os` instead. That function returns an iterator -> that produces `OsString` values instead of `String` values. We’ve chosen to -> use `std::env::args` here for simplicity, because `OsString` values differ -> per platform and are more complex to work with than `String` values. - -On the first line of `main`, we call `env::args`, and we immediately use -`collect` to turn the iterator into a vector containing all the values produced -by the iterator. We can use the `collect` function to create many kinds of -collections, so we explicitly annotate the type of `args` to specify that we -want a vector of strings. Although we very rarely need to annotate types in -Rust, `collect` is one function you do often need to annotate because Rust -isn’t able to infer the kind of collection you want. - -Finally, we print the vector using the debug formatter, `:?`. Let’s try running -the code first with no arguments and then with two arguments: - -``` -$ cargo run ---snip-- -["target/debug/minigrep"] - -$ cargo run needle haystack ---snip-- -["target/debug/minigrep", "needle", "haystack"] -``` - -Notice that the first value in the vector is `"target/debug/minigrep"`, which -is the name of our binary. This matches the behavior of the arguments list in -C, letting programs use the name by which they were invoked in their execution. -It’s often convenient to have access to the program name in case you want to -print it in messages or change behavior of the program based on what command -line alias was used to invoke the program. But for the purposes of this -chapter, we’ll ignore it and save only the two arguments we need. - -### Saving the Argument Values in Variables - -Printing the value of the vector of arguments illustrated that the program is -able to access the values specified as command line arguments. Now we need to -save the values of the two arguments in variables so we can use the values -throughout the rest of the program. We do that in Listing 12-2: - -Filename: src/main.rs - -``` -use std::env; - -fn main() { - let args: Vec = env::args().collect(); - - let query = &args[1]; - let filename = &args[2]; - - println!("Searching for {}", query); - println!("In file {}", filename); -} -``` - -Listing 12-2: Creating variables to hold the query argument and filename -argument - -As we saw when we printed the vector, the program’s name takes up the first -value in the vector at `args[0]`, so we’re starting at index `1`. The first -argument `minigrep` takes is the string we’re searching for, so we put a -reference to the first argument in the variable `query`. The second argument -will be the filename, so we put a reference to the second argument in the -variable `filename`. - -We temporarily print the values of these variables to prove that the code is -working as we intend. Let’s run this program again with the arguments `test` -and `sample.txt`: - -``` -$ cargo run test sample.txt - Compiling minigrep v0.1.0 (file:///projects/minigrep) - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target/debug/minigrep test sample.txt` -Searching for test -In file sample.txt -``` - -Great, the program is working! The values of the arguments we need are being -saved into the right variables. Later we’ll add some error handling to deal -with certain potential erroneous situations, such as when the user provides no -arguments; for now, we’ll ignore that situation and work on adding file-reading -capabilities instead. - -## Reading a File - -Now we’ll add functionality to read the file that is specified in the -`filename` command line argument. First, we need a sample file to test it with: -the best kind of file to use to make sure `minigrep` is working is one with a -small amount of text over multiple lines with some repeated words. Listing 12-3 -has an Emily Dickinson poem that will work well! Create a file called -*poem.txt* at the root level of your project, and enter the poem “I’m Nobody! -Who are you?” - -Filename: poem.txt - -``` -I’m nobody! Who are you? -Are you nobody, too? -Then there’s a pair of us — don’t tell! -They’d banish us, you know. - -How dreary to be somebody! -How public, like a frog -To tell your name the livelong day -To an admiring bog! -``` - -Listing 12-3: A poem by Emily Dickinson makes a good test case - -With the text in place, edit *src/main.rs* and add code to open the file, as -shown in Listing 12-4: - -Filename: src/main.rs - -``` -use std::env; -use std::fs::File; -use std::io::prelude::*; - -fn main() { - // --snip-- - println!("In file {}", filename); - - let mut f = File::open(filename).expect("file not found"); - - let mut contents = String::new(); - f.read_to_string(&mut contents) - .expect("something went wrong reading the file"); - - println!("With text:\n{}", contents); -} -``` - -Listing 12-4: Reading the contents of the file specified by the second argument - -First, we add some more `use` statements to bring in relevant parts of the -standard library: we need `std::fs::File` to handle files, and -`std::io::prelude::*` contains various useful traits for doing I/O, including -file I/O. In the same way that Rust has a general prelude that brings certain -types and functions into scope automatically, the `std::io` module has its own -prelude of common types and functions you’ll need when working with I/O. Unlike -with the default prelude, we must explicitly add a `use` statement for the -prelude from `std::io`. - -In `main`, we’ve added three statements: first, we get a mutable handle to the -file by calling the `File::open` function and passing it the value of the -`filename` variable. Second, we create a variable called `contents` and set it -to a mutable, empty `String`. This will hold the content of the file after we -read it in. Third, we call `read_to_string` on our file handle and pass a -mutable reference to `contents` as an argument. - -After those lines, we’ve again added a temporary `println!` statement that -prints the value of `contents` after the file is read, so we can check that the -program is working so far. - -Let’s run this code with any string as the first command line argument (because -we haven’t implemented the searching part yet) and the *poem.txt* file as the -second argument: - -``` -$ cargo run the poem.txt - Compiling minigrep v0.1.0 (file:///projects/minigrep) - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target/debug/minigrep the poem.txt` -Searching for the -In file poem.txt -With text: -I’m nobody! Who are you? -Are you nobody, too? -Then there’s a pair of us — don’t tell! -They’d banish us, you know. - -How dreary to be somebody! -How public, like a frog -To tell your name the livelong day -To an admiring bog! -``` - -Great! The code read and then printed the contents of the file. But the code -has a few flaws. The `main` function has multiple responsibilities: generally, -functions are clearer and easier to maintain if each function is responsible -for only one idea. The other problem is that we’re not handling errors as well -as we could. The program is still small, so these flaws aren’t a big problem, -but as the program grows, it will be harder to fix them cleanly. It’s good -practice to begin refactoring early on when developing a program, because it’s -much easier to refactor smaller amounts of code. We’ll do that next. - -## Refactoring to Improve Modularity and Error Handling - -To improve our program, we’ll fix four problems that have to do with the -program’s structure and how it’s handling potential errors. - -First, our `main` function now performs two tasks: it parses arguments and -opens files. For such a small function, this isn’t a major problem. However, if -we continue to grow our program inside `main`, the number of separate tasks the -`main` function handles will increase. As a function gains responsibilities, it -becomes more difficult to reason about, harder to test, and harder to change -without breaking one of its parts. It’s best to separate functionality so each -function is responsible for one task. - -This issue also ties into the second problem: although `query` and `filename` -are configuration variables to our program, variables like `f` and `contents` -are used to perform the program’s logic. The longer `main` becomes, the more -variables we’ll need to bring into scope; the more variables we have in scope, -the harder it will be to keep track of the purpose of each. It’s best to group -the configuration variables into one structure to make their purpose clear. - -The third problem is that we’ve used `expect` to print an error message when -opening the file fails, but the error message just prints `file not found`. -Opening a file can fail in a number of ways besides the file being missing: for -example, the file might exist, but we might not have permission to open it. -Right now, if we’re in that situation, we’d print the `file not found` error -message, which would give the user the wrong information! - -Fourth, we use `expect` repeatedly to handle different errors, and if the user -runs our program without specifying enough arguments, they’ll get an `index out -of bounds` error from Rust that doesn’t clearly explain the problem. It would -be best if all the error-handling code were in one place so future maintainers -had only one place to consult in the code if the error-handling logic needed to -change. Having all the error-handling code in one place will also ensure that -we’re printing messages that will be meaningful to our end users. - -Let’s address these four problems by refactoring our project. - -### Separation of Concerns for Binary Projects - -The organizational problem of allocating responsibility for multiple tasks to -the `main` function is common to many binary projects. As a result, the Rust -community has developed a process to use as a guideline for splitting the -separate concerns of a binary program when `main` starts getting large. The -process has the following steps: - -* Split your program into a *main.rs* and a *lib.rs* and move your program’s - logic to *lib.rs*. -* As long as your command line parsing logic is small, it can remain in - *main.rs*. -* When the command line parsing logic starts getting complicated, extract it - from *main.rs* and move it to *lib.rs*. -* The responsibilities that remain in the `main` function after this process - should be limited to the following: - - * Calling the command line parsing logic with the argument values - * Setting up any other configuration - * Calling a `run` function in *lib.rs* - * Handling the error if `run` returns an error - -This pattern is about separating concerns: *main.rs* handles running the -program, and *lib.rs* handles all the logic of the task at hand. Because you -can’t test the `main` function directly, this structure lets you test all of -your program’s logic by moving it into functions in *lib.rs*. The only code -that remains in *main.rs* will be small enough to verify its correctness by -reading it. Let’s rework our program by following this process. - -#### Extracting the Argument Parser - -We’ll extract the functionality for parsing arguments into a function that -`main` will call to prepare for moving the command line parsing logic to -*src/lib.rs*. Listing 12-5 shows the new start of `main` that calls a new -function `parse_config`, which we’ll define in *src/main.rs* for the moment. - -Filename: src/main.rs - -``` -fn main() { - let args: Vec = env::args().collect(); - - let (query, filename) = parse_config(&args); - - // --snip-- -} - -fn parse_config(args: &[String]) -> (&str, &str) { - let query = &args[1]; - let filename = &args[2]; - - (query, filename) -} -``` - -Listing 12-5: Extracting a `parse_config` function from `main` - -We’re still collecting the command line arguments into a vector, but instead of -assigning the argument value at index `1` to the variable `query` and the -argument value at index `2` to the variable `filename` within the `main` -function, we pass the whole vector to the `parse_config` function. The -`parse_config` function then holds the logic that determines which argument -goes in which variable and passes the values back to `main`. We still create -the `query` and `filename` variables in `main`, but `main` no longer has the -responsibility of determining how the command line arguments and variables -correspond. - -This rework may seem like overkill for our small program, but we’re refactoring -in small, incremental steps. After making this change, run the program again to -verify that the argument parsing still works. It’s good to check your progress -often, to help identify the cause of problems when they occur. - -#### Grouping Configuration Values - -We can take another small step to improve the `parse_config` function further. -At the moment, we’re returning a tuple, but then we immediately break that -tuple into individual parts again. This is a sign that perhaps we don’t have -the right abstraction yet. - -Another indicator that shows there’s room for improvement is the `config` part -of `parse_config`, which implies that the two values we return are related and -are both part of one configuration value. We’re not currently conveying this -meaning in the structure of the data other than by grouping the two values into -a tuple; we could put the two values into one struct and give each of the -struct fields a meaningful name. Doing so will make it easier for future -maintainers of this code to understand how the different values relate to each -other and what their purpose is. - -> Note: Some people call this anti-pattern of using primitive values when a -> complex type would be more appropriate *primitive obsession*. - -Listing 12-6 shows the addition of a struct named `Config` defined to have -fields named `query` and `filename`. We’ve also changed the `parse_config` -function to return an instance of the `Config` struct and updated `main` to use -the struct fields rather than having separate variables: - -Filename: src/main.rs - -``` -fn main() { - let args: Vec = env::args().collect(); - - let config = parse_config(&args); - - println!("Searching for {}", config.query); - println!("In file {}", config.filename); - - let mut f = File::open(config.filename).expect("file not found"); - - // --snip-- -} - -struct Config { - query: String, - filename: String, -} - -fn parse_config(args: &[String]) -> Config { - let query = args[1].clone(); - let filename = args[2].clone(); - - Config { query, filename } -} -``` - -Listing 12-6: Refactoring `parse_config` to return an instance of a `Config` -struct - -The signature of `parse_config` now indicates that it returns a `Config` value. -In the body of `parse_config`, where we used to return string slices that -reference `String` values in `args`, we now define `Config` to contain owned -`String` values. The `args` variable in `main` is the owner of the argument -values and is only letting the `parse_config` function borrow them, which means -we’d violate Rust’s borrowing rules if `Config` tried to take ownership of the -values in `args`. - -We could manage the `String` data in a number of different ways, but the -easiest, though somewhat inefficient, route is to call the `clone` method on -the values. This will make a full copy of the data for the `Config` instance to -own, which takes more time and memory than storing a reference to the string -data. However, cloning the data also makes our code very straightforward -because we don’t have to manage the lifetimes of the references; in this -circumstance, giving up a little performance to gain simplicity is a worthwhile -trade-off. - -> ### The Trade-Offs of Using `clone` -> -> There’s a tendency among many Rustaceans to avoid using `clone` to fix -> ownership problems because of its runtime cost. In Chapter 13, you’ll learn -> how to use more efficient methods in this type of situation. But for now, -> it’s okay to copy a few strings to continue making progress because you’ll -> make these copies only once and your filename and query string are very -> small. It’s better to have a working program that’s a bit inefficient than to -> try to hyperoptimize code on your first pass. As you become more experienced -> with Rust, it’ll be easier to start with the most efficient solution, but for -> now, it’s perfectly acceptable to call `clone`. - -We’ve updated `main` so it places the instance of `Config` returned by -`parse_config` into a variable named `config`, and we updated the code that -previously used the separate `query` and `filename` variables so it now uses -the fields on the `Config` struct instead. - -Now our code more clearly conveys that `query` and `filename` are related and -that their purpose is to configure how the program will work. Any code that -uses these values knows to find them in the `config` instance in the fields -named for their purpose. - -#### Creating a Constructor for `Config` - -So far, we’ve extracted the logic responsible for parsing the command line -arguments from `main` and placed it in the `parse_config` function. Doing so -helped us to see that the `query` and `filename` values were related and that -relationship should be conveyed in our code. We then added a `Config` struct to -name the related purpose of `query` and `filename` and to be able to return the -values’ names as struct field names from the `parse_config` function. - -So now that the purpose of the `parse_config` function is to create a `Config` -instance, we can change `parse_config` from a plain function to a function -named `new` that is associated with the `Config` struct. Making this change -will make the code more idiomatic. We can create instances of types in the -standard library, such as `String`, by calling `String::new`. Similarly, by -changing `parse_config` into a `new` function associated with `Config`, we’ll -be able to create instances of `Config` by calling `Config::new`. Listing 12-7 -shows the changes we need to make: - -Filename: src/main.rs - -``` -fn main() { - let args: Vec = env::args().collect(); - - let config = Config::new(&args); - - // --snip-- -} - -// --snip-- - -impl Config { - fn new(args: &[String]) -> Config { - let query = args[1].clone(); - let filename = args[2].clone(); - - Config { query, filename } - } -} -``` - -Listing 12-7: Changing `parse_config` into `Config::new` - -We’ve updated `main` where we were calling `parse_config` to instead call -`Config::new`. We’ve changed the name of `parse_config` to `new` and moved it -within an `impl` block, which associates the `new` function with `Config`. Try -compiling this code again to make sure it works. - -### Fixing the Error Handling - -Now we’ll work on fixing our error handling. Recall that attempting to access -the values in the `args` vector at index `1` or index `2` will cause the -program to panic if the vector contains fewer than three items. Try running the -program without any arguments; it will look like this: - -``` -$ cargo run - Compiling minigrep v0.1.0 (file:///projects/minigrep) - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target/debug/minigrep` -thread 'main' panicked at 'index out of bounds: the len is 1 -but the index is 1', src/main.rs:29:21 -note: Run with `RUST_BACKTRACE=1` for a backtrace. -``` - -The line `index out of bounds: the len is 1 but the index is 1` is an error -message intended for programmers. It won’t help our end users understand what -happened and what they should do instead. Let’s fix that now. - -#### Improving the Error Message - -In Listing 12-8, we add a check in the `new` function that will verify that the -slice is long enough before accessing index `1` and `2`. If the slice isn’t -long enough, the program panics and displays a better error message than the -`index out of bounds` message. - -Filename: src/main.rs - -``` -// --snip-- -fn new(args: &[String]) -> Config { - if args.len() < 3 { - panic!("not enough arguments"); - } - // --snip-- -``` - -Listing 12-8: Adding a check for the number of arguments - -This code is similar to the `Guess::new` function we wrote in Listing 9-9, where -we called `panic!` when the `value` argument was out of the range of valid -values. Instead of checking for a range of values here, we’re checking that the -length of `args` is at least `3` and the rest of the function can operate under -the assumption that this condition has been met. If `args` has fewer than three -items, this condition will be true, and we call the `panic!` macro to end the -program immediately. - -With these extra few lines of code in `new`, let’s run the program without any -arguments again to see what the error looks like now: - -``` -$ cargo run - Compiling minigrep v0.1.0 (file:///projects/minigrep) - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target/debug/minigrep` -thread 'main' panicked at 'not enough arguments', src/main.rs:30:12 -note: Run with `RUST_BACKTRACE=1` for a backtrace. -``` - -This output is better: we now have a reasonable error message. However, we also -have extraneous information we don’t want to give to our users. Perhaps using -the technique we used in Listing 9-9 isn’t the best to use here: a call to -`panic!` is more appropriate for a programming problem rather than a usage -problem, as discussed in Chapter 9. Instead, we can use the other technique you -learned about in Chapter 9—returning a `Result` that indicates either success -or an error. - -#### Returning a `Result` from `new` Instead of Calling `panic!` - -We can instead return a `Result` value that will contain a `Config` instance in -the successful case and will describe the problem in the error case. When -`Config::new` is communicating to `main`, we can use the `Result` type to -signal there was a problem. Then we can change `main` to convert an `Err` -variant into a more practical error for our users without the surrounding text -about `thread 'main'` and `RUST_BACKTRACE` that a call to `panic!` causes. - -Listing 12-9 shows the changes we need to make to the return value of -`Config::new` and the body of the function needed to return a `Result`. Note -that this won’t compile until we update `main` as well, which we’ll do in the -next listing. - -Filename: src/main.rs - -``` -impl Config { - fn new(args: &[String]) -> Result { - if args.len() < 3 { - return Err("not enough arguments"); - } - - let query = args[1].clone(); - let filename = args[2].clone(); - - Ok(Config { query, filename }) - } -} -``` - -Listing 12-9: Returning a `Result` from `Config::new` - -Our `new` function now returns a `Result` with a `Config` instance in the -success case and a `&'static str` in the error case. Recall from “The Static -Lifetime” section in Chapter 10 that `&'static str` is the type of string -literals, which is our error message type for now. - -We’ve made two changes in the body of the `new` function: instead of calling -`panic!` when the user doesn’t pass enough arguments, we now return an `Err` -value, and we’ve wrapped the `Config` return value in an `Ok`. These changes -make the function conform to its new type signature. - -Returning an `Err` value from `Config::new` allows the `main` function to -handle the `Result` value returned from the `new` function and exit the process -more cleanly in the error case. - -#### Calling `Config::new` and Handling Errors - -To handle the error case and print a user-friendly message, we need to update -`main` to handle the `Result` being returned by `Config::new`, as shown in -Listing 12-10. We’ll also take the responsibility of exiting the command line -tool with a nonzero error code from `panic!` and implement it by hand. A -nonzero exit status is a convention to signal to the process that called our -program that the program exited with an error state. - -Filename: src/main.rs - -``` -use std::process; - -fn main() { - let args: Vec = env::args().collect(); - - let config = Config::new(&args).unwrap_or_else(|err| { - println!("Problem parsing arguments: {}", err); - process::exit(1); - }); - - // --snip-- -``` - -Listing 12-10: Exiting with an error code if creating a new `Config` fails - -In this listing, we’ve used a method we haven’t covered before: -`unwrap_or_else`, which is defined on `Result` by the standard library. -Using `unwrap_or_else` allows us to define some custom, non-`panic!` error -handling. If the `Result` is an `Ok` value, this method’s behavior is similar -to `unwrap`: it returns the inner value `Ok` is wrapping. However, if the value -is an `Err` value, this method calls the code in the *closure*, which is an -anonymous function we define and pass as an argument to `unwrap_or_else`. We’ll -cover closures in more detail in Chapter 13. For now, you just need to know -that `unwrap_or_else` will pass the inner value of the `Err`, which in this -case is the static string `not enough arguments` that we added in Listing 12-9, -to our closure in the argument `err` that appears between the vertical pipes. -The code in the closure can then use the `err` value when it runs. - -We’ve added a new `use` line to import `process` from the standard library. The -code in the closure that will be run in the error case is only two lines: we -print the `err` value and then call `process::exit`. The `process::exit` -function will stop the program immediately and return the number that was -passed as the exit status code. This is similar to the `panic!`-based handling -we used in Listing 12-8, but we no longer get all the extra output. Let’s try -it: - -``` -$ cargo run - Compiling minigrep v0.1.0 (file:///projects/minigrep) - Finished dev [unoptimized + debuginfo] target(s) in 0.48 secs - Running `target/debug/minigrep` -Problem parsing arguments: not enough arguments -``` - -Great! This output is much friendlier for our users. - -### Extracting Logic from `main` - -Now that we’ve finished refactoring the configuration parsing, let’s turn to -the program’s logic. As we stated in “Separation of Concerns for Binary -Projects”, we’ll extract a function named `run` that will hold all the logic -currently in the `main` function that isn’t involved with setting up -configuration or handling errors. When we’re done, `main` will be concise and -easy to verify by inspection, and we’ll be able to write tests for all the -other logic. - -Listing 12-11 shows the extracted `run` function. For now, we’re just making -the small, incremental improvement of extracting the function. We’re still -defining the function in *src/main.rs*. - -Filename: src/main.rs - -``` -fn main() { - // --snip-- - - println!("Searching for {}", config.query); - println!("In file {}", config.filename); - - run(config); -} - -fn run(config: Config) { - let mut f = File::open(config.filename).expect("file not found"); - - let mut contents = String::new(); - f.read_to_string(&mut contents) - .expect("something went wrong reading the file"); - - println!("With text:\n{}", contents); -} - -// --snip-- -``` - -Listing 12-11: Extracting a `run` function containing the rest of the program -logic - -The `run` function now contains all the remaining logic from `main`, starting -from reading the file. The `run` function takes the `Config` instance as an -argument. - -#### Returning Errors from the `run` Function - -With the remaining program logic separated into the `run` function, we can -improve the error handling, as we did with `Config::new` in Listing 12-9. -Instead of allowing the program to panic by calling `expect`, the `run` -function will return a `Result` when something goes wrong. This will let -us further consolidate into `main` the logic around handling errors in a -user-friendly way. Listing 12-12 shows the changes we need to make to the -signature and body of `run`: - -Filename: src/main.rs - -``` -use std::error::Error; - -// --snip-- - -fn run(config: Config) -> Result<(), Box> { - let mut f = File::open(config.filename)?; - - let mut contents = String::new(); - f.read_to_string(&mut contents)?; - - println!("With text:\n{}", contents); - - Ok(()) -} -``` - -Listing 12-12: Changing the `run` function to return `Result` - -We’ve made three significant changes here. First, we changed the return type of -the `run` function to `Result<(), Box>`. This function previously -returned the unit type, `()`, and we keep that as the value returned in the -`Ok` case. - -For the error type, we used the *trait object* `Box` (and we’ve brought -`std::error::Error` into scope with a `use` statement at the top). We’ll cover -trait objects in Chapter 17. For now, just know that `Box` means the -function will return a type that implements the `Error` trait, but we don’t -have to specify what particular type the return value will be. This gives us -flexibility to return error values that may be of different types in different -error cases. - -Second, we’ve removed the calls to `expect` in favor of `?`, as we talked about -in Chapter 9. Rather than `panic!` on an error, `?` will return the error value -from the current function for the caller to handle. - -Third, the `run` function now returns an `Ok` value in the success case. We’ve -declared the `run` function’s success type as `()` in the signature, which -means we need to wrap the unit type value in the `Ok` value. This `Ok(())` -syntax might look a bit strange at first, but using `()` like this is the -idiomatic way to indicate that we’re calling `run` for its side effects only; -it doesn’t return a value we need. - -When you run this code, it will compile but will display a warning: - -``` -warning: unused `std::result::Result` which must be used - --> src/main.rs:18:5 - | -18 | run(config); - | ^^^^^^^^^^^^ -= note: #[warn(unused_must_use)] on by default -``` - -Rust tells us that our code ignored the `Result` value and the `Result` value -might indicate that an error occurred. But we’re not checking to see whether or -not there was an error, and the compiler reminds us that we probably meant to -have some error handling code here! Let’s rectify that problem now. - -#### Handling Errors Returned from `run` in `main` - -We’ll check for errors and handle them using a technique similar to one we used -with `Config::new` in Listing 12-10, but with a slight difference: - -Filename: src/main.rs - -``` -fn main() { - // --snip-- - - println!("Searching for {}", config.query); - println!("In file {}", config.filename); - - if let Err(e) = run(config) { - println!("Application error: {}", e); - - process::exit(1); - } -} -``` - -We use `if let` rather than `unwrap_or_else` to check whether `run` returns an -`Err` value and call `process::exit(1)` if it does. The `run` function doesn’t -return a value that we want to `unwrap` in the same way that `Config::new` -returns the `Config` instance. Because `run` returns `()` in the success case, -we only care about detecting an error, so we don’t need `unwrap_or_else` to -return the unwrapped value because it would only be `()`. - -The bodies of the `if let` and the `unwrap_or_else` functions are the same in -both cases: we print the error and exit. - -### Splitting Code into a Library Crate - -Our `minigrep` project is looking good so far! Now we’ll split the -*src/main.rs* file and put some code into the *src/lib.rs* file so we can test -it and have a *src/main.rs* file with fewer responsibilities. - -Let’s move all the code that isn’t the `main` function from *src/main.rs* to -*src/lib.rs*: - -* The `run` function definition -* The relevant `use` statements -* The definition of `Config` -* The `Config::new` function definition - -The contents of *src/lib.rs* should have the signatures shown in Listing 12-13 -(we’ve omitted the bodies of the functions for brevity). Note that this won’t -compile until we modify *src/main.rs* in the listing after this one. - -Filename: src/lib.rs - -``` -use std::error::Error; -use std::fs::File; -use std::io::prelude::*; - -pub struct Config { - pub query: String, - pub filename: String, -} - -impl Config { - pub fn new(args: &[String]) -> Result { - // --snip-- - } -} - -pub fn run(config: Config) -> Result<(), Box> { - // --snip-- -} -``` - -Listing 12-13: Moving `Config` and `run` into *src/lib.rs* - -We’ve made liberal use of the `pub` keyword: on `Config`, on its fields and its -`new` method, and on the `run` function. We now have a library crate that has a -public API that we can test! - -Now we need to bring the code we moved to *src/lib.rs* into the scope of the -binary crate in *src/main.rs*, as shown in Listing 12-14: - -Filename: src/main.rs - -``` -extern crate minigrep; - -use std::env; -use std::process; - -use minigrep::Config; - -fn main() { - // --snip-- - if let Err(e) = minigrep::run(config) { - // --snip-- - } -} -``` - -Listing 12-14: Bringing the `minigrep` crate into the scope of *src/main.rs* - -To bring the library crate into the binary crate, we use `extern crate -minigrep`. Then we add a `use minigrep::Config` line to bring the `Config` type -into scope, and we prefix the `run` function with our crate name. Now all the -functionality should be connected and should work. Run the program with `cargo -run` and make sure everything works correctly. - -Whew! That was a lot of work, but we’ve set ourselves up for success in the -future. Now it’s much easier to handle errors, and we’ve made the code more -modular. Almost all of our work will be done in *src/lib.rs* from here on out. - -Let’s take advantage of this newfound modularity by doing something that would -have been difficult with the old code but is easy with the new code: we’ll -write some tests! - -## Developing the Library’s Functionality with Test-Driven Development - -Now that we’ve extracted the logic into *src/lib.rs* and left the argument -collecting and error handling in *src/main.rs*, it’s much easier to write tests -for the core functionality of our code. We can call functions directly with -various arguments and check return values without having to call our binary -from the command line. Feel free to write some tests for the functionality in -the `Config::new` and `run` functions on your own. - -In this section, we’ll add the searching logic to the `minigrep` program by -using the Test-driven development (TDD) process. This software development -technique follows these steps: - -1. Write a test that fails and run it to make sure it fails for the reason you - expect. -2. Write or modify just enough code to make the new test pass. -3. Refactor the code you just added or changed and make sure the tests - continue to pass. -4. Repeat from step 1! - -This process is just one of many ways to write software, but TDD can help drive -code design as well. Writing the test before you write the code that makes the -test pass helps to maintain high test coverage throughout the process. - -We’ll test drive the implementation of the functionality that will actually do -the searching for the query string in the file contents and produce a list of -lines that match the query. We’ll add this functionality in a function called -`search`. - -### Writing a Failing Test - -Because we don’t need them anymore, let’s remove the `println!` statements from -*src/lib.rs* and *src/main.rs* that we used to check the program’s behavior. -Then, in *src/lib.rs*, we’ll add a `test` module with a test function, as we -did in Chapter 11. The test function specifies the behavior we want the -`search` function to have: it will take a query and the text to search for the -query in, and it will return only the lines from the text that contain the -query. Listing 12-15 shows this test, which won’t compile yet: - -Filename: src/lib.rs - -``` -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn one_result() { - let query = "duct"; - let contents = "\ -Rust: -safe, fast, productive. -Pick three."; - - assert_eq!( - vec!["safe, fast, productive."], - search(query, contents) - ); - } -} -``` - -Listing 12-15: Creating a failing test for the `search` function we wish we had - -This test searches for the string `"duct"`. The text we’re searching is three -lines, only one of which contains `"duct"`. We assert that the value returned -from the `search` function contains only the line we expect. - -We aren’t able to run this test and watch it fail because the test doesn’t even -compile: the `search` function doesn’t exist yet! So now we’ll add just enough -code to get the test to compile and run by adding a definition of the `search` -function that always returns an empty vector, as shown in Listing 12-16. Then -the test should compile and fail because an empty vector doesn’t match a vector -containing the line `"safe, fast, productive."` - -Filename: src/lib.rs - -``` -pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { - vec![] -} -``` - -Listing 12-16: Defining just enough of the `search` function so our test will -compile - -Notice that we need an explicit lifetime `'a` defined in the signature of -`search` and used with the `contents` argument and the return value. Recall in -Chapter 10 that the lifetime parameters specify which argument lifetime is -connected to the lifetime of the return value. In this case, we indicate that -the returned vector should contain string slices that reference slices of the -argument `contents` (rather than the argument `query`). - -In other words, we tell Rust that the data returned by the `search` function -will live as long as the data passed into the `search` function in the -`contents` argument. This is important! The data referenced *by* a slice needs -to be valid for the reference to be valid; if the compiler assumes we’re making -string slices of `query` rather than `contents`, it will do its safety checking -incorrectly. - -If we forget the lifetime annotations and try to compile this function, we’ll -get this error: - -``` -error[E0106]: missing lifetime specifier - --> src/lib.rs:5:51 - | -5 | pub fn search(query: &str, contents: &str) -> Vec<&str> { - | ^ expected lifetime -parameter - | - = help: this function's return type contains a borrowed value, but the - signature does not say whether it is borrowed from `query` or `contents` -``` - -Rust can’t possibly know which of the two arguments we need, so we need to tell -it. Because `contents` is the argument that contains all of our text and we -want to return the parts of that text that match, we know `contents` is the -argument that should be connected to the return value using the lifetime syntax. - -Other programming languages don’t require you to connect arguments to return -values in the signature. So although this might seem strange, it will get -easier over time. You might want to compare this example with the “Validating -References with Lifetimes” section in Chapter 10. - -Now let’s run the test: - -``` -$ cargo test - Compiling minigrep v0.1.0 (file:///projects/minigrep) ---warnings-- - Finished dev [unoptimized + debuginfo] target(s) in 0.43 secs - Running target/debug/deps/minigrep-abcabcabc - -running 1 test -test test::one_result ... FAILED - -failures: - ----- test::one_result stdout ---- - thread 'test::one_result' panicked at 'assertion failed: `(left == -right)` -left: `["safe, fast, productive."]`, -right: `[]`)', src/lib.rs:48:8 -note: Run with `RUST_BACKTRACE=1` for a backtrace. - - -failures: - test::one_result - -test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out - -error: test failed, to rerun pass '--lib' -``` - -Great, the test fails, exactly as we expected. Let’s get the test to pass! - -### Writing Code to Pass the Test - -Currently, our test is failing because we always return an empty vector. To fix -that and implement `search`, our program needs to follow these steps: - -* Iterate through each line of the contents. -* Check whether the line contains our query string. -* If it does, add it to the list of values we’re returning. -* If it doesn’t, do nothing. -* Return the list of results that match. - -Let’s work through each step, starting with iterating through lines. - -#### Iterating Through Lines with the `lines` Method - -Rust has a helpful method to handle line-by-line iteration of strings, -conveniently named `lines`, that works as shown in Listing 12-17. Note this -won’t compile yet: - -Filename: src/lib.rs - -``` -pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { - for line in contents.lines() { - // do something with line - } -} -``` - -Listing 12-17: Iterating through each line in `contents` - -The `lines` method returns an iterator. We’ll talk about iterators in depth in -Chapter 13, but recall that you saw this way of using an iterator in Listing -3-5, where we used a `for` loop with an iterator to run some code on each item -in a collection. - -#### Searching Each Line for the Query - -Next, we’ll check whether the current line contains our query string. -Fortunately, strings have a helpful method named `contains` that does this for -us! Add a call to the `contains` method in the `search` function, as shown in -Listing 12-18. Note this still won’t compile yet: - -Filename: src/lib.rs - -``` -pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { - for line in contents.lines() { - if line.contains(query) { - // do something with line - } - } -} -``` - -Listing 12-18: Adding functionality to see whether the line contains the string -in `query` - -#### Storing Matching Lines - -We also need a way to store the lines that contain our query string. For that, -we can make a mutable vector before the `for` loop and call the `push` method -to store a `line` in the vector. After the `for` loop, we return the vector, as -shown in Listing 12-19: - -Filename: src/lib.rs - -``` -pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { - let mut results = Vec::new(); - - for line in contents.lines() { - if line.contains(query) { - results.push(line); - } - } - - results -} -``` - -Listing 12-19: Storing the lines that match so we can return them - -Now the `search` function should return only the lines that contain `query`, -and our test should pass. Let’s run the test: - -``` -$ cargo test ---snip-- -running 1 test -test test::one_result ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out -``` - -Our test passed, so we know it works! - -At this point, we could consider opportunities for refactoring the -implementation of the search function while keeping the tests passing to -maintain the same functionality. The code in the search function isn’t too bad, -but it doesn’t take advantage of some useful features of iterators. We’ll -return to this example in Chapter 13, where we’ll explore iterators in detail, -and look at how to improve it. - -#### Using the `search` Function in the `run` Function - -Now that the `search` function is working and tested, we need to call `search` -from our `run` function. We need to pass the `config.query` value and the -`contents` that `run` reads from the file to the `search` function. Then `run` -will print each line returned from `search`: - -Filename: src/lib.rs - -``` -pub fn run(config: Config) -> Result<(), Box> { - let mut f = File::open(config.filename)?; - - let mut contents = String::new(); - f.read_to_string(&mut contents)?; - - for line in search(&config.query, &contents) { - println!("{}", line); - } - - Ok(()) -} -``` - -We’re still using a `for` loop to return each line from `search` and print it. - -Now the entire program should work! Let’s try it out, first with a word that -should return exactly one line from the Emily Dickinson poem, “frog”: - -``` -$ cargo run frog poem.txt - Compiling minigrep v0.1.0 (file:///projects/minigrep) - Finished dev [unoptimized + debuginfo] target(s) in 0.38 secs - Running `target/debug/minigrep frog poem.txt` -How public, like a frog -``` - -Cool! Now let’s try a word that will match multiple lines, like “body”: - -``` -$ cargo run body poem.txt - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target/debug/minigrep body poem.txt` -I’m nobody! Who are you? -Are you nobody, too? -How dreary to be somebody! -``` - -And finally, let’s make sure that we don’t get any lines when we search for a -word that isn’t anywhere in the poem, such as “monomorphization”: - -``` -$ cargo run monomorphization poem.txt - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target/debug/minigrep monomorphization poem.txt` -``` - -Excellent! We’ve built our own mini version of a classic tool and learned a lot -about how to structure applications. We’ve also learned a bit about file input -and output, lifetimes, testing, and command line parsing. - -To round out this project, we’ll briefly demonstrate how to work with -environment variables and how to print to standard error, both of which are -useful when you’re writing command line programs. - -## Working with Environment Variables - -We’ll improve `minigrep` by adding an extra feature: an option for -case-insensitive searching that the user can turn on via an environment -variable. We could make this feature a command line option and require that -users enter it each time they want it to apply, but instead we’ll use an -environment variable. Doing so allows our users to set the environment variable -once and have all their searches be case insensitive in that terminal session. - -### Writing a Failing Test for the Case-Insensitive `search` Function - -We want to add a new `search_case_insensitive` function that we’ll call when -the environment variable is on. We’ll continue to follow the TDD process, so -the first step is again to write a failing test. We’ll add a new test for the -new `search_case_insensitive` function and rename our old test from -`one_result` to `case_sensitive` to clarify the differences between the two -tests, as shown in Listing 12-20: - -Filename: src/lib.rs - -``` -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn case_sensitive() { - let query = "duct"; - let contents = "\ -Rust: -safe, fast, productive. -Pick three. -Duct tape."; - - assert_eq!( - vec!["safe, fast, productive."], - search(query, contents) - ); - } - - #[test] - fn case_insensitive() { - let query = "rUsT"; - let contents = "\ -Rust: -safe, fast, productive. -Pick three. -Trust me."; - - assert_eq!( - vec!["Rust:", "Trust me."], - search_case_insensitive(query, contents) - ); - } -} -``` - -Listing 12-20: Adding a new failing test for the case-insensitive function -we’re about to add - -Note that we’ve edited the old test’s `contents` too. We’ve added a new line -with the text `"Duct tape."` using a capital D that shouldn’t match the query -“duct” when we’re searching in a case-sensitive manner. Changing the old test -in this way helps ensure that we don’t accidentally break the case-sensitive -search functionality that we’ve already implemented. This test should pass now -and should continue to pass as we work on the case-insensitive search. - -The new test for the case-*insensitive* search uses `"rUsT"` as its query. In -the `search_case_insensitive` function we’re about to add, the query `"rUsT"` -should match the line containing `"Rust:"` with a capital R and match the line -`"Trust me."` even though both have different casing than the query. This is -our failing test, and it will fail to compile because we haven’t yet defined -the `search_case_insensitive` function. Feel free to add a skeleton -implementation that always returns an empty vector, similar to the way we did -for the `search` function in Listing 12-16 to see the test compile and fail. - -### Implementing the `search_case_insensitive` Function - -The `search_case_insensitive` function, shown in Listing 12-21, will be almost -the same as the `search` function. The only difference is that we’ll lowercase -the `query` and each `line` so whatever the case of the input arguments, -they’ll be the same case when we check whether the line contains the query. - -Filename: src/lib.rs - -``` -fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { - let query = query.to_lowercase(); - let mut results = Vec::new(); - - for line in contents.lines() { - if line.to_lowercase().contains(&query) { - results.push(line); - } - } - - results -} -``` - -Listing 12-21: Defining the `search_case_insensitive` function to lowercase the -query and the line before comparing them - -First, we lowercase the `query` string and store it in a shadowed variable with -the same name. Calling `to_lowercase` on the query is necessary so no matter -whether the user’s query is `"rust"`, `"RUST"`, `"Rust:"`, or `"rUsT"`, we’ll -treat the query as if it were `"rust"` and be insensitive to the case. - -Note that `query` is now a `String` rather than a string slice, because calling -`to_lowercase` creates new data rather than referencing existing data. Say the -query is `"rUsT"`, as an example: that string slice doesn’t contain a lowercase -`u` or `t` for us to use, so we have to allocate a new `String` containing -`"rust"`. When we pass `query` as an argument to the `contains` method now, we -need to add an ampersand because the signature of `contains` is defined to take -a string slice. - -Next, we add a call to `to_lowercase` on each `line` before we check whether it -contains `query` to lowercase all characters. Now that we’ve converted `line` -and `query` to lowercase, we’ll find matches no matter what the case of the -query is. - -Let’s see if this implementation passes the tests: - -``` -running 2 tests -test test::case_insensitive ... ok -test test::case_sensitive ... ok - -test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out -``` - -Great! They passed. Now, let’s call the new `search_case_insensitive` function -from the `run` function. First, we’ll add a configuration option to the -`Config` struct to switch between case-sensitive and case-insensitive search. -Adding this field will cause compiler errors since we aren’t initializing this -field anywhere yet: - -Filename: src/lib.rs - -``` -pub struct Config { - pub query: String, - pub filename: String, - pub case_sensitive: bool, -} -``` - -Note that we added the `case_sensitive` field that holds a Boolean. Next, we -need the `run` function to check the `case_sensitive` field’s value and use -that to decide whether to call the `search` function or the -`search_case_insensitive` function, as shown in Listing 12-22. Note this still -won’t compile yet: - -Filename: src/lib.rs - -``` -pub fn run(config: Config) -> Result<(), Box> { - let mut f = File::open(config.filename)?; - - let mut contents = String::new(); - f.read_to_string(&mut contents)?; - - let results = if config.case_sensitive { - search(&config.query, &contents) - } else { - search_case_insensitive(&config.query, &contents) - }; - - for line in results { - println!("{}", line); - } - - Ok(()) -} -``` - -Listing 12-22: Calling either `search` or `search_case_insensitive` based on -the value in `config.case_sensitive` - -Finally, we need to check for the environment variable. The functions for -working with environment variables are in the `env` module in the standard -library, so we want to bring that module into scope with a `use std::env;` line -at the top of *src/lib.rs*. Then we’ll use the `var` method from the `env` -module to check for an environment variable named `CASE_INSENSITIVE`, as shown -in Listing 12-23: - -Filename: src/lib.rs - -``` -use std::env; - -// --snip-- - -impl Config { - pub fn new(args: &[String]) -> Result { - if args.len() < 3 { - return Err("not enough arguments"); - } - - let query = args[1].clone(); - let filename = args[2].clone(); - - let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); - - Ok(Config { query, filename, case_sensitive }) - } -} -``` - -Listing 12-23: Checking for an environment variable named `CASE_INSENSITIVE` - -Here, we create a new variable `case_sensitive`. To set its value, we call the -`env::var` function and pass it the name of the `CASE_INSENSITIVE` environment -variable. The `env::var` method returns a `Result` that will be the successful -`Ok` variant that contains the value of the environment variable if the -environment variable is set. It will return the `Err` variant if the -environment variable is not set. - -We’re using the `is_err` method on the `Result` to check whether it’s an error -and therefore unset, which means it *should* do a case-sensitive search. If the -`CASE_INSENSITIVE` environment variable is set to anything, `is_err` will -return false and the program will perform a case-insensitive search. We don’t -care about the *value* of the environment variable, just whether it’s set or -unset, so we’re checking `is_err` rather than using `unwrap`, `expect`, or any -of the other methods we’ve seen on `Result`. - -We pass the value in the `case_sensitive` variable to the `Config` instance so -the `run` function can read that value and decide whether to call `search` or -`search_case_insensitive`, as we implemented in Listing 12-22. - -Let’s give it a try! First, we’ll run our program without the environment -variable set and with the query `to`, which should match any line that contains -the word “to” in all lowercase: - -``` -$ cargo run to poem.txt - Compiling minigrep v0.1.0 (file:///projects/minigrep) - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target/debug/minigrep to poem.txt` -Are you nobody, too? -How dreary to be somebody! -``` - -Looks like that still works! Now, let’s run the program with `CASE_INSENSITIVE` -set to `1` but with the same query `to`. - -If you’re using PowerShell, you will need to set the environment variable and -run the program in two commands rather than one: - -``` -$ $env:CASE_INSENSITIVE=1 -$ cargo run to poem.txt -``` - -We should get lines that contain “to” that might have uppercase letters: - -``` -$ CASE_INSENSITIVE=1 cargo run to poem.txt - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target/debug/minigrep to poem.txt` -Are you nobody, too? -How dreary to be somebody! -To tell your name the livelong day -To an admiring bog! -``` - -Excellent, we also got lines containing “To”! Our `minigrep` program can now do -case-insensitive searching controlled by an environment variable. Now you know -how to manage options set using either command line arguments or environment -variables. - -Some programs allow arguments *and* environment variables for the same -configuration. In those cases, the programs decide that one or the other takes -precedence. For another exercise on your own, try controlling case -insensitivity through either a command line argument or an environment -variable. Decide whether the command line argument or the environment variable -should take precedence if the program is run with one set to case sensitive and -one set to case insensitive. - -The `std::env` module contains many more useful features for dealing with -environment variables: check out its documentation to see what is available. - -## Writing Error Messages to Standard Error Instead of Standard Output - -At the moment, we’re writing all of our output to the terminal using the -`println!` function. Most terminals provide two kinds of output: *standard -output* (`stdout`) for general information and *standard error* (`stderr`) -for error messages. This distinction enables users to choose to direct the -successful output of a program to a file but still print error messages to the -screen. - -The `println!` function is only capable of printing to standard output, so we -have to use something else to print to standard error. - -### Checking Where Errors Are Written - -First, let’s observe how the content printed by `minigrep` is currently being -written to standard output, including any error messages we want to write to -standard error instead. We’ll do that by redirecting the standard output stream -to a file while also intentionally causing an error. We won’t redirect the -standard error stream, so any content sent to standard error will continue to -display on the screen. - -Command line programs are expected to send error messages to the standard error -stream so we can still see error messages on the screen even if we redirect the -standard output stream to a file. Our program is not currently well-behaved: -we’re about to see that it saves the error message output to a file instead! - -The way to demonstrate this behavior is by running the program with `>` and the -filename, *output.txt*, that we want to redirect the standard output stream to. -We won’t pass any arguments, which should cause an error: - -``` -$ cargo run > output.txt -``` - -The `>` syntax tells the shell to write the contents of standard output to -*output.txt* instead of the screen. We didn’t see the error message we were -expecting printed to the screen, so that means it must have ended up in the -file. This is what *output.txt* contains: - -``` -Problem parsing arguments: not enough arguments -``` - -Yup, our error message is being printed to standard output. It’s much more -useful for error messages like this to be printed to standard error so only -data from a successful run ends up in the file. We’ll change that. - -### Printing Errors to Standard Error - -We’ll use the code in Listing 12-24 to change how error messages are printed. -Because of the refactoring we did earlier in this chapter, all the code that -prints error messages is in one function, `main`. The standard library provides -the `eprintln!` macro that prints to the standard error stream, so let’s change -the two places we were calling `println!` to print errors to use `eprintln!` -instead. - -Filename: src/main.rs - -``` -fn main() { - let args: Vec = env::args().collect(); - - let config = Config::new(&args).unwrap_or_else(|err| { - eprintln!("Problem parsing arguments: {}", err); - process::exit(1); - }); - - if let Err(e) = minigrep::run(config) { - eprintln!("Application error: {}", e); - - process::exit(1); - } -} -``` - -Listing 12-24: Writing error messages to standard error instead of standard -output using `eprintln!` - -After changing `println!` to `eprintln!`, let’s run the program again in the -same way, without any arguments and redirecting standard output with `>`: - -``` -$ cargo run > output.txt -Problem parsing arguments: not enough arguments -``` - -Now we see the error onscreen and *output.txt* contains nothing, which is the -behavior we expect of command line programs. - -Let’s run the program again with arguments that don’t cause an error but still -redirect standard output to a file, like so: - -``` -$ cargo run to poem.txt > output.txt -``` - -We won’t see any output to the terminal, and *output.txt* will contain our -results: - -Filename: output.txt - -``` -Are you nobody, too? -How dreary to be somebody! -``` - -This demonstrates that we’re now using standard output for successful output -and standard error for error output as appropriate. - -## Summary - -This chapter recapped some of the major concepts you’ve learned so far and -covered how to perform common I/O operations in Rust. By using command line -arguments, files, environment variables, and the `eprintln!` macro for printing -errors, you’re now prepared to write command line applications. By using the -concepts in previous chapters, your code will be well organized, store data -effectively in the appropriate data structures, handle errors nicely, and be -well tested. - -Next, we’ll explore some Rust features that were influenced by functional -languages: closures and iterators. diff --git a/second-edition/nostarch/chapter13.md b/second-edition/nostarch/chapter13.md deleted file mode 100644 index f592c137bb..0000000000 --- a/second-edition/nostarch/chapter13.md +++ /dev/null @@ -1,1528 +0,0 @@ - -[TOC] - -# Functional Language Features: Iterators and Closures - -Rust’s design has taken inspiration from many existing languages and -techniques, and one significant influence is *functional programming*. -Programming in a functional style often includes using functions as values by -passing them in arguments, returning them from other functions, assigning them -to variables for later execution, and so forth. - -In this chapter, we won’t debate the issue of what functional programming is or -isn’t but will instead discuss some features of Rust that are similar to -features in many languages often referred to as functional. - -More specifically, we’ll cover: - -* *Closures*, a function-like construct you can store in a variable -* *Iterators*, a way of processing a series of elements -* How to use these two features to improve the I/O project in Chapter 12 -* The performance of these two features (Spoiler alert: they’re faster than you - might think!) - -Other Rust features, such as pattern matching and enums, which we’ve covered in -other chapters, are influenced by the functional style as well. Mastering -closures and iterators is an important part of writing idiomatic, fast Rust -code, so we’ll devote this entire chapter to them. - -## Closures: Anonymous Functions that Can Capture Their Environment - -Rust’s closures are anonymous functions you can save in a variable or pass as -arguments to other functions. You can create the closure in one place and then -call the closure to evaluate it in a different context. Unlike functions, -closures can capture values from the scope in which they’re called. We’ll -demonstrate how these closure features allow for code reuse and behavior -customization. - -### Creating an Abstraction of Behavior with Closures - -Let’s work on an example of a situation in which it’s useful to store a closure -to be executed later. Along the way, we’ll talk about the syntax of closures, -type inference, and traits. - -Consider this hypothetical situation: we work at a startup that’s making an app -to generate custom exercise workout plans. The backend is written in Rust, and -the algorithm that generates the workout plan takes into account many factors, -such as the app user’s age, body mass index, exercise preferences, recent -workouts, and an intensity number they specify. The actual algorithm used isn’t -important in this example; what’s important is that this calculation takes a -few seconds. We want to call this algorithm only when we need to and only call -it once so we don’t make the user wait more than necessary. - -We’ll simulate calling this hypothetical algorithm with the function -`simulated_expensive_calculation` shown in Listing 13-1, which will print -`calculating slowly...`, wait for two seconds, and then return whatever number -we passed in: - -Filename: src/main.rs - -``` -use std::thread; -use std::time::Duration; - -fn simulated_expensive_calculation(intensity: u32) -> u32 { - println!("calculating slowly..."); - thread::sleep(Duration::from_secs(2)); - intensity -} -``` - -Listing 13-1: A function to stand in for a hypothetical calculation that takes -about 2 seconds to run - -Next is the `main` function, which contains the parts of the workout app -important for this example. This function represents the code that the app will -call when a user asks for a workout plan. Because the interaction with the -app’s frontend isn’t relevant to the use of closures, we’ll hardcode values -representing inputs to our program and print the outputs. - -The required inputs are these: - -* An intensity number from the user, which is specified when they request - a workout to indicate whether they want a low-intensity workout or a - high-intensity workout -* A random number that will generate some variety in the workout plans - -The output will be the recommended workout plan. Listing 13-2 shows the `main` -function we’ll use: - -Filename: src/main.rs - -``` -fn main() { - let simulated_user_specified_value = 10; - let simulated_random_number = 7; - - generate_workout( - simulated_user_specified_value, - simulated_random_number - ); -} -``` - -Listing 13-2: A `main` function with hardcoded values to simulate user input -and random number generation - -We’ve hardcoded the variable `simulated_user_specified_value` as 10 and the -variable `simulated_random_number` as 7 for simplicity’s sake; in an actual -program, we’d get the intensity number from the app frontend, and we’d use the -`rand` crate to generate a random number, as we did in the Guessing Game -example in Chapter 2. The `main` function calls a `generate_workout` function -with the simulated input values. - -Now that we have the context, let’s get to the algorithm. The function -`generate_workout` in Listing 13-3 contains the business logic of the -app that we’re most concerned with in this example. The rest of the code -changes in this example will be made to this function. - -Filename: src/main.rs - -``` -fn generate_workout(intensity: u32, random_number: u32) { - if intensity < 25 { - println!( - "Today, do {} pushups!", - simulated_expensive_calculation(intensity) - ); - println!( - "Next, do {} situps!", - simulated_expensive_calculation(intensity) - ); - } else { - if random_number == 3 { - println!("Take a break today! Remember to stay hydrated!"); - } else { - println!( - "Today, run for {} minutes!", - simulated_expensive_calculation(intensity) - ); - } - } -} -``` - -Listing 13-3: The business logic that prints the workout plans based on the -inputs and calls to the `simulated_expensive_calculation` function - -The code in Listing 13-3 has multiple calls to the slow calculation function. -The first `if` block calls `simulated_expensive_calculation` twice, the `if` -inside the outer `else` doesn’t call it at all, and the code inside the -second `else` case calls it once. - -The desired behavior of the `generate_workout` function is to first check -whether the user wants a low-intensity workout (indicated by a number less -than 25) or a high-intensity workout (a number of 25 or greater). - -Low-intensity workout plans will recommend a number of push-ups and sit-ups -based on the complex algorithm we’re simulating. - -If the user wants a high-intensity workout, there’s some additional logic: if -the value of the random number generated by the app happens to be 3, the app -will recommend a break and hydration. If not, the user will get a number of -minutes of running based on the complex algorithm. - -This code works the way the business wants it to now, but let’s say the data -science team decides that we need to make some changes to the way we call the -`simulated_expensive_calculation` function in the future. To simplify the -update when those changes happen, we want to refactor this code so it calls the -`simulated_expensive_calculation` function only once. We also want to cut the -place where we’re currently unnecessarily calling the function twice without -adding any other calls to that function in the process. That is, we don’t want -to call it if the result isn’t needed, and we still want to call it only once. - -#### Refactoring Using Functions - -We could restructure the workout program in many ways. First, we’ll try -extracting the duplicated call to the `simulated_expensive_calculation` -function into a variable, as shown in Listing 13-4: - -Filename: src/main.rs - -``` -fn generate_workout(intensity: u32, random_number: u32) { - let expensive_result = - simulated_expensive_calculation(intensity); - - if intensity < 25 { - println!( - "Today, do {} pushups!", - expensive_result - ); - println!( - "Next, do {} situps!", - expensive_result - ); - } else { - if random_number == 3 { - println!("Take a break today! Remember to stay hydrated!"); - } else { - println!( - "Today, run for {} minutes!", - expensive_result - ); - } - } -} -``` - -Listing 13-4: Extracting the calls to `simulated_expensive_calculation` to one -place and storing the result in the `expensive_result` variable - -This change unifies all the calls to `simulated_expensive_calculation` and -solves the problem of the first `if` block unnecessarily calling the function -twice. Unfortunately, we’re now calling this function and waiting for the -result in all cases, which includes the inner `if` block that doesn’t use the -result value at all. - -We want to define code in one place in our program, but only *execute* that -code where we actually need the result. This is a use case for closures! - -#### Refactoring with Closures to Store Code - -Instead of always calling the `simulated_expensive_calculation` function before -the `if` blocks, we can define a closure and store the *closure* in a variable -rather than storing the result of the function call, as shown in Listing 13-5. -We can actually move the whole body of `simulated_expensive_calculation` within -the closure we’re introducing here: - -Filename: src/main.rs - -``` -let expensive_closure = |num| { - println!("calculating slowly..."); - thread::sleep(Duration::from_secs(2)); - num -}; -``` - -Listing 13-5: Defining a closure and storing it in the `expensive_closure` -variable - -The closure definition comes after the `=` to assign it to the variable -`expensive_closure`. To define a closure, we start with a pair of vertical -pipes (`|`), inside which we specify the parameters to the closure; this syntax -was chosen because of its similarity to closure definitions in Smalltalk and -Ruby. This closure has one parameter named `num`: if we had more than one -parameter, we would separate them with commas, like `|param1, param2|`. - -After the parameters, we place curly brackets that hold the body of the -closure—these are optional if the closure body is a single expression. The end -of the closure, after the curly brackets, needs a semicolon to complete the -`let` statement. The value returned from the last line in the closure body -(`num`) will be the value returned from the closure when it’s called, because -that line doesn’t end in a semicolon; just like in function bodies. - -Note that this `let` statement means `expensive_closure` contains the -*definition* of an anonymous function, not the *resulting value* of calling the -anonymous function. Recall that we’re using a closure because we want to define -the code to call at one point, store that code, and call it at a later point; -the code we want to call is now stored in `expensive_closure`. - -With the closure defined, we can change the code in the `if` blocks to call the -closure to execute the code and get the resulting value. We call a closure like -we do a function: we specify the variable name that holds the closure -definition and follow it with parentheses containing the argument values we -want to use, as shown in Listing 13-6: - -Filename: src/main.rs - -``` -fn generate_workout(intensity: u32, random_number: u32) { - let expensive_closure = |num| { - println!("calculating slowly..."); - thread::sleep(Duration::from_secs(2)); - num - }; - - if intensity < 25 { - println!( - "Today, do {} pushups!", - expensive_closure(intensity) - ); - println!( - "Next, do {} situps!", - expensive_closure(intensity) - ); - } else { - if random_number == 3 { - println!("Take a break today! Remember to stay hydrated!"); - } else { - println!( - "Today, run for {} minutes!", - expensive_closure(intensity) - ); - } - } -} -``` - -Listing 13-6: Calling the `expensive_closure` we’ve defined - -Now the expensive calculation is called in only one place, and we’re only -executing that code where we need the results. - -However, we’ve reintroduced one of the problems from Listing 13-3: we’re still -calling the closure twice in the first `if` block, which will call the -expensive code twice and make the user wait twice as long as they need to. We -could fix this problem by creating a variable local to that `if` block to hold -the result of calling the closure, but closures provide us with another -solution. We’ll talk about that solution in a bit. But first let’s talk about -why there aren’t type annotations in the closure definition and the traits -involved with closures. - -### Closure Type Inference and Annotation - -Closures don’t require you to annotate the types of the parameters or the -return value like `fn` functions do. Type annotations are required on functions -because they’re part of an explicit interface exposed to your users. Defining -this interface rigidly is important for ensuring that everyone agrees on what -types of values a function uses and returns. But closures aren’t used in an -exposed interface like this: they’re stored in variables and used without -naming them and exposing them to users of our library. - -Closures are usually short and relevant only within a narrow context rather -than in any arbitrary scenario. Within these limited contexts, the compiler is -reliably able to infer the types of the parameters and the return type, similar -to how it’s able to infer the types of most variables. - -Making programmers annotate the types in these small, anonymous functions would -be annoying and largely redundant with the information the compiler already has -available. - -As with variables, we can add type annotations if we want to increase -explicitness and clarity at the cost of being more verbose than is strictly -necessary. Annotating the types for the closure we defined in Listing 13-5 -would look like the definition shown in Listing 13-7: - -Filename: src/main.rs - -``` -let expensive_closure = |num: u32| -> u32 { - println!("calculating slowly..."); - thread::sleep(Duration::from_secs(2)); - num -}; -``` - -Listing 13-7: Adding optional type annotations of the parameter and return -value types in the closure - -With type annotations added, the syntax of closures looks more similar to the -syntax of functions. The following is a vertical comparison of the syntax for -the definition of a function that adds 1 to its parameter and a closure that -has the same behavior. We’ve added some spaces to line up the relevant parts. -This illustrates how closure syntax is similar to function syntax except for -the use of pipes and the amount of syntax that is optional: - -``` -fn add_one_v1 (x: u32) -> u32 { x + 1 } -let add_one_v2 = |x: u32| -> u32 { x + 1 }; -let add_one_v3 = |x| { x + 1 }; -let add_one_v4 = |x| x + 1 ; -``` - -The first line shows a function definition, and the second line shows a fully -annotated closure definition. The third line removes the type annotations from -the closure definition, and the fourth line removes the brackets, which are -optional because the closure body has only one expression. These are all valid -definitions that will produce the same behavior when they’re called. - -Closure definitions will have one concrete type inferred for each of their -parameters and for their return value. For instance, Listing 13-8 shows the -definition of a short closure that just returns the value it receives as a -parameter. This closure isn’t very useful except for the purposes of this -example. Note that we haven’t added any type annotations to the definition: if -we then try to call the closure twice, using a `String` as an argument the -first time and a `u32` the second time, we’ll get an error. - -Filename: src/main.rs - -``` -let example_closure = |x| x; - -let s = example_closure(String::from("hello")); -let n = example_closure(5); -``` - -Listing 13-8: Attempting to call a closure whose types are inferred with two -different types - -The compiler gives us this error: - -``` -error[E0308]: mismatched types - --> src/main.rs - | - | let n = example_closure(5); - | ^ expected struct `std::string::String`, found - integral variable - | - = note: expected type `std::string::String` - found type `{integer}` -``` - -The first time we call `example_closure` with the `String` value, the compiler -infers the type of `x` and the return type of the closure to be `String`. Those -types are then locked in to the closure in `example_closure`, and we get a type -error if we try to use a different type with the same closure. - -### Storing Closures Using Generic Parameters and the `Fn` Traits - -Let’s return to our workout generation app. In Listing 13-6, our code was still -calling the expensive calculation closure more times than it needed to. One -option to solve this issue is to save the result of the expensive closure in a -variable for reuse and use the variable in each place we need the result, -instead of calling the closure again. However, this method could result in a -lot of repeated code. - -Fortunately, another solution is available to us. We can create a struct that -will hold the closure and the resulting value of calling the closure. The -struct will execute the closure only if we need the resulting value, and it -will cache the resulting value so the rest of our code doesn’t have to be -responsible for saving and reusing the result. You may know this pattern as -*memoization* or *lazy evaluation*. - -To make a struct that holds a closure, we need to specify the type of the -closure, because a struct definition needs to know the types of each of its -fields. Each closure instance has its own unique anonymous type: that is, even -if two closures have the same signature, their types are still considered -different. To define structs, enums, or function parameters that use closures, -we use generics and trait bounds, as we discussed in Chapter 10. - -The `Fn` traits are provided by the standard library. All closures implement at -least one of the traits: `Fn`, `FnMut`, or `FnOnce`. We’ll discuss the -difference between these traits in the “Capturing the Environment with -Closures” section; in this example, we can use the `Fn` trait. - -We add types to the `Fn` trait bound to represent the types of the parameters -and return values the closures must have to match this trait bound. In this -case, our closure has a parameter of type `u32` and returns a `u32`, so the -trait bound we specify is `Fn(u32) -> u32`. - -Listing 13-9 shows the definition of the `Cacher` struct that holds a closure -and an optional result value: - -Filename: src/main.rs - -``` -struct Cacher - where T: Fn(u32) -> u32 -{ - calculation: T, - value: Option, -} -``` - -Listing 13-9: Defining a `Cacher` struct that holds a closure in `calculation` -and an optional result in `value` - -The `Cacher` struct has a `calculation` field of the generic type `T`. The -trait bounds on `T` specify that it’s a closure by using the `Fn` trait. Any -closure we want to store in the `calculation` field must have one `u32` -parameter (specified within the parentheses after `Fn`) and must return a -`u32` (specified after the `->`). - -> Note: Functions implement all three of the `Fn` traits too. If what we want -> to do doesn’t require capturing a value from the environment, we can use a -> function rather than a closure where we need something that implements an `Fn` -> trait. - -The `value` field is of type `Option`. Before we execute the closure, -`value` will be `None`. When code using a `Cacher` asks for the *result* of the -closure, the `Cacher` will execute the closure at that time and store the -result within a `Some` variant in the `value` field. Then if the code asks for -the result of the closure again, instead of executing the closure again, the -`Cacher` will return the result held in the `Some` variant. - -The logic around the `value` field we’ve just described is defined in Listing -13-10: - -Filename: src/main.rs - -``` -impl Cacher - where T: Fn(u32) -> u32 -{ - fn new(calculation: T) -> Cacher { - Cacher { - calculation, - value: None, - } - } - - fn value(&mut self, arg: u32) -> u32 { - match self.value { - Some(v) => v, - None => { - let v = (self.calculation)(arg); - self.value = Some(v); - v - }, - } - } -} -``` - -Listing 13-10: The caching logic of `Cacher` - -We want `Cacher` to manage the struct fields’ values rather than letting the -calling code potentially change the values in these fields directly, so these -fields are private. - -The `Cacher::new` function takes a generic parameter `T`, which we’ve defined -as having the same trait bound as the `Cacher` struct. Then `Cacher::new` -returns a `Cacher` instance that holds the closure specified in the -`calculation` field and a `None` value in the `value` field, because we haven’t -executed the closure yet. - -When the calling code needs the result of evaluating the closure, instead of -calling the closure directly, it will call the `value` method. This method -checks whether we already have a resulting value in `self.value` in a `Some`; -if we do, it returns the value within the `Some` without executing the closure -again. - -If `self.value` is `None`, the code calls the closure stored in -`self.calculation`, saves the result in `self.value` for future use, and -returns the value as well. - -Listing 13-11 shows how we can use this `Cacher` struct in the function -`generate_workout` from Listing 13-6: - -Filename: src/main.rs - -``` -fn generate_workout(intensity: u32, random_number: u32) { - let mut expensive_result = Cacher::new(|num| { - println!("calculating slowly..."); - thread::sleep(Duration::from_secs(2)); - num - }); - - if intensity < 25 { - println!( - "Today, do {} pushups!", - expensive_result.value(intensity) - ); - println!( - "Next, do {} situps!", - expensive_result.value(intensity) - ); - } else { - if random_number == 3 { - println!("Take a break today! Remember to stay hydrated!"); - } else { - println!( - "Today, run for {} minutes!", - expensive_result.value(intensity) - ); - } - } -} -``` - -Listing 13-11: Using `Cacher` in the `generate_workout` function to abstract -away the caching logic - -Instead of saving the closure in a variable directly, we save a new instance of -`Cacher` that holds the closure. Then, in each place we want the result, we -call the `value` method on the `Cacher` instance. We can call the `value` -method as many times as we want, or not call it at all, and the expensive -calculation will be run a maximum of once. - -Try running this program with the `main` function from Listing 13-2. Change the -values in the `simulated_user_specified_value` and `simulated_random_number` -variables to verify that in all the cases in the various `if` and `else` -blocks, `calculating slowly...` appears only once and only when needed. The -`Cacher` takes care of the logic necessary to ensure we aren’t calling the -expensive calculation more than we need to so `generate_workout` can focus on -the business logic. - -### Limitations of the `Cacher` Implementation - -Caching values is a generally useful behavior that we might want to use in -other parts of our code with different closures. However, there are two -problems with the current implementation of `Cacher` that would make reusing it -in different contexts difficult. - -The first problem is that a `Cacher` instance assumes it will always get the -same value for the parameter `arg` to the `value` method. That is, this test of -`Cacher` will fail: - -``` -#[test] -fn call_with_different_values() { - let mut c = Cacher::new(|a| a); - - let v1 = c.value(1); - let v2 = c.value(2); - - assert_eq!(v2, 2); -} -``` - -This test creates a new `Cacher` instance with a closure that returns the value -passed into it. We call the `value` method on this `Cacher` instance with an -`arg` value of 1 and then an `arg` value of 2, and we expect the call to -`value` with the `arg` value of 2 should return 2. - -Run this test with the `Cacher` implementation in Listing 13-9 and Listing -13-10, and the test will fail on the `assert_eq!` with this message: - -``` -thread 'call_with_different_values' panicked at 'assertion failed: `(left == right)` - left: `1`, - right: `2`', src/main.rs -``` - -The problem is that the first time we called `c.value` with 1, the `Cacher` -instance saved `Some(1)` in `self.value`. Thereafter, no matter what we pass in -to the `value` method, it will always return 1. - -Try modifying `Cacher` to hold a hash map rather than a single value. The keys -of the hash map will be the `arg` values that are passed in, and the values of -the hash map will be the result of calling the closure on that key. Instead of -looking at whether `self.value` directly has a `Some` or a `None` value, the -`value` function will look up the `arg` in the hash map and return the value if -it’s present. If it’s not present, the `Cacher` will call the closure and save -the resulting value in the hash map associated with its `arg` value. - -The second problem with the current `Cacher` implementation is that it only -accepts closures that take one parameter of type `u32` and return a `u32`. We -might want to cache the results of closures that take a string slice and return -`usize` values, for example. To fix this issue, try introducing more generic -parameters to increase the flexibility of the `Cacher` functionality. - -### Capturing the Environment with Closures - -In the workout generator example, we only used closures as inline anonymous -functions. However, closures have an additional capability that functions don’t -have: they can capture their environment and access variables from the scope in -which they’re defined. - -Listing 13-12 has an example of a closure stored in the `equal_to_x` variable -that uses the `x` variable from the closure’s surrounding environment: - -Filename: src/main.rs - -``` -fn main() { - let x = 4; - - let equal_to_x = |z| z == x; - - let y = 4; - - assert!(equal_to_x(y)); -} -``` - -Listing 13-12: Example of a closure that refers to a variable in its enclosing -scope - -Here, even though `x` is not one of the parameters of `equal_to_x`, the -`equal_to_x` closure is allowed to use the `x` variable that’s defined in the -same scope that `equal_to_x` is defined in. - -We can’t do the same with functions; if we try with the following example, our -code won’t compile: - -Filename: src/main.rs - -``` -fn main() { - let x = 4; - - fn equal_to_x(z: i32) -> bool { z == x } - - let y = 4; - - assert!(equal_to_x(y)); -} -``` - -We get an error: - -``` -error[E0434]: can't capture dynamic environment in a fn item; use the || { ... -} closure form instead - --> src/main.rs - | -4 | fn equal_to_x(z: i32) -> bool { z == x } - | ^ -``` - -The compiler even reminds us that this only works with closures! - -When a closure captures a value from its environment, it uses memory to store -the values for use in the closure body. This use of memory is overhead that we -don’t want to pay in more common cases where we want to execute code that -doesn’t capture its environment. Because functions are never allowed to capture -their environment, defining and using functions will never incur this overhead. - -Closures can capture values from their environment in three ways, which -directly map to the three ways a function can take a parameter: taking -ownership, borrowing mutably, and borrowing immutably. These are encoded in the -three `Fn` traits as follows: - -* `FnOnce` consumes the variables it captures from its enclosing scope, known - as the closure’s *environment*. To consume the captured variables, the - closure must take ownership of these variables and move them into the closure - when it is defined. The `Once` part of the name represents the fact that the - closure can’t take ownership of the same variables more than once, so it can - be called only once. -* `FnMut` can change the environment because it mutably borrows values. -* `Fn` borrows values from the environment immutably. - -When you create a closure, Rust infers which trait to use based on how the -closure uses the values from the environment. All closures implement `FnOnce` -because they can all be called at least once. Closures that don’t move the -captured variables also implement `FnMut`, and closures that don’t need mutable -access to the captured variables also implement `Fn`. In Listing 13-12, the -`equal_to_x` closure borrows `x` immutably (so `equal_to_x` has the `Fn` trait) -because the body of the closure only needs to read the value in `x`. - -If you want to force the closure to take ownership of the values it uses in the -environment, you can use the `move` keyword before the parameter list. This -technique is mostly useful when passing a closure to a new thread to move the -data so it’s owned by the new thread. - -We’ll have more examples of `move` closures in Chapter 16 when we talk about -concurrency. For now, here’s the code from Listing 13-12 with the `move` -keyword added to the closure definition and using vectors instead of integers, -because integers can be copied rather than moved; note that this code will not -yet compile. - -Filename: src/main.rs - -``` -fn main() { - let x = vec![1, 2, 3]; - - let equal_to_x = move |z| z == x; - - println!("can't use x here: {:?}", x); - - let y = vec![1, 2, 3]; - - assert!(equal_to_x(y)); -} -``` - -We receive the following error: - -``` -error[E0382]: use of moved value: `x` - --> src/main.rs:6:40 - | -4 | let equal_to_x = move |z| z == x; - | -------- value moved (into closure) here -5 | -6 | println!("can't use x here: {:?}", x); - | ^ value used here after move - | - = note: move occurs because `x` has type `std::vec::Vec`, which does not - implement the `Copy` trait -``` - -The `x` value is moved into the closure when the closure is defined, because we -added the `move` keyword. The closure then has ownership of `x`, and `main` -isn’t allowed to use `x` anymore in the `println!` statement. Removing -`println!` will fix this example. - -Most of the time when specifying one of the `Fn` trait bounds, you can start -with `Fn` and the compiler will tell you if you need `FnMut` or `FnOnce` based -on what happens in the closure body. - -To illustrate situations where closures that can capture their environment are -useful as function parameters, let’s move on to our next topic: iterators. - -## Processing a Series of Items with Iterators - -The iterator pattern allows you to perform some task on a sequence of items in -turn. An iterator is responsible for the logic of iterating over each item and -determining when the sequence has finished. When you use iterators, you don’t -have to reimplement that logic yourself. - -In Rust, iterators are *lazy*, meaning they have no effect until you call -methods that consume the iterator to use it up. For example, the code in -Listing 13-13 creates an iterator over the items in the vector `v1` by calling -the `iter` method defined on `Vec`. This code by itself doesn’t do anything -useful. - -``` -let v1 = vec![1, 2, 3]; - -let v1_iter = v1.iter(); -``` - -Listing 13-13: Creating an iterator - -Once we’ve created an iterator, we can use it in a variety of ways. In Listing -3-5 in Chapter 3, we used iterators with `for` loops to execute some code on -each item, although we glossed over what the call to `iter` did until now. - -The example in Listing 13-14 separates the creation of the iterator from the -use of the iterator in the `for` loop. The iterator is stored in the `v1_iter` -variable, and no iteration takes place at that time. When the `for` loop is -called using the iterator in `v1_iter`, each element in the iterator is used in -one iteration of the loop, which prints out each value. - -``` -let v1 = vec![1, 2, 3]; - -let v1_iter = v1.iter(); - -for val in v1_iter { - println!("Got: {}", val); -} -``` - -Listing 13-14: Using an iterator in a `for` loop - -In languages that don’t have iterators provided by their standard libraries, -you would likely write this same functionality by starting a variable at index -0, using that variable to index into the vector to get a value, and -incrementing the variable value in a loop until it reached the total number of -items in the vector. - -Iterators handle all that logic for you, cutting down on repetitive code you -could potentially mess up. Iterators give you more flexibility to use the same -logic with many different kinds of sequences, not just data structures you can -index into, like vectors. Let’s examine how iterators do that. - -### The `Iterator` Trait and the `next` Method - -All iterators implement a trait named `Iterator` that is defined in the -standard library. The definition of the trait looks like this: - -``` -trait Iterator { - type Item; - - fn next(&mut self) -> Option; - - // methods with default implementations elided -} -``` - -Notice this definition uses some new syntax: `type Item` and `Self::Item`, -which are defining an *associated type* with this trait. We’ll talk about -associated types in depth in Chapter 19. For now, all you need to know is that -this code says implementing the `Iterator` trait requires that you also define -an `Item` type, and this `Item` type is used in the return type of the `next` -method. In other words, the `Item` type will be the type returned from the -iterator. - -The `Iterator` trait only requires implementors to define one method: the -`next` method, which returns one item of the iterator at a time wrapped in -`Some` and, when iteration is over, returns `None`. - -We can call the `next` method on iterators directly; Listing 13-15 demonstrates -what values are returned from repeated calls to `next` on the iterator created -from the vector: - -Filename: src/lib.rs - -``` -#[test] -fn iterator_demonstration() { - let v1 = vec![1, 2, 3]; - - let mut v1_iter = v1.iter(); - - assert_eq!(v1_iter.next(), Some(&1)); - assert_eq!(v1_iter.next(), Some(&2)); - assert_eq!(v1_iter.next(), Some(&3)); - assert_eq!(v1_iter.next(), None); -} -``` - -Listing 13-15: Calling the `next` method on an iterator - -Note that we needed to make `v1_iter` mutable: calling the `next` method on an -iterator changes internal state that the iterator uses to keep track of where -it is in the sequence. In other words, this code *consumes*, or uses up, the -iterator. Each call to `next` eats up an item from the iterator. We didn’t need -to make `v1_iter` mutable when we used a `for` loop because the loop took -ownership of `v1_iter` and made it mutable behind the scenes. - -Also note that the values we get from the calls to `next` are immutable -references to the values in the vector. The `iter` method produces an iterator -over immutable references. If we want to create an iterator that takes -ownership of `v1` and returns owned values, we can call `into_iter` instead of -`iter`. Similarly, if we want to iterate over mutable references, we can call -`iter_mut` instead of `iter`. - -### Methods that Consume the Iterator - -The `Iterator` trait has a number of different methods with default -implementations provided by the standard library; you can find out about these -methods by looking in the standard library API documentation for the `Iterator` -trait. Some of these methods call the `next` method in their definition, which -is why you’re required to implement the `next` method when implementing the -`Iterator` trait. - -Methods that call `next` are called *consuming adaptors*, because calling them -uses up the iterator. One example is the `sum` method, which takes ownership of -the iterator and iterates through the items by repeatedly calling `next`, thus -consuming the iterator. As it iterates through, it adds each item to a running -total and returns the total when iteration is complete. Listing 13-16 has a -test illustrating a use of the `sum` method: - -Filename: src/lib.rs - -``` -#[test] -fn iterator_sum() { - let v1 = vec![1, 2, 3]; - - let v1_iter = v1.iter(); - - let total: i32 = v1_iter.sum(); - - assert_eq!(total, 6); -} -``` - -Listing 13-16: Calling the `sum` method to get the total of all items in the -iterator - -We aren’t allowed to use `v1_iter` after the call to `sum` because `sum` takes -ownership of the iterator we call it on. - -### Methods that Produce Other Iterators - -Other methods defined on the `Iterator` trait, known as *iterator adaptors*, -allow you to change iterators into different kinds of iterators. You can chain -multiple calls to iterator adaptors to perform complex actions in a readable -way. But because all iterators are lazy, you have to call one of the consuming -adaptor methods to get results from calls to iterator adaptors. - -Listing 13-17 shows an example of calling the iterator adaptor method `map`, -which takes a closure to call on each item to produce a new iterator. The -closure here creates a new iterator in which each item from the vector has been -incremented by 1. However, this code produces a warning: - -Filename: src/main.rs - -``` -let v1: Vec = vec![1, 2, 3]; - -v1.iter().map(|x| x + 1); -``` - -Listing 13-17: Calling the iterator adaptor `map` to create a new iterator - -The warning we get is this: - -``` -warning: unused `std::iter::Map` which must be used: iterator adaptors are lazy -and do nothing unless consumed - --> src/main.rs:4:5 - | -4 | v1.iter().map(|x| x + 1); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: #[warn(unused_must_use)] on by default -``` - -The code in Listing 13-17 doesn’t do anything; the closure we’ve specified -never gets called. The warning reminds us why: iterator adaptors are lazy, and -we need to consume the iterator here. - -To fix this and consume the iterator, we’ll use the `collect` method, which we -used in Chapter 12 with `env::args` in Listing 12-1. This method consumes the -iterator and collects the resulting values into a collection data type. - -In Listing 13-18, we collect the results of iterating over the iterator that’s -returned from the call to `map` into a vector. This vector will end up -containing each item from the original vector incremented by 1. - -Filename: src/main.rs - -``` -let v1: Vec = vec![1, 2, 3]; - -let v2: Vec<_> = v1.iter().map(|x| x + 1).collect(); - -assert_eq!(v2, vec![2, 3, 4]); -``` - -Listing 13-18: Calling the `map` method to create a new iterator and then -calling the `collect` method to consume the new iterator and create a vector - -Because `map` takes a closure, we can specify any operation we want to perform -on each item. This is a great example of how closures let you customize some -behavior while reusing the iteration behavior that the `Iterator` trait -provides. - -### Using Closures that Capture Their Environment - -Now that we’ve introduced iterators, we can demonstrate a common use of -closures that capture their environment by using the `filter` iterator adaptor. -The `filter` method on an iterator takes a closure that takes each item from -the iterator and returns a Boolean. If the closure returns `true`, the value -will be included in the iterator produced by `filter`. If the closure returns -`false`, the value won’t be included in the resulting iterator. - -In Listing 13-19, we use `filter` with a closure that captures the `shoe_size` -variable from its environment to iterate over a collection of `Shoe` struct -instances. It will return only shoes that are the specified size. - -Filename: src/lib.rs - -``` -#[derive(PartialEq, Debug)] -struct Shoe { - size: u32, - style: String, -} - -fn shoes_in_my_size(shoes: Vec, shoe_size: u32) -> Vec { - shoes.into_iter() - .filter(|s| s.size == shoe_size) - .collect() -} - -#[test] -fn filters_by_size() { - let shoes = vec![ - Shoe { size: 10, style: String::from("sneaker") }, - Shoe { size: 13, style: String::from("sandal") }, - Shoe { size: 10, style: String::from("boot") }, - ]; - - let in_my_size = shoes_in_my_size(shoes, 10); - - assert_eq!( - in_my_size, - vec![ - Shoe { size: 10, style: String::from("sneaker") }, - Shoe { size: 10, style: String::from("boot") }, - ] - ); -} -``` - -Listing 13-19: Using the `filter` method with a closure that captures -`shoe_size` - -The `shoes_in_my_size` function takes ownership of a vector of shoes and a shoe -size as parameters. It returns a vector containing only shoes of the specified -size. - -In the body of `shoes_in_my_size`, we call `into_iter` to create an iterator -that takes ownership of the vector. Then we call `filter` to adapt that -iterator into a new iterator that only contains elements for which the closure -returns `true`. - -The closure captures the `shoe_size` parameter from the environment and -compares the value with each shoe’s size, keeping only shoes of the size -specified. Finally, calling `collect` gathers the values returned by the -adapted iterator into a vector that’s returned by the function. - -The test shows that when we call `shoes_in_my_size`, we get back only shoes -that have the same size as the value we specified. - -### Creating Our Own Iterators with the `Iterator` Trait - -We’ve shown that you can create an iterator by calling `iter`, `into_iter`, or -`iter_mut` on a vector. You can create iterators from the other collection -types in the standard library, such as hash map. You can also create iterators -that do anything you want by implementing the `Iterator` trait on your own -types. As previously mentioned, the only method you’re required to provide a -definition for is the `next` method. Once you’ve done that, you can use all -other methods that have default implementations provided by the `Iterator` -trait! - -To demonstrate, let’s create an iterator that will only ever count from 1 to 5. -First, we’ll create a struct to hold some values. Then we’ll make this struct -into an iterator by implementing the `Iterator` trait and using the values in -that implementation. - -Listing 13-20 has the definition of the `Counter` struct and an associated -`new` function to create instances of `Counter`: - -Filename: src/lib.rs - -``` -struct Counter { - count: u32, -} - -impl Counter { - fn new() -> Counter { - Counter { count: 0 } - } -} -``` - -Listing 13-20: Defining the `Counter` struct and a `new` function that creates -instances of `Counter` with an initial value of 0 for `count` - -The `Counter` struct has one field named `count`. This field holds a `u32` -value that will keep track of where we are in the process of iterating from 1 -to 5. The `count` field is private because we want the implementation of -`Counter` to manage its value. The `new` function enforces the behavior of -always starting new instances with a value of 0 in the `count` field. - -Next, we’ll implement the `Iterator` trait for our `Counter` type by defining -the body of the `next` method to specify what we want to happen when this -iterator is used, as shown in Listing 13-21: - -Filename: src/lib.rs - -``` -impl Iterator for Counter { - type Item = u32; - - fn next(&mut self) -> Option { - self.count += 1; - - if self.count < 6 { - Some(self.count) - } else { - None - } - } -} -``` - -Listing 13-21: Implementing the `Iterator` trait on our `Counter` struct - -We set the associated `Item` type for our iterator to `u32`, meaning the -iterator will return `u32` values. Again, don’t worry about associated types -yet, we’ll cover them in Chapter 19. - -We want our iterator to add 1 to the current state, so we initialized `count` -to 0 so it would return 1 first. If the value of `count` is less than 6, `next` -will return the current value wrapped in `Some`, but if `count` is 6 or higher, -our iterator will return `None`. - -#### Using Our `Counter` Iterator’s `next` Method - -Once we’ve implemented the `Iterator` trait, we have an iterator! Listing 13-22 -shows a test demonstrating that we can use the iterator functionality of our -`Counter` struct by calling the `next` method on it directly, just as we did -with the iterator created from a vector in Listing 13-15. - -Filename: src/lib.rs - -``` -#[test] -fn calling_next_directly() { - let mut counter = Counter::new(); - - assert_eq!(counter.next(), Some(1)); - assert_eq!(counter.next(), Some(2)); - assert_eq!(counter.next(), Some(3)); - assert_eq!(counter.next(), Some(4)); - assert_eq!(counter.next(), Some(5)); - assert_eq!(counter.next(), None); -} -``` - -Listing 13-22: Testing the functionality of the `next` method implementation - -This test creates a new `Counter` instance in the `counter` variable and then -calls `next` repeatedly, verifying that we have implemented the behavior we -want this iterator to have: returning the values from 1 to 5. - -#### Using Other `Iterator` Trait Methods - -We implemented the `Iterator` trait by defining the `next` method, so we -can now use any `Iterator` trait method’s default implementations as defined in -the standard library, because they all use the `next` method’s functionality. - -For example, if for some reason we wanted to take the values produced by an -instance of `Counter`, pair them with values produced by another `Counter` -instance after skipping the first value, multiply each pair together, keep only -those results that are divisible by 3, and add all the resulting values -together, we could do so, as shown in the test in Listing 13-23: - -Filename: src/lib.rs - -``` -#[test] -fn using_other_iterator_trait_methods() { - let sum: u32 = Counter::new().zip(Counter::new().skip(1)) - .map(|(a, b)| a * b) - .filter(|x| x % 3 == 0) - .sum(); - assert_eq!(18, sum); -} -``` - -Listing 13-23: Using a variety of `Iterator` trait methods on our `Counter` -iterator - -Note that `zip` produces only four pairs; the theoretical fifth pair `(5, -None)` is never produced because `zip` returns `None` when either of its input -iterators return `None`. - -All of these method calls are possible because we specified how the `next` -method works, and the standard library provides default implementations for -other methods that call `next`. - -## Improving Our I/O Project - -With this new knowledge about iterators, we can improve the I/O project in -Chapter 12 by using iterators to make places in the code clearer and more -concise. Let’s look at how iterators can improve our implementation of the -`Config::new` function and the `search` function. - - -### Removing a `clone` Using an Iterator - -In Listing 12-6, we added code that took a slice of `String` values and created -an instance of the `Config` struct by indexing into the slice and cloning the -values, allowing the `Config` struct to own those values. In Listing 13-24, -we’ve reproduced the implementation of the `Config::new` function as it was in -Listing 12-23: - -Filename: src/lib.rs - -``` -impl Config { - pub fn new(args: &[String]) -> Result { - if args.len() < 3 { - return Err("not enough arguments"); - } - - let query = args[1].clone(); - let filename = args[2].clone(); - - let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); - - Ok(Config { query, filename, case_sensitive }) - } -} -``` - -Listing 13-24: Reproduction of the `Config::new` function from Listing 12-23 - -At the time, we said not to worry about the inefficient `clone` calls because -we would remove them in the future. Well, that time is now! - -We needed `clone` here because we have a slice with `String` elements in the -parameter `args`, but the `new` function doesn’t own `args`. To return -ownership of a `Config` instance, we had to clone the values from the `query` -and `filename` fields of `Config` so the `Config` instance can own its values. - -With our new knowledge about iterators, we can change the `new` function to -take ownership of an iterator as its argument instead of borrowing a slice. -We’ll use the iterator functionality instead of the code that checks the length -of the slice and indexes into specific locations. This will clarify what the -`Config::new` function is doing because the iterator will access the values. - -Once `Config::new` takes ownership of the iterator and stops using indexing -operations that borrow, we can move the `String` values from the iterator into -`Config` rather than calling `clone` and making a new allocation. - -#### Using the Returned Iterator Directly - -Open your I/O project’s *src/main.rs* file, which should look like this: - -Filename: src/main.rs - -``` -fn main() { - let args: Vec = env::args().collect(); - - let config = Config::new(&args).unwrap_or_else(|err| { - eprintln!("Problem parsing arguments: {}", err); - process::exit(1); - }); - - // --snip-- -} -``` - -We’ll change the start of the `main` function that we had in Listing 12-24 at -to the code in Listing 13-25. This won’t compile until we update `Config::new` -as well. - -Filename: src/main.rs - -``` -fn main() { - let config = Config::new(env::args()).unwrap_or_else(|err| { - eprintln!("Problem parsing arguments: {}", err); - process::exit(1); - }); - - // --snip-- -} -``` - -Listing 13-25: Passing the return value of `env::args` to `Config::new` - -The `env::args` function returns an iterator! Rather than collecting the -iterator values into a vector and then passing a slice to `Config::new`, now -we’re passing ownership of the iterator returned from `env::args` to -`Config::new` directly. - -Next, we need to update the definition of `Config::new`. In your I/O project’s -*src/lib.rs* file, let’s change the signature of `Config::new` to look like -Listing 13-26. This still won’t compile because we need to update the function -body. - -Filename: src/lib.rs - -``` -impl Config { - pub fn new(mut args: std::env::Args) -> Result { - // --snip-- -``` - -Listing 13-26: Updating the signature of `Config::new` to expect an iterator - -The standard library documentation for the `env::args` function shows that the -type of the iterator it returns is `std::env::Args`. We’ve updated the -signature of the `Config::new` function so the parameter `args` has the type -`std::env::Args` instead of `&[String]`. Because we’re taking ownership of -`args` and we’ll be mutating `args` by iterating over it, we can add the `mut` -keyword into the specification of the `args` parameter to make it mutable. - -#### Using `Iterator` Trait Methods Instead of Indexing - -Next, we’ll fix the body of `Config::new`. The standard library documentation -also mentions that `std::env::Args` implements the `Iterator` trait, so we know -we can call the `next` method on it! Listing 13-27 updates the code from -Listing 12-23 to use the `next` method: - -Filename: src/lib.rs - -``` -impl Config { - pub fn new(mut args: std::env::Args) -> Result { - args.next(); - - let query = match args.next() { - Some(arg) => arg, - None => return Err("Didn't get a query string"), - }; - - let filename = match args.next() { - Some(arg) => arg, - None => return Err("Didn't get a file name"), - }; - - let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); - - Ok(Config { query, filename, case_sensitive }) - } -} -``` - -Listing 13-27: Changing the body of `Config::new` to use iterator methods - -Remember that the first value in the return value of `env::args` is the name of -the program. We want to ignore that and get to the next value, so first we call -`next` and do nothing with the return value. Second, we call `next` to get the -value we want to put in the `query` field of `Config`. If `next` returns a -`Some`, we use a `match` to extract the value. If it returns `None`, it means -not enough arguments were given and we return early with an `Err` value. We do -the same thing for the `filename` value. - -### Making Code Clearer with Iterator Adaptors - -We can also take advantage of iterators in the `search` function in our I/O -project, which is reproduced here in Listing 13-28 as it was in Listing 12-19: - -Filename: src/lib.rs - -``` -pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { - let mut results = Vec::new(); - - for line in contents.lines() { - if line.contains(query) { - results.push(line); - } - } - - results -} -``` - -Listing 13-28: The implementation of the `search` function from Listing 12-19 - -We can write this code in a more concise way using iterator adaptor methods. -Doing so also lets us avoid having a mutable intermediate `results` vector. The -functional programming style prefers to minimize the amount of mutable state to -make code clearer. Removing the mutable state might enable a future enhancement -to make searching happen in parallel, because we wouldn’t have to manage -concurrent access to the `results` vector. Listing 13-29 shows this change: - -Filename: src/lib.rs - -``` -pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { - contents.lines() - .filter(|line| line.contains(query)) - .collect() -} -``` - -Listing 13-29: Using iterator adaptor methods in the implementation of the -`search` function - -Recall that the purpose of the `search` function is to return all lines in -`contents` that contain the `query`. Similar to the `filter` example in Listing -13-19, this code uses the `filter` adaptor to keep only the lines that -`line.contains(query)` returns `true` for. We then collect the matching lines -into another vector with `collect`. Much simpler! Feel free to make the same -change to use iterator methods in the `search_case_insensitive` function as -well. - -The next logical question is which style you should choose in your own code and -why: the original implementation in Listing 13-28 or the version using -iterators in Listing 13-29. Most Rust programmers prefer to use the iterator -style. It’s a bit tougher to get the hang of at first, but once you get a feel -for the various iterator adaptors and what they do, iterators can be easier to -understand. Instead of fiddling with the various bits of looping and building -new vectors, the code focuses on the high-level objective of the loop. This -abstracts away some of the commonplace code so it’s easier to see the concepts -that are unique to this code, such as the filtering condition each element in -the iterator must pass. - -But are the two implementations truly equivalent? The intuitive assumption -might be that the more low-level loop will be faster. Let’s talk about -performance. - -## Comparing Performance: Loops vs. Iterators - -To determine whether to use loops or iterators, you need to know which version -of our `search` functions is faster: the version with an explicit `for` loop or -the version with iterators. - -We ran a benchmark by loading the entire contents of *The Adventures of -Sherlock Holmes* by Sir Arthur Conan Doyle into a `String` and looking for the -word *the* in the contents. Here are the results of the benchmark on the -version of `search` using the `for` loop and the version using iterators: - -``` -test bench_search_for ... bench: 19,620,300 ns/iter (+/- 915,700) -test bench_search_iter ... bench: 19,234,900 ns/iter (+/- 657,200) -``` - -The iterator version was slightly faster! We won’t explain the benchmark code -here, because the point is not to prove that the two versions are equivalent -but to get a general sense of how these two implementations compare -performance-wise. - -For a more comprehensive benchmark, you should check using various texts of -various sizes as the `contents`, different words and words of different lengths -as the `query`, and all kinds of other variations. The point is this: -iterators, although a high-level abstraction, get compiled down to roughly the -same code as if you’d written the lower-level code yourself. Iterators are one -of Rust’s *zero-cost abstractions*, by which we mean using the abstraction -imposes no additional runtime overhead. This is analogous to how Bjarne -Stroustrup, the original designer and implementor of C++, defines -*zero-overhead* in “Foundations of C++” (2012): - -> In general, C++ implementations obey the zero-overhead principle: What you -> don’t use, you don’t pay for. And further: What you do use, you couldn’t hand -> code any better. - -As another example, the following code is taken from an audio decoder. The -decoding algorithm uses the linear prediction mathematical operation to -estimate future values based on a linear function of the previous samples. This -code uses an iterator chain to do some math on three variables in scope: a -`buffer` slice of data, an array of 12 `coefficients`, and an amount by which -to shift data in `qlp_shift`. We’ve declared the variables within this example -but not given them any values; although this code doesn’t have much meaning -outside of its context, it’s still a concise, real-world example of how Rust -translates high-level ideas to low-level code. - -``` -let buffer: &mut [i32]; -let coefficients: [i64; 12]; -let qlp_shift: i16; - -for i in 12..buffer.len() { - let prediction = coefficients.iter() - .zip(&buffer[i - 12..i]) - .map(|(&c, &s)| c * s as i64) - .sum::() >> qlp_shift; - let delta = buffer[i]; - buffer[i] = prediction as i32 + delta; -} -``` - -To calculate the value of `prediction`, this code iterates through each of the -12 values in `coefficients` and uses the `zip` method to pair the coefficient -values with the previous 12 values in `buffer`. Then, for each pair, we -multiply the values together, sum all the results, and shift the bits in the -sum `qlp_shift` bits to the right. - -Calculations in applications like audio decoders often prioritize performance -most highly. Here, we’re creating an iterator, using two adaptors, and then -consuming the value. What assembly code would this Rust code compile to? Well, -as of this writing, it compiles down to the same assembly you’d write by hand. -There’s no loop at all corresponding to the iteration over the values in -`coefficients`: Rust knows that there are 12 iterations, so it “unrolls” the -loop. *Unrolling* is an optimization that removes the overhead of the loop -controlling code and instead generates repetitive code for each iteration of -the loop. - -All of the coefficients get stored in registers, which means accessing the -values is very fast. There are no bounds checks on the array access at runtime. -All these optimizations that Rust is able to apply make the resulting code -extremely efficient. Now that you know this, you can use iterators and closures -without fear! They make code seem like it’s higher level but don’t impose a -runtime performance penalty for doing so. - -## Summary - -Closures and iterators are Rust features inspired by functional programming -language ideas. They contribute to Rust’s capability to clearly express -high-level ideas at low-level performance. The implementations of closures and -iterators are such that runtime performance is not affected. This is part of -Rust’s goal to strive to provide zero-cost abstractions. - -Now that we’ve improved the expressiveness of our I/O project, let’s look at -some more features of `cargo` that will help us share the project with the -world. diff --git a/second-edition/nostarch/chapter14.md b/second-edition/nostarch/chapter14.md deleted file mode 100644 index 2cbdde02f3..0000000000 --- a/second-edition/nostarch/chapter14.md +++ /dev/null @@ -1,984 +0,0 @@ - -[TOC] - -# More About Cargo and Crates.io - -So far we’ve used only the most basic features of Cargo to build, run, and test -our code, but it can do a lot more. In this chapter, we’ll discuss some of its -other, more advanced features to show you how to: - -* Customize your build through release profiles -* Publish libraries on *https://crates.io/* -* Organize large projects with workspaces -* Install binaries from *https://crates.io/* -* Extend Cargo using custom commands - -Cargo can do even more than what we cover in this chapter, so for a full -explanation of all its features, see its documentation at -*https://doc.rust-lang.org/cargo/*. - -## Customizing Builds with Release Profiles - -In Rust, *release profiles* are predefined and customizable profiles with -different configurations that allow a programmer to have more control over -various options for compiling code. Each profile is configured independently of -the others. - -Cargo has two main profiles: the `dev` profile Cargo uses when you run `cargo -build` and the `release` profile Cargo uses when you run `cargo build ---release`. The `dev` profile is defined with good defaults for developing, and -the `release` profile has good defaults for release builds. - -These profile names might be familiar from the output of your builds, which -shows the profile used in the build: - -``` -$ cargo build - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs -$ cargo build --release - Finished release [optimized] target(s) in 0.0 secs -``` - -The `dev` and `release` shown in this build output indicate that the compiler -is using different profiles. - -Cargo has default settings for each of the profiles that apply when there -aren’t any `[profile.*]` sections in the project’s *Cargo.toml* file. By adding -`[profile.*]` sections for any profile we want to customize, we can override -any subset of the default settings. For example, here are the default values -for the `opt-level` setting for the `dev` and `release` profiles: - -Filename: Cargo.toml - -``` -[profile.dev] -opt-level = 0 - -[profile.release] -opt-level = 3 -``` - -The `opt-level` setting controls the number of optimizations Rust will apply to -your code with a range of zero to three. Applying more optimizations extends -compiling time, so if you’re in development and compiling your code often, you -want faster compiling even at the expense of the resulting code running slower. -That is the reason the default `opt-level` for `dev` is `0`. When you’re ready -to release your code, it’s best to spend more time compiling. You’ll only -compile in release mode once and run the compiled program many times, so -release mode trades longer compile time for code that runs faster. That is the -reason the default `opt-level` for the `release` profile is `3`. - -We can override any default setting by adding a different value for it in -*Cargo.toml*. For example, if we want to use optimization level 1 in the -development profile, we can add these two lines to our project’s *Cargo.toml* -file: - -Filename: Cargo.toml - -``` -[profile.dev] -opt-level = 1 -``` - -This code overrides the default setting of `0`. Now when we run `cargo build`, -Cargo will use the defaults for the `dev` profile plus our customization to -`opt-level`. Because we set `opt-level` to `1`, Cargo will apply more -optimizations than the default, but not as many as a release build. - -For the full list of configuration options and defaults for each profile, see -Cargo’s documentation at *https://doc.rust-lang.org/cargo/*. - -## Publishing a Crate to Crates.io - -We’ve used packages from *https://crates.io/* as dependencies of our project, -but you can also share your code for other people to use by publishing your own -packages. The crate registry at *https://crates.io/* distributes the source -code of your packages, so it primarily hosts code that is open source. - -Rust and Cargo have features that help make your published package easier for -people to use and to find in the first place. We’ll talk about some of these -features next, and then explain how to publish a package. - -### Making Useful Documentation Comments - -Accurately documenting your packages will help other users know how and when to -use them, so it’s worth spending time writing documentation. In Chapter 3, we -discussed how to comment Rust code using `//`. Rust also has a particular kind -of comment for documentation, which is known conveniently as *documentation -comments*, that will generate HTML documentation. The HTML displays the -contents of documentation comments for public API items intended for -programmers interested in knowing how to *use* your crate as opposed to how -your crate is *implemented*. - -Documentation comments use `///` instead of `//` and support Markdown notation -for formatting the text if you want to use it. You place documentation comments -just before the item they’re documenting. Listing 14-1 shows documentation -comments for an `add_one` function in a crate named `my_crate`: - -Filename: src/lib.rs - -``` -/// Adds one to the number given. -/// -/// # Examples -/// -/// ``` -/// let five = 5; -/// -/// assert_eq!(6, my_crate::add_one(5)); -/// ``` -pub fn add_one(x: i32) -> i32 { - x + 1 -} -``` - -Listing 14-1: A documentation comment for a function - -Here, we give a description of what the `add_one` function does, start a -section with the heading `Examples`, and then provide code that demonstrates -how to use the `add_one` function. We can generate the HTML documentation from -this documentation comment by running `cargo doc`. This command runs the -`rustdoc` tool distributed with Rust and puts the generated HTML documentation -in the *target/doc* directory. - -For convenience, running `cargo doc --open` will build the HTML for your -current crate’s documentation (as well as the documentation for all of your -crate’s dependencies) and open the result in a web browser. Navigate to the -`add_one` function and you’ll see how the text in the documentation comments is -rendered, as shown in Figure 14-1: - -Rendered HTML documentation for the `add_one` function of `my_crate` - -Figure 14-1: HTML documentation for the `add_one` function - -#### Commonly Used Sections - -We used the `# Examples` Markdown heading in Listing 14-1 to create a section -in the HTML with the title “Examples.” Some other sections that crate authors -commonly use in their documentation include: - -* **Panics**: The scenarios in which the function being documented could - `panic!`. Callers of the function who don’t want their programs to panic - should make sure they don’t call the function in these situations. -* **Errors**: If the function returns a `Result`, describing the kinds of - errors that might occur and what conditions might cause those errors to be - returned can be helpful to callers so they can write code to handle the - different kinds of errors in different ways. -* **Safety**: If the function is `unsafe` to call (we discuss unsafety in - Chapter 19), there should be a section explaining why the function is unsafe - and covering the invariants that the function expects callers to uphold. - -Most documentation comment sections don’t need all of these sections, but it’s -a good list to check to remind you of the aspects of your code that people -calling your code will be interested in knowing about. - -#### Documentation Comments as Tests - -Adding examples in code blocks in your documentation comments can clearly -demonstrate how to use your library, and doing so has an additional bonus: -running `cargo test` will run the code examples in your documentation as -tests! Nothing is better than documentation with examples. But nothing is worse -than examples that don’t work because the code has changed since the -documentation was written. Run `cargo test` with the documentation for the -`add_one` function from Listing 14-1; you should see a section in the test -results like this: - -``` - Doc-tests my_crate - -running 1 test -test src/lib.rs - add_one (line 5) ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out -``` - -Now change either the function or the example so the `assert_eq!` in the -example panics. Run `cargo test` again; you’ll see that the doc tests catch -that the example and the code are out of sync from one another! - -#### Commenting Contained Items - -Another style of doc comment, `//!`, adds documentation to the item that -contains the comments rather than adding documentation to the items following -the comments. We typically use these doc comments inside the crate root file -(*src/lib.rs* by convention) or inside a module to document the crate or the -module as a whole. - -For example, if we want to add documentation that describes the purpose of the -`my_crate` crate that contains the `add_one` function, we can add documentation -comments that start with `//!` to the beginning of the *src/lib.rs* file, as -shown in Listing 14-2: - -Filename: src/lib.rs - -``` -//! # My Crate -//! -//! `my_crate` is a collection of utilities to make performing certain -//! calculations more convenient. - -/// Adds one to the number given. -// --snip-- -``` - -Listing 14-2: Documentation for the `my_crate` crate as a whole - -Notice there isn’t any code after the last line that begins with `//!`. Because -we started the comments with `//!` instead of `///`, we’re documenting the item -that contains this comment rather than an item that follows this comment. In -this case, the item that contains this comment is the *src/lib.rs* file, which -is the crate root. These comments describe the entire crate. - -When we run `cargo doc --open`, these comments will display on the front -page of the documentation for `my_crate` above the list of public items in the -crate, as shown in Figure 14-2: - -Rendered HTML documentation with a comment for the crate as a whole - -Figure 14-2: Rendered documentation for `my_crate` including the comment -describing the crate as a whole - -Documentation comments within items are useful for describing crates and -modules especially. Use them to explain the purpose of the container overall to -help your crate users understand your organization. - -### Exporting a Convenient Public API with `pub use` - -In Chapter 7, we covered how to organize our code into modules using the `mod` -keyword, how to make items public using the `pub` keyword, and how to bring -items into a scope with the `use` keyword. However, the structure that makes -sense to you while you’re developing a crate might not be very convenient for -your users. You might want to organize your structs in a hierarchy containing -multiple levels, but people who want to use a type you’ve defined deep in the -hierarchy might have trouble finding out that those types exist. They might -also be annoyed at having to enter `use` -`my_crate::some_module::another_module::UsefulType;` rather than `use` -`my_crate::UsefulType;`. - -The structure of your public API is a major consideration when publishing a -crate. People who use your crate are less familiar with the structure than you -are and might have difficulty finding the pieces they want to use if your crate -has a large module hierarchy. - -The good news is that if the structure *isn’t* convenient for others to use -from another library, you don’t have to rearrange your internal organization: -instead, you can re-export items to make a public structure that’s different -than your private structure by using `pub use`. Re-exporting takes a public -item in one location and makes it public in another location, as if it was -defined in the other location instead. - -For example, say we made a library named `art` for modeling artistic concepts. -Within this library are two modules: a `kinds` module containing two enums -named `PrimaryColor` and `SecondaryColor`, and a `utils` module containing a -function named `mix`, as shown in Listing 14-3: - -Filename: src/lib.rs - -``` -//! # Art -//! -//! A library for modeling artistic concepts. - -pub mod kinds { - /// The primary colors according to the RYB color model. - pub enum PrimaryColor { - Red, - Yellow, - Blue, - } - - /// The secondary colors according to the RYB color model. - pub enum SecondaryColor { - Orange, - Green, - Purple, - } -} - -pub mod utils { - use kinds::*; - - /// Combines two primary colors in equal amounts to create - /// a secondary color. - pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor { - // --snip-- - } -} -``` - -Listing 14-3: An `art` library with items organized into `kinds` and `utils` -modules - -Figure 14-3 shows what the front page of the documentation for this crate -generated by `cargo doc` would look like: - -Rendered documentation for the `art` crate that lists the `kinds` and `utils` modules - -Figure 14-3: Front page of the documentation for `art` that lists the `kinds` -and `utils` modules - -Note that the `PrimaryColor` and `SecondaryColor` types aren’t listed on the -front page, nor is the `mix` function. We have to click `kinds` and `utils` to -see them. - -Another crate that depends on this library would need `use` statements that -import the items from `art`, including specifying the module structure that’s -currently defined. Listing 14-4 shows an example of a crate that uses the -`PrimaryColor` and `mix` items from the `art` crate: - -Filename: src/main.rs - -``` -extern crate art; - -use art::kinds::PrimaryColor; -use art::utils::mix; - -fn main() { - let red = PrimaryColor::Red; - let yellow = PrimaryColor::Yellow; - mix(red, yellow); -} -``` - -Listing 14-4: A crate using the `art` crate’s items with its internal structure -exported - -The author of the code in Listing 14-4, which uses the `art` crate, had to -figure out that `PrimaryColor` is in the `kinds` module and `mix` is in the -`utils` module. The module structure of the `art` crate is more relevant to -developers working on the `art` crate than developers using the `art` crate. -The internal structure that organizes parts of the crate into the `kinds` -module and the `utils` module doesn’t contain any useful information for -someone trying to understand how to use the `art` crate. Instead, the `art` -crate’s module structure causes confusion because developers have to figure out -where to look, and the structure is inconvenient because developers must -specify the module names in the `use` statements. - -To remove the internal organization from the public API, we can modify the -`art` crate code in Listing 14-3 to add `pub use` statements to re-export the -items at the top level, as shown in Listing 14-5: - -Filename: src/lib.rs - -``` -//! # Art -//! -//! A library for modeling artistic concepts. - -pub use kinds::PrimaryColor; -pub use kinds::SecondaryColor; -pub use utils::mix; - -pub mod kinds { - // --snip-- -} - -pub mod utils { - // --snip-- -} -``` - -Listing 14-5: Adding `pub use` statements to re-export items - -The API documentation that `cargo doc` generates for this crate will now list -and link re-exports on the front page, as shown in Figure 14-4, which makes the -`PrimaryColor` and `SecondaryColor` types and the `mix` function easier to find: - -Rendered documentation for the `art` crate with the re-exports on the front page - -Figure 14-4: The front page of the documentation for `art` that lists the -re-exports - -The `art` crate users can still see and use the internal structure from Listing -14-3 as demonstrated in Listing 14-4, or they can use the more convenient -structure in Listing 14-5, as shown in Listing 14-6: - -Filename: src/main.rs - -``` -extern crate art; - -use art::PrimaryColor; -use art::mix; - -fn main() { - // --snip-- -} -``` - -Listing 14-6: A program using the re-exported items from the `art` crate - -In cases where there are many nested modules, re-exporting the types at the top -level with `pub use` can make a significant difference in the experience of -people who use the crate. - -Creating a useful public API structure is more of an art than a science, and -you can iterate to find the API that works best for your users. Choosing `pub -use` gives you flexibility in how you structure your crate internally and -decouples that internal structure with what you present to your users. Look at -some of the code of crates you’ve installed to see if their internal structure -differs from their public API. - -### Setting Up a Crates.io Account - -Before you can publish any crates, you need to create an account on -*https://crates.io/* and get an API token. To do so, visit the home page at -*https://crates.io/* and log in via a GitHub account: the GitHub account is -currently a requirement, but the site might support other ways of creating an -account in the future. Once you’re logged in, visit your account settings at -*https://crates.io/me/* and retrieve your API key. Then run the `cargo` -`login` command with your API key, like this: - -``` -$ cargo login abcdefghijklmnopqrstuvwxyz012345 -``` - -This command will inform Cargo of your API token and store it locally in -*~/.cargo/credentials*. Note that this token is a *secret*: do not share it -with anyone else. If you do share it with anyone for any reason, you should -revoke it and generate a new token on *https://crates.io/*. - -### Before Publishing a New Crate - -Now that you have an account, let’s say you have a crate you want to publish. -Before publishing, you’ll need to add some metadata to your crate by adding it -to the `[package]` section of the crate’s *Cargo.toml* file. - -Your crate will need a unique name. While you’re working on a crate locally, -you can name a crate whatever you’d like. However, crate names on -*https://crates.io/* are allocated on a first-come, first-served basis. Once -a crate name is taken, no one else can publish a crate with that name. Search -for the name you want to use on the site to find out if it has been used. If it -hasn’t, edit the name in the *Cargo.toml* file under `[package]` to use the -name for publishing, like so: - -Filename: Cargo.toml - -``` -[package] -name = "guessing_game" -``` - -Even if you’ve chosen a unique name, when you run `cargo publish` to publish -the crate at this point, you’ll get a warning and then an error: - -``` -$ cargo publish - Updating registry `https://github.com/rust-lang/crates.io-index` -warning: manifest has no description, license, license-file, documentation, -homepage or repository. ---snip-- -error: api errors: missing or empty metadata fields: description, license. -``` - -The reason is that you’re missing some crucial information: a description and -license are required so people will know what your crate does and under what -terms they can use it. To rectify this error, you need to include this -information in the *Cargo.toml* file. - -Add a description that is just a sentence or two, because it will appear with -your crate in search results. For the `license` field, you need to give a -*license identifier value*. The Linux Foundation’s Software Package Data -Exchange (SPDX) at *http://spdx.org/licenses/* lists the identifiers you can -use for this value. For example, to specify that you’ve licensed your crate -using the MIT License, add the `MIT` identifier: - -Filename: Cargo.toml - -``` -[package] -name = "guessing_game" -license = "MIT" -``` - -If you want to use a license that doesn’t appear in the SPDX, you need to place -the text of that license in a file, include the file in your project, and then -use `license-file` to specify the name of that file instead of using the -`license` key. - -Guidance on which license is appropriate for your project is beyond the scope -of this book. Many people in the Rust community license their projects in the -same way as Rust by using a dual license of `MIT OR Apache-2.0`, which -demonstrates that you can also specify multiple license identifiers separated -by `OR` to have multiple licenses for your project. - -With a unique name, the version, the author details that `cargo new` added -when you created the crate, your description, and a license added, the -*Cargo.toml* file for a project that is ready to publish might look like this: - -Filename: Cargo.toml - -``` -[package] -name = "guessing_game" -version = "0.1.0" -authors = ["Your Name "] -description = "A fun game where you guess what number the computer has chosen." -license = "MIT OR Apache-2.0" - -[dependencies] -``` - -Cargo’s documentation at *https://doc.rust-lang.org/cargo/* describes other -metadata you can specify to ensure others can discover and use your crate more -easily! - -### Publishing to Crates.io - -Now that you’ve created an account, saved your API token, chosen a name for -your crate, and specified the required metadata, you’re ready to publish! -Publishing a crate uploads a specific version to *https://crates.io/* for -others to use. - -Be careful when publishing a crate because a publish is *permanent*. The -version can never be overwritten, and the code cannot be deleted. One major -goal of *https://crates.io/* is to act as a permanent archive of code so that -builds of all projects that depend on crates from *https://crates.io/* will -continue to work. Allowing version deletions would make fulfilling that goal -impossible. However, there is no limit to the number of crate versions you can -publish. - -Run the `cargo publish` command again. It should succeed now: - -``` -$ cargo publish - Updating registry `https://github.com/rust-lang/crates.io-index` -Packaging guessing_game v0.1.0 (file:///projects/guessing_game) -Verifying guessing_game v0.1.0 (file:///projects/guessing_game) -Compiling guessing_game v0.1.0 -(file:///projects/guessing_game/target/package/guessing_game-0.1.0) - Finished dev [unoptimized + debuginfo] target(s) in 0.19 secs -Uploading guessing_game v0.1.0 (file:///projects/guessing_game) -``` - -Congratulations! You’ve now shared your code with the Rust community, and -anyone can easily add your crate as a dependency of their project. - -### Publishing a New Version of an Existing Crate - -When you’ve made changes to your crate and are ready to release a new version, -you change the `version` value specified in your *Cargo.toml* file and -republish. Use the Semantic Versioning rules at *http://semver.org/* to -decide what an appropriate next version number is based on the kinds of changes -you’ve made. Then run `cargo publish` to upload the new version. - -### Removing Versions from Crates.io with `cargo yank` - -Although you can’t remove previous versions of a crate, you can prevent any -future projects from adding them as a new dependency. This is useful when a -crate version is broken for one reason or another. In such situations, Cargo -supports *yanking* a crate version. - -Yanking a version prevents new projects from starting to depend on that version -while allowing all existing projects that depend on it to continue to download -and depend on that version. Essentially, a yank means that all projects with a -*Cargo.lock* will not break, and any future *Cargo.lock* files generated will -not use the yanked version. - -To yank a version of a crate, run `cargo yank` and specify which version you -want to yank: - -``` -$ cargo yank --vers 1.0.1 -``` - -By adding `--undo` to the command, you can also undo a yank and allow projects -to start depending on a version again: - -``` -$ cargo yank --vers 1.0.1 --undo -``` - -A yank *does not* delete any code. For example, the yank feature is not -intended for deleting accidentally uploaded secrets. If that happens, you must -reset those secrets immediately. - -## Cargo Workspaces - -In Chapter 12, we built a package that included a binary crate and a library -crate. As your project develops, you might find that the library crate -continues to get bigger and you want to split up your package further into -multiple library crates. In this situation, Cargo offers a feature called -*workspaces* that can help manage multiple related packages that are developed -in tandem. - -A *workspace* is a set of packages that share the same *Cargo.lock* and output -directory. Let’s make a project using a workspace—we’ll use trivial code so we -can concentrate on the structure of the workspace. There are multiple ways to -structure a workspace; we’re going to show one common way. We’ll have a -workspace containing a binary and two libraries. The binary will provide the -main functionality, and will depend on the two libraries. One library will -provide an `add_one` function, and a second library an `add_two` function. -These three crates will be part of the same workspace. We’ll start by creating -a new directory for the workspace: - -``` -$ mkdir add -$ cd add -``` - -Next, in the *add* directory, we create the *Cargo.toml* file that will -configure the entire workspace. This file won’t have a `[package]` section or -the metadata we’ve seen in other *Cargo.toml* files, but will instead start -with a `[workspace]` section that will allow us to add members to the workspace -by specifying the path to our binary crate; in this case, that path is *adder*: - -Filename: Cargo.toml - -``` -[workspace] - -members = [ - "adder", -] -``` - -Next, we’ll create the `adder` binary crate by running `cargo new` within the -*add* directory: - -``` -$ cargo new --bin adder - Created binary (application) `adder` project -``` - -At this point, we can build the workspace by running `cargo build`. The files -in your *add* directory should look like this: - -``` -├── Cargo.lock -├── Cargo.toml -├── adder -│ ├── Cargo.toml -│ └── src -│ └── main.rs -└── target -``` - -The workspace has one *target* directory at the top level for the compiled -artifacts to be placed into; the `adder` crate doesn’t have its own *target* -directory. Even if we were to run `cargo build` from inside the *adder* -directory, the compiled artifacts would still end up in *add/target* rather -than *add/adder/target*. Cargo structures the *target* directory in a workspace -like this because the crates in a workspace are meant to depend on each other. -If each crate had its own *target* directory, each crate would have to -recompile each of the other crates in the workspace to have the artifacts in -its own *target* directory. By sharing one *target* directory, the crates can -avoid unnecessary rebuilding. - -### Creating the Second Crate in the Workspace - -Next, let’s create another member crate in the workspace and call it `add-one`. -Change the top-level *Cargo.toml* to specify the *add-one* path in the -`members` list: - -Filename: Cargo.toml - -``` -[workspace] - -members = [ - "adder", - "add-one", -] -``` - -Then generate a new library crate named `add-one`: - -``` -$ cargo new add-one - Created library `add-one` project -``` - -Your *add* directory should now have these directories and files: - -``` -├── Cargo.lock -├── Cargo.toml -├── add-one -│ ├── Cargo.toml -│ └── src -│ └── lib.rs -├── adder -│ ├── Cargo.toml -│ └── src -│ └── main.rs -└── target -``` - -In the *add-one/src/lib.rs* file, let’s add an `add_one` function: - -Filename: add-one/src/lib.rs - -``` -pub fn add_one(x: i32) -> i32 { - x + 1 -} -``` - -Now that we have a library crate in the workspace, we can have the binary crate -`adder` depend on the library crate `add-one`. First, we’ll need to add a path -dependency on `add-one` to *adder/Cargo.toml*. - -Filename: adder/Cargo.toml - -``` -[dependencies] - -add-one = { path = "../add-one" } -``` - -Cargo doesn’t assume that crates in a workspace will depend on each other, so -we need to be explicit about the dependency relationships between the crates. - -Next, let’s use the `add_one` function from the `add-one` crate in the `adder` -crate. Open the *adder/src/main.rs* file and add an `extern crate` line at -the top to bring the new `add-one` library crate into scope. Then change the -`main` function to call the `add_one` function, as in Listing 14-7: - -Filename: adder/src/main.rs - -``` -extern crate add_one; - -fn main() { - let num = 10; - println!("Hello, world! {} plus one is {}!", num, add_one::add_one(num)); -} -``` - -Listing 14-7: Using the `add-one` library crate from the `adder` crate - -Let’s build the workspace by running `cargo build` in the top-level *add* -directory! - -``` -$ cargo build - Compiling add-one v0.1.0 (file:///projects/add/add-one) - Compiling adder v0.1.0 (file:///projects/add/adder) - Finished dev [unoptimized + debuginfo] target(s) in 0.68 secs -``` - -To run the binary crate from the *add* directory, we need to specify which -package in the workspace we want to use by using the `-p` argument and the -package name with `cargo run`: - -``` -$ cargo run -p adder - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target/debug/adder` -Hello, world! 10 plus one is 11! -``` - -This runs the code in *adder/src/main.rs*, which depends on the `add-one` crate. - -#### Depending on an External Crate in a Workspace - -Notice that the workspace has only one *Cargo.lock* file at the top level of -the workspace rather than having a *Cargo.lock* in each crate’s directory. This -ensures that all crates are using the same version of all dependencies. If we -add the `rand` crate to the *adder/Cargo.toml* and *add-one/Cargo.toml* -files, Cargo will resolve both of those to one version of `rand` and record -that in the one *Cargo.lock*. Making all crates in the workspace use the same -dependencies means the crates in the workspace will always be compatible with -each other. Let’s add the `rand` crate to the `[dependencies]` section in the -*add-one/Cargo.toml* file to be able to use the `rand` crate in the `add-one` -crate: - -Filename: add-one/Cargo.toml - -``` -[dependencies] - -rand = "0.3.14" -``` - -We can now add `extern crate rand;` to the *add-one/src/lib.rs* file, and -building the whole workspace by running `cargo build` in the *add* directory -will bring in and compile the `rand` crate: - -``` -$ cargo build - Updating registry `https://github.com/rust-lang/crates.io-index` - Downloading rand v0.3.14 - --snip-- - Compiling rand v0.3.14 - Compiling add-one v0.1.0 (file:///projects/add/add-one) - Compiling adder v0.1.0 (file:///projects/add/adder) - Finished dev [unoptimized + debuginfo] target(s) in 10.18 secs -``` - -The top-level *Cargo.lock* now contains information about the dependency of -`add-one` on `rand`. However, even though `rand` is used somewhere in the -workspace, we can’t use it in other crates in the workspace unless we add -`rand` to their *Cargo.toml* files as well. For example, if we add `extern -crate rand;` to the *adder/src/main.rs* file for the `adder` crate, we’ll get -an error: - -``` -$ cargo build - Compiling adder v0.1.0 (file:///projects/add/adder) -error: use of unstable library feature 'rand': use `rand` from crates.io (see -issue #27703) - --> adder/src/main.rs:1:1 - | -1 | extern crate rand; -``` - -To fix this, edit the *Cargo.toml* file for the `adder` crate and indicate that -`rand` is a dependency for that crate as well. Building the `adder` crate will -add `rand` to the list of dependencies for `adder` in *Cargo.lock*, but no -additional copies of `rand` will be downloaded. Cargo has ensured that any -crate in the workspace using the `rand` crate will be using the same version. -Using the same version of `rand` across the workspace saves space because we -won’t have multiple copies and ensures that the crates in the workspace will be -compatible with each other. - -#### Adding a Test to a Workspace - -For another enhancement, let’s add a test of the `add_one::add_one` function -within the `add_one` crate: - -Filename: add-one/src/lib.rs - -``` -pub fn add_one(x: i32) -> i32 { - x + 1 -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn it_works() { - assert_eq!(3, add_one(2)); - } -} -``` - -Now run `cargo test` in the top-level *add* directory: - -``` -$ cargo test - Compiling add-one v0.1.0 (file:///projects/add/add-one) - Compiling adder v0.1.0 (file:///projects/add/adder) - Finished dev [unoptimized + debuginfo] target(s) in 0.27 secs - Running target/debug/deps/add_one-f0253159197f7841 - -running 1 test -test tests::it_works ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out - - Running target/debug/deps/adder-f88af9d2cc175a5e - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out - - Doc-tests add-one - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out -``` - -The first section of the output shows that the `it_works` test in the `add-one` -crate passed. The next section shows that 0 tests were found in the `adder` -crate, and then the last section shows 0 documentation tests were found in the -`add-one` crate. Running `cargo test` in a workspace structured like this one -will run the tests for all the crates in the workspace. - -We can also run tests for one particular crate in a workspace from the -top-level directory by using the `-p` flag and specifying the name of the crate -we want to test: - -``` -$ cargo test -p add-one - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running target/debug/deps/add_one-b3235fea9a156f74 - -running 1 test -test tests::it_works ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out - - Doc-tests add-one - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out -``` - -This output shows `cargo test` only ran the tests for the `add-one` crate and -didn’t run the `adder` crate tests. - -If you publish the crates in the workspace to *https://crates.io/*, each crate -in the workspace will need to be published separately. The `cargo publish` -command does not have an `--all` flag or a `-p` flag, so you must change to -each crate’s directory and run `cargo publish` on each crate in the workspace -to publish them. - -For additional practice, add an `add-two` crate to this workspace in a similar -way as the `add-one` crate! - -As your project grows, consider using a workspace: it’s easier to understand -smaller, individual components than one big blob of code. Keeping the crates in -a workspace can make coordination between them easier if they are often changed -at the same time. - -## Installing Binaries from Crates.io with `cargo install` - -The `cargo install` command allows you to install and use binary crates -locally. This isn’t intended to replace system packages; it’s meant to be a -convenient way for Rust developers to install tools that others have shared on -*https://crates.io/*. You can only install packages that have binary targets. -A binary target is the runnable program that is created if the crate has a -*src/main.rs* file or another file specified as a binary, as opposed to a -library target that isn’t runnable on its own but is suitable for including -within other programs. Usually, crates have information in the *README* file -about whether a crate is a library, has a binary target, or both. - -All binaries installed with `cargo install` are stored in the installation -root’s *bin* folder. If you installed Rust using *rustup.rs* and don’t have any -custom configurations, this directory will be *$HOME/.cargo/bin*. Ensure that -directory is in your `$PATH` to be able to run programs you’ve installed with -`cargo install`. - -For example, in Chapter 12 we mentioned that there’s a Rust implementation of -the `grep` tool called `ripgrep` for searching files. If we want to install -`ripgrep`, we can run the following: - -``` -$ cargo install ripgrep -Updating registry `https://github.com/rust-lang/crates.io-index` - Downloading ripgrep v0.3.2 - --snip-- - Compiling ripgrep v0.3.2 - Finished release [optimized + debuginfo] target(s) in 97.91 secs - Installing ~/.cargo/bin/rg -``` - -The last line of the output shows the location and the name of the installed -binary, which in the case of `ripgrep` is `rg`. As long as the installation -directory is in your `$PATH`, as mentioned previously, you can then run `rg ---help` and start using a faster, rustier tool for searching files! - -## Extending Cargo with Custom Commands - -Cargo is designed so you can extend it with new subcommands without having to -modify Cargo. If a binary in your `$PATH` is named `cargo-something`, you can -run it as if it was a Cargo subcommand by running `cargo something`. Custom -commands like this are also listed when you run `cargo --list`. Being able to -use `cargo install` to install extensions and then run them just like the -built-in Cargo tools is a super convenient benefit of Cargo’s design! - -## Summary - -Sharing code with Cargo and *https://crates.io/* is part of what makes the -Rust ecosystem useful for many different tasks. Rust’s standard library is -small and stable, but crates are easy to share, use, and improve on a timeline -different from the language. Don’t be shy about sharing code that’s useful to -you on *https://crates.io/*; it’s likely that it will be useful to someone -else as well! diff --git a/second-edition/nostarch/chapter15.md b/second-edition/nostarch/chapter15.md deleted file mode 100644 index d97f8266fb..0000000000 --- a/second-edition/nostarch/chapter15.md +++ /dev/null @@ -1,1977 +0,0 @@ - -[TOC] - -# Smart Pointers - -A *pointer* is a general concept for a variable that contains an address in -memory. This address refers to, or “points at,” some other data. The most -common kind of pointer in Rust is a reference, which you learned about in -Chapter 4. References are indicated by the `&` symbol and borrow the value they -point to. They don’t have any special capabilities other than referring to -data. Also, they don’t have any overhead and are the kind of pointer we use -most often. - -*Smart pointers*, on the other hand, are data structures that act like a -pointer but also have additional metadata and capabilities. The concept of -smart pointers isn’t unique to Rust: smart pointers originated in C++ and exist -in other languages as well. In Rust, the different smart pointers defined in -the standard library provide extra functionality beyond that provided by -references. One example that we’ll explore in this chapter is the *reference -counting* smart pointer type. This pointer enables you to have multiple owners -of data by keeping track of the number of owners and, when no owners remain, -taking care of cleaning up the data. - -In Rust, where we have the concept of ownership and borrowing, an additional -difference between references and smart pointers is that references are -pointers that only borrow data; in contrast, in many cases, smart pointers -*own* the data they point to. - -We’ve already encountered a few smart pointers in this book, such as `String` -and `Vec` in Chapter 8, although we didn’t call them smart pointers at the -time. Both these types count as smart pointers because they own some memory and -allow you to manipulate it. They also have metadata (such as their capacity) -and extra capabilities or guarantees (such as with `String` ensuring its data -will always be valid UTF-8). - -Smart pointers are usually implemented using structs. The characteristic that -distinguishes a smart pointer from an ordinary struct is that smart pointers -implement the `Deref` and `Drop` traits. The `Deref` trait allows an instance -of the smart pointer struct to behave like a reference so we can write code -that works with either references or smart pointers. The `Drop` trait allows us -to customize the code that is run when an instance of the smart pointer goes -out of scope. In this chapter, we’ll discuss both traits and demonstrate why -they’re important to smart pointers. - -Given that the smart pointer pattern is a general design pattern used -frequently in Rust, this chapter won’t cover every existing smart pointer. Many -libraries have their own smart pointers, and you can even write your own. We’ll -cover the most common smart pointers in the standard library: - -* `Box` for allocating values on the heap -* `Rc`, a reference counted type that enables multiple ownership -* `Ref` and `RefMut`, accessed through `RefCell`, a type that enforces - the borrowing rules at runtime instead of compile time - -In addition, we’ll cover the *interior mutability* pattern where an immutable -type exposes an API for mutating an interior value. We’ll also discuss -*reference cycles*: how they can leak memory and how to prevent them. - -Let’s dive in! - -## `Box` Points to Data on the Heap and Has a Known Size - -The most straightforward smart pointer is a *box*, whose type is written -`Box`. Boxes allow you to store data on the heap rather than the stack. What -remains on the stack is the pointer to the heap data. Refer to Chapter 4 to -review the difference between the stack and the heap. - -Boxes don’t have performance overhead, other than storing their data on the -heap instead of on the stack. But they don’t have many extra capabilities -either. You’ll use them most often in these situations: - -* When you have a type whose size can’t be known at compile time, and you want - to use a value of that type in a context that needs to know an exact size -* When you have a large amount of data and you want to transfer ownership but - ensure the data won’t be copied when you do so -* When you want to own a value and only care that it’s a type that implements a - particular trait rather than knowing the concrete type - -We’ll demonstrate the first situation in this section. But before we do so, -we’ll elaborate on the other two situations a bit more: in the second case, -transferring ownership of a large amount of data can take a long time because -the data is copied around on the stack. To improve performance in this -situation, we can store the large amount of data on the heap in a box. Then, -only the small amount of pointer data is copied around on the stack, and the -data stays in one place on the heap. The third case is known as a *trait -object*, and Chapter 17 devotes an entire section just to that topic. So what -you learn here you’ll apply again in Chapter 17! - -### Using a `Box` to Store Data on the Heap - -Before we discuss this use case for `Box`, we’ll cover the syntax and how to -interact with values stored within a `Box`. - -Listing 15-1 shows how to use a box to store an `i32` value on the heap: - -Filename: src/main.rs - -``` -fn main() { - let b = Box::new(5); - println!("b = {}", b); -} -``` - -Listing 15-1: Storing an `i32` value on the heap using a box - -We define the variable `b` to have the value of a `Box` that points to the -value `5`, which is allocated on the heap. This program will print `b = 5`; in -this case, we can access the data in the box in a similar way as we would if -this data was on the stack. Just like any owned value, when a box goes out of -scope like `b` does at the end of `main`, it will be deallocated. The -deallocation happens for the box (stored on the stack) and the data it points -to (stored on the heap). - -Putting a single value on the heap isn’t very useful, so you won’t use boxes by -themselves in this way very often. Having values like a single `i32` on the -stack, where they’re stored by default, is more appropriate in the majority of -situations. Let’s look at a case where boxes allow us to define types that we -wouldn’t be allowed to if we didn’t have boxes. - -### Boxes Enable Recursive Types - -At compile time, Rust needs to know how much space a type takes up. One type -whose size can’t be known at compile time is a *recursive type*, where a value -can have as part of itself another value of the same type. Because this nesting -of values could theoretically continue infinitely, Rust doesn’t know how much -space a value of a recursive type needs. However, boxes have a known size, so -by inserting a box in a recursive type definition, we can have recursive types. - -Let’s explore the *cons list*, which is a data type common in functional -programming languages, as an example of a recursive type. The cons list type -we’ll define is straightforward except for the recursion; therefore, the -concepts in the example we’ll work with will be useful any time you get into -more complex situations involving recursive types. - -#### More Information About the Cons List - -A *cons list* is a data structure that comes from the Lisp programming language -and its dialects. In Lisp, the `cons` function (short for “construct function”) -constructs a new pair from its two arguments, which usually are a single value -and another pair. These pairs containing pairs form a list. - -The cons function concept has made its way into more general functional -programming jargon: “to cons x onto y” informally means to construct a new -container instance by putting the element x at the start of this new container, -followed by the container y. - -Each item in a cons list contains two elements: the value of the current item -and the next item. The last item in the list contains only a value called `Nil` -without a next item. A cons list is produced by recursively calling the `cons` -function. The canonical name to denote the base case of the recursion is `Nil`. -Note that this is not the same as the “null” or “nil” concept in Chapter 6, -which is an invalid or absent value. - -Although functional programming languages use cons lists frequently, it isn’t a -commonly used data structure in Rust. Most of the time when you have a list of -items in Rust, `Vec` is a better choice to use. Other, more complex -recursive data types *are* useful in various situations, but by starting with -the cons list, we can explore how boxes let us define a recursive data type -without much distraction. - -Listing 15-2 contains an enum definition for a cons list. Note that this code -won’t compile yet because the `List` type doesn’t have a known size, which -we’ll demonstrate: - -Filename: src/main.rs - -``` -enum List { - Cons(i32, List), - Nil, -} -``` - -Listing 15-2: The first attempt at defining an enum to represent a cons list -data structure of `i32` values - -> Note: We’re implementing a cons list that only holds `i32` values for the -> purposes of this example. We could have implemented it using generics, as we -> discussed in Chapter 10, to define a cons list type that could store values of -> any type. - -Using the `List` type to store the list `1, 2, 3` would look like the code in -Listing 15-3: - -Filename: src/main.rs - -``` -use List::{Cons, Nil}; - -fn main() { - let list = Cons(1, Cons(2, Cons(3, Nil))); -} -``` - -Listing 15-3: Using the `List` enum to store the list `1, 2, 3` - -The first `Cons` value holds `1` and another `List` value. This `List` value is -another `Cons` value that holds `2` and another `List` value. This `List` value -is one more `Cons` value that holds `3` and a `List` value, which is finally -`Nil`, the non-recursive variant that signals the end of the list. - -If we try to compile the code in Listing 15-3, we get the error shown in -Listing 15-4: - -``` -error[E0072]: recursive type `List` has infinite size - --> src/main.rs:1:1 - | -1 | enum List { - | ^^^^^^^^^ recursive type has infinite size -2 | Cons(i32, List), - | ----- recursive without indirection - | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to - make `List` representable -``` - -Listing 15-4: The error we get when attempting to define a recursive enum - -The error shows this type “has infinite size.” The reason is that we’ve defined -`List` with a variant that is recursive: it holds another value of itself -directly. As a result, Rust can’t figure out how much space it needs to store a -`List` value. Let’s break down why we get this error a bit: first, let’s look -at how Rust decides how much space it needs to store a value of a non-recursive -type. - -#### Computing the Size of a Non-Recursive Type - -Recall the `Message` enum we defined in Listing 6-2 when we discussed enum -definitions in Chapter 6: - -``` -enum Message { - Quit, - Move { x: i32, y: i32 }, - Write(String), - ChangeColor(i32, i32, i32), -} -``` - -To determine how much space to allocate for a `Message` value, Rust goes -through each of the variants to see which variant needs the most space. Rust -sees that `Message::Quit` doesn’t need any space, `Message::Move` needs enough -space to store two `i32` values, and so forth. Because only one variant will be -used, the most space a `Message` value will need is the space it would take to -store the largest of its variants. - -Contrast this to what happens when Rust tries to determine how much space a -recursive type like the `List` enum in Listing 15-2 needs. The compiler starts -by looking at the `Cons` variant, which holds a value of type `i32` and a value -of type `List`. Therefore, `Cons` needs an amount of space equal to the size of -an `i32` plus the size of a `List`. To figure out how much memory the `List` -type needs, the compiler looks at the variants, starting with the `Cons` -variant. The `Cons` variant holds a value of type `i32` and a value of type -`List`, and this process continues infinitely, as shown in Figure 15-1: - -An infinite Cons list - -Figure 15-1: An infinite `List` consisting of infinite `Cons` variants - -#### Using `Box` to Get a Recursive Type with a Known Size - -Rust can’t figure out how much space to allocate for recursively defined types, -so the compiler gives the error in Listing 15-4. But the error does include -this helpful suggestion: - -``` - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to - make `List` representable -``` - -In this suggestion, “indirection” means that instead of storing a value -directly, we’ll change the data structure to store the value indirectly by -storing a pointer to the value instead. - -Because a `Box` is a pointer, Rust always knows how much space a `Box` -needs: a pointer’s size doesn’t change based on the amount of data it’s -pointing to. This means we can put a `Box` inside the `Cons` variant instead -of another `List` value directly. The `Box` will point to the next `List` -value that will be on the heap rather than inside the `Cons` variant. -Conceptually, we still have a list, created with lists “holding” other lists, -but this implementation is now more like the items being next to one another -rather than inside one another. - -We can change the definition of the `List` enum in Listing 15-2 and the usage -of the `List` in Listing 15-3 to the code in Listing 15-5, which will compile: - -Filename: src/main.rs - -``` -enum List { - Cons(i32, Box), - Nil, -} - -use List::{Cons, Nil}; - -fn main() { - let list = Cons(1, - Box::new(Cons(2, - Box::new(Cons(3, - Box::new(Nil)))))); -} -``` - -Listing 15-5: Definition of `List` that uses `Box` in order to have a known -size - -The `Cons` variant will need the size of an `i32` plus the space to store the -box’s pointer data. The `Nil` variant stores no values, so it needs less space -than the `Cons` variant. We now know that any `List` value will take up the -size of an `i32` plus the size of a box’s pointer data. By using a box, we’ve -broken the infinite, recursive chain, so the compiler can figure out the size -it needs to store a `List` value. Figure 15-2 shows what the `Cons` variant -looks like now: - -A finite Cons list - -Figure 15-2: A `List` that is not infinitely sized because `Cons` holds a `Box` - -Boxes only provide the indirection and heap allocation; they don’t have any -other special capabilities, like those we’ll see with the other smart pointer -types. They also don’t have any performance overhead that these special -capabilities incur, so they can be useful in cases like the cons list where the -indirection is the only feature we need. We’ll look at more use cases for boxes -in Chapter 17, too. - -The `Box` type is a smart pointer because it implements the `Deref` trait, -which allows `Box` values to be treated like references. When a `Box` -value goes out of scope, the heap data that the box is pointing to is cleaned -up as well because of the `Drop` trait implementation. Let’s explore these two -traits in more detail. These two traits will be even more important to the -functionality provided by the other smart pointer types we’ll discuss in the -rest of this chapter. - -## Treating Smart Pointers Like Regular References with the `Deref` Trait - -Implementing the `Deref` trait allows us to customize the behavior of the -*dereference operator*, `*` (as opposed to the multiplication or glob -operator). By implementing `Deref` in such a way that a smart pointer can be -treated like a regular reference, we can write code that operates on references -and use that code with smart pointers too. - -Let’s first look at how `*` works with regular references, and then try to -define our own type like `Box` and see why `*` doesn’t work like a reference -on our newly defined type. We’ll explore how implementing the `Deref` trait -makes it possible for smart pointers to work in a similar way as references. -Then we’ll look at Rust’s *deref coercion* feature and how it lets us work with -either references or smart pointers. - -### Following the Pointer to the Value with `*` - -A regular reference is a type of pointer, and one way to think of a pointer is -as an arrow to a value stored somewhere else. In Listing 15-6, we create a -reference to an `i32` value and then use the dereference operator to follow the -reference to the data: - -Filename: src/main.rs - -``` -fn main() { - let x = 5; - let y = &x; - - assert_eq!(5, x); - assert_eq!(5, *y); -} -``` - -Listing 15-6: Using the dereference operator to follow a reference to an `i32` -value - -The variable `x` holds an `i32` value, `5`. We set `y` equal to a reference to -`x`. We can assert that `x` is equal to `5`. However, if we want to make an -assertion about the value in `y`, we have to use `*y` to follow the reference -to the value it’s pointing to (hence *dereference*). Once we dereference `y`, -we have access to the integer value `y` is pointing to that we can compare with -`5`. - -If we tried to write `assert_eq!(5, y);` instead, we would get this compilation -error: - -``` -error[E0277]: the trait bound `{integer}: std::cmp::PartialEq<&{integer}>` is -not satisfied - --> src/main.rs:6:5 - | -6 | assert_eq!(5, y); - | ^^^^^^^^^^^^^^^^^ can't compare `{integer}` with `&{integer}` - | - = help: the trait `std::cmp::PartialEq<&{integer}>` is not implemented for - `{integer}` -``` - -Comparing a number and a reference to a number isn’t allowed because they’re -different types. We must use `*` to follow the reference to the value it’s -pointing to. - -### Using `Box` Like a Reference - -We can rewrite the code in Listing 15-6 to use a `Box` instead of a -reference, and the dereference operator will work the same way as shown in -Listing 15-7: - -Filename: src/main.rs - -``` -fn main() { - let x = 5; - let y = Box::new(x); - - assert_eq!(5, x); - assert_eq!(5, *y); -} -``` - -Listing 15-7: Using the dereference operator on a `Box` - -The only difference between Listing 15-7 and Listing 15-6 is that here we set -`y` to be an instance of a box pointing to the value in `x` rather than a -reference pointing to the value of `x`. In the last assertion, we can use the -dereference operator to follow the box’s pointer in the same way that we did -when `y` was a reference. Next, we’ll explore what is special about `Box` -that enables us to use the dereference operator by defining our own box type. - -### Defining Our Own Smart Pointer - -Let’s build a smart pointer similar to the `Box` type provided by the -standard library to experience how smart pointers behave differently to -references by default. Then we’ll look at how to add the ability to use the -dereference operator. - -The `Box` type is ultimately defined as a tuple struct with one element, so -Listing 15-8 defines a `MyBox` type in the same way. We’ll also define a -`new` function to match the `new` function defined on `Box`: - -Filename: src/main.rs - -``` -struct MyBox(T); - -impl MyBox { - fn new(x: T) -> MyBox { - MyBox(x) - } -} -``` - -Listing 15-8: Defining a `MyBox` type - -We define a struct named `MyBox` and declare a generic parameter `T`, because -we want our type to hold values of any type. The `MyBox` type is a tuple struct -with one element of type `T`. The `MyBox::new` function takes one parameter of -type `T` and returns a `MyBox` instance that holds the value passed in. - -Let’s try adding the `main` function in Listing 15-7 to Listing 15-8 and -changing it to use the `MyBox` type we’ve defined instead of `Box`. The -code in Listing 15-9 won’t compile because Rust doesn’t know how to dereference -`MyBox`: - -Filename: src/main.rs - -``` -fn main() { - let x = 5; - let y = MyBox::new(x); - - assert_eq!(5, x); - assert_eq!(5, *y); -} -``` - -Listing 15-9: Attempting to use `MyBox` in the same way we used references -and `Box` - -Here’s the resulting compilation error: - -``` -error[E0614]: type `MyBox<{integer}>` cannot be dereferenced - --> src/main.rs:14:19 - | -14 | assert_eq!(5, *y); - | ^^ -``` - -Our `MyBox` type can’t be dereferenced because we haven’t implemented that -ability on our type. To enable dereferencing with the `*` operator, we -implement the `Deref` trait. - -### Treating a Type Like a Reference by Implementing the `Deref` Trait - -As discussed in Chapter 10, to implement a trait, we need to provide -implementations for the trait’s required methods. The `Deref` trait, provided -by the standard library, requires us to implement one method named `deref` that -borrows `self` and returns a reference to the inner data. Listing 15-10 -contains an implementation of `Deref` to add to the definition of `MyBox`: - -Filename: src/main.rs - -``` -use std::ops::Deref; - -impl Deref for MyBox { - type Target = T; - - fn deref(&self) -> &T { - &self.0 - } -} -``` - -Listing 15-10: Implementing `Deref` on `MyBox` - -The `type Target = T;` syntax defines an associated type for the `Deref` trait -to use. Associated types are a slightly different way of declaring a generic -parameter, but you don’t need to worry about them for now; we’ll cover them in -more detail in Chapter 19. - -We fill in the body of the `deref` method with `&self.0` so `deref` returns a -reference to the value we want to access with the `*` operator. The `main` -function in Listing 15-9 that calls `*` on the `MyBox` value now compiles -and the assertions pass! - -Without the `Deref` trait, the compiler can only dereference `&` references. -The `deref` method gives the compiler the ability to take a value of any type -that implements `Deref` and call the `deref` method to get a `&` reference that -it knows how to dereference. - -When we entered `*y` in Listing 15-9, behind the scenes Rust actually ran this -code: - -``` -*(y.deref()) -``` - -Rust substitutes the `*` operator with a call to the `deref` method and then a -plain dereference so as programmers we don’t have to think about whether or not -we need to call the `deref` method. This Rust feature lets us write code that -functions identically whether we have a regular reference or a type that -implements `Deref`. - -The reason the `deref` method returns a reference to a value and that the plain -dereference outside the parentheses in `*(y.deref())` is still necessary is due -to the ownership system. If the `deref` method returned the value directly -instead of a reference to the value, the value would be moved out of `self`. We -don’t want to take ownership of the inner value inside `MyBox` in this case -and in most cases where we use the dereference operator. - -Note that the `*` is replaced with a call to the `deref` method and then a call -to `*` just once, each time we type a `*` in our code. Because the substitution -of `*` does not recurse infinitely, we end up with data of type `i32`, which -matches the `5` in `assert_eq!` in Listing 15-9. - -### Implicit Deref Coercions with Functions and Methods - -*Deref coercion* is a convenience that Rust performs on arguments to functions -and methods. Deref coercion converts a reference to a type that implements -`Deref` into a reference to a type that `Deref` can convert the original type -into. Deref coercion happens automatically when we pass a reference to a -particular type’s value as an argument to a function or method that doesn’t -match the parameter type in the function or method definition. A sequence of -calls to the `deref` method converts the type we provided into the type the -parameter needs. - -Deref coercion was added to Rust so that programmers writing function and -method calls don’t need to add as many explicit references and dereferences -with `&` and `*`. The deref coercion feature also lets us write more code that -can work for either references or smart pointers. - -To see deref coercion in action, let’s use the `MyBox` type we defined in -Listing 15-8 as well as the implementation of `Deref` that we added in Listing -15-10. Listing 15-11 shows the definition of a function that has a string slice -parameter: - -Filename: src/main.rs - -``` -fn hello(name: &str) { - println!("Hello, {}!", name); -} -``` - -Listing 15-11: A `hello` function that has the parameter `name` of type `&str` - -We can call the `hello` function with a string slice as an argument, such as -`hello("Rust");` for example. Deref coercion makes it possible to call `hello` -with a reference to a value of type `MyBox`, as shown in Listing 15-12: - -Filename: src/main.rs - -``` -fn main() { - let m = MyBox::new(String::from("Rust")); - hello(&m); -} -``` - -Listing 15-12: Calling `hello` with a reference to a `MyBox` value, -which works because of deref coercion - -Here we’re calling the `hello` function with the argument `&m`, which is a -reference to a `MyBox` value. Because we implemented the `Deref` trait -on `MyBox` in Listing 15-10, Rust can turn `&MyBox` into `&String` -by calling `deref`. The standard library provides an implementation of `Deref` -on `String` that returns a string slice, which is in the API documentation for -`Deref`. Rust calls `deref` again to turn the `&String` into `&str`, which -matches the `hello` function’s definition. - -If Rust didn’t implement deref coercion, we would have to write the code in -Listing 15-13 instead of the code in Listing 15-12 to call `hello` with a value -of type `&MyBox`: - -Filename: src/main.rs - -``` -fn main() { - let m = MyBox::new(String::from("Rust")); - hello(&(*m)[..]); -} -``` - -Listing 15-13: The code we would have to write if Rust didn’t have deref -coercion - -The `(*m)` dereferences the `MyBox` into a `String`. Then the `&` and -`[..]` take a string slice of the `String` that is equal to the whole string to -match the signature of `hello`. The code without deref coercions is harder to -read, write, and understand with all of these symbols involved. Deref coercion -allows Rust to handle these conversions for us automatically. - -When the `Deref` trait is defined for the types involved, Rust will analyze the -types and use `Deref::deref` as many times as necessary to get a reference to -match the parameter’s type. The number of times that `Deref::deref` needs to be -inserted is resolved at compile time, so there is no runtime penalty for taking -advantage of deref coercion! - -### How Deref Coercion Interacts with Mutability - -Similar to how we use the `Deref` trait to override `*` on immutable -references, Rust provides a `DerefMut` trait for overriding `*` on mutable -references. - -Rust does deref coercion when it finds types and trait implementations in three -cases: - -* From `&T` to `&U` when `T: Deref` -* From `&mut T` to `&mut U` when `T: DerefMut` -* From `&mut T` to `&U` when `T: Deref` - -The first two cases are the same except for mutability. The first case states -that if you have a `&T`, and `T` implements `Deref` to some type `U`, you can -get a `&U` transparently. The second case states that the same deref coercion -happens for mutable references. - -The third case is trickier: Rust will also coerce a mutable reference to an -immutable one. But the reverse is *not* possible: immutable references will -never coerce to mutable references. Because of the borrowing rules, if you have -a mutable reference, that mutable reference must be the only reference to that -data (otherwise, the program wouldn’t compile). Converting one mutable -reference to one immutable reference will never break the borrowing rules. -Converting an immutable reference to a mutable reference would require that -there is only one immutable reference to that data, and the borrowing rules -don’t guarantee that. Therefore, Rust can’t make the assumption that converting -an immutable reference to a mutable reference is possible. - -## The `Drop` Trait Runs Code on Cleanup - -The second trait important to the smart pointer pattern is `Drop`, which lets -us customize what happens when a value is about to go out of scope. We can -provide an implementation for the `Drop` trait on any type, and the code we -specify can be used to release resources like files or network connections. -We’re introducing `Drop` in the context of smart pointers because the -functionality of the `Drop` trait is almost always used when implementing a -smart pointer. For example, `Box` customizes `Drop` to deallocate the space -on the heap that the box points to. - -In some languages, the programmer must call code to free memory or resources -every time they finish using an instance of a smart pointer. If they forget, -the system might become overloaded and crash. In Rust, we can specify that a -particular bit of code should be run whenever a value goes out of scope, and -the compiler will insert this code automatically. As a result, we don’t need to -be careful about placing cleanup code everywhere in a program that an instance -of a particular type is finished with, but we still won’t leak resources! - -We specify the code to run when a value goes out of scope by implementing the -`Drop` trait. The `Drop` trait requires us to implement one method named `drop` -that takes a mutable reference to `self`. To see when Rust calls `drop`, let’s -implement `drop` with `println!` statements for now. - -Listing 15-14 shows a `CustomSmartPointer` struct whose only custom -functionality is that it will print `Dropping CustomSmartPointer!` when the -instance goes out of scope. This example demonstrates when Rust runs the `drop` -function: - -Filename: src/main.rs - -``` -struct CustomSmartPointer { - data: String, -} - -impl Drop for CustomSmartPointer { - fn drop(&mut self) { - println!("Dropping CustomSmartPointer with data `{}`!", self.data); - } -} - -fn main() { - let c = CustomSmartPointer { data: String::from("my stuff") }; - let d = CustomSmartPointer { data: String::from("other stuff") }; - println!("CustomSmartPointers created."); -} -``` - -Listing 15-14: A `CustomSmartPointer` struct that implements the `Drop` trait -where we would put our cleanup code - -The `Drop` trait is included in the prelude, so we don’t need to import it. We -implement the `Drop` trait on `CustomSmartPointer` and provide an -implementation for the `drop` method that calls `println!`. The body of the -`drop` function is where you would place any logic that you wanted to run when -an instance of your type goes out of scope. We’re printing some text here to -demonstrate when Rust will call `drop`. - -In `main`, we create two instances of `CustomSmartPointer` and then print -`CustomSmartPointers created.`. At the end of `main`, our instance of -`CustomSmartPointer` will go out of scope, and Rust will call the code we put -in the `drop` method, printing our final message. Note that we didn’t need to -call the `drop` method explicitly. - -When we run this program, we’ll see the following output: - -``` -CustomSmartPointers created. -Dropping CustomSmartPointer with data `other stuff`! -Dropping CustomSmartPointer with data `my stuff`! -``` - -Rust automatically called `drop` for us when our instance went out of scope, -calling the code we specified. Variables are dropped in the reverse order of -the order in which they were created, so `d` was dropped before `c`. This -example just gives you a visual guide to how the `drop` method works, but -usually you would specify the cleanup code that your type needs to run rather -than a print message. - -### Dropping a Value Early with `std::mem::drop` - -Unfortunately, it’s not straightforward to disable the automatic `drop` -functionality. Disabling `drop` isn’t usually necessary; the whole point of the -`Drop` trait is that it’s taken care of automatically. Occasionally, you might -want to clean up a value early. One example is when using smart pointers that -manage locks: you might want to force the `drop` method that releases the lock -to run so other code in the same scope can acquire the lock. Rust doesn’t let -us call the `Drop` trait’s `drop` method manually; instead we have to call the -`std::mem::drop` function provided by the standard library if we want to force -a value to be dropped before the end of its scope. - -Let’s see what happens when we try to call the `Drop` trait’s `drop` method -manually by modifying the `main` function in Listing 15-14, as shown in Listing -15-15: - -Filename: src/main.rs - -``` -fn main() { - let c = CustomSmartPointer { data: String::from("some data") }; - println!("CustomSmartPointer created."); - c.drop(); - println!("CustomSmartPointer dropped before the end of main."); -} -``` - -Listing 15-15: Attempting to call the `drop` method from the `Drop` trait -manually to clean up early - -When we try to compile this code, we’ll get this error: - -``` -error[E0040]: explicit use of destructor method - --> src/main.rs:14:7 - | -14 | c.drop(); - | ^^^^ explicit destructor calls not allowed -``` - -This error message states that we’re not allowed to explicitly call `drop`. The -error message uses the term *destructor*, which is the general programming term -for a function that cleans up an instance. A *destructor* is analogous to a -*constructor* that creates an instance. The `drop` function in Rust is one -particular destructor. - -Rust doesn’t let us call `drop` explicitly because Rust would still -automatically call `drop` on the value at the end of `main`. This would be a -*double free* error because Rust would be trying to clean up the same value -twice. - -We can’t disable the automatic insertion of `drop` when a value goes out of -scope, and we can’t call the `drop` method explicitly. So, if we need to force -a value to be cleaned up early, we can use the `std::mem::drop` function. - -The `std::mem::drop` function is different than the `drop` method in the `Drop` -trait. We call it by passing the value we want to force to be dropped early as -an argument. The function is in the prelude, so we can modify `main` in Listing -15-14 to call the `drop` function, as shown in Listing 15-16: - -Filename: src/main.rs - -``` -fn main() { - let c = CustomSmartPointer { data: String::from("some data") }; - println!("CustomSmartPointer created."); - drop(c); - println!("CustomSmartPointer dropped before the end of main."); -} -``` - -Listing 15-16: Calling `std::mem::drop` to explicitly drop a value before it -goes out of scope - -Running this code will print the following: - -``` -CustomSmartPointer created. -Dropping CustomSmartPointer with data `some data`! -CustomSmartPointer dropped before the end of main. -``` - -The text ```Dropping CustomSmartPointer with data `some data`!``` is printed -between the `CustomSmartPointer created.` and `CustomSmartPointer dropped -before the end of main.` text, showing that the `drop` method code is called to -drop `c` at that point. - -We can use code specified in a `Drop` trait implementation in many ways to make -cleanup convenient and safe: for instance, we could use it to create our own -memory allocator! With the `Drop` trait and Rust’s ownership system, we don’t -have to remember to clean up because Rust does it automatically. - -We also don’t have to worry about accidentally cleaning up values still in use -because that would cause a compiler error: the ownership system that makes sure -references are always valid also ensures that `drop` gets called only once when -the value is no longer being used. - -Now that we’ve examined `Box` and some of the characteristics of smart -pointers, let’s look at a few other smart pointers defined in the standard -library. - -## `Rc`, the Reference Counted Smart Pointer - -In the majority of cases, ownership is clear: you know exactly which variable -owns a given value. However, there are cases when a single value might have -multiple owners. For example, in graph data structures, multiple edges might -point to the same node, and that node is conceptually owned by all of the edges -that point to it. A node shouldn’t be cleaned up unless it doesn’t have any -edges pointing to it. - -To enable multiple ownership, Rust has a type called `Rc`. Its name is an -abbreviation for *reference counting*, which keeps track of the number of -references to a value to know whether or not a value is still in use. If there -are zero references to a value, the value can be cleaned up without any -references becoming invalid. - -Imagine `Rc` as a TV in a family room. When one person enters to watch TV, -they turn it on. Others can come into the room and watch the TV. When the last -person leaves the room, they turn off the TV because it’s no longer being used. -If someone turns off the TV while others are still watching it, there would be -uproar from the remaining TV watchers! - -We use the `Rc` type when we want to allocate some data on the heap for -multiple parts of our program to read, and we can’t determine at compile time -which part will finish using the data last. If we knew which part would finish -last, we could just make that part the data’s owner and the normal ownership -rules enforced at compile time would take effect. - -Note that `Rc` is only for use in single-threaded scenarios. When we discuss -concurrency in Chapter 16, we’ll cover how to do reference counting in -multithreaded programs. - -### Using `Rc` to Share Data - -Let’s return to our cons list example in Listing 15-5. Recall that we defined -it using `Box`. This time, we’ll create two lists that both share ownership -of a third list, which conceptually will look similar to Figure 15-3: - -Two lists that share ownership of a third list - -Figure 15-3: Two lists, `b` and `c`, sharing ownership of a third list, `a` - -We’ll create list `a` that contains 5 and then 10. Then we’ll make two more -lists: `b` that starts with 3 and `c` that starts with 4. Both `b` and `c` -lists will then continue on to the first `a` list containing 5 and 10. In other -words, both lists will share the first list containing 5 and 10. - -Trying to implement this scenario using our definition of `List` with `Box` -won’t work, as shown in Listing 15-17: - -Filename: src/main.rs - -``` -enum List { - Cons(i32, Box), - Nil, -} - -use List::{Cons, Nil}; - -fn main() { - let a = Cons(5, - Box::new(Cons(10, - Box::new(Nil)))); - let b = Cons(3, Box::new(a)); - let c = Cons(4, Box::new(a)); -} -``` - -Listing 15-17: Demonstrating we’re not allowed to have two lists using `Box` -that try to share ownership of a third list - -When we compile this code, we get this error: - -``` -error[E0382]: use of moved value: `a` - --> src/main.rs:13:30 - | -12 | let b = Cons(3, Box::new(a)); - | - value moved here -13 | let c = Cons(4, Box::new(a)); - | ^ value used here after move - | - = note: move occurs because `a` has type `List`, which does not implement - the `Copy` trait -``` - -The `Cons` variants own the data they hold, so when we create the `b` list, `a` -is moved into `b` and `b` owns `a`. Then, when we try to use `a` again when -creating `c`, we’re not allowed to because `a` has been moved. - -We could change the definition of `Cons` to hold references instead, but then -we would have to specify lifetime parameters. By specifying lifetime -parameters, we would be specifying that every element in the list will live at -least as long as the entire list. The borrow checker wouldn’t let us compile -`let a = Cons(10, &Nil);` for example, because the temporary `Nil` value would -be dropped before `a` could take a reference to it. - -Instead, we’ll change our definition of `List` to use `Rc` in place of -`Box`, as shown in Listing 15-18. Each `Cons` variant will now hold a value -and an `Rc` pointing to a `List`. When we create `b`, instead of taking -ownership of `a`, we’ll clone the `Rc` that `a` is holding, which -increases the number of references from one to two and lets `a` and `b` share -ownership of the data in that `Rc`. We’ll also clone `a` when creating -`c`, which increases the number of references from two to three. Every time we -call `Rc::clone`, the reference count to the data within the `Rc` will -increase, and the data won’t be cleaned up unless there are zero references to -it: - -Filename: src/main.rs - -``` -enum List { - Cons(i32, Rc), - Nil, -} - -use List::{Cons, Nil}; -use std::rc::Rc; - -fn main() { - let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); - let b = Cons(3, Rc::clone(&a)); - let c = Cons(4, Rc::clone(&a)); -} -``` - -Listing 15-18: A definition of `List` that uses `Rc` - -We need to add a `use` statement to bring `Rc` into scope because it’s not -in the prelude. In `main`, we create the list holding 5 and 10 and store it in -a new `Rc` in `a`. Then when we create `b` and `c`, we call the -`Rc::clone` function and pass a reference to the `Rc` in `a` as an -argument. - -We could have called `a.clone()` rather than `Rc::clone(&a)`, but Rust’s -convention is to use `Rc::clone` in this case. The implementation of -`Rc::clone` doesn’t make a deep copy of all the data like most types’ -implementations of `clone` do. The call to `Rc::clone` only increments the -reference count, which doesn’t take much time. Deep copies of data can take a -lot of time. By using `Rc::clone` for reference counting, we can visually -distinguish between the deep copy kinds of clones and the kinds of clones that -increase the reference count. When looking for performance problems in the -code, we only need to consider the deep copy clones and can disregard calls to -`Rc::clone`. - -### Cloning an `Rc` Increases the Reference Count - -Let’s change our working example in Listing 15-18 so we can see the reference -counts changing as we create and drop references to the `Rc` in `a`. - -In Listing 15-19, we’ll change `main` so it has an inner scope around list `c`; -then we can see how the reference count changes when `c` goes out of scope. At -each point in the program where the reference count changes, we’ll print the -reference count, which we can get by calling the `Rc::strong_count` function. -This function is named `strong_count` rather than `count` because the `Rc` -type also has a `weak_count`; we’ll see what `weak_count` is used for in the -“Preventing Reference Cycles” section. - -Filename: src/main.rs - -``` -fn main() { - let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); - println!("count after creating a = {}", Rc::strong_count(&a)); - let b = Cons(3, Rc::clone(&a)); - println!("count after creating b = {}", Rc::strong_count(&a)); - { - let c = Cons(4, Rc::clone(&a)); - println!("count after creating c = {}", Rc::strong_count(&a)); - } - println!("count after c goes out of scope = {}", Rc::strong_count(&a)); -} -``` - -Listing 15-19: Printing the reference count - -This code prints the following: - -``` -count after creating a = 1 -count after creating b = 2 -count after creating c = 3 -count after c goes out of scope = 2 -``` - -We can see that the `Rc` in `a` has an initial reference count of one; -then each time we call `clone`, the count goes up by one. When `c` goes out of -scope, the count goes down by one. We don’t have to call a function to decrease -the reference count like we have to call `Rc::clone` to increase the reference -count: the implementation of the `Drop` trait decreases the reference count -automatically when an `Rc` value goes out of scope. - -What we can’t see in this example is that when `b` and then `a` go out of scope -at the end of `main`, the count is then 0, and the `Rc` is cleaned up -completely at that point. Using `Rc` allows a single value to have -multiple owners, and the count ensures that the value remains valid as long as -any of the owners still exist. - -Via immutable references, `Rc` allows us to share data between multiple -parts of our program for reading only. If `Rc` allowed us to have multiple -mutable references too, we might violate one of the borrowing rules discussed -in Chapter 4: multiple mutable borrows to the same place can cause data races -and inconsistencies. But being able to mutate data is very useful! In the next -section, we’ll discuss the interior mutability pattern and the `RefCell` -type that we can use in conjunction with an `Rc` to work with this -immutability restriction. - -## `RefCell` and the Interior Mutability Pattern - -*Interior mutability* is a design pattern in Rust that allows you to mutate -data even when there are immutable references to that data: normally, this -action is disallowed by the borrowing rules. To do so, the pattern uses -`unsafe` code inside a data structure to bend Rust’s usual rules that govern -mutation and borrowing. We haven’t yet covered unsafe code; we will in Chapter -19. We can use types that use the interior mutability pattern when we can -ensure that the borrowing rules will be followed at runtime, even though the -compiler can’t guarantee that. The `unsafe` code involved is then wrapped in a -safe API, and the outer type is still immutable. - -Let’s explore this concept by looking at the `RefCell` type that follows the -interior mutability pattern. - -### Enforcing Borrowing Rules at Runtime with `RefCell` - -Unlike `Rc`, the `RefCell` type represents single ownership over the data -it holds. So, what makes `RefCell` different than a type like `Box`? -Recall the borrowing rules you learned in Chapter 4: - -* At any given time, you can have *either* but not both of the following: one - mutable reference or any number of immutable references. -* References must always be valid. - -With references and `Box`, the borrowing rules’ invariants are enforced at -compile time. With `RefCell`, these invariants are enforced *at runtime*. -With references, if you break these rules, you’ll get a compiler error. With -`RefCell`, if you break these rules, your program will `panic!` and exit. - -The advantages of checking the borrowing rules at compile time are that errors -will be caught sooner in the development process, and there is no impact on -runtime performance because all the analysis is completed beforehand. For those -reasons, checking the borrowing rules at compile time is the best choice in the -majority of cases, which is why this is Rust’s default. - -The advantage of checking the borrowing rules at runtime instead is that -certain memory safe scenarios are then allowed, whereas they are disallowed by -the compile time checks. Static analysis, like the Rust compiler, is inherently -conservative. Some properties of code are impossible to detect by analyzing the -code: the most famous example is the Halting Problem, which is beyond the scope -of this book but is an interesting topic to research. - -Because some analysis is impossible, if the Rust compiler can’t be sure the -code complies with the ownership rules, it might reject a correct program; in -this way, it’s conservative. If Rust accepted an incorrect program, users -wouldn’t be able to trust in the guarantees Rust makes. However, if Rust -rejects a correct program, the programmer will be inconvenienced, but nothing -catastrophic can occur. The `RefCell` type is useful when you’re sure your -code follows the borrowing rules, but the compiler is unable to understand and -guarantee that. - -Similar to `Rc`, `RefCell` is only for use in single-threaded scenarios -and will give you a compile time error if you try using it in a multithreaded -context. We’ll talk about how to get the functionality of `RefCell` in a -multithreaded program in Chapter 16. - -Here is a recap of the reasons to choose `Box`, `Rc`, or `RefCell`: - -* `Rc` enables multiple owners of the same data; `Box` and `RefCell` - have single owners. -* `Box` allows immutable or mutable borrows checked at compile time; `Rc` - only allows immutable borrows checked at compile time; `RefCell` allows - immutable or mutable borrows checked at runtime. -* Because `RefCell` allows mutable borrows checked at runtime, we can mutate - the value inside the `RefCell` even when the `RefCell` is immutable. - -Mutating the value inside an immutable value is the *interior mutability* -pattern. Let’s look at a situation in which interior mutability is useful and -examine how it’s possible. - -### Interior Mutability: A Mutable Borrow to an Immutable Value - -A consequence of the borrowing rules is that when we have an immutable value, -we can’t borrow it mutably. For example, this code won’t compile: - -``` -fn main() { - let x = 5; - let y = &mut x; -} -``` - -When we try to compile this code, we’ll get the following error: - -``` -error[E0596]: cannot borrow immutable local variable `x` as mutable - --> src/main.rs:3:18 - | -2 | let x = 5; - | - consider changing this to `mut x` -3 | let y = &mut x; - | ^ cannot borrow mutably -``` - -However, there are situations in which it would be useful for a value to mutate -itself in its methods, but to other code, the value would appear immutable. -Code outside the value’s methods would not be able to mutate the value. Using -`RefCell` is one way to get the ability to have interior mutability. But -`RefCell` doesn’t get around the borrowing rules completely: the borrow -checker in the compiler allows this interior mutability, and the borrowing -rules are checked at runtime instead. If we violate the rules, we’ll get a -`panic!` instead of a compiler error. - -Let’s work through a practical example where we can use `RefCell` to mutate -an immutable value and see why that is useful. - -#### A Use Case for Interior Mutability: Mock Objects - -A *test double* is the general programming concept for a type used in place of -another type during testing. *Mock objects* are specific types of test doubles -that record what happens during a test so we can assert that the correct -actions took place. - -Rust doesn’t have objects in the same sense as other languages have objects, -and Rust doesn’t have mock object functionality built into the standard library -like some other languages do. However, we can definitely create a struct that -will serve the same purposes as a mock object. - -Here’s the scenario we’ll test: we’ll create a library that tracks a value -against a maximum value and sends messages based on how close to the maximum -value the current value is. This library could be used for keeping track of a -user’s quota for the number of API calls they’re allowed to make, for example. - -Our library will only provide the functionality of tracking how close to the -maximum a value is and what the messages should be at what times. Applications -that use our library will be expected to provide the mechanism for sending the -messages: the application could put a message in the application, send an -email, send a text message, or something else. The library doesn’t need to know -that detail. All it needs is something that implements a trait we’ll provide -called `Messenger`. Listing 15-20 shows the library code: - -Filename: src/lib.rs - -``` -pub trait Messenger { - fn send(&self, msg: &str); -} - -pub struct LimitTracker<'a, T: 'a + Messenger> { - messenger: &'a T, - value: usize, - max: usize, -} - -impl<'a, T> LimitTracker<'a, T> - where T: Messenger { - pub fn new(messenger: &T, max: usize) -> LimitTracker { - LimitTracker { - messenger, - value: 0, - max, - } - } - - pub fn set_value(&mut self, value: usize) { - self.value = value; - - let percentage_of_max = self.value as f64 / self.max as f64; - - if percentage_of_max >= 0.75 && percentage_of_max < 0.9 { - self.messenger.send("Warning: You've used up over 75% of your -quota!"); - } else if percentage_of_max >= 0.9 && percentage_of_max < 1.0 { - self.messenger.send("Urgent warning: You've used up over 90% of -your quota!"); - } else if percentage_of_max >= 1.0 { - self.messenger.send("Error: You are over your quota!"); - } - } -} -``` - -Listing 15-20: A library to keep track of how close to a maximum value a value -is and warn when the value is at certain levels - -One important part of this code is that the `Messenger` trait has one method -called `send` that takes an immutable reference to `self` and text of the -message. This is the interface our mock object needs to have. The other -important part is that we want to test the behavior of the `set_value` method -on the `LimitTracker`. We can change what we pass in for the `value` parameter, -but `set_value` doesn’t return anything for us to make assertions on. We want -to be able to say that if we create a `LimitTracker` with something that -implements the `Messenger` trait and a particular value for `max`, when we pass -different numbers for `value`, the messenger is told to send the appropriate -messages. - -We need a mock object that instead of sending an email or text message when we -call `send` will only keep track of the messages it’s told to send. We can -create a new instance of the mock object, create a `LimitTracker` that uses the -mock object, call the `set_value` method on `LimitTracker`, and then check that -the mock object has the messages we expect. Listing 15-21 shows an attempt of -implementing a mock object to do just that but that the borrow checker won’t -allow: - -Filename: src/lib.rs - -``` -#[cfg(test)] -mod tests { - use super::*; - - struct MockMessenger { - sent_messages: Vec, - } - - impl MockMessenger { - fn new() -> MockMessenger { - MockMessenger { sent_messages: vec![] } - } - } - - impl Messenger for MockMessenger { - fn send(&self, message: &str) { - self.sent_messages.push(String::from(message)); - } - } - - #[test] - fn it_sends_an_over_75_percent_warning_message() { - let mock_messenger = MockMessenger::new(); - let mut limit_tracker = LimitTracker::new(&mock_messenger, 100); - - limit_tracker.set_value(80); - - assert_eq!(mock_messenger.sent_messages.len(), 1); - } -} -``` - -Listing 15-21: An attempt to implement a `MockMessenger` that isn’t allowed by -the borrow checker - -This test code defines a `MockMessenger` struct that has a `sent_messages` -field with a `Vec` of `String` values to keep track of the messages it’s told -to send. We also define an associated function `new` to make it convenient to -create new `MockMessenger` values that start with an empty list of messages. We -then implement the `Messenger` trait for `MockMessenger` so we can give a -`MockMessenger` to a `LimitTracker`. In the definition of the `send` method, we -take the message passed in as a parameter and store it in the `MockMessenger` -list of `sent_messages`. - -In the test, we’re testing what happens when the `LimitTracker` is told to set -`value` to something that is more than 75 percent of the `max` value. First, we -create a new `MockMessenger`, which will start with an empty list of messages. -Then we create a new `LimitTracker` and give it a reference to the new -`MockMessenger` and a `max` value of 100. We call the `set_value` method on the -`LimitTracker` with a value of 80, which is more than 75 percent of 100. Then -we assert that the list of messages that the `MockMessenger` is keeping track -of should now have one message in it. - -However, there’s one problem with this test, as shown here: - -``` -error[E0596]: cannot borrow immutable field `self.sent_messages` as mutable - --> src/lib.rs:52:13 - | -51 | fn send(&self, message: &str) { - | ----- use `&mut self` here to make mutable -52 | self.sent_messages.push(String::from(message)); - | ^^^^^^^^^^^^^^^^^^ cannot mutably borrow immutable field -``` - -We can’t modify the `MockMessenger` to keep track of the messages because the -`send` method takes an immutable reference to `self`. We also can’t take the -suggestion from the error text to use `&mut self` instead because then the -signature of `send` wouldn’t match the signature in the `Messenger` trait -definition (feel free to try and see what error message you get). - -This is a situation in which interior mutability can help! We’ll store the -`sent_messages` within a `RefCell`, and then the `send` message will be -able to modify `sent_messages` to store the messages we’ve seen. Listing 15-22 -shows what that looks like: - -Filename: src/lib.rs - -``` -#[cfg(test)] -mod tests { - use super::*; - use std::cell::RefCell; - - struct MockMessenger { - sent_messages: RefCell>, - } - - impl MockMessenger { - fn new() -> MockMessenger { - MockMessenger { sent_messages: RefCell::new(vec![]) } - } - } - - impl Messenger for MockMessenger { - fn send(&self, message: &str) { - self.sent_messages.borrow_mut().push(String::from(message)); - } - } - - #[test] - fn it_sends_an_over_75_percent_warning_message() { - // --snip-- - - assert_eq!(mock_messenger.sent_messages.borrow().len(), 1); - } -} -``` - -Listing 15-22: Using `RefCell` to mutate an inner value while the outer -value is considered immutable - -The `sent_messages` field is now of type `RefCell>` instead of -`Vec`. In the `new` function, we create a new `RefCell>` -instance around the empty vector. - -For the implementation of the `send` method, the first parameter is still an -immutable borrow of `self`, which matches the trait definition. We call -`borrow_mut` on the `RefCell>` in `self.sent_messages` to get a -mutable reference to the value inside the `RefCell>`, which is -the vector. Then we can call `push` on the mutable reference to the vector to -keep track of the messages sent during the test. - -The last change we have to make is in the assertion: to see how many items are -in the inner vector, we call `borrow` on the `RefCell>` to get an -immutable reference to the vector. - -Now that you’ve seen how to use `RefCell`, let’s dig into how it works! - -#### `RefCell` Keeps Track of Borrows at Runtime - -When creating immutable and mutable references, we use the `&` and `&mut` -syntax, respectively. With `RefCell`, we use the `borrow` and `borrow_mut` -methods, which are part of the safe API that belongs to `RefCell`. The -`borrow` method returns the smart pointer type `Ref`, and `borrow_mut` -returns the smart pointer type `RefMut`. Both types implement `Deref` so -we can treat them like regular references. - -The `RefCell` keeps track of how many `Ref` and `RefMut` smart -pointers are currently active. Every time we call `borrow`, the `RefCell` -increases its count of how many immutable borrows are active. When a `Ref` -value goes out of scope, the count of immutable borrows goes down by one. Just -like the compile time borrowing rules, `RefCell` lets us have many immutable -borrows or one mutable borrow at any point in time. - -If we try to violate these rules, rather than getting a compiler error like we -would with references, the implementation of `RefCell` will `panic!` at -runtime. Listing 15-23 shows a modification of the implementation of `send` in -Listing 15-22. We’re deliberately trying to create two mutable borrows active -for the same scope to illustrate that `RefCell` prevents us from doing this -at runtime: - -Filename: src/lib.rs - -``` -impl Messenger for MockMessenger { - fn send(&self, message: &str) { - let mut one_borrow = self.sent_messages.borrow_mut(); - let mut two_borrow = self.sent_messages.borrow_mut(); - - one_borrow.push(String::from(message)); - two_borrow.push(String::from(message)); - } -} -``` - -Listing 15-23: Creating two mutable references in the same scope to see that -`RefCell` will panic - -We create a variable `one_borrow` for the `RefMut` smart pointer returned -from `borrow_mut`. Then we create another mutable borrow in the same way in the -variable `two_borrow`. This makes two mutable references in the same scope, -which isn’t allowed. When we run the tests for our library, the code in Listing -15-23 will compile without any errors, but the test will fail: - -``` ----- tests::it_sends_an_over_75_percent_warning_message stdout ---- - thread 'tests::it_sends_an_over_75_percent_warning_message' panicked at - 'already borrowed: BorrowMutError', src/libcore/result.rs:906:4 -note: Run with `RUST_BACKTRACE=1` for a backtrace. -``` - -Notice that the code panicked with the message `already borrowed: -BorrowMutError`. This is how `RefCell` handles violations of the borrowing -rules at runtime. - -Catching borrowing errors at runtime rather than compile time means that we -would find a mistake in our code later in the development process and possibly -not even until our code was deployed to production. Also, our code will incur a -small runtime performance penalty as a result of keeping track of the borrows -at runtime rather than compile time. However, using `RefCell` makes it -possible for us to write a mock object that can modify itself to keep track of -the messages it has seen while we’re using it in a context where only immutable -values are allowed. We can use `RefCell` despite its trade-offs to get more -functionality than regular references give us. - -### Having Multiple Owners of Mutable Data by Combining `Rc` and `RefCell` - -A common way to use `RefCell` is in combination with `Rc`. Recall that -`Rc` lets us have multiple owners of some data, but it only gives us -immutable access to that data. If we have an `Rc` that holds a `RefCell`, -we can get a value that can have multiple owners *and* that we can mutate! - -For example, recall the cons list example in Listing 15-18 where we used -`Rc` to let us have multiple lists share ownership of another list. Because -`Rc` only holds immutable values, we can’t change any of the values in the -list once we’ve created them. Let’s add in `RefCell` to gain the ability to -change the values in the lists. Listing 15-24 shows that by using a -`RefCell` in the `Cons` definition, we can modify the value stored in all -the lists: - -Filename: src/main.rs - -``` -#[derive(Debug)] -enum List { - Cons(Rc>, Rc), - Nil, -} - -use List::{Cons, Nil}; -use std::rc::Rc; -use std::cell::RefCell; - -fn main() { - let value = Rc::new(RefCell::new(5)); - - let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil))); - - let b = Cons(Rc::new(RefCell::new(6)), Rc::clone(&a)); - let c = Cons(Rc::new(RefCell::new(10)), Rc::clone(&a)); - - *value.borrow_mut() += 10; - - println!("a after = {:?}", a); - println!("b after = {:?}", b); - println!("c after = {:?}", c); -} -``` - -Listing 15-24: Using `Rc>` to create a `List` that we can mutate - -We create a value that is an instance of `Rc` and store it in a -variable named `value` so we can access it directly later. Then we create a -`List` in `a` with a `Cons` variant that holds `value`. We need to clone -`value` so both `a` and `value` have ownership of the inner `5` value rather -than transferring ownership from `value` to `a` or having `a` borrow from -`value`. - -We wrap the list `a` in an `Rc` so when we create lists `b` and `c`, they -can both refer to `a`, which is what we did in Listing 15-18. - -After we’ve created the lists in `a`, `b`, and `c`, we add 10 to the value in -`value`. We do this by calling `borrow_mut` on `value`, which uses the -automatic dereferencing feature we discussed in Chapter 5 (see the section -“Where’s the `->` Operator?”) to dereference the `Rc` to the inner -`RefCell` value. The `borrow_mut` method returns a `RefMut` smart -pointer, and we use the dereference operator on it and change the inner value. - -When we print `a`, `b`, and `c`, we can see that they all have the modified -value of 15 rather than 5: - -``` -a after = Cons(RefCell { value: 15 }, Nil) -b after = Cons(RefCell { value: 6 }, Cons(RefCell { value: 15 }, Nil)) -c after = Cons(RefCell { value: 10 }, Cons(RefCell { value: 15 }, Nil)) -``` - -This technique is pretty neat! By using `RefCell`, we have an outwardly -immutable `List`. But we can use the methods on `RefCell` that provide -access to its interior mutability so we can modify our data when we need to. -The runtime checks of the borrowing rules protect us from data races, and it’s -sometimes worth trading a bit of speed for this flexibility in our data -structures. - -The standard library has other types that provide interior mutability, such as -`Cell`, which is similar except that instead of giving references to the -inner value, the value is copied in and out of the `Cell`. There’s also -`Mutex`, which offers interior mutability that’s safe to use across threads; -we’ll discuss its use in Chapter 16. Check out the standard library docs for -more details on the differences between these types. - -## Reference Cycles Can Leak Memory - -Rust’s memory safety guarantees make it *difficult* but not impossible to -accidentally create memory that is never cleaned up (known as a *memory leak*). -Preventing memory leaks entirely is not one of Rust’s guarantees in the same -way that disallowing data races at compile time is, meaning memory leaks are -memory safe in Rust. We can see that Rust allows memory leaks by using `Rc` -and `RefCell`: it’s possible to create references where items refer to each -other in a cycle. This creates memory leaks because the reference count of each -item in the cycle will never reach 0, and the values will never be dropped. - -### Creating a Reference Cycle - -Let’s look at how a reference cycle might happen and how to prevent it, -starting with the definition of the `List` enum and a `tail` method in Listing -15-25: - -Filename: src/main.rs - -``` -use std::rc::Rc; -use std::cell::RefCell; -use List::{Cons, Nil}; - -#[derive(Debug)] -enum List { - Cons(i32, RefCell>), - Nil, -} - -impl List { - fn tail(&self) -> Option<&RefCell>> { - match *self { - Cons(_, ref item) => Some(item), - Nil => None, - } - } -} -``` - -Listing 15-25: A cons list definition that holds a `RefCell` so we can -modify what a `Cons` variant is referring to - -We’re using another variation of the `List` definition in Listing 15-5. The -second element in the `Cons` variant is now `RefCell>`, meaning that -instead of having the ability to modify the `i32` value like we did in Listing -15-24, we want to modify which `List` a `Cons` variant is pointing to. We’re -also adding a `tail` method to make it convenient for us to access the second -item if we have a `Cons` variant. - -In Listing 15-26, we’re adding a `main` function that uses the definitions in -Listing 15-25. This code creates a list in `a` and a list in `b` that points to -the list in `a`, and then modifies the list in `a` to point to `b`, which -creates a reference cycle. There are `println!` statements along the way to -show what the reference counts are at various points in this process: - -Filename: src/main.rs - -``` -fn main() { - let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil)))); - - println!("a initial rc count = {}", Rc::strong_count(&a)); - println!("a next item = {:?}", a.tail()); - - let b = Rc::new(Cons(10, RefCell::new(Rc::clone(&a)))); - - println!("a rc count after b creation = {}", Rc::strong_count(&a)); - println!("b initial rc count = {}", Rc::strong_count(&b)); - println!("b next item = {:?}", b.tail()); - - if let Some(link) = a.tail() { - *link.borrow_mut() = Rc::clone(&b); - } - - println!("b rc count after changing a = {}", Rc::strong_count(&b)); - println!("a rc count after changing a = {}", Rc::strong_count(&a)); - - // Uncomment the next line to see that we have a cycle; it will - // overflow the stack - // println!("a next item = {:?}", a.tail()); -} -``` - -Listing 15-26: Creating a reference cycle of two `List` values pointing to each -other - -We create an `Rc` instance holding a `List` value in the variable `a` -with an initial list of `5, Nil`. We then create an `Rc` instance -holding another `List` value in the variable `b` that contains the value 10 and -then points to the list in `a`. - -We modify `a` so it points to `b` instead of `Nil`, which creates a cycle. We -do that by using the `tail` method to get a reference to the -`RefCell>` in `a`, which we put in the variable `link`. Then we use -the `borrow_mut` method on the `RefCell>` to change the value inside -from an `Rc` that holds a `Nil` value to the `Rc` in `b`. - -When we run this code, keeping the last `println!` commented out for the -moment, we’ll get this output: - -``` -a initial rc count = 1 -a next item = Some(RefCell { value: Nil }) -a rc count after b creation = 2 -b initial rc count = 1 -b next item = Some(RefCell { value: Cons(5, RefCell { value: Nil }) }) -b rc count after changing a = 2 -a rc count after changing a = 2 -``` - -The reference count of the `Rc` instances in both `a` and `b` are 2 -after we change the list in `a` to point to `b`. At the end of `main`, Rust -will try to drop `b` first, which will decrease the count in each of the -`Rc` instances in `a` and `b` by one. - -However, because `a` is still referencing the `Rc` that was in `b`, -that `Rc` has a count of 1 rather than 0, so the memory the -`Rc` has on the heap won’t be dropped. The memory will just sit there -with a count of one, forever. To visualize this reference cycle, we’ve created -a diagram in Figure 15-4: - -Reference cycle of lists - -Figure 15-4: A reference cycle of lists `a` and `b` pointing to each other - -If you uncomment the last `println!` and run the program, Rust will try to -print this cycle with `a` pointing to `b` pointing to `a` and so forth until it -overflows the stack. - -In this case, right after we create the reference cycle, the program ends. The -consequences of this cycle aren’t very dire. If a more complex program -allocates lots of memory in a cycle and holds onto it for a long time, the -program would use more memory than it needs and might overwhelm the system, -causing it to run out of available memory. - -Creating reference cycles is not easily done, but it’s not impossible either. -If you have `RefCell` values that contain `Rc` values or similar nested -combinations of types with interior mutability and reference counting, you must -ensure that you don’t create cycles; you can’t rely on Rust to catch them. -Creating a reference cycle would be a logic bug in your program that you should -use automated tests, code reviews, and other software development practices to -minimize. - -Another solution for avoiding reference cycles is reorganizing your data -structures so that some references express ownership and some references don’t. -As a result, you can have cycles made up of some ownership relationships and -some non-ownership relationships, and only the ownership relationships affect -whether or not a value can be dropped. In Listing 15-25, we always want `Cons` -variants to own their list, so reorganizing the data structure isn’t possible. -Let’s look at an example using graphs made up of parent nodes and child nodes -to see when non-ownership relationships are an appropriate way to prevent -reference cycles. - -### Preventing Reference Cycles: Turn an `Rc` into a `Weak` - -So far, we’ve demonstrated that calling `Rc::clone` increases the -`strong_count` of an `Rc` instance, and an `Rc` instance is only -cleaned up if its `strong_count` is 0. We can also create a *weak reference* to -the value within an `Rc` instance by calling `Rc::downgrade` and passing a -reference to the `Rc`. When we call `Rc::downgrade`, we get a smart -pointer of type `Weak`. Instead of increasing the `strong_count` in the -`Rc` instance by one, calling `Rc::downgrade` increases the `weak_count` -by one. The `Rc` type uses `weak_count` to keep track of how many -`Weak` references exist, similar to `strong_count`. The difference is the -`weak_count` doesn’t need to be 0 for the `Rc` instance to be cleaned up. - -Strong references are how we can share ownership of an `Rc` instance. Weak -references don’t express an ownership relationship. They won’t cause a -reference cycle because any cycle involving some weak references will be broken -once the strong reference count of values involved is 0. - -Because the value that `Weak` references might have been dropped, to do -anything with the value that a `Weak` is pointing to, we must make sure the -value still exists. We do this by calling the `upgrade` method on a `Weak` -instance, which will return an `Option>`. We’ll get a result of `Some` if -the `Rc` value has not been dropped yet and a result of `None` if the -`Rc` value has been dropped. Because `upgrade` returns an `Option`, Rust -will ensure that we handle the `Some` case and the `None` case, and there won’t -be an invalid pointer. - -As an example, rather than using a list whose items know only about the next -item, we’ll create a tree whose items know about their children items *and* -their parent items. - -#### Creating a Tree Data Structure: a `Node` with Child Nodes - -To start, we’ll build a tree with nodes that know about their child nodes. -We’ll create a struct named `Node` that holds its own `i32` value as well as -references to its children `Node` values: - -Filename: src/main.rs - -``` -use std::rc::Rc; -use std::cell::RefCell; - -#[derive(Debug)] -struct Node { - value: i32, - children: RefCell>>, -} -``` - -We want a `Node` to own its children, and we want to share that ownership with -variables so we can access each `Node` in the tree directly. To do this, we -define the `Vec` items to be values of type `Rc`. We also want to -modify which nodes are children of another node, so we have a `RefCell` in -`children` around the `Vec>`. - -Next, we’ll use our struct definition and create one `Node` instance named -`leaf` with the value 3 and no children, and another instance named `branch` -with the value 5 and `leaf` as one of its children, as shown in Listing 15-27: - -Filename: src/main.rs - -``` -fn main() { - let leaf = Rc::new(Node { - value: 3, - children: RefCell::new(vec![]), - }); - - let branch = Rc::new(Node { - value: 5, - children: RefCell::new(vec![Rc::clone(&leaf)]), - }); -} -``` - -Listing 15-27: Creating a `leaf` node with no children and a `branch` node with -`leaf` as one of its children - -We clone the `Rc` in `leaf` and store that in `branch`, meaning the -`Node` in `leaf` now has two owners: `leaf` and `branch`. We can get from -`branch` to `leaf` through `branch.children`, but there’s no way to get from -`leaf` to `branch`. The reason is that `leaf` has no reference to `branch` and -doesn’t know they’re related. We want `leaf` to know that `branch` is its -parent. We’ll do that next. - -#### Adding a Reference from a Child to Its Parent - -To make the child node aware of its parent, we need to add a `parent` field to -our `Node` struct definition. The trouble is in deciding what the type of -`parent` should be. We know it can’t contain an `Rc` because that would -create a reference cycle with `leaf.parent` pointing to `branch` and -`branch.children` pointing to `leaf`, which would cause their `strong_count` -values to never be 0. - -Thinking about the relationships another way, a parent node should own its -children: if a parent node is dropped, its child nodes should be dropped as -well. However, a child should not own its parent: if we drop a child node, the -parent should still exist. This is a case for weak references! - -So instead of `Rc`, we’ll make the type of `parent` use `Weak`, -specifically a `RefCell>`. Now our `Node` struct definition looks -like this: - -Filename: src/main.rs - -``` -use std::rc::{Rc, Weak}; -use std::cell::RefCell; - -#[derive(Debug)] -struct Node { - value: i32, - parent: RefCell>, - children: RefCell>>, -} -``` - -Now a node will be able to refer to its parent node but doesn’t own its parent. -In Listing 15-28, we update `main` to use this new definition so the `leaf` -node will have a way to refer to its parent, `branch`: - -Filename: src/main.rs - -``` -fn main() { - let leaf = Rc::new(Node { - value: 3, - parent: RefCell::new(Weak::new()), - children: RefCell::new(vec![]), - }); - - println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); - - let branch = Rc::new(Node { - value: 5, - parent: RefCell::new(Weak::new()), - children: RefCell::new(vec![Rc::clone(&leaf)]), - }); - - *leaf.parent.borrow_mut() = Rc::downgrade(&branch); - - println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); -} -``` - -Listing 15-28: A `leaf` node with a `Weak` reference to its parent node `branch` - -Creating the `leaf` node looks similar to how creating the `leaf` node looked -in Listing 15-27 with the exception of the `parent` field: `leaf` starts out -without a parent, so we create a new, empty `Weak` reference instance. - -At this point, when we try to get a reference to the parent of `leaf` by using -the `upgrade` method, we get a `None` value. We see this in the output from the -first `println!` statement: - -``` -leaf parent = None -``` - -When we create the `branch` node, it will also have a new `Weak` -reference in the `parent` field, because `branch` doesn’t have a parent node. -We still have `leaf` as one of the children of `branch`. Once we have the -`Node` instance in `branch`, we can modify `leaf` to give it a `Weak` -reference to its parent. We use the `borrow_mut` method on the -`RefCell>` in the `parent` field of `leaf`, and then we use the -`Rc::downgrade` function to create a `Weak` reference to `branch` from -the `Rc` in `branch.` - -When we print the parent of `leaf` again, this time we’ll get a `Some` variant -holding `branch`: now `leaf` can access its parent! When we print `leaf`, we -also avoid the cycle that eventually ended in a stack overflow like we had in -Listing 15-26: the `Weak` references are printed as `(Weak)`: - -``` -leaf parent = Some(Node { value: 5, parent: RefCell { value: (Weak) }, -children: RefCell { value: [Node { value: 3, parent: RefCell { value: (Weak) }, -children: RefCell { value: [] } }] } }) -``` - -The lack of infinite output indicates that this code didn’t create a reference -cycle. We can also tell this by looking at the values we get from calling -`Rc::strong_count` and `Rc::weak_count`. - -#### Visualizing Changes to `strong_count` and `weak_count` - -Let’s look at how the `strong_count` and `weak_count` values of the `Rc` -instances change by creating a new inner scope and moving the creation of -`branch` into that scope. By doing so, we can see what happens when `branch` is -created and then dropped when it goes out of scope. The modifications are shown -in Listing 15-29: - -Filename: src/main.rs - -``` -fn main() { - let leaf = Rc::new(Node { - value: 3, - parent: RefCell::new(Weak::new()), - children: RefCell::new(vec![]), - }); - - println!( - "leaf strong = {}, weak = {}", - Rc::strong_count(&leaf), - Rc::weak_count(&leaf), - ); - - { - let branch = Rc::new(Node { - value: 5, - parent: RefCell::new(Weak::new()), - children: RefCell::new(vec![Rc::clone(&leaf)]), - }); - - *leaf.parent.borrow_mut() = Rc::downgrade(&branch); - - println!( - "branch strong = {}, weak = {}", - Rc::strong_count(&branch), - Rc::weak_count(&branch), - ); - - println!( - "leaf strong = {}, weak = {}", - Rc::strong_count(&leaf), - Rc::weak_count(&leaf), - ); - } - - println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); - println!( - "leaf strong = {}, weak = {}", - Rc::strong_count(&leaf), - Rc::weak_count(&leaf), - ); -} -``` - -Listing 15-29: Creating `branch` in an inner scope and examining strong and -weak reference counts - -After `leaf` is created, its `Rc` has a strong count of 1 and a weak -count of 0. In the inner scope, we create `branch` and associate it with -`leaf`, at which point when we print the counts, the `Rc` in `branch` -will have a strong count of 1 and a weak count of 1 (for `leaf.parent` pointing -to `branch` with a `Weak`). When we print the counts in `leaf`, we’ll see -it will have a strong count of 2, because `branch` now has a clone of the -`Rc` of `leaf` stored in `branch.children` but will still have a weak -count of 0. - -When the inner scope ends, `branch` goes out of scope and the strong count of -the `Rc` decreases to 0, so its `Node` is dropped. The weak count of 1 -from `leaf.parent` has no bearing on whether or not `Node` is dropped, so we -don’t get any memory leaks! - -If we try to access the parent of `leaf` after the end of the scope, we’ll get -`None` again. At the end of the program, the `Rc` in `leaf` has a strong -count of 1 and a weak count of 0, because the variable `leaf` is now the only -reference to the `Rc` again. - -All of the logic that manages the counts and value dropping is built into -`Rc` and `Weak` and their implementations of the `Drop` trait. By -specifying that the relationship from a child to its parent should be a -`Weak` reference in the definition of `Node`, we’re able to have parent -nodes point to child nodes and vice versa without creating a reference cycle -and memory leaks. - -## Summary - -This chapter covered how to use smart pointers to make different guarantees and -trade-offs than those Rust makes by default with regular references. The -`Box` type has a known size and points to data allocated on the heap. The -`Rc` type keeps track of the number of references to data on the heap, so -that data can have multiple owners. The `RefCell` type with its interior -mutability gives us a type that we can use when we need an immutable type but -need to change an inner value of that type; it also enforces the borrowing -rules at runtime instead of at compile time. - -Also discussed were the `Deref` and `Drop` traits that enable a lot of the -functionality of smart pointers. We explored reference cycles that can cause -memory leaks and how to prevent them using `Weak`. - -If this chapter has piqued your interest and you want to implement your own -smart pointers, check out “The Rustonomicon” at -*https://doc.rust-lang.org/stable/nomicon/* for more useful information. - -Next, we’ll talk about concurrency in Rust. You’ll even learn about a few new -smart pointers. diff --git a/second-edition/nostarch/chapter16.md b/second-edition/nostarch/chapter16.md deleted file mode 100644 index e6f2a55db6..0000000000 --- a/second-edition/nostarch/chapter16.md +++ /dev/null @@ -1,1306 +0,0 @@ - -[TOC] - -# Fearless Concurrency - -Handling concurrent programming safely and efficiently is another of Rust’s -major goals. *Concurrent programming*, where different parts of a program -execute independently, and *parallel programming*, where different parts of a -program execute at the same time, are becoming increasingly important as more -computers take advantage of their multiple processors. Historically, -programming in these contexts has been difficult and error prone: Rust hopes to -change that. - -Initially, the Rust team thought that ensuring memory safety and preventing -concurrency problems were two separate challenges to be solved with different -methods. Over time, the team discovered that the ownership and type systems are -a powerful set of tools to help manage memory safety *and* concurrency -problems! By leveraging ownership and type checking, many concurrency errors -are *compile time* errors in Rust rather than runtime errors. Therefore, rather -than you spending lots of time trying to reproduce the exact circumstances -under which a runtime concurrency bug occurs, incorrect code will refuse to -compile and present an error explaining the problem. As a result, you can fix -your code while you’re working on it rather than potentially after it has been -shipped to production. We’ve nicknamed this aspect of Rust *fearless* -*concurrency*. Fearless concurrency allows you to write code that is free of -subtle bugs and is easy to refactor without introducing new bugs. - -> Note: For simplicity’s sake, we’ll refer to many of the problems as -> concurrent rather than being more precise by saying concurrent and/or -> parallel. If this book was specifically about concurrency and/or parallelism, -> we’d be more. specific. For this chapter, please mentally substitute -> concurrent and/or parallel whenever we use concurrent. - -Many languages are dogmatic about the solutions they offer for handling -concurrent problems. For example, Erlang has elegant functionality for message -passing concurrency but has only obscure ways to share state between threads. -Supporting only a subset of possible solutions is a reasonable strategy for -higher-level languages, because a higher-level language promises benefits from -giving up some control to gain abstractions. However, lower-level languages are -expected to provide the solution with the best performance in any given -situation and have fewer abstractions over the hardware. Therefore, Rust offers -a variety of tools for modeling problems in whatever way is appropriate for -your situation and requirements. - -Here are the topics we’ll cover in this chapter: - -* How to create threads to run multiple pieces of code at the same time -* *Message passing* concurrency, where channels send messages between threads -* *Shared state* concurrency, where multiple threads have access to some piece - of data -* The `Sync` and `Send` traits, which extend Rust’s concurrency guarantees to - user-defined types as well as types provided by the standard library - -## Using Threads to Run Code Simultaneously - -In most current operating systems, an executed program’s code is run in a -*process*, and the operating system manages multiple processes at once. Within -your program, you can also have independent parts that run simultaneously. The -feature that runs these independent parts is called *threads*. - -Splitting the computation in your program into multiple threads can improve -performance because the program does multiple tasks at the same time, but it -also adds complexity. Because threads can run simultaneously, there’s no -inherent guarantee about the order in which parts of your code on different -threads will run. This can lead to problems, such as: - -* Race conditions, where threads are accessing data or resources in an - inconsistent order -* Deadlocks, where two threads are waiting for each other to finish using a - resource the other thread has, preventing both threads from continuing -* Bugs that only happen in certain situations and are hard to reproduce and fix - reliably - -Rust attempts to mitigate the negative effects of using threads. Programming in -a multithreaded context still takes careful thought and requires a code -structure that is different from programs that run in a single thread. - -Programming languages implement threads in a few different ways. Many operating -systems provide an API for creating new threads. This model where a language -calls the operating system APIs to create threads is sometimes called *1:1*, -one operating system thread per one language thread. - -Many programming languages provide their own special implementation of threads. -Programming language-provided threads are known as *green* threads, and -languages that use these green threads will execute them in the context of a -different number of operating system threads. For this reason, the green -threaded model is called the *M:N* model: `M` green threads per `N` operating -system threads, where `M` and `N` are not necessarily the same number. - -Each model has its own advantages and trade-offs, and the trade-off most -important to Rust is runtime support. Runtime is a confusing term and can have -different meanings in different contexts. - -In this context, by *runtime* we mean code that is included by the language in -every binary. This code can be large or small depending on the language, but -every non-assembly language will have some amount of runtime code. For that -reason, colloquially when people say a language has “no runtime,” they often -mean “small runtime.” Smaller runtimes have fewer features but have the -advantage of resulting in smaller binaries, which make it easier to combine the -language with other languages in more contexts. Although many languages are -okay with increasing the runtime size in exchange for more features, Rust needs -to have nearly no runtime and cannot compromise on being able to call into C to -maintain performance. - -The green threading M:N model requires a larger language runtime to manage -threads. As such, the Rust standard library only provides an implementation of -1:1 threading. Because Rust is such a low-level language, there are crates that -implement M:N threading if you would rather trade overhead for aspects such as -more control over which threads run when and lower costs of context switching, -for example. - -Now that we’ve defined threads in Rust, let’s explore how to use the -thread-related API provided by the standard library. - -### Creating a New Thread with `spawn` - -To create a new thread, we call the `thread::spawn` function and pass it a -closure (we talked about closures in Chapter 13) containing the code we want to -run in the new thread. The example in Listing 16-1 prints some text from a main -thread and other text from a new thread: - -Filename: src/main.rs - -``` -use std::thread; -use std::time::Duration; - -fn main() { - thread::spawn(|| { - for i in 1..10 { - println!("hi number {} from the spawned thread!", i); - thread::sleep(Duration::from_millis(1)); - } - }); - - for i in 1..5 { - println!("hi number {} from the main thread!", i); - thread::sleep(Duration::from_millis(1)); - } -} -``` - -Listing 16-1: Creating a new thread to print one thing while the main thread -prints something else - -Note that with this function, the new thread will be stopped when the main -thread ends, whether or not it has finished running. The output from this -program might be a little different every time, but it will look similar to the -following: - -``` -hi number 1 from the main thread! -hi number 1 from the spawned thread! -hi number 2 from the main thread! -hi number 2 from the spawned thread! -hi number 3 from the main thread! -hi number 3 from the spawned thread! -hi number 4 from the main thread! -hi number 4 from the spawned thread! -hi number 5 from the spawned thread! -``` - -The calls to `thread::sleep` force a thread to stop its execution for a short -duration, which allows a different thread to run. The threads will probably -take turns, but that isn’t guaranteed: it depends on how your operating system -schedules the threads. In this run, the main thread printed first, even though -the print statement from the spawned thread appears first in the code. And even -though we told the spawned thread to print until `i` is 9, it only got to 5 -before the main thread shut down. - -If you run this code and only see output from the main thread, or don’t see any -overlap, try increasing the numbers in the ranges to create more opportunities -for the operating system to switch between the threads. - -### Waiting for All Threads to Finish Using `join` Handles - -The code in Listing 16-1 not only stops the spawned thread prematurely most of -the time due to the main thread ending, but there is no guarantee that the -spawned thread will get to run at all. The reason is that there is no guarantee -on the order in which threads run! - -We can fix the problem of the spawned thread not getting to run, or not getting -to run completely, by saving the return value of `thread::spawn` in a variable. -The return type of `thread::spawn` is `JoinHandle`. A `JoinHandle` is an owned -value that, when we call the `join` method on it, will wait for its thread to -finish. Listing 16-2 shows how to use the `JoinHandle` of the thread we created -in Listing 16-1 and call `join` to make sure the spawned thread finishes before -`main` exits: - -Filename: src/main.rs - -``` -use std::thread; -use std::time::Duration; - -fn main() { - let handle = thread::spawn(|| { - for i in 1..10 { - println!("hi number {} from the spawned thread!", i); - thread::sleep(Duration::from_millis(1)); - } - }); - - for i in 1..5 { - println!("hi number {} from the main thread!", i); - thread::sleep(Duration::from_millis(1)); - } - - handle.join().unwrap(); -} -``` - -Listing 16-2: Saving a `JoinHandle` from `thread::spawn` to guarantee the -thread is run to completion - -Calling `join` on the handle blocks the thread currently running until the -thread represented by the handle terminates. *Blocking* a thread means that -thread is prevented from performing work or exiting. Because we’ve put the call -to `join` after the main thread’s `for` loop, running Listing 16-2 should -produce output similar to this: - -``` -hi number 1 from the main thread! -hi number 2 from the main thread! -hi number 1 from the spawned thread! -hi number 3 from the main thread! -hi number 2 from the spawned thread! -hi number 4 from the main thread! -hi number 3 from the spawned thread! -hi number 4 from the spawned thread! -hi number 5 from the spawned thread! -hi number 6 from the spawned thread! -hi number 7 from the spawned thread! -hi number 8 from the spawned thread! -hi number 9 from the spawned thread! -``` - -The two threads continue alternating, but the main thread waits because of the -call to `handle.join()` and does not end until the spawned thread is finished. - -But let’s see what happens when we instead move `handle.join()` before the -`for` loop in `main`, like this: - -Filename: src/main.rs - -``` -use std::thread; -use std::time::Duration; - -fn main() { - let handle = thread::spawn(|| { - for i in 1..10 { - println!("hi number {} from the spawned thread!", i); - thread::sleep(Duration::from_millis(1)); - } - }); - - handle.join().unwrap(); - - for i in 1..5 { - println!("hi number {} from the main thread!", i); - thread::sleep(Duration::from_millis(1)); - } -} -``` - -The main thread will wait for the spawned thread to finish and then run its -`for` loop, so the output won’t be interleaved anymore, as shown here: - -``` -hi number 1 from the spawned thread! -hi number 2 from the spawned thread! -hi number 3 from the spawned thread! -hi number 4 from the spawned thread! -hi number 5 from the spawned thread! -hi number 6 from the spawned thread! -hi number 7 from the spawned thread! -hi number 8 from the spawned thread! -hi number 9 from the spawned thread! -hi number 1 from the main thread! -hi number 2 from the main thread! -hi number 3 from the main thread! -hi number 4 from the main thread! -``` - -Thinking about such a small detail as where to call `join` can affect whether -or not your threads run at the same time. - -### Using `move` Closures with Threads - -The `move` closure, which we mentioned briefly in Chapter 13, is often used -alongside `thread::spawn` because it allows us to use data from one thread in -another thread. - -In Chapter 13, we said that “If we want to force the closure to take ownership -of the values it uses in the environment, we can use the `move` keyword before -the parameter list. This technique is mostly useful when passing a closure to a -new thread to move the data so it’s owned by the new thread.” - -Now that we’re creating new threads, we’ll talk about capturing values in -closures. - -Notice in Listing 16-1 that the closure we pass to `thread::spawn` takes no -arguments: we’re not using any data from the main thread in the spawned -thread’s code. To do so, the spawned thread’s closure must capture the values -it needs. Listing 16-3 shows an attempt to create a vector in the main thread -and use it in the spawned thread. However, this won’t yet work, as you’ll see -in a moment: - -Filename: src/main.rs - -``` -use std::thread; - -fn main() { - let v = vec![1, 2, 3]; - - let handle = thread::spawn(|| { - println!("Here's a vector: {:?}", v); - }); - - handle.join().unwrap(); -} -``` - -Listing 16-3: Attempting to use a vector created by the main thread in another -thread - -The closure uses `v`, so it will capture `v` and make it part of the closure’s -environment. Because `thread::spawn` runs this closure in a new thread, we -should be able to access `v` inside that new thread. But when we compile this -example, we get the following error: - -``` -error[E0373]: closure may outlive the current function, but it borrows `v`, -which is owned by the current function - --> src/main.rs:6:32 - | -6 | let handle = thread::spawn(|| { - | ^^ may outlive borrowed value `v` -7 | println!("Here's a vector: {:?}", v); - | - `v` is borrowed here - | -help: to force the closure to take ownership of `v` (and any other referenced -variables), use the `move` keyword - | -6 | let handle = thread::spawn(move || { - | ^^^^^^^ -``` - -Rust *infers* how to capture `v`, and because `println!` only needs a reference -to `v`, the closure tries to borrow `v`. However, there’s a problem: Rust can’t -tell how long the spawned thread will run, so it doesn’t know if the reference -to `v` will always be valid. - -Listing 16-4 provides a scenario that’s more likely to have a reference to `v` -that won’t be valid: - -Filename: src/main.rs - -``` -use std::thread; - -fn main() { - let v = vec![1, 2, 3]; - - let handle = thread::spawn(|| { - println!("Here's a vector: {:?}", v); - }); - - drop(v); // oh no! - - handle.join().unwrap(); -} -``` - -Listing 16-4: A thread with a closure that attempts to capture a reference to -`v` from a main thread that drops `v` - -If we were allowed to run this code, there’s a possibility the spawned thread -will be immediately put in the background without running at all. The spawned -thread has a reference to `v` inside, but the main thread immediately drops -`v`, using the `drop` function we discussed in Chapter 15. Then, when the -spawned thread starts to execute, `v` is no longer valid, so a reference to it -is also invalid. Oh no! - -To fix the compiler error in Listing 16-3, we can use the error message’s -advice: - -``` -help: to force the closure to take ownership of `v` (and any other referenced -variables), use the `move` keyword - | -6 | let handle = thread::spawn(move || { - | ^^^^^^^ -``` - -By adding the `move` keyword before the closure, we force the closure to take -ownership of the values it’s using rather than allowing Rust to infer that it -should borrow the values. The modification to Listing 16-3 shown in Listing -16-5 will compile and run as we intend: - -Filename: src/main.rs - -``` -use std::thread; - -fn main() { - let v = vec![1, 2, 3]; - - let handle = thread::spawn(move || { - println!("Here's a vector: {:?}", v); - }); - - handle.join().unwrap(); -} -``` - -Listing 16-5: Using the `move` keyword to force a closure to take ownership of -the values it uses - -What would happen to the code in Listing 16-4 where the main thread called -`drop` if we use a `move` closure? Would `move` fix that case? Unfortunately, -no; we would get a different error because what Listing 16-4 is trying to do -isn’t allowed for a different reason. If we add `move` to the closure, we would -move `v` into the closure’s environment, and we could no longer call `drop` on -it in the main thread. We would get this compiler error instead: - -``` -error[E0382]: use of moved value: `v` - --> src/main.rs:10:10 - | -6 | let handle = thread::spawn(move || { - | ------- value moved (into closure) here -... -10 | drop(v); // oh no! - | ^ value used here after move - | - = note: move occurs because `v` has type `std::vec::Vec`, which does - not implement the `Copy` trait -``` - -Rust’s ownership rules have saved us again! We got an error from the code in -Listing 16-3 because Rust was being conservative and only borrowing `v` for the -thread, which meant the main thread could theoretically invalidate the spawned -thread’s reference. By telling Rust to move ownership of `v` to the spawned -thread, we’re guaranteeing Rust that the main thread won’t use `v` anymore. If -we change Listing 16-4 in the same way, we’re then violating the ownership -rules when we try to use `v` in the main thread. The `move` keyword overrides -Rust’s conservative default of borrowing; it doesn’t let us violate the -ownership rules. - -With a basic understanding of threads and the thread API, let’s look at what we -can *do* with threads. - -## Message Passing to Transfer Data Between Threads - -One increasingly popular approach to ensuring safe concurrency is *message -passing*, where threads or actors communicate by sending each other messages -containing data. Here’s the idea in a slogan from the Go language documentation: - -> Do not communicate by sharing memory; instead, share memory by -> communicating. -> -> --Effective Go at *http://golang.org/doc/effective_go.html* - -One major tool Rust has for accomplishing message sending concurrency is the -*channel*, a programming concept that Rust’s standard library provides an -implementation of. You can imagine a channel in programming like a channel of -water, such as a stream or a river. If you put something like a rubber duck or -a boat into a stream, it will travel downstream to the end of the river. - -A channel in programming has two halves: a transmitter and a receiver. The -transmitter half is the upstream location where we put rubber ducks into the -river, and the receiver half is where the rubber duck ends up downstream. One -part of our code calls methods on the transmitter with the data we want to -send, and another part checks the receiving end for arriving messages. A -channel is said to be *closed* if either the transmitter or receiver half is -dropped. - -Here, we’ll work up to a program that has one thread to generate values and -send them down a channel, and another thread that will receive the values and -print them out. We’ll be sending simple values between threads using a channel -to illustrate the feature. Once you’re familiar with the technique, you could -use channels to implement a chat system or a system where many threads perform -parts of a calculation and send the parts to one thread that aggregates the -results. - -First, in Listing 16-6, we’ll create a channel but not do anything with it. -Note that this won’t compile yet because Rust can’t tell what type of values we -want to send over the channel: - -Filename: src/main.rs - -``` -use std::sync::mpsc; - -fn main() { - let (tx, rx) = mpsc::channel(); -} -``` - -Listing 16-6: Creating a channel and assigning the two halves to `tx` and `rx` - -We create a new channel using the `mpsc::channel` function; `mpsc` stands for -*multiple producer, single consumer*. In short, the way Rust’s standard library -implements channels means a channel can have multiple *sending* ends that -produce values but only one *receiving* end that consumes those values. Imagine -multiple rivers and streams flowing together into one big river: everything -sent down any of the streams will end up in one river at the end. We’ll start -with a single producer for now, but we’ll add multiple producers when we get -this example working. - -The `mpsc::channel` function returns a tuple, the first element of which is the -sending end and the second element is the receiving end. The abbreviations `tx` -and `rx` are traditionally used in many fields for *transmitter* and *receiver* -respectively, so we name our variables as such to indicate each end. We’re -using a `let` statement with a pattern that destructures the tuples; we’ll -discuss the use of patterns in `let` statements and destructuring in Chapter -18. Using a `let` statement this way is a convenient approach to extract the -pieces of the tuple returned by `mpsc::channel`. - -Let’s move the transmitting end into a spawned thread and have it send one -string so the spawned thread is communicating with the main thread, as shown in -Listing 16-7. This is like putting a rubber duck in the river upstream or -sending a chat message from one thread to another: - -Filename: src/main.rs - -``` -use std::thread; -use std::sync::mpsc; - -fn main() { - let (tx, rx) = mpsc::channel(); - - thread::spawn(move || { - let val = String::from("hi"); - tx.send(val).unwrap(); - }); -} -``` - -Listing 16-7: Moving `tx` to a spawned thread and sending “hi” - -Again, we’re using `thread::spawn` to create a new thread and then using `move` -to move `tx` into the closure so the spawned thread owns `tx`. The spawned -thread needs to own the transmitting end of the channel to be able to send -messages through the channel. - -The transmitting end has a `send` method that takes the value we want to send. -The `send` method returns a `Result` type, so if the receiving end has -already been dropped and there’s nowhere to send a value, the send operation -will return an error. In this example, we’re calling `unwrap` to panic in case -of an error. But in a real application, we would handle it properly: return to -Chapter 9 to review strategies for proper error handling. - -In Listing 16-8, we’ll get the value from the receiving end of the channel in -the main thread. This is like retrieving the rubber duck from the water at the -end of the river or like getting a chat message: - -Filename: src/main.rs - -``` -use std::thread; -use std::sync::mpsc; - -fn main() { - let (tx, rx) = mpsc::channel(); - - thread::spawn(move || { - let val = String::from("hi"); - tx.send(val).unwrap(); - }); - - let received = rx.recv().unwrap(); - println!("Got: {}", received); -} -``` - -Listing 16-8: Receiving the value “hi” in the main thread and printing it - -The receiving end of a channel has two useful methods: `recv` and `try_recv`. -We’re using `recv`, short for *receive*, which will block the main thread’s -execution and wait until a value is sent down the channel. Once a value is -sent, `recv` will return it in a `Result`. When the sending end of the -channel closes, `recv` will return an error to signal that no more values will -be coming. - -The `try_recv` method doesn’t block, but will instead return a `Result` -immediately: an `Ok` value holding a message if one is available and an `Err` -value if there aren’t any messages this time. Using `try_recv` is useful if -this thread has other work to do while waiting for messages: we could write a -loop that calls `try_recv` every so often, handles a message if one is -available, and otherwise does other work for a little while until checking -again. - -We’ve used `recv` in this example for simplicity; we don’t have any other work -for the main thread to do other than wait for messages, so blocking the main -thread is appropriate. - -When we run the code in Listing 16-8, we’ll see the value printed from the main -thread: - -``` -Got: hi -``` - -Perfect! - -### Channels and Ownership Transference - -The ownership rules play a vital role in message sending because they help us -write safe, concurrent code. Preventing errors in concurrent programming is the -advantage we get by making the trade-off of having to think about ownership -throughout our Rust programs. Let’s do an experiment to show how channels and -ownership work together to prevent problems: we’ll try to use a `val` value in -the spawned thread *after* we’ve sent it down the channel. Try compiling the -code in Listing 16-9: - -Filename: src/main.rs - -``` -use std::thread; -use std::sync::mpsc; - -fn main() { - let (tx, rx) = mpsc::channel(); - - thread::spawn(move || { - let val = String::from("hi"); - tx.send(val).unwrap(); - println!("val is {}", val); - }); - - let received = rx.recv().unwrap(); - println!("Got: {}", received); -} -``` - -Listing 16-9: Attempting to use `val` after we’ve sent it down the channel - -Here, we try to print `val` after we’ve sent it down the channel via `tx.send`. -Allowing this would be a bad idea: once the value has been sent to another -thread, that thread could modify or drop it before we try to use the value -again. Potentially, the other thread's modifications could cause errors or -unexpected results due to inconsistent or nonexistent data. However, Rust gives -us an error if we try to compile the code in Listing 16-9: - -``` -error[E0382]: use of moved value: `val` - --> src/main.rs:10:31 - | -9 | tx.send(val).unwrap(); - | --- value moved here -10 | println!("val is {}", val); - | ^^^ value used here after move - | - = note: move occurs because `val` has type `std::string::String`, which does -not implement the `Copy` trait -``` - -Our concurrency mistake has caused a compile time error. The `send` function -takes ownership of its parameter, and when the value is moved, the receiver -takes ownership of it. This stops us from accidentally using the value again -after sending it; the ownership system checks that everything is okay. - -### Sending Multiple Values and Seeing the Receiver Waiting - -The code in Listing 16-8 compiled and ran, but it didn’t clearly show us that -two separate threads were talking to each other over the channel. In Listing -16-10 we’ve made some modifications that will prove the code in Listing 16-8 is -running concurrently: the spawned thread will now send multiple messages and -pause for a second between each message: - -Filename: src/main.rs - -``` -use std::thread; -use std::sync::mpsc; -use std::time::Duration; - -fn main() { - let (tx, rx) = mpsc::channel(); - - thread::spawn(move || { - let vals = vec![ - String::from("hi"), - String::from("from"), - String::from("the"), - String::from("thread"), - ]; - - for val in vals { - tx.send(val).unwrap(); - thread::sleep(Duration::from_secs(1)); - } - }); - - for received in rx { - println!("Got: {}", received); - } -} -``` - -Listing 16-10: Sending multiple messages and pausing between each one - -This time, the spawned thread has a vector of strings that we want to send to -the main thread. We iterate over them, sending each individually, and pause -between each by calling the `thread::sleep` function with a `Duration` value of -one second. - -In the main thread, we’re not calling the `recv` function explicitly anymore: -instead, we’re treating `rx` as an iterator. For each value received, we’re -printing it. When the channel is closed, iteration will end. - -When running the code in Listing 16-10, you should see the following output -with a one second pause in between each line: - -``` -Got: hi -Got: from -Got: the -Got: thread -``` - -Because we don’t have any code that pauses or delays in the `for` loop in the -main thread, we can tell that the main thread is waiting to receive values from -the spawned thread. - -### Creating Multiple Producers by Cloning the Transmitter - -Earlier we mentioned that `mpsc` was an acronym for *multiple* *producer, -single consumer*. Let’s put `mpsc` to use and expand the code in Listing 16-10 -to create multiple threads that all send values to the same receiver. We can do -so by cloning the transmitting half of the channel, as shown in Listing 16-11: - -Filename: src/main.rs - -``` -// --snip-- - -let (tx, rx) = mpsc::channel(); - -let tx1 = mpsc::Sender::clone(&tx); -thread::spawn(move || { - let vals = vec![ - String::from("hi"), - String::from("from"), - String::from("the"), - String::from("thread"), - ]; - - for val in vals { - tx1.send(val).unwrap(); - thread::sleep(Duration::from_secs(1)); - } -}); - -thread::spawn(move || { - let vals = vec![ - String::from("more"), - String::from("messages"), - String::from("for"), - String::from("you"), - ]; - - for val in vals { - tx.send(val).unwrap(); - thread::sleep(Duration::from_secs(1)); - } -}); - -for received in rx { - println!("Got: {}", received); -} - -// --snip-- -``` - -Listing 16-11: Sending multiple messages from multiple producers - -This time, before we create the first spawned thread, we call `clone` on the -sending end of the channel. This will give us a new sending handle we can pass -to the first spawned thread. We pass the original sending end of the channel to -a second spawned thread. This gives us two threads, each sending different -messages to the receiving end of the channel. - -When you run the code, you’ll *probably* see output like this: - -``` -Got: hi -Got: more -Got: from -Got: messages -Got: for -Got: the -Got: thread -Got: you -``` - -You might see the values in another order; it depends on your system. This is -what makes concurrency interesting as well as difficult. If you experiment with -`thread::sleep`, giving it various values in the different threads, each run -will be more non-deterministic and create different output each time. - -Now that we’ve looked at how channels work, let’s look at a different method of -concurrency. - -## Shared State Concurrency - -Message passing is a fine way of handling concurrency, but it’s not the only -one. Consider this part of the slogan from the Go language documentation again: -“communicate by sharing memory.” - -What would communicating by sharing memory look like? In addition, why would -message passing enthusiasts not use it and do the opposite instead? - -In a way, channels in any programming language are similar to single ownership, -because once you transfer a value down a channel, you should no longer use that -value. Shared memory concurrency is like multiple ownership: multiple threads -can access the same memory location at the same time. As you saw in Chapter 15 -where smart pointers made multiple ownership possible, multiple ownership can -add additional complexity because these different owners need managing. Rust’s -type system and ownership rules greatly assist in getting this management -correct. For an example, let’s look at mutexes, one of the more common -concurrency primitives for shared memory. - -### Mutexes Allow Access to Data from One Thread at a Time - -A *mutex* is an abbreviation for “mutual exclusion,” as in, it only allows one -thread to access some data at any given time. To access the data in a mutex, a -thread must first signal that it wants access by asking to acquire the mutex’s -*lock*. The lock is a data structure that is part of the mutex that keeps track -of who currently has exclusive access to the data. Therefore, we describe the -mutex as *guarding* the data it holds via the locking system. - -Mutexes have a reputation for being difficult to use because you have to -remember two rules: - -1. You must attempt to acquire the lock before using the data. -2. When you’re done with the data that the mutex guards, you must unlock the - data so other threads can acquire the lock. - -For a real-world metaphor of a mutex, imagine a panel discussion at a -conference with only one microphone. Before a panelist can speak, they have to -ask or signal that they want to use the microphone. When they get the -microphone, they can talk for as long as they want to and then hand the -microphone to the next panelist who requests to speak. If a panelist forgets to -hand the microphone off when they’re finished with it, no one else is able to -speak. If management of the shared microphone goes wrong, the panel wouldn’t -work as planned! - -Management of mutexes can be incredibly tricky to get right, which is why so -many people are enthusiastic about channels. However, thanks to Rust’s type -system and ownership rules, we can’t get locking and unlocking wrong. - -#### The API of `Mutex` - -As an example of how to use a mutex, let’s start by using a mutex in a -single-threaded context, as shown in Listing 16-12: - -Filename: src/main.rs - -``` -use std::sync::Mutex; - -fn main() { - let m = Mutex::new(5); - - { - let mut num = m.lock().unwrap(); - *num = 6; - } - - println!("m = {:?}", m); -} -``` - -Listing 16-12: Exploring the API of `Mutex` in a single-threaded context for -simplicity - -As with many types, we create a `Mutex` using the associated function `new`. -To access the data inside the mutex, we use the `lock` method to acquire the -lock. This call will block the current thread so it can’t do any work until -it’s our turn to have the lock. - -The call to `lock` would fail if another thread holding the lock panicked. In -that case, no one would ever be able to get the lock, so we’ve chosen to -`unwrap` and have this thread panic if we’re in that situation. - -After we’ve acquired the lock, we can treat the return value, named `num` in -this case, as a mutable reference to the data inside. The type system ensures -that we acquire a lock before using the value in `m`: `Mutex` is not an -`i32`, so we *must* acquire the lock to be able to use the `i32` value. We -can’t forget; the type system won’t let us access the inner `i32` otherwise. - -As you might suspect, `Mutex` is a smart pointer. More accurately, the call -to `lock` *returns* a smart pointer called `MutexGuard`. This smart pointer -implements `Deref` to point at our inner data; the smart pointer also has a -`Drop` implementation that releases the lock automatically when a `MutexGuard` -goes out of scope, which happens at the end of the inner scope in Listing -16-12. As a result, we don’t risk forgetting to release the lock and blocking -the mutex from being used by other threads because the lock release happens -automatically. - -After dropping the lock, we can print the mutex value and see that we were able -to change the inner `i32` to 6. - -#### Sharing a `Mutex` Between Multiple Threads - -Now, let’s try to share a value between multiple threads using `Mutex`. -We’ll spin up 10 threads and have them each increment a counter value by 1, so -the counter goes from 0 to 10. Note that the next few examples will have -compiler errors, and we’ll use those errors to learn more about using -`Mutex` and how Rust helps us use it correctly. Listing 16-13 has our -starting example: - -Filename: src/main.rs - -``` -use std::sync::Mutex; -use std::thread; - -fn main() { - let counter = Mutex::new(0); - let mut handles = vec![]; - - for _ in 0..10 { - let handle = thread::spawn(move || { - let mut num = counter.lock().unwrap(); - - *num += 1; - }); - handles.push(handle); - } - - for handle in handles { - handle.join().unwrap(); - } - - println!("Result: {}", *counter.lock().unwrap()); -} -``` - -Listing 16-13: Ten threads each increment a counter guarded by a `Mutex` - -We’re creating a `counter` variable to hold an `i32` inside a `Mutex`, as we -did in Listing 16-12. Next, we’re creating 10 threads by mapping over a range -of numbers. We use `thread::spawn` and give all the threads the same closure, -one that moves the counter into the thread, acquires a lock on the `Mutex` -by calling the `lock` method, and then adds 1 to the value in the mutex. When a -thread finishes running its closure, `num` will go out of scope and release the -lock so another thread can acquire it. - -In the main thread, we collect all the join handles, as we did in Listing 16-2, -and then call `join` on each to make sure all the threads finish. At that -point, the main thread will acquire the lock and print the result of this -program. - -We hinted that this example won’t compile, now let’s find out why! - -``` -error[E0382]: capture of moved value: `counter` - --> src/main.rs:10:27 - | -9 | let handle = thread::spawn(move || { - | ------- value moved (into closure) here -10 | let mut num = counter.lock().unwrap(); - | ^^^^^^^ value captured here after move - | - = note: move occurs because `counter` has type `std::sync::Mutex`, - which does not implement the `Copy` trait - -error[E0382]: use of moved value: `counter` - --> src/main.rs:21:29 - | -9 | let handle = thread::spawn(move || { - | ------- value moved (into closure) here -... -21 | println!("Result: {}", *counter.lock().unwrap()); - | ^^^^^^^ value used here after move - | - = note: move occurs because `counter` has type `std::sync::Mutex`, - which does not implement the `Copy` trait - -error: aborting due to 2 previous errors -``` - -The error message states that the `counter` value is moved into the closure and -then is captured when we call `lock`. That description sounds like what we -wanted, but it’s not allowed! - -Let’s figure this out by simplifying the program. Instead of making 10 threads -in a `for` loop, let’s just make two threads without a loop and see what -happens. Replace the first `for` loop in Listing 16-13 with this code instead: - -``` -let handle = thread::spawn(move || { - let mut num = counter.lock().unwrap(); - - *num += 1; -}); -handles.push(handle); - -let handle2 = thread::spawn(move || { - let mut num2 = counter.lock().unwrap(); - - *num2 += 1; -}); -handles.push(handle2); -``` - -We make two threads and change the variable names used with the second thread -to `handle2` and `num2`. When we run the code this time, compiling gives us the -following: - -``` -error[E0382]: capture of moved value: `counter` - --> src/main.rs:16:24 - | -8 | let handle = thread::spawn(move || { - | ------- value moved (into closure) here -... -16 | let mut num2 = counter.lock().unwrap(); - | ^^^^^^^ value captured here after move - | - = note: move occurs because `counter` has type `std::sync::Mutex`, - which does not implement the `Copy` trait - -error[E0382]: use of moved value: `counter` - --> src/main.rs:26:29 - | -8 | let handle = thread::spawn(move || { - | ------- value moved (into closure) here -... -26 | println!("Result: {}", *counter.lock().unwrap()); - | ^^^^^^^ value used here after move - | - = note: move occurs because `counter` has type `std::sync::Mutex`, - which does not implement the `Copy` trait - -error: aborting due to 2 previous errors -``` - -Aha! The first error message indicates that `counter` is moved into the closure -for the thread associated with `handle`. That move is preventing us from -capturing `counter` when we try to call `lock` on it and store the result in -`num2` in the second thread! So Rust is telling us that we can’t move ownership -of `counter` into multiple threads. This was hard to see earlier because our -threads were in a loop, and Rust can’t point to different threads in different -iterations of the loop. Let’s fix the compiler error with a multiple-ownership -method we discussed in Chapter 15. - -#### Multiple Ownership with Multiple Threads - -In Chapter 15, we gave a value multiple owners by using the smart pointer -`Rc` to create a reference-counted value. Let’s do the same here and see -what happens. We’ll wrap the `Mutex` in `Rc` in Listing 16-14 and clone -the `Rc` before moving ownership to the thread. Now that we’ve seen the -errors, we’ll also switch back to using the `for` loop, and we’ll keep the -`move` keyword with the closure: - -Filename: src/main.rs - -``` -use std::rc::Rc; -use std::sync::Mutex; -use std::thread; - -fn main() { - let counter = Rc::new(Mutex::new(0)); - let mut handles = vec![]; - - for _ in 0..10 { - let counter = Rc::clone(&counter); - let handle = thread::spawn(move || { - let mut num = counter.lock().unwrap(); - - *num += 1; - }); - handles.push(handle); - } - - for handle in handles { - handle.join().unwrap(); - } - - println!("Result: {}", *counter.lock().unwrap()); -} -``` - -Listing 16-14: Attempting to use `Rc` to allow multiple threads to own the -`Mutex` - -Once again, we compile and get... different errors! The compiler is teaching us -a lot. - -``` -error[E0277]: the trait bound `std::rc::Rc>: -std::marker::Send` is not satisfied in `[closure@src/main.rs:11:36: -15:10 counter:std::rc::Rc>]` - --> src/main.rs:11:22 - | -11 | let handle = thread::spawn(move || { - | ^^^^^^^^^^^^^ `std::rc::Rc>` -cannot be sent between threads safely - | - = help: within `[closure@src/main.rs:11:36: 15:10 -counter:std::rc::Rc>]`, the trait `std::marker::Send` is -not implemented for `std::rc::Rc>` - = note: required because it appears within the type -`[closure@src/main.rs:11:36: 15:10 counter:std::rc::Rc>]` - = note: required by `std::thread::spawn` -``` - -Wow, that error message is very wordy! Here are some important parts to focus -on: the first inline error says `` `std::rc::Rc>` cannot -be sent between threads safely ``. The reason for this is in the next important -part to focus on, the error message. The distilled error message says `` the -trait bound `Send` is not satisfied ``. We’ll talk about `Send` in the next -section: it’s one of the traits that ensures the types we use with threads are -meant for use in concurrent situations. - -Unfortunately, `Rc` is not safe to share across threads. When `Rc` -manages the reference count, it adds to the count for each call to `clone` and -subtracts from the count when each clone is dropped. But it doesn’t use any -concurrency primitives to make sure that changes to the count can’t be -interrupted by another thread. This could lead to wrong counts—subtle bugs that -could in turn lead to memory leaks or a value being dropped before we’re done -with it. What we need is a type exactly like `Rc` but one that makes changes -to the reference count in a thread-safe way. - -#### Atomic Reference Counting with `Arc` - -Fortunately, `Arc` *is* a type like `Rc` that is safe to use in -concurrent situations. The ‘a’ stands for *atomic*, meaning it’s an *atomically -reference counted* type. Atomics are an additional kind of concurrency -primitive that we won’t cover in detail here: see the standard library -documentation for `std::sync::atomic` for more details. At this point, you just -need to know that atomics work like primitive types but are safe to share -across threads. - -You might then wonder why all primitive types aren’t atomic and why standard -library types aren’t implemented to use `Arc` by default. The reason is that -thread safety comes with a performance penalty that you only want to pay when -you really need to. If you’re just performing operations on values within a -single thread, your code can run faster if it doesn’t have to enforce the -guarantees atomics provide. - -Let’s return to our example: `Arc` and `Rc` have the same API, so we fix -our program by changing the `use` line, the call to `new`, and the call to -`clone`. The code in Listing 16-15 will finally compile and run: - -Filename: src/main.rs - -``` -use std::sync::{Mutex, Arc}; -use std::thread; - -fn main() { - let counter = Arc::new(Mutex::new(0)); - let mut handles = vec![]; - - for _ in 0..10 { - let counter = Arc::clone(&counter); - let handle = thread::spawn(move || { - let mut num = counter.lock().unwrap(); - - *num += 1; - }); - handles.push(handle); - } - - for handle in handles { - handle.join().unwrap(); - } - - println!("Result: {}", *counter.lock().unwrap()); -} -``` - -Listing 16-15: Using an `Arc` to wrap the `Mutex` to be able to share -ownership across multiple threads - -This code will print the following: - -``` -Result: 10 -``` - -We did it! We counted from 0 to 10, which may not seem very impressive, but it -did teach us a lot about `Mutex` and thread safety. You could also use this -program’s structure to do more complicated operations than just incrementing a -counter. Using this strategy, you can divide a calculation into independent -parts, split those parts across threads, then use a `Mutex` to have each -thread update the final result with its part. - -### Similarities Between `RefCell`/`Rc` and `Mutex`/`Arc` - -You might have noticed that `counter` is immutable, but we could get a mutable -reference to the value inside it; this means `Mutex` provides interior -mutability, like the `Cell` family does. In the same way we used `RefCell` -in Chapter 15 to allow us to mutate contents inside an `Rc`, we use -`Mutex` to mutate contents inside an `Arc`. - -Another detail to note is that Rust can’t protect us from all kinds of logic -errors when we use `Mutex`. Recall in Chapter 15 that using `Rc` came -with the risk of creating reference cycles, where two `Rc` values refer to -each other, causing memory leaks. Similarly, `Mutex` comes with the risk of -creating *deadlocks*. These occur when an operation needs to lock two resources -and two threads have each acquired one of the locks, causing them to wait for -each other forever. If you’re interested in deadlocks, try creating a Rust -program that has a deadlock; then research deadlock mitigation strategies for -mutexes in any language and have a go at implementing them in Rust. The -standard library API documentation for `Mutex` and `MutexGuard` offers -useful information. - -We’ll round out this chapter by talking about the `Send` and `Sync` traits, and -how we can use them with custom types. - -## Extensible Concurrency with the `Sync` and `Send` Traits - -Interestingly, the Rust language has *very* few concurrency features. Almost -every concurrency feature we’ve talked about so far in this chapter has been -part of the standard library, not the language. Our options for handling -concurrency are not limited to the language or the standard library; we can -write our own concurrency features or use those written by others. - -However, two concurrency concepts are embedded in the language: the -`std::marker` traits `Sync` and `Send`. - -### Allowing Transference of Ownership Between Threads with `Send` - -The `Send` marker trait indicates that ownership of the type implementing -`Send` can be transferred between threads. Almost every Rust type is `Send`, -but there are some exceptions, including `Rc`: this cannot be `Send` because -if we cloned an `Rc` value and tried to transfer ownership of the clone to -another thread, both threads might update the reference count at the same time. -For this reason, `Rc` is implemented for use in single-threaded situations -where you don’t want to pay the thread-safe performance penalty. - -Therefore, Rust’s type system and trait bounds ensure that we can never -accidentally send an `Rc` value across threads unsafely. When we tried to do -this in Listing 16-14, we got the error `the trait Send is not implemented for -Rc>`. When we switched to `Arc`, which is `Send`, the code -compiled. - -Any type composed entirely of `Send` types is automatically marked as `Send` as -well. Almost all primitive types are `Send`, aside from raw pointers, which -we’ll discuss in Chapter 19. - -### Allowing Access from Multiple Threads with `Sync` - -The `Sync` marker trait indicates that it is safe for the type implementing -`Sync` to be referenced from multiple threads. In other words, any type `T` is -`Sync` if `&T` (a reference to `T`) is `Send`, meaning the reference can be -sent safely to another thread. Similar to `Send`, primitive types are `Sync` -and types composed entirely of types that are `Sync` are also `Sync`. - -The smart pointer `Rc` is also not `Sync` for the same reasons that it’s not -`Send`. The `RefCell` type (which we talked about in Chapter 15) and the -family of related `Cell` types are not `Sync`. The implementation of borrow -checking that `RefCell` does at runtime is not thread-safe. The smart -pointer `Mutex` is `Sync` and can be used to share access with multiple -threads, as you saw in the “Sharing a `Mutex` Between Multiple Threads” -section. - -### Implementing `Send` and `Sync` Manually Is Unsafe - -Because types that are made up of `Send` and `Sync` traits are automatically -also `Send` and `Sync`, we don’t have to implement those traits manually. As -marker traits, they don’t even have any methods to implement. They’re just -useful for enforcing invariants related to concurrency. - -Manually implementing these traits involves implementing unsafe Rust code. -We’ll talk about using unsafe Rust code in Chapter 19; for now, the important -information is that building new concurrent types not made up of `Send` and -`Sync` parts requires careful thought to uphold the safety guarantees. -The Rustonomicon at *https://doc.rust-lang.org/stable/nomicon/* has more -information about these guarantees and how to uphold them. - -## Summary - -This isn’t the last you’ll see of concurrency in this book: the project in -Chapter 20 will use the concepts examined in this chapter in a more realistic -situation than the smaller examples discussed here. - -As mentioned earlier, because very little of how Rust handles concurrency is -part of the language, many concurrency solutions are implemented as crates. -These evolve more quickly than the standard library, so be sure to search -online for the current, state-of-the-art crates to use in multithreaded -situations. - -The Rust standard library provides channels for message passing and smart -pointer types, such as `Mutex` and `Arc`, that are safe to use in -concurrent contexts. The type system and the borrow checker ensure that the -code using these solutions won’t end up with data races or invalid references. -Once we get our code to compile, we can rest assured that it will happily run -on multiple threads without the kinds of hard-to-track-down bugs common in -other languages. Concurrent programming is no longer a concept to be afraid of: -go forth and make your programs concurrent, fearlessly! - -Next, we’ll talk about idiomatic ways to model problems and structure solutions -as your Rust programs get bigger. In addition, we’ll discuss how Rust’s idioms -relate to those you might be familiar with from object-oriented programming. diff --git a/second-edition/nostarch/chapter17.md b/second-edition/nostarch/chapter17.md deleted file mode 100644 index 4bbb004b9c..0000000000 --- a/second-edition/nostarch/chapter17.md +++ /dev/null @@ -1,1267 +0,0 @@ - -[TOC] - -# Is Rust an Object-Oriented Programming Language? - -Object-oriented programming (OOP) is a way of modeling programs. Objects came -from Simula in the 1960s. Those objects influenced Alan Kay’s programming -architecture where objects pass messages to each other. He coined the term -object-oriented programming in 1967 to describe this architecture. Many -competing definitions describe what OOP is; some definitions would classify -Rust as object oriented but other definitions would not. In this chapter, we’ll -explore certain characteristics that are commonly considered object oriented -and how those characteristics translate to idiomatic Rust. We’ll then show you -how to implement an object-oriented design pattern in Rust and discuss the -trade-offs of doing so versus implementing a solution using some of Rust’s -strengths instead. - -## What Does Object Oriented Mean? - -There is no consensus in the programming community about what features a -language needs to be considered object oriented. Rust is influenced by many -different programming paradigms, including OOP; for example, we explored the -features that came from functional programming in Chapter 13. Arguably, OOP -languages share certain common characteristics, namely objects, encapsulation, -and inheritance. Let’s look at what each of those characteristics mean and -whether Rust supports them. - -### Objects Contain Data and Behavior - -The book *Design Patterns: Elements of Reusable Object-Oriented Software*, -colloquially referred to as *The Gang of Four book*, is a catalog of -object-oriented design patterns. It defines OOP this way: - -> Object-oriented programs are made up of objects. An *object* packages both -> data and the procedures that operate on that data. The procedures are -> typically called *methods* or *operations*. - -Using this definition, Rust is object oriented: structs and enums have data, -and `impl` blocks provide methods on structs and enums. Even though structs and -enums with methods aren’t *called* objects, they provide the same -functionality, according to the Gang of Four’s definition of objects. - -### Encapsulation that Hides Implementation Details - -Another aspect commonly associated with OOP is the idea of *encapsulation*, -which means that the implementation details of an object aren’t accessible to -code using that object. Therefore, the only way to interact with an object is -through its public API; code using the object shouldn’t be able to reach into -the object’s internals and change data or behavior directly. This enables the -programmer to change and refactor an object’s internals without needing to -change the code that uses the object. - -We discussed how to control encapsulation in Chapter 7: we can use the `pub` -keyword to decide which modules, types, functions, and methods in our code -should be public, and by default everything else is private. For example, we -can define a struct `AveragedCollection` that has a field containing a vector -of `i32` values. The struct can also have a field that contains the average of -the values in the vector, meaning the average doesn’t have to be computed -on-demand whenever anyone needs it. In other words, `AveragedCollection` will -cache the calculated average for us. Listing 17-1 has the definition of the -`AveragedCollection` struct: - -Filename: src/lib.rs - -``` -pub struct AveragedCollection { - list: Vec, - average: f64, -} -``` - -Listing 17-1: An `AveragedCollection` struct that maintains a list of integers -and the average of the items in the collection - -The struct is marked `pub` so that other code can use it, but the fields within -the struct remain private. This is important in this case because we want to -ensure that whenever a value is added or removed from the list, the average is -also updated. We do this by implementing `add`, `remove`, and `average` methods -on the struct, as shown in Listing 17-2: - -Filename: src/lib.rs - -``` -impl AveragedCollection { - pub fn add(&mut self, value: i32) { - self.list.push(value); - self.update_average(); - } - - pub fn remove(&mut self) -> Option { - let result = self.list.pop(); - match result { - Some(value) => { - self.update_average(); - Some(value) - }, - None => None, - } - } - - pub fn average(&self) -> f64 { - self.average - } - - fn update_average(&mut self) { - let total: i32 = self.list.iter().sum(); - self.average = total as f64 / self.list.len() as f64; - } -} -``` - -Listing 17-2: Implementations of the public methods `add`, `remove`, and -`average` on `AveragedCollection` - -The public methods `add`, `remove`, and `average` are the only ways to modify -an instance of `AveragedCollection`. When an item is added to `list` using the -`add` method or removed using the `remove` method, the implementations of each -call the private `update_average` method that handles updating the `average` -field as well. - -We leave the `list` and `average` fields private so there is no way for -external code to add or remove items to the `list` field directly; otherwise, -the `average` field might become out of sync when the `list` changes. The -`average` method returns the value in the `average` field, allowing external -code to read the `average` but not modify it. - -Because we’ve encapsulated the implementation details of `AveragedCollection`, -we can easily change aspects, such as the data structure, in the future. For -instance, we could use a `HashSet` instead of a `Vec` for the `list` field. As -long as the signatures of the `add`, `remove`, and `average` public methods -stay the same, code using `AveragedCollection` wouldn’t need to change. If we -made `list` public instead, this wouldn’t necessarily be the case: `HashSet` -and `Vec` have different methods for adding and removing items, so the external -code would likely have to change if it was modifying `list` directly. - -If encapsulation is a required aspect for a language to be considered object -oriented, then Rust meets that requirement. The option to use `pub` or not for -different parts of code enables encapsulation of implementation details. - -### Inheritance as a Type System and as Code Sharing - -*Inheritance* is a mechanism whereby an object can inherit from another -object’s definition, thus gaining the parent object’s data and behavior without -you having to define them again. - -If a language must have inheritance to be an object-oriented language, then -Rust is not. There is no way to define a struct that inherits the parent -struct’s fields and method implementations. However, if you’re used to having -inheritance in your programming toolbox, you can use other solutions in Rust -depending on your reason for reaching for inheritance in the first place. - -You choose inheritance for two main reasons. One is for reuse of code: you can -implement particular behavior for one type, and inheritance enables you to -reuse that implementation for a different type. You can share Rust code using -default trait method implementations instead, which you saw in Listing 10-14 -when we added a default implementation of the `summarize` method on the -`Summary` trait. Any type implementing the `Summary` trait would have the -`summarize` method available on it without any further code. This is similar to -a parent class having an implementation of a method and an inheriting child -class also having the implementation of the method. We can also override the -default implementation of the `summarize` method when we implement the -`Summary` trait, which is similar to a child class overriding the -implementation of a method inherited from a parent class. - -The other reason to use inheritance relates to the type system: to enable a -child type to be used in the same places as the parent type. This is also -called *polymorphism*, which means that you can substitute multiple objects for -each other at runtime if they share certain characteristics. - -> ### Polymorphism -> -> To many people, polymorphism is synonymous with inheritance. But it’s -> actually a more general concept that refers to code that can work with data -> of multiple types. For inheritance, those types are generally subclasses. -> -> Rust instead uses generics to abstract over different possible types and -> trait bounds to impose constraints on what those types must provide. This is -> sometimes called *bounded parametric polymorphism*. - -Inheritance has recently fallen out of favor as a programming design solution -in many programming languages because it’s often at risk of sharing more code -than needs be. Subclasses shouldn’t always share all characteristics of their -parent class but will do so with inheritance. This can make a program’s design -less flexible and introduces the possibility of calling methods on subclasses -that don’t make sense or that cause errors because the methods don’t apply to -the subclass. Some languages will also only allow a subclass to inherit from -one class, further restricting the flexibility of a program’s design. - -For these reasons, Rust takes a different approach, using trait objects instead -of inheritance. Let’s look at how trait objects enable polymorphism in Rust. - -## Using Trait Objects that Allow for Values of Different Types - -In Chapter 8, we mentioned that one limitation of vectors is that they can only -store elements of one type. We created a workaround in Listing 8-10 where we -defined a `SpreadsheetCell` enum that had variants to hold integers, floats, -and text. This meant we could store different types of data in each cell and -still have a vector that represented a row of cells. This is a perfectly good -solution when our interchangeable items are a fixed set of types that we know -when our code is compiled. - -However, sometimes we want our library user to be able to extend the set of -types that are valid in a particular situation. To show how we might achieve -this, we’ll create an example graphical user interface (GUI) tool that iterates -through a list of items, calling a `draw` method on each one to draw it to the -screen—a common technique for GUI tools. We’ll create a library crate called -`gui` that contains the structure of a GUI library. This crate might include -some types for people to use, such as `Button` or `TextField`. In addition, -`gui` users will want to create their own types that can be drawn: for -instance, one programmer might add an `Image` and another might add a -`SelectBox`. - -We won’t implement a fully fledged GUI library for this example but will show -how the pieces would fit together. At the time of writing the library, we can’t -know and define all the types other programmers might want to create. But we do -know that `gui` needs to keep track of many values of different types, and it -needs to call a `draw` method on each of these differently typed values. It -doesn’t need to know exactly what will happen when we call the `draw` method, -just that the value will have that method available for us to call. - -To do this in a language with inheritance, we might define a class named -`Component` that has a method named `draw` on it. The other classes, such as -`Button`, `Image`, and `SelectBox`, would inherit from `Component` and thus -inherit the `draw` method. They could each override the `draw` method to define -their custom behavior, but the framework could treat all of the types as if -they were `Component` instances and call `draw` on them. But because Rust -doesn’t have inheritance, we need another way to structure the `gui` library to -allow users to extend it with new types. - -### Defining a Trait for Common Behavior - -To implement the behavior we want `gui` to have, we’ll define a trait named -`Draw` that will have one method named `draw`. Then we can define a vector that -takes a *trait object*. A trait object points to an instance of a type that -implements the trait we specify. We create a trait object by specifying some -sort of pointer, such as a `&` reference or a `Box` smart pointer, and then -specifying the relevant trait (we’ll talk about the reason trait objects must -use a pointer in Chapter 19 in the section “Dynamically Sized Types & Sized”). -We can use trait objects in place of a generic or concrete type. Wherever we -use a trait object, Rust’s type system will ensure at compile time that any -value used in that context will implement the trait object’s trait. -Consequently, we don’t need to know all the possible types at compile time. - -We’ve mentioned that in Rust we refrain from calling structs and enums -“objects” to distinguish them from other languages’ objects. In a struct or -enum, the data in the struct fields and the behavior in `impl` blocks are -separated, whereas in other languages the data and behavior combined into one -concept is often labeled an object. However, trait objects *are* more like -objects in other languages in the sense that they combine data and behavior. -But trait objects differ from traditional objects in that we can’t add data to -a trait object. Trait objects aren’t as generally useful as objects in other -languages: their specific purpose is to allow abstraction across common -behavior. - -Listing 17-3 shows how to define a trait named `Draw` with one method named -`draw`: - -Filename: src/lib.rs - -``` -pub trait Draw { - fn draw(&self); -} -``` - -Listing 17-3: Definition of the `Draw` trait - -This syntax should look familiar from our discussions on how to define traits -in Chapter 10. Next comes some new syntax: Listing 17-4 defines a struct named -`Screen` that holds a vector named `components`. This vector is of type -`Box`, which is a trait object: it’s a stand-in for any type inside a -`Box` that implements the `Draw` trait. - -Filename: src/lib.rs - -``` -pub struct Screen { - pub components: Vec>, -} -``` - -Listing 17-4: Definition of the `Screen` struct with a `components` field -holding a vector of trait objects that implement the `Draw` trait - -On the `Screen` struct, we’ll define a method named `run` that will call the -`draw` method on each of its `components`, as shown in Listing 17-5: - -Filename: src/lib.rs - -``` -impl Screen { - pub fn run(&self) { - for component in self.components.iter() { - component.draw(); - } - } -} -``` - -Listing 17-5: Implementing a `run` method on `Screen` that calls the `draw` -method on each component - -This works differently than defining a struct that uses a generic type -parameter with trait bounds. A generic type parameter can only be substituted -with one concrete type at a time, whereas trait objects allow for multiple -concrete types to fill in for the trait object at runtime. For example, we -could have defined the `Screen` struct using a generic type and a trait bound -as in Listing 17-6: - -Filename: src/lib.rs - -``` -pub struct Screen { - pub components: Vec, -} - -impl Screen - where T: Draw { - pub fn run(&self) { - for component in self.components.iter() { - component.draw(); - } - } -} -``` - -Listing 17-6: An alternate implementation of the `Screen` struct and its `run` -method using generics and trait bounds - -This restricts us to a `Screen` instance that has a list of components all of -type `Button` or all of type `TextField`. If you’ll only ever have homogeneous -collections, using generics and trait bounds is preferable because the -definitions will be monomorphized at compile time to use the concrete types. - -On the other hand, with the method using trait objects, one `Screen` instance -can hold a `Vec` that contains a `Box