├── first-edition ├── src │ ├── chapter_1.md │ ├── effective-rust.md │ ├── syntax-and-semantics.md │ ├── attributes.md │ ├── using-rust-without-the-standard-library.md │ ├── type-aliases.md │ ├── drop.md │ ├── if.md │ ├── comments.md │ ├── unsized-types.md │ ├── if-let.md │ ├── conditional-compilation.md │ ├── README.md │ ├── SUMMARY.md │ ├── const-and-static.md │ ├── release-channels.md │ ├── glossary.md │ ├── borrow-and-asref.md │ ├── deref-coercions.md │ ├── ufcs.md │ ├── match.md │ ├── enums.md │ ├── operators-and-overloading.md │ ├── raw-pointers.md │ └── vectors.md └── book.toml ├── .gitignore ├── ci ├── stable-check │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── main.rs └── build.sh ├── second-edition ├── src │ ├── img │ │ ├── hello.png │ │ ├── trpl15-02.svg │ │ ├── trpl15-01.svg │ │ ├── trpl15-04.svg │ │ └── trpl04-01.svg │ ├── appendix-00.md │ ├── ch04-00-understanding-ownership.md │ ├── ch17-00-oop.md │ ├── ch14-00-more-about-cargo.md │ ├── appendix-06-translation.md │ ├── ch05-00-structs.md │ ├── ch06-00-enums.md │ ├── ch14-05-extending-cargo.md │ ├── ch18-00-patterns.md │ ├── ch03-00-common-programming-concepts.md │ ├── ch19-00-advanced-features.md │ ├── ch08-00-common-collections.md │ ├── ch03-04-comments.md │ ├── ch07-00-modules.md │ ├── ch09-00-error-handling.md │ ├── ch14-04-installing-binaries.md │ ├── ch20-00-final-project-a-web-server.md │ ├── appendix-07-newest-features.md │ ├── ch13-00-functional-features.md │ ├── ch01-00-introduction.md │ ├── ch11-00-testing.md │ ├── ch14-01-release-profiles.md │ ├── ch15-00-smart-pointers.md │ ├── appendix-01-keywords.md │ ├── ch16-00-concurrency.md │ ├── ch12-00-an-io-project.md │ ├── ch01-01-installation.md │ ├── ch06-03-if-let.md │ ├── ch18-02-refutability.md │ └── ch12-02-reading-a-file.md ├── nostarch │ ├── odt │ │ ├── chapter02.doc │ │ ├── chapter03.docx │ │ ├── chapter04.docx │ │ ├── chapter05.docx │ │ ├── chapter06.docx │ │ ├── chapter07.docx │ │ ├── chapter08.docx │ │ └── chapter09.docx │ └── appendix.md ├── book.toml ├── dot │ ├── trpl15-02.dot │ ├── trpl04-01.dot │ ├── trpl15-01.dot │ ├── trpl04-05.dot │ ├── trpl04-02.dot │ ├── trpl04-04.dot │ ├── trpl04-06.dot │ ├── trpl04-03.dot │ └── trpl15-03.dot ├── Cargo.toml ├── LICENSE-MIT ├── doc-to-md.sh ├── nostarch.sh ├── style-guide.md ├── tools │ └── src │ │ └── bin │ │ ├── remove_links.rs │ │ ├── remove_markup.rs │ │ └── concat_chapters.rs └── spellcheck.sh ├── .gitattributes ├── redirects ├── compiler-plugins.md ├── if.md ├── drop.md ├── enums.md ├── ffi.md ├── loops.md ├── match.md ├── ufcs.md ├── if-let.md ├── macros.md ├── strings.md ├── structs.md ├── testing.md ├── traits.md ├── unsafe.md ├── vectors.md ├── attributes.md ├── closures.md ├── comments.md ├── functions.md ├── generics.md ├── glossary.md ├── iterators.md ├── lifetimes.md ├── mutability.md ├── ownership.md ├── patterns.md ├── bibliography.md ├── concurrency.md ├── raw-pointers.md ├── syntax-index.md ├── type-aliases.md ├── deref-coercions.md ├── documentation.md ├── effective-rust.md ├── error-handling.md ├── getting-started.md ├── guessing-game.md ├── method-syntax.md ├── primitive-types.md ├── trait-objects.md ├── unsized-types.md ├── associated-types.md ├── borrow-and-asref.md ├── const-and-static.md ├── procedural-macros.md ├── release-channels.md ├── variable-bindings.md ├── crates-and-modules.md ├── syntax-and-semantics.md ├── casting-between-types.md ├── the-stack-and-the-heap.md ├── choosing-your-guarantees.md ├── conditional-compilation.md ├── operators-and-overloading.md ├── references-and-borrowing.md ├── README.md ├── SUMMARY.md └── using-rust-without-the-standard-library.md ├── .travis.yml ├── index.md ├── .github ├── PULL_REQUEST_TEMPLATE.md └── ISSUE_TEMPLATE.md ├── LICENSE-MIT ├── CONTRIBUTING.md └── README.md /first-edition/src/chapter_1.md: -------------------------------------------------------------------------------- 1 | # Chapter 1 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | book/ 2 | *~ 3 | .idea 4 | .DS_Store 5 | target 6 | tmp 7 | 8 | -------------------------------------------------------------------------------- /ci/stable-check/Cargo.lock: -------------------------------------------------------------------------------- 1 | [root] 2 | name = "stable-check" 3 | version = "0.1.0" 4 | 5 | -------------------------------------------------------------------------------- /first-edition/book.toml: -------------------------------------------------------------------------------- 1 | title = "The Rust Programming Language" 2 | author = "The Rust Project Developers" 3 | -------------------------------------------------------------------------------- /second-edition/src/img/hello.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/overmind1980/book/master/second-edition/src/img/hello.png -------------------------------------------------------------------------------- /second-edition/nostarch/odt/chapter02.doc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/overmind1980/book/master/second-edition/nostarch/odt/chapter02.doc -------------------------------------------------------------------------------- /second-edition/nostarch/odt/chapter03.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/overmind1980/book/master/second-edition/nostarch/odt/chapter03.docx -------------------------------------------------------------------------------- /second-edition/nostarch/odt/chapter04.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/overmind1980/book/master/second-edition/nostarch/odt/chapter04.docx -------------------------------------------------------------------------------- /second-edition/nostarch/odt/chapter05.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/overmind1980/book/master/second-edition/nostarch/odt/chapter05.docx -------------------------------------------------------------------------------- /second-edition/nostarch/odt/chapter06.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/overmind1980/book/master/second-edition/nostarch/odt/chapter06.docx -------------------------------------------------------------------------------- /second-edition/nostarch/odt/chapter07.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/overmind1980/book/master/second-edition/nostarch/odt/chapter07.docx -------------------------------------------------------------------------------- /second-edition/nostarch/odt/chapter08.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/overmind1980/book/master/second-edition/nostarch/odt/chapter08.docx -------------------------------------------------------------------------------- /second-edition/nostarch/odt/chapter09.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/overmind1980/book/master/second-edition/nostarch/odt/chapter09.docx -------------------------------------------------------------------------------- /second-edition/src/appendix-00.md: -------------------------------------------------------------------------------- 1 | # Appendix 2 | 3 | The following sections contain reference material you may find useful in your 4 | Rust journey. 5 | -------------------------------------------------------------------------------- /second-edition/book.toml: -------------------------------------------------------------------------------- 1 | title = "The Rust Programming Language" 2 | author = "Steve Klabnik and Carol Nichols, with Contributions from the Rust Community" 3 | -------------------------------------------------------------------------------- /ci/stable-check/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "stable-check" 3 | version = "0.1.0" 4 | authors = ["steveklabnik "] 5 | 6 | [dependencies] 7 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Set the default behavior, in case people don't have core.autocrlf set. 2 | * text=auto eol=lf 3 | *.docx binary 4 | *.odt binary 5 | *.png binary 6 | 7 | -------------------------------------------------------------------------------- /redirects/compiler-plugins.md: -------------------------------------------------------------------------------- 1 | % The Rust Programming Language Has Moved 2 | 3 | This chapter of the book has moved to [a chapter in the Unstable 4 | Book][unstable book plugins]. Please check it out there. 5 | 6 | [unstable book plugins]: ../unstable-book/language-features/plugin.html 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: rust 3 | cache: cargo 4 | rust: 5 | - nightly 6 | branches: 7 | only: 8 | - master 9 | addons: 10 | apt: 11 | packages: 12 | - aspell 13 | - aspell-en 14 | before_script: 15 | - (cargo install mdbook --git https://github.com/azerupi/mdBook.git --force || true) 16 | script: 17 | - bash ci/build.sh 18 | -------------------------------------------------------------------------------- /second-edition/src/ch04-00-understanding-ownership.md: -------------------------------------------------------------------------------- 1 | # Understanding Ownership 2 | 3 | Ownership is Rust’s most unique feature, and it enables Rust to make memory 4 | safety guarantees without needing a garbage collector. Therefore, it’s 5 | important to understand how ownership works in Rust. In this chapter we’ll talk 6 | about ownership as well as several related features: borrowing, slices, and how 7 | Rust lays data out in memory. 8 | -------------------------------------------------------------------------------- /first-edition/src/effective-rust.md: -------------------------------------------------------------------------------- 1 | # Effective Rust 2 | 3 | So you’ve learned how to write some Rust code. But there’s a difference between 4 | writing *any* Rust code and writing *good* Rust code. 5 | 6 | This chapter consists of relatively independent tutorials which show you how to 7 | take your Rust to the next level. Common patterns and standard library features 8 | will be introduced. Read these sections in any order of your choosing. 9 | -------------------------------------------------------------------------------- /first-edition/src/syntax-and-semantics.md: -------------------------------------------------------------------------------- 1 | # Syntax and Semantics 2 | 3 | This chapter breaks Rust down into small chunks, one for each concept. 4 | 5 | If you’d like to learn Rust from the bottom up, reading this in order is a 6 | great way to do that. 7 | 8 | These sections also form a reference for each concept, so if you’re reading 9 | another tutorial and find something confusing, you can find it explained 10 | somewhere in here. 11 | -------------------------------------------------------------------------------- /redirects/if.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/if.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/drop.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/drop.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/enums.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/enums.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/ffi.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/ffi.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/loops.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/loops.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/match.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/match.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/ufcs.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/ufcs.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/if-let.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/if-let.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/macros.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/macros.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/strings.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/strings.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/structs.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/structs.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/testing.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/testing.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/traits.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/traits.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/unsafe.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/unsafe.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/vectors.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/vectors.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/attributes.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/attributes.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/closures.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/closures.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/comments.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/comments.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/functions.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/functions.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/generics.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/generics.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/glossary.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/glossary.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/iterators.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/iterators.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/lifetimes.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/lifetimes.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/mutability.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/mutability.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/ownership.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/ownership.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/patterns.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/patterns.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/bibliography.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/bibliography.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/concurrency.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/concurrency.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/raw-pointers.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/raw-pointers.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/syntax-index.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/syntax-index.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/type-aliases.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/type-aliases.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/deref-coercions.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/deref-coercions.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/documentation.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/documentation.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/effective-rust.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/effective-rust.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/error-handling.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/error-handling.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/getting-started.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/getting-started.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/guessing-game.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/guessing-game.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/method-syntax.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/method-syntax.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/primitive-types.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/primitive-types.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/trait-objects.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/trait-objects.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/unsized-types.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/unsized-types.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/associated-types.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/associated-types.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/borrow-and-asref.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/borrow-and-asref.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/const-and-static.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/const-and-static.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/procedural-macros.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/procedural-macros.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/release-channels.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/release-channels.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/variable-bindings.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/variable-bindings.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/crates-and-modules.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/crates-and-modules.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/syntax-and-semantics.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/syntax-and-semantics.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /index.md: -------------------------------------------------------------------------------- 1 | % The Rust Programming Language 2 | 3 | There are two editions of "The Rust Programming Language": 4 | 5 | * [First edition](first-edition/index.html) 6 | * [Second edition](second-edition/index.html) 7 | 8 | The second edition is a complete re-write. It is still under construction, 9 | though it is far enough along to learn most of Rust. We suggest reading the 10 | second edition and then checking out the first edition later to pick up some of 11 | the more esoteric parts of the language. 12 | -------------------------------------------------------------------------------- /redirects/casting-between-types.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/casting-between-types.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/the-stack-and-the-heap.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/the-stack-and-the-heap.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/choosing-your-guarantees.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/choosing-your-guarantees.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/conditional-compilation.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/conditional-compilation.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/operators-and-overloading.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/operators-and-overloading.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/references-and-borrowing.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/references-and-borrowing.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /redirects/README.md: -------------------------------------------------------------------------------- 1 | % The Rust Programming Language 2 | 3 | There are two editions of "The Rust Programming Language": 4 | 5 | * [First edition](first-edition/index.html) 6 | * [Second edition](second-edition/index.html) 7 | 8 | The second edition is a complete re-write. It is still under construction; 9 | though it is far enough along to learn most of Rust; we suggest reading the 10 | second edition and then checking out the first edition later to pick up some of 11 | the more esoteric parts of the language. 12 | -------------------------------------------------------------------------------- /redirects/SUMMARY.md: -------------------------------------------------------------------------------- 1 | % The Rust Programming Language 2 | 3 | There are two editions of "The Rust Programming Language": 4 | 5 | * [First edition](first-edition/index.html) 6 | * [Second edition](second-edition/index.html) 7 | 8 | The second edition is a complete re-write. It is still under construction; 9 | though it is far enough along to learn most of Rust; we suggest reading the 10 | second edition and then checking out the first edition later to pick up some of 11 | the more esoteric parts of the language. 12 | -------------------------------------------------------------------------------- /redirects/using-rust-without-the-standard-library.md: -------------------------------------------------------------------------------- 1 | % There is a new edition of the book 2 | 3 | This is an old link. You can [continue to the exact older page][1]. 4 | If you're trying to learn Rust, checking out [the second edition][2] might be a better choice. 5 | 6 | * [This page in the first edition of the The Rust Programming Language][1] 7 | 8 | * [Index of the second edition of The Rust Programming Language][2] 9 | 10 | 11 | [1]: first-edition/using-rust-without-the-standard-library.html 12 | [2]: second-edition/index.html 13 | -------------------------------------------------------------------------------- /second-edition/dot/trpl15-02.dot: -------------------------------------------------------------------------------- 1 | digraph { 2 | rankdir=LR; 3 | dpi=300.0; 4 | node [shape="plaintext"]; 5 | 6 | table0[label=< 7 | 8 | 9 | 15 |
Cons
i32 10 | 11 | 12 | 13 |
Box
usize
14 |
>]; 16 | } 17 | 18 | -------------------------------------------------------------------------------- /second-edition/src/ch17-00-oop.md: -------------------------------------------------------------------------------- 1 | # Is Rust an Object-Oriented Programming Language? 2 | 3 | Object-Oriented Programming is a way of modeling programs that originated with 4 | Simula in the 1960s and became popular with C++ in the 1990s. There are many 5 | competing definitions for what OOP is: under some definitions, Rust is 6 | object-oriented; under other definitions, Rust is not. In this chapter, we'll 7 | explore some characteristics that are commonly considered to be object-oriented 8 | and how those characteristics translate to idiomatic Rust. 9 | -------------------------------------------------------------------------------- /second-edition/src/ch14-00-more-about-cargo.md: -------------------------------------------------------------------------------- 1 | # More about Cargo and Crates.io 2 | 3 | We've used some features of Cargo in this book so far, but only the most basic 4 | ones. We've used Cargo to build, run, and test our code, but it can do a lot 5 | more. Let's go over some of its other features now. Cargo can do even more than 6 | what we will cover in this chapter; for a full explanation, see its 7 | documentation. 8 | 9 | We're going to cover: 10 | 11 | * Customizing your build through release profiles 12 | * Publishing libraries on crates.io 13 | * Organizing larger projects with workspaces 14 | * Installing binaries from crates.io 15 | * Extending Cargo with your own custom commands 16 | -------------------------------------------------------------------------------- /second-edition/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rust-book" 3 | version = "0.0.1" 4 | authors = ["Steve Klabnik "] 5 | description = "The Rust Book" 6 | 7 | [[bin]] 8 | name = "concat_chapters" 9 | path = "tools/src/bin/concat_chapters.rs" 10 | 11 | [[bin]] 12 | name = "lfp" 13 | path = "tools/src/bin/lfp.rs" 14 | 15 | [[bin]] 16 | name = "link2print" 17 | path = "tools/src/bin/link2print.rs" 18 | 19 | [[bin]] 20 | name = "remove_links" 21 | path = "tools/src/bin/remove_links.rs" 22 | 23 | [[bin]] 24 | name = "remove_markup" 25 | path = "tools/src/bin/remove_markup.rs" 26 | 27 | [dependencies] 28 | walkdir = "0.1.5" 29 | docopt = "0.6.82" 30 | rustc-serialize = "0.3.19" 31 | regex = "0.1.73" 32 | lazy_static = "0.2.1" 33 | -------------------------------------------------------------------------------- /second-edition/src/appendix-06-translation.md: -------------------------------------------------------------------------------- 1 | ## Appendix F: Translations of the Book 2 | 3 | For resources in languages other than English. Most are still in progress; see 4 | [the Translations label][label] to help or let us know about a new translation! 5 | 6 | [label]: https://github.com/rust-lang/book/issues?q=is%3Aopen+is%3Aissue+label%3ATranslations 7 | 8 | - [Português](https://coreh.github.io/rust-book-pt-br/) 9 | - [Tiếng việt](https://rust-vietnam.github.io/book/) 10 | - [简体中文](http://www.broadview.com.cn/article/144), [alternate](https://github.com/KaiserY/trpl-zh-cn) 11 | - [українська мова](https://github.com/pavloslav/rust-book-uk-ua) 12 | - [Español](https://github.com/z1mvader/book) 13 | - [Italiano](https://github.com/CodelessFuture/trpl2-it) -------------------------------------------------------------------------------- /second-edition/src/ch05-00-structs.md: -------------------------------------------------------------------------------- 1 | # Using Structs to Structure Related Data 2 | 3 | A *struct*, or *structure*, is a custom data type that lets us name and package 4 | together multiple related values that make up a meaningful group. If you’re 5 | familiar with an object-oriented language, a *struct* is like an object’s data 6 | attributes. In this chapter, we'll compare and contrast tuples with structs, 7 | demonstrate how to use structs, and discuss how to define methods and 8 | associated functions on structs to specify behavior associated with a struct's 9 | data. The struct and *enum* (which is discussed in Chapter 6) concepts are the 10 | building blocks for creating new types in your program’s domain to take full 11 | advantage of Rust’s compile time type checking. 12 | -------------------------------------------------------------------------------- /ci/build.sh: -------------------------------------------------------------------------------- 1 | # Copyright 2016 The Rust Project Developers. See the COPYRIGHT 2 | # file at the top-level directory of this distribution and at 3 | # http://rust-lang.org/COPYRIGHT. 4 | # 5 | # Licensed under the Apache License, Version 2.0 or the MIT license 7 | # , at your 8 | # option. This file may not be copied, modified, or distributed 9 | # except according to those terms. 10 | 11 | set -e 12 | 13 | export PATH=$PATH:/home/travis/.cargo/bin; 14 | 15 | # feature check 16 | cd ci/stable-check 17 | 18 | cargo run -- ../../first-edition/src 19 | cargo run -- ../../second-edition/src 20 | 21 | cd ../.. 22 | 23 | # tests for the second edition 24 | 25 | cd second-edition 26 | bash spellcheck.sh list 27 | mdbook test 28 | mdbook build 29 | cargo run --bin lfp src 30 | -------------------------------------------------------------------------------- /second-edition/dot/trpl04-01.dot: -------------------------------------------------------------------------------- 1 | digraph { 2 | rankdir=LR; 3 | dpi=300.0; 4 | node [shape="plaintext"]; 5 | 6 | table0[label=< 7 | 8 | 9 | 10 | 11 | 12 |
s1
namevalue
ptr
len5
capacity5
>]; 13 | table1[label=< 14 | 15 | 16 | 17 | 18 | 19 | 20 |
indexvalue
0h
1e
2l
3l
4o
>]; 21 | 22 | edge[tailclip="false"]; 23 | table0:pointer:c -> table1:pointee; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /second-edition/src/ch06-00-enums.md: -------------------------------------------------------------------------------- 1 | # Enums and Pattern Matching 2 | 3 | In this chapter we’ll look at *enumerations*, also referred to as *enums*. 4 | Enums allow you to define a type by enumerating its possible values. First, 5 | we’ll define and use an enum to show how an enum can encode meaning along with 6 | data. Next, we’ll explore a particularly useful enum, called `Option`, which 7 | expresses that a value can be either something or nothing. Then we’ll look at 8 | how pattern matching in the `match` expression makes it easy to run different 9 | code for different values of an enum. Finally, we’ll cover how the `if let` 10 | construct is another convenient and concise idiom available to you to handle 11 | enums in your code. 12 | 13 | Enums are a feature in many languages, but their capabilities differ in each 14 | language. Rust’s enums are most similar to *algebraic data types* in functional 15 | languages like F#, OCaml, and Haskell. 16 | -------------------------------------------------------------------------------- /second-edition/src/ch14-05-extending-cargo.md: -------------------------------------------------------------------------------- 1 | ## Extending Cargo with Custom Commands 2 | 3 | Cargo is designed to be extensible with new subcommands without having to 4 | modify Cargo itself. If a binary in your `$PATH` is named `cargo-something`, 5 | you can run it as if it were a Cargo subcommand by running `cargo something`. 6 | Custom commands like this are also listed when you run `cargo --list`. It's 7 | convenient to `cargo install` extensions to Cargo then be able to run them just 8 | like the built-in Cargo tools! 9 | 10 | ## Summary 11 | 12 | Sharing code with Cargo and crates.io is part of what makes the Rust ecosystem 13 | useful for many different tasks. Rust's standard library is small and stable, 14 | but crates are easy to share, use, and improve on a different timeline than the 15 | language itself. Don't be shy about sharing code that's useful to you on 16 | crates.io; it's likely that it will be useful to someone else as well! 17 | -------------------------------------------------------------------------------- /second-edition/dot/trpl15-01.dot: -------------------------------------------------------------------------------- 1 | digraph { 2 | rankdir=LR; 3 | dpi=300.0; 4 | node [shape="plaintext"]; 5 | 6 | table0[label=< 7 | 8 | 21 |
Cons
i32 9 | 10 | 20 |
Cons
i32 11 | 12 | 19 |
Cons
i32 13 | 14 | 18 |
Cons
i32 15 | 16 | 17 |
Cons
i32
>]; 22 | } 23 | 24 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## What to expect when you open a pull request here 2 | 3 | ### First edition 4 | 5 | The first edition is no longer being actively worked on. We accept pull 6 | requests for the first edition, but prefer small tweaks to large changes, as 7 | larger work should be spent improving the second edition. 8 | 9 | ### Second edition 10 | 11 | For the second edition, we are currently working with No Starch Press to bring 12 | it to print. Chapters go through a number of stages in the editing process, and 13 | once they've gotten to the layout stage, they're effectively frozen. 14 | 15 | For chapters that have gotten to the layout stage, we will likely only be 16 | accepting changes that correct factual errors or major problems and not, for 17 | example, minor wording changes. 18 | 19 | Scroll all the way to the right on https://github.com/rust-lang/book/projects/1 20 | to see which chapters have been frozen. 21 | 22 | Please see CONTRIBUTING.md for more details. 23 | 24 | Thank you for reading, you may now delete this text! 25 | -------------------------------------------------------------------------------- /second-edition/src/ch18-00-patterns.md: -------------------------------------------------------------------------------- 1 | # Patterns Match the Structure of Values 2 | 3 | Patterns are a special syntax within Rust for matching against the structure of 4 | our types, complex or simple. A pattern is made up of some combination of 5 | literals; destructured arrays, enums, structs, or tuples; variables, wildcards, 6 | and placeholders. These pieces describe the "shape" of the data we're working 7 | with. 8 | 9 | We use a pattern by taking some value and comparing it against the pattern. If 10 | the pattern matches our value, we do something with the value parts. Recall in 11 | Chapter 6 when we discussed the `match` expression that uses patterns like a 12 | coin sorting machine. We can name pieces within the shape, like we named the 13 | state that appeared on quarters in Chapter 6, and if the data fits the shape, 14 | we can use the named pieces. 15 | 16 | This chapter is a reference on all things related to patterns. We'll cover the 17 | valid places to use patterns, the difference between *refutable* and 18 | *irrefutable* patterns, and the different kinds of pattern syntax that you 19 | might see. 20 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## What to expect when you file an issue here 2 | 3 | ### First edition 4 | 5 | The first edition of the book is no longer being actively worked on. 6 | 7 | Issues for the first edition of the book are worthwhile if you are planning to 8 | submit a pull request, and want to discuss it first. But as we aren't actively 9 | working on the first edition, general bugs will be closed. 10 | 11 | ### Second edition 12 | 13 | For the second edition, we are currently working with No Starch Press to bring 14 | it to print. Chapters go through a number of stages in the editing process, and 15 | once they've gotten to the layout stage, they're effectively frozen. 16 | 17 | For chapters that have gotten to the layout stage, we will likely only be 18 | accepting changes that correct factual errors or major problems and not, for 19 | example, minor wording changes. 20 | 21 | Scroll all the way to the right on https://github.com/rust-lang/book/projects/1 22 | to see which chapters have been frozen. 23 | 24 | Please see CONTRIBUTING.md for more details. 25 | 26 | Thank you for reading, you may now delete this text! 27 | -------------------------------------------------------------------------------- /second-edition/nostarch/appendix.md: -------------------------------------------------------------------------------- 1 | # Appendix 2 | 3 | The following sections contain reference material you may find useful in your 4 | Rust journey. 5 | 6 | ## Keywords 7 | 8 | The following keywords are reserved by the Rust language and may not be used as 9 | names of functions, variables, macros, modules, crates, constants, static 10 | values, attributes, struct fields, or arguments. 11 | 12 | * `abstract` 13 | * `alignof` 14 | * `as` 15 | * `become` 16 | * `box` 17 | * `break` 18 | * `const` 19 | * `continue` 20 | * `crate` 21 | * `do` 22 | * `else` 23 | * `enum` 24 | * `extern` 25 | * `false` 26 | * `final` 27 | * `fn` 28 | * `for` 29 | * `if` 30 | * `impl` 31 | * `in` 32 | * `let` 33 | * `loop` 34 | * `macro` 35 | * `match` 36 | * `mod` 37 | * `move` 38 | * `mut` 39 | * `offsetof` 40 | * `override` 41 | * `priv` 42 | * `proc` 43 | * `pub` 44 | * `pure` 45 | * `ref` 46 | * `return` 47 | * `Self` 48 | * `self` 49 | * `sizeof` 50 | * `static` 51 | * `struct` 52 | * `super` 53 | * `trait` 54 | * `true` 55 | * `type` 56 | * `typeof` 57 | * `unsafe` 58 | * `unsized` 59 | * `use` 60 | * `virtual` 61 | * `where` 62 | * `while` 63 | * `yield` 64 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2010 The Rust Project Developers 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /second-edition/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2010-2017 The Rust Project Developers 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /second-edition/src/ch03-00-common-programming-concepts.md: -------------------------------------------------------------------------------- 1 | # Common Programming Concepts 2 | 3 | This chapter covers concepts that appear in almost every programming language 4 | and how they work in Rust. Many programming languages have much in common at 5 | their core. None of the concepts presented in this chapter are unique to Rust, 6 | but we’ll discuss them in the context of Rust and explain their conventions. 7 | 8 | Specifically, you’ll learn about variables, basic types, functions, comments, 9 | and control flow. These foundations will be in every Rust program, and learning 10 | them early will give you a strong core to start from. 11 | 12 | > ### Keywords 13 | > 14 | > The Rust language has a set of *keywords* that have been reserved for use by 15 | > the language only, much like other languages do. Keep in mind that you cannot 16 | > use these words as names of variables or functions. Most of the keywords have 17 | > special meanings, and you’ll be using them to do various tasks in your Rust 18 | > programs; a few have no current functionality associated with them but have 19 | > been reserved for functionality that might be added to Rust in the future. You 20 | > can find a list of the keywords in Appendix A. 21 | -------------------------------------------------------------------------------- /second-edition/doc-to-md.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Copyright 2016 The Rust Project Developers. See the COPYRIGHT 3 | # file at the top-level directory of this distribution and at 4 | # http://rust-lang.org/COPYRIGHT. 5 | # 6 | # Licensed under the Apache License, Version 2.0 or the MIT license 8 | # , at your 9 | # option. This file may not be copied, modified, or distributed 10 | # except according to those terms. 11 | 12 | set -eu 13 | 14 | # Get all the docx files in the tmp dir, 15 | ls tmp/*.docx | \ 16 | # Extract just the filename so we can reuse it easily. 17 | xargs -n 1 basename -s .docx | \ 18 | while IFS= read -r filename; do 19 | # Make a directory to put the XML in 20 | mkdir -p "tmp/$filename" 21 | # Unzip the docx to get at the xml 22 | unzip -o "tmp/$filename.docx" -d "tmp/$filename" 23 | # Convert to markdown with XSL 24 | xsltproc tools/docx-to-md.xsl "tmp/$filename/word/document.xml" | \ 25 | # Hard wrap at 80 chars at word bourdaries 26 | fold -w 80 -s | \ 27 | # Remove trailing whitespace & save in the nostarch dir for comparison 28 | sed -e "s/ *$//" > "nostarch/$filename.md" 29 | done 30 | -------------------------------------------------------------------------------- /second-edition/dot/trpl04-05.dot: -------------------------------------------------------------------------------- 1 | digraph { 2 | rankdir=LR; 3 | dpi=300.0; 4 | node [shape="plaintext"]; 5 | 6 | table0[label=< 7 | 8 | 9 | 10 |
s
namevalue
ptr
>]; 11 | table1[label=< 12 | 13 | 14 | 15 | 16 | 17 |
s1
namevalue
ptr
len5
capacity5
>]; 18 | table2[label=< 19 | 20 | 21 | 22 | 23 | 24 | 25 |
indexvalue
0h
1e
2l
3l
4o
>]; 26 | 27 | edge[tailclip="false"]; 28 | table1:pointer:c -> table2:pointee; 29 | table0:borrower:c -> table1:borrowee; 30 | } 31 | 32 | -------------------------------------------------------------------------------- /second-edition/nostarch.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Copyright 2016 The Rust Project Developers. See the COPYRIGHT 3 | # file at the top-level directory of this distribution and at 4 | # http://rust-lang.org/COPYRIGHT. 5 | # 6 | # Licensed under the Apache License, Version 2.0 or the MIT license 8 | # , at your 9 | # option. This file may not be copied, modified, or distributed 10 | # except according to those terms. 11 | 12 | set -eu 13 | 14 | cargo build --release 15 | 16 | mkdir -p tmp 17 | rm -rf tmp/*.md 18 | 19 | # Get all the markdown files in the src dir, 20 | ls src/*.md | \ 21 | # except for SUMMARY.md. 22 | grep -v SUMMARY.md | \ 23 | # Extract just the filename so we can reuse it easily. 24 | xargs -n 1 basename | \ 25 | # Remove all links followed by , then 26 | # Change all remaining links from markdown to italicized inline text. 27 | while IFS= read -r filename; do 28 | < "src/$filename" cargo run --bin remove_links \ 29 | | cargo run --bin link2print \ 30 | | cargo run --bin remove_markup > "tmp/$filename" 31 | done 32 | # Concat the files into the nostarch dir. 33 | cargo run --bin concat_chapters tmp nostarch 34 | -------------------------------------------------------------------------------- /second-edition/dot/trpl04-02.dot: -------------------------------------------------------------------------------- 1 | digraph { 2 | rankdir=LR; 3 | dpi=300.0; 4 | node [shape="plaintext"]; 5 | 6 | table0[label=< 7 | 8 | 9 | 10 | 11 | 12 |
s1
namevalue
ptr
len5
capacity5
>]; 13 | table3[label=< 14 | 15 | 16 | 17 | 18 | 19 |
s2
namevalue
ptr
len5
capacity5
>]; 20 | 21 | table1[label=< 22 | 23 | 24 | 25 | 26 | 27 | 28 |
indexvalue
0h
1e
2l
3l
4o
>]; 29 | 30 | edge[tailclip="false"]; 31 | table0:pointer:c -> table1:pointee; 32 | table3:pointer:c -> table1:pointee; 33 | } 34 | 35 | -------------------------------------------------------------------------------- /second-edition/src/ch19-00-advanced-features.md: -------------------------------------------------------------------------------- 1 | # Advanced Features 2 | 3 | We've come a long way! By now, we've learned 99% of the things you'll need to 4 | know when writing Rust. Before we do one more project in Chapter 20, let's talk 5 | about a few things that you may run into that last 1% of the time. Feel free to 6 | skip this chapter and come back to it once you run into these things in the 7 | wild; the features we'll learn to use here are useful in very specific 8 | situations. We don't want to leave these features out, but you won't find 9 | yourself reaching for them often. 10 | 11 | In this chapter, we're going to cover: 12 | 13 | * Unsafe Rust: for when you need to opt out of some of Rust's guarantees and 14 | tell the compiler that you will be responsible for upholding the guarantees 15 | instead 16 | * Advanced Lifetimes: Additional lifetime syntax for complex situations 17 | * Advanced Traits: Associated Types, default type parameters, fully qualified 18 | syntax, supertraits, and the newtype pattern in relation to traits 19 | * Advanced Types: some more about the newtype pattern, type aliases, the 20 | "never" type, and dynamically sized types 21 | * Advanced Functions and Closures: function pointers and returning closures 22 | 23 | It's a panoply of Rust features with something for everyone! Let's dive in! 24 | -------------------------------------------------------------------------------- /second-edition/dot/trpl04-04.dot: -------------------------------------------------------------------------------- 1 | digraph { 2 | rankdir=LR; 3 | dpi=300.0; 4 | node [shape="plaintext"]; 5 | 6 | table0[label=< 7 | 8 | 9 | 10 | 11 | 12 |
s1
namevalue
ptr
len5
capacity5
>]; 13 | table3[label=< 14 | 15 | 16 | 17 | 18 | 19 |
s2
namevalue
ptr
len5
capacity5
>]; 20 | 21 | table1[label=< 22 | 23 | 24 | 25 | 26 | 27 | 28 |
indexvalue
0h
1e
2l
3l
4o
>]; 29 | 30 | edge[tailclip="false"]; 31 | table0:pointer:c -> table1:pointee; 32 | table3:pointer:c -> table1:pointee; 33 | } 34 | 35 | -------------------------------------------------------------------------------- /second-edition/src/ch08-00-common-collections.md: -------------------------------------------------------------------------------- 1 | # Common Collections 2 | 3 | Rust’s standard library includes a number of really useful data structures 4 | called *collections*. Most other data types represent one specific value, but 5 | collections can contain multiple values. Unlike the built-in array and tuple 6 | types, the data these collections point to is stored on the heap, which means 7 | the amount of data does not need to be known at compile time and can grow or 8 | shrink as the program runs. Each kind of collection has different capabilities 9 | and costs, and choosing an appropriate one for the situation you’re in is a 10 | skill you’ll develop over time. In this chapter, we’ll go over three 11 | collections which are used very often in Rust programs: 12 | 13 | * A *vector* allows us to store a variable number of values next to each other. 14 | * A *string* is a collection of characters. We’ve seen the `String` type 15 | before, but we’ll talk about it in depth now. 16 | * A *hash map* allows us to associate a value with a particular key. It's a 17 | particular implementation of the more general data structure called a *map*. 18 | 19 | To learn about the other kinds of collections provided by the standard library, 20 | see [the documentation][collections]. 21 | 22 | [collections]: ../../std/collections/index.html 23 | 24 | We’re going to discuss how to create and update vectors, strings, and hash 25 | maps, as well as what makes each special. 26 | -------------------------------------------------------------------------------- /second-edition/src/ch03-04-comments.md: -------------------------------------------------------------------------------- 1 | ## Comments 2 | 3 | All programmers strive to make their code easy to understand, but sometimes 4 | extra explanation is warranted. In these cases, programmers leave notes, or 5 | *comments*, in their source code that the compiler will ignore but people 6 | reading the source code may find useful. 7 | 8 | Here’s a simple comment: 9 | 10 | ```rust 11 | // Hello, world. 12 | ``` 13 | 14 | In Rust, comments must start with two slashes and continue until the end of the 15 | line. For comments that extend beyond a single line, you’ll need to include 16 | `//` on each line, like this: 17 | 18 | ```rust 19 | // So we’re doing something complicated here, long enough that we need 20 | // multiple lines of comments to do it! Whew! Hopefully, this comment will 21 | // explain what’s going on. 22 | ``` 23 | 24 | Comments can also be placed at the end of lines containing code: 25 | 26 | Filename: src/main.rs 27 | 28 | ```rust 29 | fn main() { 30 | let lucky_number = 7; // I’m feeling lucky today. 31 | } 32 | ``` 33 | 34 | But you’ll more often see them used in this format, with the comment on a 35 | separate line above the code it's annotating: 36 | 37 | Filename: src/main.rs 38 | 39 | ```rust 40 | fn main() { 41 | // I’m feeling lucky today. 42 | let lucky_number = 7; 43 | } 44 | ``` 45 | 46 | That’s all there is to comments. They’re not particularly complicated. 47 | -------------------------------------------------------------------------------- /second-edition/src/ch07-00-modules.md: -------------------------------------------------------------------------------- 1 | # Using Modules to Reuse and Organize Code 2 | 3 | When you start writing programs in Rust, your code might live solely in the 4 | `main` function. As your code grows, you’ll eventually move functionality into 5 | other functions for reuse and better organization. By splitting your code into 6 | smaller chunks, each chunk is easier to understand on its own. But what happens 7 | if you have too many functions? Rust has a module system that enables the reuse 8 | of code in an organized fashion. 9 | 10 | In the same way that you extract lines of code into a function, you can extract 11 | functions (and other code, like structs and enums) into different modules. A 12 | *module* is a namespace that contains definitions of functions or types, and 13 | you can choose whether those definitions are visible outside their module 14 | (public) or not (private). Here’s an overview of how modules work: 15 | 16 | * The `mod` keyword declares a new module. Code within the module appears 17 | either immediately following this declaration within curly braces or in 18 | another file. 19 | * By default, functions, types, constants, and modules are private. The `pub` 20 | keyword makes an item public and therefore visible outside its namespace. 21 | * The `use` keyword brings modules, or the definitions inside modules, into 22 | scope so it’s easier to refer to them. 23 | 24 | We’ll look at each of these parts to see how they fit into the whole. 25 | -------------------------------------------------------------------------------- /second-edition/src/ch09-00-error-handling.md: -------------------------------------------------------------------------------- 1 | # Error Handling 2 | 3 | Rust’s commitment to reliability extends to error handling. Errors are a fact 4 | of life in software, so Rust has a number of features for handling situations 5 | in which something goes wrong. In many cases, Rust will require you to 6 | acknowledge the possibility of an error occurring and take some action before 7 | your code will compile. This makes your program more robust by ensuring that 8 | you won’t only discover errors after you’ve deployed your code to production. 9 | 10 | Rust groups errors into two major categories: *recoverable* and *unrecoverable* 11 | errors. Recoverable errors are situations when it’s usually reasonable to 12 | report the problem to the user and retry the operation, like a file not being 13 | found. Unrecoverable errors are always symptoms of bugs, like trying to access 14 | a location beyond the end of an array. 15 | 16 | Most languages don’t distinguish between the two kinds of errors, and handle 17 | both in the same way using mechanisms like exceptions. Rust doesn’t have 18 | exceptions. Instead, it has the value `Result` for recoverable errors and 19 | the `panic!` macro that stops execution when it encounters unrecoverable 20 | errors. This chapter will cover calling `panic!` first, then talk about 21 | returning `Result` values. Finally, we’ll discuss considerations to take 22 | into account when deciding whether to try to recover from an error or to stop 23 | execution. 24 | -------------------------------------------------------------------------------- /second-edition/src/ch14-04-installing-binaries.md: -------------------------------------------------------------------------------- 1 | ## Installing Binaries from Crates.io with `cargo install` 2 | 3 | The `cargo install` command allows you to install and use binary crates 4 | locally. This isn't intended to replace system packages; it's meant to be a 5 | convenient way for Rust developers to install tools that others have shared on 6 | crates.io. Only packages which have binary targets can be installed, and all 7 | binaries are installed into the installation root's *bin* folder. If you 8 | installed Rust using *rustup.rs* and don't have any custom configurations, this 9 | will be `$HOME/.cargo/bin`. Add that directory to your `$PATH` to be able to 10 | run programs you've gotten through `cargo install`. 11 | 12 | For example, we mentioned in Chapter 12 that there's a Rust implementation of 13 | the `grep` tool for searching files called `ripgrep`. If we want to install 14 | `ripgrep`, we can run: 15 | 16 | ```text 17 | $ cargo install ripgrep 18 | Updating registry `https://github.com/rust-lang/crates.io-index` 19 | Downloading ripgrep v0.3.2 20 | ...snip... 21 | Compiling ripgrep v0.3.2 22 | Finished release [optimized + debuginfo] target(s) in 97.91 secs 23 | Installing ~/.cargo/bin/rg 24 | ``` 25 | 26 | The last line of the output shows the location and the name of the installed 27 | binary, which in the case of `ripgrep` is named `rg`. As long as the 28 | installation directory is in our `$PATH` as mentioned above, we can then run 29 | `rg --help` and start using a faster, rustier tool for searching files! 30 | -------------------------------------------------------------------------------- /second-edition/dot/trpl04-06.dot: -------------------------------------------------------------------------------- 1 | digraph { 2 | rankdir=LR; 3 | dpi=300.0; 4 | node [shape="plaintext"]; 5 | 6 | table0[label=< 7 | 8 | 9 | 10 | 11 |
world
namevalue
ptr
len5
>]; 12 | 13 | table3[label=< 14 | 15 | 16 | 17 | 18 | 19 |
s
namevalue
ptr
len11
capacity11
>]; 20 | table4[label=< 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 |
indexvalue
0h
1e
2l
3l
4o
5
6w
7o
8r
9l
10d
>]; 34 | 35 | 36 | edge[tailclip="false"]; 37 | table0:pointer2:c -> table4:pointee2; 38 | table3:pointer:c -> table4:pointee; 39 | } 40 | 41 | -------------------------------------------------------------------------------- /second-edition/src/img/trpl15-02.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | %3 11 | 12 | 13 | table0 14 | 15 | Cons 16 | 17 | i32 18 | 19 | 20 | Box 21 | 22 | usize 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /second-edition/src/ch20-00-final-project-a-web-server.md: -------------------------------------------------------------------------------- 1 | # Final Project: Building a Multithreaded Web Server 2 | 3 | It's been a long journey, but here we are! It's the end of the book. Parting is 4 | such sweet sorrow. But before we go, let's build one more project together, to 5 | show off some of the things we learned in these final chapters, as well as 6 | re-cap some of the earlier ones. 7 | 8 | Here's what we're going to make: a web server that says hello: 9 | 10 | ![hello from rust](hello.png) 11 | 12 | To do this, we will: 13 | 14 | 1. Learn a little bit about TCP and HTTP 15 | 2. Listen for TCP connections on a socket 16 | 3. Parse a tiny number of HTTP requests 17 | 4. Create a proper HTTP response 18 | 5. Improve the throughput of our server with a thread pool 19 | 20 | Before we get started, however, there's one thing we should mention: if you 21 | were writing this code in production, there are a lot of better ways to write 22 | it. Specifically, there are a number of robust crates on crates.io that provide 23 | much more complete web server and thread pool implementations than we are going 24 | to build. 25 | 26 | However, for this chapter, our intention is to learn, not to take the easy 27 | route. Since Rust is a systems programming language, we're able to choose what 28 | level of abstraction we want to work with. We're able to go to a lower level 29 | than is possible or practical in other languages if we so choose. So we'll be 30 | writing a basic HTTP server and thread pool ourselves in order to learn the 31 | general ideas and techniques behind the crates we might use in the future. 32 | -------------------------------------------------------------------------------- /second-edition/src/appendix-07-newest-features.md: -------------------------------------------------------------------------------- 1 | # Appendix G - Newest Features 2 | 3 | This appendix documents features that have been added to stable Rust since the 4 | main part of the book was completed. 5 | 6 | 7 | ## Field init shorthand 8 | 9 | We can initialize a data structure (struct, enum, union) with named 10 | fields, by writing `fieldname` as a shorthand for `fieldname: fieldname`. 11 | This allows a compact syntax for initialization, with less duplication: 12 | 13 | ```rust 14 | #[derive(Debug)] 15 | struct Person { 16 | name: String, 17 | age: u8, 18 | } 19 | 20 | fn main() { 21 | let name = String::from("Peter"); 22 | let age = 27; 23 | 24 | // Using full syntax: 25 | let peter = Person { name: name, age: age }; 26 | 27 | let name = String::from("Portia"); 28 | let age = 27; 29 | 30 | // Using field init shorthand: 31 | let portia = Person { name, age }; 32 | 33 | println!("{:?}", portia); 34 | } 35 | ``` 36 | 37 | 38 | ## Returning from loops 39 | 40 | One of the uses of a `loop` is to retry an operation you know can fail, such as 41 | checking if a thread completed its job. However, you might need to pass the 42 | result of that operation to the rest of your code. If you add it to the `break` 43 | expression you use to stop the loop, it will be returned by the broken loop: 44 | 45 | ```rust 46 | fn main() { 47 | let mut counter = 0; 48 | 49 | let result = loop { 50 | counter += 1; 51 | 52 | if counter == 10 { 53 | break counter * 2; 54 | } 55 | }; 56 | 57 | assert_eq!(result, 20); 58 | } 59 | ``` 60 | -------------------------------------------------------------------------------- /second-edition/src/ch13-00-functional-features.md: -------------------------------------------------------------------------------- 1 | # Functional Language features in Rust: Iterators and Closures 2 | 3 | 4 | 7 | 8 | Rust's design has taken inspiration from a lot of existing languages and 9 | techniques, and one significant influence is *functional programming*. 10 | Programming in a functional style often includes using functions as values in 11 | arguments or return values of other functions, assigning functions to variables 12 | for later execution, and so forth. We won't debate here the issue of what, 13 | exactly, functional programming is or is not, but will instead show off some 14 | features of Rust that are similar to features in many languages often referred 15 | to as functional. 16 | 17 | More specifically, we're going to cover: 18 | 19 | * *Closures*: a function-like construct you can store in a variable. 20 | * *Iterators*: a way of processing a series of elements. 21 | * How to use these features to improve on the I/O project from Chapter 12. 22 | * The performance of these features. Spoiler alert: they're faster than you 23 | might think! 24 | 25 | There are other Rust features influenced by the functional style, like pattern 26 | matching and enums, that we've covered in other chapters as well. Mastering 27 | closures and iterators is an important part of writing idiomatic, fast Rust 28 | code, so we're devoting an entire chapter to them here. 29 | -------------------------------------------------------------------------------- /second-edition/style-guide.md: -------------------------------------------------------------------------------- 1 | # Style Guide 2 | 3 | ## Prose 4 | 5 | * Prefer title case for chapter/section headings, ex: `## Generating a Secret 6 | Number` rather than `## Generating a secret number`. 7 | * Prefer italics over single quotes when calling out a term, ex: `is an 8 | *associated function* of` rather than `is an ‘associated function’ of`. 9 | * When talking about a method in prose, DO NOT include the parentheses, ex: 10 | `read_line` rather than `read_line()`. 11 | * Hard wrap at 80 chars 12 | * Prefer not mixing code and not-code in one word, ex: ``Remember when we wrote 13 | `use std::io`?`` rather than ``Remember when we `use`d `std::io`?`` 14 | 15 | ## Code 16 | 17 | * Add the file name before markdown blocks to make it clear which file we're 18 | talking about, when applicable. 19 | * When making changes to code, make it clear which parts of the code changed 20 | and which stayed the same... not sure how to do this yet 21 | * Split up long lines as appropriate to keep them under 80 chars if possible 22 | * Use `bash` syntax highlighting for command line output code blocks 23 | 24 | ## Links 25 | 26 | Once all the scripts are done: 27 | 28 | * If a link shouldn't be printed, mark it to be ignored 29 | * This includes all "Chapter XX" intra-book links, which *should* be links 30 | for the HTML version 31 | * Make intra-book links and stdlib API doc links relative so they work whether 32 | the book is read offline or on docs.rust-lang.org 33 | * Use markdown links and keep in mind that they will be changed into `text at 34 | *url*` in print, so word them in a way that it reads well in that format 35 | -------------------------------------------------------------------------------- /second-edition/dot/trpl04-03.dot: -------------------------------------------------------------------------------- 1 | digraph { 2 | rankdir=LR; 3 | dpi=300.0; 4 | node [shape="plaintext"]; 5 | 6 | table0[label=< 7 | 8 | 9 | 10 | 11 | 12 |
s2
namevalue
ptr
len5
capacity5
>]; 13 | table1[label=< 14 | 15 | 16 | 17 | 18 | 19 | 20 |
indexvalue
0h
1e
2l
3l
4o
>]; 21 | 22 | table3[label=< 23 | 24 | 25 | 26 | 27 | 28 |
s1
namevalue
ptr
len5
capacity5
>]; 29 | table4[label=< 30 | 31 | 32 | 33 | 34 | 35 | 36 |
indexvalue
0h
1e
2l
3l
4o
>]; 37 | 38 | 39 | edge[tailclip="false"]; 40 | table0:pointer:c -> table1:pointee; 41 | table3:pointer:c -> table4:pointee; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /ci/stable-check/src/main.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT 2 | // file at the top-level directory of this distribution and at 3 | // http://rust-lang.org/COPYRIGHT. 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | 11 | use std::error::Error; 12 | use std::env; 13 | use std::fs; 14 | use std::fs::File; 15 | use std::io::prelude::*; 16 | use std::path::Path; 17 | 18 | fn main() { 19 | let arg = env::args().nth(1).unwrap_or_else(|| { 20 | println!("Please pass a src directory as the first argument"); 21 | std::process::exit(1); 22 | }); 23 | 24 | match check_directory(&Path::new(&arg)) { 25 | Ok(()) => println!("passed!"), 26 | Err(e) => { 27 | println!("Error: {}", e); 28 | std::process::exit(1); 29 | } 30 | } 31 | 32 | } 33 | 34 | fn check_directory(dir: &Path) -> Result<(), Box> { 35 | for entry in fs::read_dir(dir)? { 36 | let entry = entry?; 37 | let path = entry.path(); 38 | 39 | if path.is_dir() { 40 | continue; 41 | } 42 | 43 | let mut file = File::open(&path)?; 44 | let mut contents = String::new(); 45 | file.read_to_string(&mut contents)?; 46 | 47 | if contents.contains("#![feature") { 48 | return Err(From::from(format!("Feature flag found in {:?}", path))); 49 | } 50 | } 51 | 52 | Ok(()) 53 | } 54 | -------------------------------------------------------------------------------- /first-edition/src/attributes.md: -------------------------------------------------------------------------------- 1 | # Attributes 2 | 3 | Declarations can be annotated with ‘attributes’ in Rust. They look like this: 4 | 5 | ```rust 6 | #[test] 7 | # fn foo() {} 8 | ``` 9 | 10 | or like this: 11 | 12 | ```rust 13 | # mod foo { 14 | #![test] 15 | # } 16 | ``` 17 | 18 | The difference between the two is the `!`, which changes what the attribute 19 | applies to: 20 | 21 | ```rust,ignore 22 | #[foo] 23 | struct Foo; 24 | 25 | mod bar { 26 | #![bar] 27 | } 28 | ``` 29 | 30 | The `#[foo]` attribute applies to the next item, which is the `struct` 31 | declaration. The `#![bar]` attribute applies to the item enclosing it, which is 32 | the `mod` declaration. Otherwise, they’re the same. Both change the meaning of 33 | the item they’re attached to somehow. 34 | 35 | For example, consider a function like this: 36 | 37 | ```rust 38 | #[test] 39 | fn check() { 40 | assert_eq!(2, 1 + 1); 41 | } 42 | ``` 43 | 44 | It is marked with `#[test]`. This means it’s special: when you run 45 | [tests][tests], this function will execute. When you compile as usual, it won’t 46 | even be included. This function is now a test function. 47 | 48 | [tests]: testing.html 49 | 50 | Attributes may also have additional data: 51 | 52 | ```rust 53 | #[inline(always)] 54 | fn super_fast_fn() { 55 | # } 56 | ``` 57 | 58 | Or even keys and values: 59 | 60 | ```rust 61 | #[cfg(target_os = "macos")] 62 | mod macos_only { 63 | # } 64 | ``` 65 | 66 | Rust attributes are used for a number of different things. There is a full list 67 | of attributes [in the reference][reference]. Currently, you are not allowed to 68 | create your own attributes, the Rust compiler defines them. 69 | 70 | [reference]: ../../reference/attributes.html 71 | -------------------------------------------------------------------------------- /second-edition/dot/trpl15-03.dot: -------------------------------------------------------------------------------- 1 | digraph { 2 | rankdir=LR; 3 | dpi=300.0; 4 | node [shape="plaintext"]; 5 | 6 | table4[label=< 7 | 8 |
b
>]; 9 | 10 | table5[label=< 11 | 12 |
3
>]; 13 | 14 | 15 | table0[label=< 16 | 17 |
a
>]; 18 | 19 | table1[label=< 20 | 21 |
5
>]; 22 | 23 | table2[label=< 24 | 25 |
10
>]; 26 | 27 | table3[label=< 28 | 29 |
Nil
>]; 30 | 31 | 32 | table6[label=< 33 | 34 |
c
>]; 35 | 36 | table7[label=< 37 | 38 |
4
>]; 39 | 40 | 41 | edge[tailclip="false"]; 42 | table0:ptr0:c -> table1:pte0; 43 | table1:ptr1:c -> table2:pte1; 44 | table2:ptr2:c -> table3:pte2; 45 | table4:ptr4:c -> table5:pte4; 46 | table5:ptr5:c -> table1:pte0; 47 | table6:ptr6:c -> table7:pte6; 48 | table7:ptr7:c -> table1:pte0; 49 | } 50 | 51 | -------------------------------------------------------------------------------- /first-edition/src/using-rust-without-the-standard-library.md: -------------------------------------------------------------------------------- 1 | # Using Rust Without the Standard Library 2 | 3 | Rust’s standard library provides a lot of useful functionality, but assumes 4 | support for various features of its host system: threads, networking, heap 5 | allocation, and others. There are systems that do not have these features, 6 | however, and Rust can work with those too! To do so, we tell Rust that we 7 | don’t want to use the standard library via an attribute: `#![no_std]`. 8 | 9 | > Note: This feature is technically stable, but there are some caveats. For 10 | > one, you can build a `#![no_std]` _library_ on stable, but not a _binary_. 11 | > For details on binaries without the standard library, see [the nightly 12 | > chapter on 'lang items'][unstable book lang items] 13 | 14 | To use `#![no_std]`, add it to your crate root: 15 | 16 | ```rust,ignore 17 | #![no_std] 18 | 19 | fn plus_one(x: i32) -> i32 { 20 | x + 1 21 | } 22 | ``` 23 | 24 | Much of the functionality that’s exposed in the standard library is also 25 | available via the [`core` crate](../../core/index.html). When we’re using the 26 | standard library, Rust automatically brings `std` into scope, allowing you to 27 | use its features without an explicit import. By the same token, when using 28 | `#![no_std]`, Rust will bring `core` into scope for you, as well as [its 29 | prelude](../../core/prelude/v1/index.html). This means that a lot of code will Just 30 | Work: 31 | 32 | ```rust,ignore 33 | #![no_std] 34 | 35 | fn may_fail(failure: bool) -> Result<(), &'static str> { 36 | if failure { 37 | Err("this didn’t work!") 38 | } else { 39 | Ok(()) 40 | } 41 | } 42 | ``` 43 | 44 | [unstable book lang items]: ../../unstable-book/language-features/lang-items.html#using-libc 45 | -------------------------------------------------------------------------------- /first-edition/src/type-aliases.md: -------------------------------------------------------------------------------- 1 | # Type Aliases 2 | 3 | The `type` keyword lets you declare an alias of another type: 4 | 5 | ```rust 6 | type Name = String; 7 | ``` 8 | 9 | You can then use this type as if it were a real type: 10 | 11 | ```rust 12 | type Name = String; 13 | 14 | let x: Name = "Hello".to_string(); 15 | ``` 16 | 17 | Note, however, that this is an _alias_, not a new type entirely. In other 18 | words, because Rust is strongly typed, you’d expect a comparison between two 19 | different types to fail: 20 | 21 | ```rust,ignore 22 | let x: i32 = 5; 23 | let y: i64 = 5; 24 | 25 | if x == y { 26 | // ... 27 | } 28 | ``` 29 | 30 | this gives 31 | 32 | ```text 33 | error: mismatched types: 34 | expected `i32`, 35 | found `i64` 36 | (expected i32, 37 | found i64) [E0308] 38 | if x == y { 39 | ^ 40 | ``` 41 | 42 | But, if we had an alias: 43 | 44 | ```rust 45 | type Num = i32; 46 | 47 | let x: i32 = 5; 48 | let y: Num = 5; 49 | 50 | if x == y { 51 | // ... 52 | } 53 | ``` 54 | 55 | This compiles without error. Values of a `Num` type are the same as a value of 56 | type `i32`, in every way. You can use [tuple struct] to really get a new type. 57 | 58 | [tuple struct]: structs.html#tuple-structs 59 | 60 | You can also use type aliases with generics: 61 | 62 | ```rust 63 | use std::result; 64 | 65 | enum ConcreteError { 66 | Foo, 67 | Bar, 68 | } 69 | 70 | type Result = result::Result; 71 | ``` 72 | 73 | This creates a specialized version of the `Result` type, which always has a 74 | `ConcreteError` for the `E` part of `Result`. This is commonly used 75 | in the standard library to create custom errors for each subsection. For 76 | example, [io::Result][ioresult]. 77 | 78 | [ioresult]: ../../std/io/type.Result.html 79 | -------------------------------------------------------------------------------- /first-edition/src/drop.md: -------------------------------------------------------------------------------- 1 | # Drop 2 | 3 | Now that we’ve discussed traits, let’s talk about a particular trait provided 4 | by the Rust standard library, [`Drop`][drop]. The `Drop` trait provides a way 5 | to run some code when a value goes out of scope. For example: 6 | 7 | [drop]: ../../std/ops/trait.Drop.html 8 | 9 | ```rust 10 | struct HasDrop; 11 | 12 | impl Drop for HasDrop { 13 | fn drop(&mut self) { 14 | println!("Dropping!"); 15 | } 16 | } 17 | 18 | fn main() { 19 | let x = HasDrop; 20 | 21 | // Do stuff. 22 | 23 | } // `x` goes out of scope here. 24 | ``` 25 | 26 | When `x` goes out of scope at the end of `main()`, the code for `Drop` will 27 | run. `Drop` has one method, which is also called `drop()`. It takes a mutable 28 | reference to `self`. 29 | 30 | That’s it! The mechanics of `Drop` are very simple, but there are some 31 | subtleties. For example, values are dropped in the opposite order they are 32 | declared. Here’s another example: 33 | 34 | ```rust 35 | struct Firework { 36 | strength: i32, 37 | } 38 | 39 | impl Drop for Firework { 40 | fn drop(&mut self) { 41 | println!("BOOM times {}!!!", self.strength); 42 | } 43 | } 44 | 45 | fn main() { 46 | let firecracker = Firework { strength: 1 }; 47 | let tnt = Firework { strength: 100 }; 48 | } 49 | ``` 50 | 51 | This will output: 52 | 53 | ```text 54 | BOOM times 100!!! 55 | BOOM times 1!!! 56 | ``` 57 | 58 | The `tnt` goes off before the `firecracker` does, because it was declared 59 | afterwards. Last in, first out. 60 | 61 | So what is `Drop` good for? Generally, `Drop` is used to clean up any resources 62 | associated with a `struct`. For example, the [`Arc` type][arc] is a 63 | reference-counted type. When `Drop` is called, it will decrement the reference 64 | count, and if the total number of references is zero, will clean up the 65 | underlying value. 66 | 67 | [arc]: ../../std/sync/struct.Arc.html 68 | -------------------------------------------------------------------------------- /first-edition/src/if.md: -------------------------------------------------------------------------------- 1 | # if 2 | 3 | Rust’s take on `if` is not particularly complex, but it’s much more like the 4 | `if` you’ll find in a dynamically typed language than in a more traditional 5 | systems language. So let’s talk about it, to make sure you grasp the nuances. 6 | 7 | `if` is a specific form of a more general concept, the ‘branch’, whose name comes 8 | from a branch in a tree: a decision point, where depending on a choice, 9 | multiple paths can be taken. 10 | 11 | In the case of `if`, there is one choice that leads down two paths: 12 | 13 | ```rust 14 | let x = 5; 15 | 16 | if x == 5 { 17 | println!("x is five!"); 18 | } 19 | ``` 20 | 21 | If we changed the value of `x` to something else, this line would not print. 22 | More specifically, if the expression after the `if` evaluates to `true`, then 23 | the block is executed. If it’s `false`, then it is not. 24 | 25 | If you want something to happen in the `false` case, use an `else`: 26 | 27 | ```rust 28 | let x = 5; 29 | 30 | if x == 5 { 31 | println!("x is five!"); 32 | } else { 33 | println!("x is not five :("); 34 | } 35 | ``` 36 | 37 | If there is more than one case, use an `else if`: 38 | 39 | ```rust 40 | let x = 5; 41 | 42 | if x == 5 { 43 | println!("x is five!"); 44 | } else if x == 6 { 45 | println!("x is six!"); 46 | } else { 47 | println!("x is not five or six :("); 48 | } 49 | ``` 50 | 51 | This is all pretty standard. However, you can also do this: 52 | 53 | ```rust 54 | let x = 5; 55 | 56 | let y = if x == 5 { 57 | 10 58 | } else { 59 | 15 60 | }; // y: i32 61 | ``` 62 | 63 | Which we can (and probably should) write like this: 64 | 65 | ```rust 66 | let x = 5; 67 | 68 | let y = if x == 5 { 10 } else { 15 }; // y: i32 69 | ``` 70 | 71 | This works because `if` is an expression. The value of the expression is the 72 | value of the last expression in whichever branch was chosen. An `if` without an 73 | `else` always results in `()` as the value. 74 | -------------------------------------------------------------------------------- /second-edition/src/ch01-00-introduction.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | Welcome to “The Rust Programming Language,” an introductory book about Rust. 4 | Rust is a programming language that’s focused on safety, speed, and 5 | concurrency. Its design lets you create programs that have the performance and 6 | control of a low-level language, but with the powerful abstractions of a 7 | high-level language. These properties make Rust suitable for programmers who 8 | have experience in languages like C and are looking for a safer alternative, as 9 | well as those from languages like Python who are looking for ways to write code 10 | that performs better without sacrificing expressiveness. 11 | 12 | Rust performs the majority of its safety checks and memory management decisions 13 | at compile time, so that your program's runtime performance isn't impacted. This 14 | makes it useful in a number of use cases that other languages aren’t good at: 15 | programs with predictable space and time requirements, embedding in other 16 | languages, and writing low-level code, like device drivers and operating 17 | systems. It's also great for web applications: it powers the Rust package 18 | registry site, [crates.io]! We're excited to see what *you* create with Rust. 19 | 20 | [crates.io]: https://crates.io/ 21 | 22 | This book is written for a reader who already knows how to program in at least 23 | one programming language. After reading this book, you should be comfortable 24 | writing Rust programs. We’ll be learning Rust through small, focused examples 25 | that build on each other to demonstrate how to use various features of Rust as 26 | well as how they work behind the scenes. 27 | 28 | ## Contributing to the book 29 | 30 | This book is open source. If you find an error, please don’t hesitate to file an 31 | issue or send a pull request [on GitHub]. Please see [CONTRIBUTING.md] for 32 | more details. 33 | 34 | [on GitHub]: https://github.com/rust-lang/book 35 | [CONTRIBUTING.md]: https://github.com/rust-lang/book/blob/master/CONTRIBUTING.md 36 | -------------------------------------------------------------------------------- /second-edition/src/ch11-00-testing.md: -------------------------------------------------------------------------------- 1 | # Testing 2 | 3 | > Program testing can be a very effective way to show the presence of bugs, but 4 | > it is hopelessly inadequate for showing their absence. 5 | > 6 | > Edsger W. Dijkstra, "The Humble Programmer" (1972) 7 | 8 | Correctness in our programs means that our code does what we intend for it to 9 | do. Rust is a programming language that cares a lot about correctness, but 10 | correctness is a complex topic and isn't easy to prove. Rust's type system 11 | shoulders a huge part of this burden, but the type system cannot catch every 12 | kind of incorrectness. As such, Rust includes support for writing software 13 | tests within the language itself. 14 | 15 | As an example, say we write a function called `add_two` that adds two to a 16 | number passed to it. This function's signature accepts an integer as a 17 | parameter and returns an integer as a result. When we implement and compile 18 | that function, Rust will do all the type checking and borrow checking that 19 | we've seen so far. Those checks will make sure that, for instance, we aren't 20 | passing a `String` value or an invalid reference to this function. What Rust 21 | *can't* check is that this function will do precisely what we intend: return 22 | the parameter plus two, rather than, say, the parameter plus 10 or the 23 | parameter minus 50! That's where tests come in. 24 | 25 | We can write tests that assert, for example, that when we pass `3` to the 26 | `add_two` function, we get `5` back. We can run these tests whenever we make 27 | changes to our code to make sure any existing correct behavior has not changed. 28 | 29 | Testing is a complex skill, and we cannot hope to cover everything about how to 30 | write good tests in one chapter of a book, so here we'll just discuss the 31 | mechanics of Rust's testing facilities. We'll talk about the annotations and 32 | macros available to you when writing your tests, the default behavior and 33 | options provided for running your tests, and how to organize tests into unit 34 | tests and integration tests. 35 | -------------------------------------------------------------------------------- /second-edition/tools/src/bin/remove_links.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT 2 | // file at the top-level directory of this distribution and at 3 | // http://rust-lang.org/COPYRIGHT. 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | 11 | extern crate regex; 12 | 13 | use std::io; 14 | use std::io::{Read, Write}; 15 | use regex::{Regex, Captures}; 16 | use std::collections::HashSet; 17 | 18 | fn main () { 19 | let mut buffer = String::new(); 20 | if let Err(e) = io::stdin().read_to_string(&mut buffer) { 21 | panic!(e); 22 | } 23 | 24 | let mut refs = HashSet::new(); 25 | 26 | // capture all links and link references 27 | let regex = r"\[([^\]]+)\](?:(?:\[([^\]]+)\])|(?:\([^\)]+\)))(?i)"; 28 | let link_regex = Regex::new(regex).unwrap(); 29 | let first_pass = link_regex.replace_all(&buffer, |caps: &Captures| { 30 | 31 | // save the link reference we want to delete 32 | if let Some(reference) = caps.at(2) { 33 | refs.insert(reference.to_owned()); 34 | } 35 | 36 | // put the link title back 37 | caps.at(1).unwrap().to_owned() 38 | }); 39 | 40 | // search for the references we need to delete 41 | let ref_regex = Regex::new(r"\n\[([^\]]+)\]:\s.*\n").unwrap(); 42 | let out = ref_regex.replace_all(&first_pass, |caps: &Captures| { 43 | let capture = caps.at(1).unwrap().to_owned(); 44 | 45 | // check if we've marked this reference for deletion... 46 | if refs.contains(capture.as_str()) { 47 | return "".to_string(); 48 | } 49 | 50 | //... else we put back everything we captured 51 | caps.at(0).unwrap().to_owned() 52 | }); 53 | 54 | write!(io::stdout(), "{}", out).unwrap(); 55 | } 56 | -------------------------------------------------------------------------------- /first-edition/src/comments.md: -------------------------------------------------------------------------------- 1 | # Comments 2 | 3 | Now that we have some functions, it’s a good idea to learn about comments. 4 | Comments are notes that you leave to other programmers to help explain things 5 | about your code. The compiler mostly ignores them. 6 | 7 | Rust has two kinds of comments that you should care about: *line comments* 8 | and *doc comments*. 9 | 10 | ```rust 11 | // Line comments are anything after ‘//’ and extend to the end of the line. 12 | 13 | let x = 5; // This is also a line comment. 14 | 15 | // If you have a long explanation for something, you can put line comments next 16 | // to each other. Put a space between the // and your comment so that it’s 17 | // more readable. 18 | ``` 19 | 20 | The other kind of comment is a doc comment. Doc comments use `///` instead of 21 | `//`, and support Markdown notation inside: 22 | 23 | ```rust 24 | /// Adds one to the number given. 25 | /// 26 | /// # Examples 27 | /// 28 | /// ``` 29 | /// let five = 5; 30 | /// 31 | /// assert_eq!(6, add_one(5)); 32 | /// # fn add_one(x: i32) -> i32 { 33 | /// # x + 1 34 | /// # } 35 | /// ``` 36 | fn add_one(x: i32) -> i32 { 37 | x + 1 38 | } 39 | ``` 40 | 41 | There is another style of doc comment, `//!`, to comment containing items (e.g. 42 | crates, modules or functions), instead of the items following it. Commonly used 43 | inside crates root (lib.rs) or modules root (mod.rs): 44 | 45 | ``` 46 | //! # The Rust Standard Library 47 | //! 48 | //! The Rust Standard Library provides the essential runtime 49 | //! functionality for building portable Rust software. 50 | ``` 51 | 52 | When writing doc comments, providing some examples of usage is very, very 53 | helpful. You’ll notice we’ve used a new macro here: `assert_eq!`. This compares 54 | two values, and `panic!`s if they’re not equal to each other. It’s very helpful 55 | in documentation. There’s another macro, `assert!`, which `panic!`s if the 56 | value passed to it is `false`. 57 | 58 | You can use the [`rustdoc`](documentation.html) tool to generate HTML documentation 59 | from these doc comments, and also to run the code examples as tests! 60 | -------------------------------------------------------------------------------- /first-edition/src/unsized-types.md: -------------------------------------------------------------------------------- 1 | # Unsized Types 2 | 3 | Most types have a particular size, in bytes, that is knowable at compile time. 4 | For example, an `i32` is thirty-two bits big, or four bytes. However, there are 5 | some types which are useful to express, but do not have a defined size. These are 6 | called ‘unsized’ or ‘dynamically sized’ types. One example is `[T]`. This type 7 | represents a certain number of `T` in sequence. But we don’t know how many 8 | there are, so the size is not known. 9 | 10 | Rust understands a few of these types, but they have some restrictions. There 11 | are three: 12 | 13 | 1. We can only manipulate an instance of an unsized type via a pointer. An 14 | `&[T]` works fine, but a `[T]` does not. 15 | 2. Variables and arguments cannot have dynamically sized types. 16 | 3. Only the last field in a `struct` may have a dynamically sized type; the 17 | other fields must not. Enum variants must not have dynamically sized types as 18 | data. 19 | 20 | So why bother? Well, because `[T]` can only be used behind a pointer, if we 21 | didn’t have language support for unsized types, it would be impossible to write 22 | this: 23 | 24 | ```rust,ignore 25 | impl Foo for str { 26 | ``` 27 | 28 | or 29 | 30 | ```rust,ignore 31 | impl Foo for [T] { 32 | ``` 33 | 34 | Instead, you would have to write: 35 | 36 | ```rust,ignore 37 | impl Foo for &str { 38 | ``` 39 | 40 | Meaning, this implementation would only work for [references][ref], and not 41 | other types of pointers. With the `impl for str`, all pointers, including (at 42 | some point, there are some bugs to fix first) user-defined custom smart 43 | pointers, can use this `impl`. 44 | 45 | [ref]: references-and-borrowing.html 46 | 47 | # ?Sized 48 | 49 | If you want to write a function that accepts a dynamically sized type, you 50 | can use the special bound syntax, `?Sized`: 51 | 52 | ```rust 53 | struct Foo { 54 | f: T, 55 | } 56 | ``` 57 | 58 | This `?Sized`, read as “T may or may not be `Sized`”, which allows us to match 59 | both sized and unsized types. All generic type parameters implicitly 60 | have the `Sized` bound, so the `?Sized` can be used to opt-out of the implicit 61 | bound. 62 | -------------------------------------------------------------------------------- /first-edition/src/if-let.md: -------------------------------------------------------------------------------- 1 | # if let 2 | 3 | `if let` permits [patterns][patterns] matching within the condition of an [if][if] statement. 4 | This allows us to reduce the overhead of certain kinds of [pattern][patterns] matches 5 | and express them in a more convenient way. 6 | 7 | For example, let’s say we have some sort of `Option`. We want to call a function 8 | on it if it’s `Some`, but do nothing if it’s `None`. That looks like this: 9 | 10 | ```rust 11 | # let option = Some(5); 12 | # fn foo(x: i32) { } 13 | match option { 14 | Some(x) => { foo(x) }, 15 | None => {}, 16 | } 17 | ``` 18 | 19 | We don’t have to use `match` here, for example, we could use `if`: 20 | 21 | ```rust 22 | # let option = Some(5); 23 | # fn foo(x: i32) { } 24 | if option.is_some() { 25 | let x = option.unwrap(); 26 | foo(x); 27 | } 28 | ``` 29 | 30 | Neither of these options is particularly appealing. We can use `if let` to 31 | do the same thing in a nicer way: 32 | 33 | ```rust 34 | # let option = Some(5); 35 | # fn foo(x: i32) { } 36 | if let Some(x) = option { 37 | foo(x); 38 | } 39 | ``` 40 | 41 | If a [pattern][patterns] matches successfully, it binds any appropriate parts of 42 | the value to the identifiers in the pattern, then evaluates the expression. If 43 | the pattern doesn’t match, nothing happens. 44 | 45 | If you want to do something else when the pattern does not match, you can 46 | use `else`: 47 | 48 | ```rust 49 | # let option = Some(5); 50 | # fn foo(x: i32) { } 51 | # fn bar() { } 52 | if let Some(x) = option { 53 | foo(x); 54 | } else { 55 | bar(); 56 | } 57 | ``` 58 | 59 | ## `while let` 60 | 61 | In a similar fashion, `while let` can be used when you want to conditionally 62 | loop as long as a value matches a certain pattern. It turns code like this: 63 | 64 | ```rust 65 | let mut v = vec![1, 3, 5, 7, 11]; 66 | loop { 67 | match v.pop() { 68 | Some(x) => println!("{}", x), 69 | None => break, 70 | } 71 | } 72 | ``` 73 | 74 | Into code like this: 75 | 76 | ```rust 77 | let mut v = vec![1, 3, 5, 7, 11]; 78 | while let Some(x) = v.pop() { 79 | println!("{}", x); 80 | } 81 | ``` 82 | 83 | [patterns]: patterns.html 84 | [if]: if.html 85 | -------------------------------------------------------------------------------- /second-edition/src/ch14-01-release-profiles.md: -------------------------------------------------------------------------------- 1 | ## Release profiles 2 | 3 | Cargo supports a notion of *release profiles*. These profiles control various 4 | options for compiling your code and let you configure each profile 5 | independently of the others. You've seen a hint of this feature in the output 6 | of your builds: 7 | 8 | ```text 9 | $ cargo build 10 | Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs 11 | $ cargo build --release 12 | Finished release [optimized] target(s) in 0.0 secs 13 | ``` 14 | 15 | The "dev" and "release" notifications here indicate that the compiler is 16 | using different profiles. Cargo supports four profiles: 17 | 18 | * `dev`: used for `cargo build` 19 | * `release` used for `cargo build --release` 20 | * `test` used for `cargo test` 21 | * `doc` used for `cargo doc` 22 | 23 | We can customize our `Cargo.toml` file with `[profile.*]` sections to tweak 24 | various compiler options for these profiles. For example, here's one of the 25 | default options for the `dev` and `release` profiles: 26 | 27 | ```toml 28 | [profile.dev] 29 | opt-level = 0 30 | 31 | [profile.release] 32 | opt-level = 3 33 | ``` 34 | 35 | The `opt-level` setting controls how many optimizations Rust will apply to your 36 | code. The setting goes from zero to three. Applying more optimizations takes 37 | more time. When you're compiling very often in development, you'd usually want 38 | compiling to be fast at the expense of the resulting code running slower. When 39 | you're ready to release, it's better to spend more time compiling the one time 40 | that you build your code to trade off for code that will run faster every time 41 | you use that compiled code. 42 | 43 | We could override these defaults by changing them in `Cargo.toml`. For example, 44 | if we wanted to use optimization level 1 in development: 45 | 46 | ```toml 47 | [profile.dev] 48 | opt-level = 1 49 | ``` 50 | 51 | This overrides the default setting of `0`, and now our development builds will 52 | use more optimizations. Not as much as a release build, but a little bit more. 53 | 54 | For the full list of settings and the defaults for each profile, see [Cargo's 55 | documentation.][cargodoc] 56 | 57 | [cargodoc]: http://doc.crates.io/ 58 | -------------------------------------------------------------------------------- /second-edition/tools/src/bin/remove_markup.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT 2 | // file at the top-level directory of this distribution and at 3 | // http://rust-lang.org/COPYRIGHT. 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | 11 | extern crate regex; 12 | use std::io; 13 | use std::io::{Read, Write}; 14 | use regex::{Regex, Captures}; 15 | 16 | fn main() { 17 | write_md(remove_markup(read_md())); 18 | } 19 | 20 | fn read_md() -> String { 21 | let mut buffer = String::new(); 22 | match io::stdin().read_to_string(&mut buffer) { 23 | Ok(_) => buffer, 24 | Err(error) => panic!(error), 25 | } 26 | } 27 | 28 | fn write_md(output: String) { 29 | write!(io::stdout(), "{}", output).unwrap(); 30 | } 31 | 32 | fn remove_markup(input: String) -> String { 33 | let filename_regex = Regex::new(r#"\A(.*)\z"#).unwrap(); 34 | // Captions sometimes take up multiple lines 35 | let caption_start_regex = Regex::new(r#"\A(.*)\z"#).unwrap(); 36 | let caption_end_regex = Regex::new(r#"(.*)\z"#).unwrap(); 37 | let regexen = vec![filename_regex, caption_start_regex, caption_end_regex]; 38 | 39 | let lines: Vec<_> = input.lines().flat_map(|line| { 40 | // Remove our figure and caption markup 41 | if line == "
" || 42 | line == "
" || 43 | line == "
" || 44 | line == "
" 45 | { 46 | None 47 | // Remove our syntax highlighting and rustdoc markers 48 | } else if line.starts_with("```") { 49 | Some(String::from("```")) 50 | // Remove the span around filenames and captions 51 | } else { 52 | let result = regexen.iter().fold(line.to_string(), |result, regex| { 53 | regex.replace_all(&result, |caps: &Captures| { 54 | caps.at(1).unwrap().to_owned() 55 | }) 56 | }); 57 | Some(result) 58 | } 59 | }).collect(); 60 | lines.join("\n") 61 | } 62 | -------------------------------------------------------------------------------- /second-edition/src/ch15-00-smart-pointers.md: -------------------------------------------------------------------------------- 1 | # Smart Pointers 2 | 3 | *Pointer* is a generic programming term for something that refers to a location 4 | that stores some other data. We learned about Rust's references in Chapter 4; 5 | they're a plain sort of pointer indicated by the `&` symbol and borrow the 6 | value that they point to. *Smart pointers* are data structures that act like a 7 | pointer, but also have additional metadata and capabilities, such as reference 8 | counting. The smart pointer pattern originated in C++. In Rust, an additional 9 | difference between plain references and smart pointers is that references are a 10 | kind of pointer that only borrow data; by contrast, in many cases, smart 11 | pointers *own* the data that they point to. 12 | 13 | We've actually already encountered a few smart pointers in this book, even 14 | though we didn't call them that by name at the time. For example, in a certain 15 | sense, `String` and `Vec` from Chapter 8 are both smart pointers. They own 16 | some memory and allow you to manipulate it, and have metadata (like their 17 | capacity) and extra capabilities or guarantees (`String` data will always be 18 | valid UTF-8). The characteristics that distinguish a smart pointer from an 19 | ordinary struct are that smart pointers implement the `Deref` and `Drop` 20 | traits, and in this chapter we'll be discussing both of those traits and why 21 | they're important to smart pointers. 22 | 23 | Given that the smart pointer pattern is a general design pattern used 24 | frequently in Rust, this chapter won't cover every smart pointer that exists. 25 | Many libraries have their own and you may write some yourself. The ones we 26 | cover here are the most common ones from the standard library: 27 | 28 | * `Box`, for allocating values on the heap 29 | * `Rc`, a reference counted type so data can have multiple owners 30 | * `RefCell`, which isn't a smart pointer itself, but manages access to the 31 | smart pointers `Ref` and `RefMut` to enforce the borrowing rules at runtime 32 | instead of compile time 33 | 34 | Along the way, we'll also cover: 35 | 36 | * The *interior mutability* pattern where an immutable type exposes an API for 37 | mutating an interior value, and the borrowing rules apply at runtime instead 38 | of compile time 39 | * Reference cycles, how they can leak memory, and how to prevent them 40 | 41 | Let's dive in! 42 | -------------------------------------------------------------------------------- /first-edition/src/conditional-compilation.md: -------------------------------------------------------------------------------- 1 | # Conditional Compilation 2 | 3 | Rust has a special attribute, `#[cfg]`, which allows you to compile code 4 | based on a flag passed to the compiler. It has two forms: 5 | 6 | ```rust 7 | #[cfg(foo)] 8 | # fn foo() {} 9 | 10 | #[cfg(bar = "baz")] 11 | # fn bar() {} 12 | ``` 13 | 14 | They also have some helpers: 15 | 16 | ```rust 17 | #[cfg(any(unix, windows))] 18 | # fn foo() {} 19 | 20 | #[cfg(all(unix, target_pointer_width = "32"))] 21 | # fn bar() {} 22 | 23 | #[cfg(not(foo))] 24 | # fn not_foo() {} 25 | ``` 26 | 27 | These can nest arbitrarily: 28 | 29 | ```rust 30 | #[cfg(any(not(unix), all(target_os="macos", target_arch = "powerpc")))] 31 | # fn foo() {} 32 | ``` 33 | 34 | As for how to enable or disable these switches, if you’re using Cargo, 35 | they get set in the [`[features]` section][features] of your `Cargo.toml`: 36 | 37 | [features]: http://doc.crates.io/manifest.html#the-features-section 38 | 39 | ```toml 40 | [features] 41 | # no features by default 42 | default = [] 43 | 44 | # Add feature "foo" here, then you can use it. 45 | # Our "foo" feature depends on nothing else. 46 | foo = [] 47 | ``` 48 | 49 | When you do this, Cargo passes along a flag to `rustc`: 50 | 51 | ```text 52 | --cfg feature="${feature_name}" 53 | ``` 54 | 55 | The sum of these `cfg` flags will determine which ones get activated, and 56 | therefore, which code gets compiled. Let’s take this code: 57 | 58 | ```rust 59 | #[cfg(feature = "foo")] 60 | mod foo { 61 | } 62 | ``` 63 | 64 | If we compile it with `cargo build --features "foo"`, it will send the `--cfg 65 | feature="foo"` flag to `rustc`, and the output will have the `mod foo` in it. 66 | If we compile it with a regular `cargo build`, no extra flags get passed on, 67 | and so, no `foo` module will exist. 68 | 69 | # cfg_attr 70 | 71 | You can also set another attribute based on a `cfg` variable with `cfg_attr`: 72 | 73 | ```rust 74 | #[cfg_attr(a, b)] 75 | # fn foo() {} 76 | ``` 77 | 78 | Will be the same as `#[b]` if `a` is set by `cfg` attribute, and nothing otherwise. 79 | 80 | # cfg! 81 | 82 | The `cfg!` macro lets you use these kinds of flags elsewhere in your code, too: 83 | 84 | ```rust 85 | if cfg!(target_os = "macos") || cfg!(target_os = "ios") { 86 | println!("Think Different!"); 87 | } 88 | ``` 89 | 90 | These will be replaced by a `true` or `false` at compile-time, depending on the 91 | configuration settings. 92 | -------------------------------------------------------------------------------- /first-edition/src/README.md: -------------------------------------------------------------------------------- 1 | # The Rust Programming Language 2 | 3 | Welcome! This book will teach you about the [Rust Programming Language][rust]. 4 | Rust is a systems programming language focused on three goals: safety, speed, 5 | and concurrency. It maintains these goals without having a garbage collector, 6 | making it a useful language for a number of use cases other languages aren’t 7 | good at: embedding in other languages, programs with specific space and time 8 | requirements, and writing low-level code, like device drivers and operating 9 | systems. It improves on current languages targeting this space by having a 10 | number of compile-time safety checks that produce no runtime overhead, while 11 | eliminating all data races. Rust also aims to achieve ‘zero-cost abstractions’ 12 | even though some of these abstractions feel like those of a high-level language. 13 | Even then, Rust still allows precise control like a low-level language would. 14 | 15 | [rust]: https://www.rust-lang.org 16 | 17 | “The Rust Programming Language” is split into chapters. This introduction 18 | is the first. After this: 19 | 20 | * [Getting started][gs] - Set up your computer for Rust development. 21 | * [Tutorial: Guessing Game][gg] - Learn some Rust with a small project. 22 | * [Syntax and Semantics][ss] - Each bit of Rust, broken down into small chunks. 23 | * [Effective Rust][er] - Higher-level concepts for writing excellent Rust code. 24 | * [Glossary][gl] - A reference of terms used in the book. 25 | * [Bibliography][bi] - Background on Rust's influences, papers about Rust. 26 | 27 | [gs]: getting-started.html 28 | [gg]: guessing-game.html 29 | [er]: effective-rust.html 30 | [ss]: syntax-and-semantics.html 31 | [gl]: glossary.html 32 | [bi]: bibliography.html 33 | 34 | ### Contributing 35 | 36 | The source files from which this book is generated can be found on 37 | [GitHub][book]. 38 | 39 | ### Second edition of this book 40 | 41 | There are two editions of "The Rust Programming Language", this being the 42 | first edition. 43 | 44 | The [second edition][second-edition] is a complete re-write. It is still under 45 | construction, though it is far enough along to learn most of Rust. We suggest 46 | reading the second edition and then checking out the first edition later to pick 47 | up some of the more esoteric parts of the language. 48 | 49 | [book]: https://github.com/rust-lang/book/tree/master/first-edition/src 50 | [second-edition]: ../second-edition/index.html 51 | -------------------------------------------------------------------------------- /first-edition/src/SUMMARY.md: -------------------------------------------------------------------------------- 1 | # Summary 2 | 3 | [Introduction](README.md) 4 | 5 | * [Getting Started](getting-started.md) 6 | * [Tutorial: Guessing Game](guessing-game.md) 7 | * [Syntax and Semantics](syntax-and-semantics.md) 8 | * [Variable Bindings](variable-bindings.md) 9 | * [Functions](functions.md) 10 | * [Primitive Types](primitive-types.md) 11 | * [Comments](comments.md) 12 | * [if](if.md) 13 | * [Loops](loops.md) 14 | * [Vectors](vectors.md) 15 | * [Ownership](ownership.md) 16 | * [References and Borrowing](references-and-borrowing.md) 17 | * [Lifetimes](lifetimes.md) 18 | * [Mutability](mutability.md) 19 | * [Structs](structs.md) 20 | * [Enums](enums.md) 21 | * [Match](match.md) 22 | * [Patterns](patterns.md) 23 | * [Method Syntax](method-syntax.md) 24 | * [Strings](strings.md) 25 | * [Generics](generics.md) 26 | * [Traits](traits.md) 27 | * [Drop](drop.md) 28 | * [if let](if-let.md) 29 | * [Trait Objects](trait-objects.md) 30 | * [Closures](closures.md) 31 | * [Universal Function Call Syntax](ufcs.md) 32 | * [Crates and Modules](crates-and-modules.md) 33 | * [`const` and `static`](const-and-static.md) 34 | * [Attributes](attributes.md) 35 | * [`type` aliases](type-aliases.md) 36 | * [Casting between types](casting-between-types.md) 37 | * [Associated Types](associated-types.md) 38 | * [Unsized Types](unsized-types.md) 39 | * [Operators and Overloading](operators-and-overloading.md) 40 | * [Deref coercions](deref-coercions.md) 41 | * [Macros](macros.md) 42 | * [Raw Pointers](raw-pointers.md) 43 | * [`unsafe`](unsafe.md) 44 | * [Effective Rust](effective-rust.md) 45 | * [The Stack and the Heap](the-stack-and-the-heap.md) 46 | * [Testing](testing.md) 47 | * [Conditional Compilation](conditional-compilation.md) 48 | * [Documentation](documentation.md) 49 | * [Iterators](iterators.md) 50 | * [Concurrency](concurrency.md) 51 | * [Error Handling](error-handling.md) 52 | * [Choosing your Guarantees](choosing-your-guarantees.md) 53 | * [FFI](ffi.md) 54 | * [Borrow and AsRef](borrow-and-asref.md) 55 | * [Release Channels](release-channels.md) 56 | * [Using Rust without the standard library](using-rust-without-the-standard-library.md) 57 | * [Procedural Macros (and custom derive)](procedural-macros.md) 58 | * [Glossary](glossary.md) 59 | * [Syntax Index](syntax-index.md) 60 | * [Bibliography](bibliography.md) 61 | -------------------------------------------------------------------------------- /first-edition/src/const-and-static.md: -------------------------------------------------------------------------------- 1 | # const and static 2 | 3 | Rust has a way of defining constants with the `const` keyword: 4 | 5 | ```rust 6 | const N: i32 = 5; 7 | ``` 8 | 9 | Unlike [`let`][let] bindings, you must annotate the type of a `const`. 10 | 11 | [let]: variable-bindings.html 12 | 13 | Constants live for the entire lifetime of a program. More specifically, 14 | constants in Rust have no fixed address in memory. This is because they’re 15 | effectively inlined to each place that they’re used. References to the same 16 | constant are not necessarily guaranteed to refer to the same memory address for 17 | this reason. 18 | 19 | # `static` 20 | 21 | Rust provides a ‘global variable’ sort of facility in static items. They’re 22 | similar to constants, but static items aren’t inlined upon use. This means that 23 | there is only one instance for each value, and it’s at a fixed location in 24 | memory. 25 | 26 | Here’s an example: 27 | 28 | ```rust 29 | static N: i32 = 5; 30 | ``` 31 | 32 | Unlike [`let`][let] bindings, you must annotate the type of a `static`. 33 | 34 | Statics live for the entire lifetime of a program, and therefore any 35 | reference stored in a static has a [`'static` lifetime][lifetimes]: 36 | 37 | ```rust 38 | static NAME: &'static str = "Steve"; 39 | ``` 40 | 41 | [lifetimes]: lifetimes.html 42 | 43 | ## Mutability 44 | 45 | You can introduce mutability with the `mut` keyword: 46 | 47 | ```rust 48 | static mut N: i32 = 5; 49 | ``` 50 | 51 | Because this is mutable, one thread could be updating `N` while another is 52 | reading it, causing memory unsafety. As such both accessing and mutating a 53 | `static mut` is [`unsafe`][unsafe], and so must be done in an `unsafe` block: 54 | 55 | ```rust 56 | # static mut N: i32 = 5; 57 | 58 | unsafe { 59 | N += 1; 60 | 61 | println!("N: {}", N); 62 | } 63 | ``` 64 | 65 | [unsafe]: unsafe.html 66 | 67 | Furthermore, any type stored in a `static` must be `Sync`, and must not have 68 | a [`Drop`][drop] implementation. 69 | 70 | [drop]: drop.html 71 | 72 | # Initializing 73 | 74 | Both `const` and `static` have requirements for giving them a value. They must 75 | be given a value that’s a constant expression. In other words, you cannot use 76 | the result of a function call or anything similarly complex or at runtime. 77 | 78 | # Which construct should I use? 79 | 80 | Almost always, if you can choose between the two, choose `const`. It’s pretty 81 | rare that you actually want a memory location associated with your constant, 82 | and using a `const` allows for optimizations like constant propagation not only 83 | in your crate but downstream crates. 84 | -------------------------------------------------------------------------------- /second-edition/src/appendix-01-keywords.md: -------------------------------------------------------------------------------- 1 | ## Appendix A: Keywords 2 | 3 | The following keywords are reserved by the Rust language and may not be used as 4 | identifiers such as names of functions, variables, parameters, struct fields, 5 | modules, crates, constants, macros, static values, attributes, types, traits, 6 | or lifetimes. 7 | 8 | ### Keywords Currently in Use 9 | 10 | * `as` - primitive casting, disambiguating the specific trait containing an 11 | item, or renaming items in `use` and `extern crate` statements 12 | * `break` - exit a loop immediately 13 | * `const` - constant items and constant raw pointers 14 | * `continue` - continue to the next loop iteration 15 | * `crate` - external crate linkage or a macro variable representing the crate 16 | in which the macro is defined 17 | * `else` - fallback for `if` and `if let` control flow constructs 18 | * `enum` - defining an enumeration 19 | * `extern` - external crate, function, and variable linkage 20 | * `false` - boolean false literal 21 | * `fn` - function definition and function pointer type 22 | * `for` - iterator loop, part of trait impl syntax, and higher-ranked lifetime 23 | syntax 24 | * `if` - conditional branching 25 | * `impl` - inherent and trait implementation block 26 | * `in` - part of `for` loop syntax 27 | * `let` - variable binding 28 | * `loop` - unconditional, infinite loop 29 | * `match` - pattern matching 30 | * `mod` - module declaration 31 | * `move` - makes a closure take ownership of all its captures 32 | * `mut` - denotes mutability in references, raw pointers, and pattern bindings 33 | * `pub` - denotes public visibility in struct fields, `impl` blocks, and modules 34 | * `ref` - by-reference binding 35 | * `return` - return from function 36 | * `Self` - type alias for the type implementing a trait 37 | * `self` - method subject or current module 38 | * `static` - global variable or lifetime lasting the entire program execution 39 | * `struct` - structure definition 40 | * `super` - parent module of the current module 41 | * `trait` - trait definition 42 | * `true` - boolean true literal 43 | * `type` - type alias and associated type definition 44 | * `unsafe` - denotes unsafe code, functions, traits, and implementations 45 | * `use` - import symbols into scope 46 | * `where` - type constraint clauses 47 | * `while` - conditional loop 48 | 49 | ### Keywords Reserved for Future Use 50 | 51 | These keywords do not have any functionality, but are reserved by Rust for 52 | potential future use. 53 | 54 | * `abstract` 55 | * `alignof` 56 | * `become` 57 | * `box` 58 | * `do` 59 | * `final` 60 | * `macro` 61 | * `offsetof` 62 | * `override` 63 | * `priv` 64 | * `proc` 65 | * `pure` 66 | * `sizeof` 67 | * `typeof` 68 | * `unsized` 69 | * `virtual` 70 | * `yield` 71 | -------------------------------------------------------------------------------- /first-edition/src/release-channels.md: -------------------------------------------------------------------------------- 1 | # Release Channels 2 | 3 | The Rust project uses a concept called ‘release channels’ to manage releases. 4 | It’s important to understand this process to choose which version of Rust 5 | your project should use. 6 | 7 | # Overview 8 | 9 | There are three channels for Rust releases: 10 | 11 | * Nightly 12 | * Beta 13 | * Stable 14 | 15 | New nightly releases are created once a day. Every six weeks, the latest 16 | nightly release is promoted to ‘Beta’. At that point, it will only receive 17 | patches to fix serious errors. Six weeks later, the beta is promoted to 18 | ‘Stable’, and becomes the next release of `1.x`. 19 | 20 | This process happens in parallel. So every six weeks, on the same day, 21 | nightly goes to beta, beta goes to stable. When `1.x` is released, at 22 | the same time, `1.(x + 1)-beta` is released, and the nightly becomes the 23 | first version of `1.(x + 2)-nightly`. 24 | 25 | # Choosing a version 26 | 27 | Generally speaking, unless you have a specific reason, you should be using the 28 | stable release channel. These releases are intended for a general audience. 29 | 30 | However, depending on your interest in Rust, you may choose to use nightly 31 | instead. The basic tradeoff is this: in the nightly channel, you can use 32 | unstable, new Rust features. However, unstable features are subject to change, 33 | and so any new nightly release may break your code. If you use the stable 34 | release, you cannot use experimental features, but the next release of Rust 35 | will not cause significant issues through breaking changes. 36 | 37 | # Helping the ecosystem through CI 38 | 39 | What about beta? We encourage all Rust users who use the stable release channel 40 | to also test against the beta channel in their continuous integration systems. 41 | This will help alert the team in case there’s an accidental regression. 42 | 43 | Additionally, testing against nightly can catch regressions even sooner, and so 44 | if you don’t mind a third build, we’d appreciate testing against all channels. 45 | 46 | As an example, many Rust programmers use [Travis](https://travis-ci.org/) to 47 | test their crates, which is free for open source projects. Travis [supports 48 | Rust directly][travis], and you can use a `.travis.yml` file like this to 49 | test on all channels: 50 | 51 | ```yaml 52 | language: rust 53 | rust: 54 | - nightly 55 | - beta 56 | - stable 57 | 58 | matrix: 59 | allow_failures: 60 | - rust: nightly 61 | ``` 62 | 63 | [travis]: http://docs.travis-ci.com/user/languages/rust/ 64 | 65 | With this configuration, Travis will test all three channels, but if something 66 | breaks on nightly, it won’t fail your build. A similar configuration is 67 | recommended for any CI system, check the documentation of the one you’re 68 | using for more details. 69 | -------------------------------------------------------------------------------- /second-edition/src/ch16-00-concurrency.md: -------------------------------------------------------------------------------- 1 | # Fearless Concurrency 2 | 3 | Ensuring memory safety isn't Rust's only goal: being a language that is better 4 | equipped to handle concurrent and parallel programming has always been another 5 | major goal of Rust. *Concurrent programming*, where different parts of a 6 | program execute independently, and *parallel programming*, where different 7 | parts of a program are executing at the same time, are becoming more important 8 | as more computers have multiple processors for our programs to take advantage 9 | of. Historically, programming in these contexts has been difficult and error 10 | prone: Rust hopes to change that. 11 | 12 | Originally, we thought that memory safety and preventing concurrency problems 13 | were two separate challenges to be solved with different methods. However, over 14 | time, we discovered that ownership and the type system are a powerful set of 15 | tools that help in dealing with both memory safety *and* concurrency problems! 16 | By leveraging ownership and type checking, many concurrency errors are *compile 17 | time* errors in Rust, rather than runtime errors. We've nicknamed this aspect 18 | of Rust *fearless concurrency*. Fearless concurrency means Rust not only allows 19 | you to have confidence that your code is free of subtle bugs, but also lets you 20 | refactor this kind of code easily without worrying about introducing new bugs. 21 | 22 | > Note: given that Rust's slogan is *fearless concurrency*, we'll be referring 23 | > to many of the problems here as *concurrent* rather than being more precise 24 | > by saying *concurrent and/or parallel*, for simplicity's sake. If this were a 25 | > book specifically about concurrency and/or parallelism, we'd be sure to be 26 | > more specific. For this chapter, please mentally substitute 27 | > *concurrent and/or parallel* whenever we say *concurrent*. 28 | 29 | Many languages are strongly opinionated about the solutions they offer you to 30 | deal with concurrent problems. That's a very reasonable strategy, especially 31 | for higher-level languages, but lower-level languages don't have that luxury. 32 | Lower-level languages are expected to enable whichever solution would provide 33 | the best performance in a given situation, and they have fewer abstractions 34 | over the hardware. Rust, therefore, gives us a variety of tools for modeling 35 | our problems in whatever way is appropriate for our situation and requirements. 36 | 37 | Here's what we'll cover in this chapter: 38 | 39 | * How to create threads to run multiple pieces of code at the same time 40 | * *Message passing* concurrency, where channels are used to send messages 41 | between threads. 42 | * *Shared state* concurrency, where multiple threads have access to some piece 43 | of data. 44 | * The `Sync` and `Send` traits, which allow Rust's concurrency guarantees to be 45 | extended to user-defined types as well as types provided by the standard 46 | library. 47 | -------------------------------------------------------------------------------- /first-edition/src/glossary.md: -------------------------------------------------------------------------------- 1 | # Glossary 2 | 3 | Not every Rustacean has a background in systems programming, nor in computer 4 | science, so we've added explanations of terms that might be unfamiliar. 5 | 6 | ### Abstract Syntax Tree 7 | 8 | When a compiler is compiling your program, it does a number of different things. 9 | One of the things that it does is turn the text of your program into an 10 | ‘abstract syntax tree’, or ‘AST’. This tree is a representation of the structure 11 | of your program. For example, `2 + 3` can be turned into a tree: 12 | 13 | ```text 14 | + 15 | / \ 16 | 2 3 17 | ``` 18 | 19 | And `2 + (3 * 4)` would look like this: 20 | 21 | ```text 22 | + 23 | / \ 24 | 2 * 25 | / \ 26 | 3 4 27 | ``` 28 | 29 | ### Arity 30 | 31 | Arity refers to the number of arguments a function or operation takes. 32 | 33 | ```rust 34 | let x = (2, 3); 35 | let y = (4, 6); 36 | let z = (8, 2, 6); 37 | ``` 38 | 39 | In the example above `x` and `y` have arity 2. `z` has arity 3. 40 | 41 | ### Bounds 42 | 43 | Bounds are constraints on a type or [trait][traits]. For example, if a bound 44 | is placed on the argument a function takes, types passed to that function 45 | must abide by that constraint. 46 | 47 | [traits]: traits.html 48 | 49 | ### Combinators 50 | 51 | Combinators are higher-order functions that apply only functions and 52 | earlier defined combinators to provide a result from its arguments. 53 | They can be used to manage control flow in a modular fashion. 54 | 55 | ### DST (Dynamically Sized Type) 56 | 57 | A type without a statically known size or alignment. ([more info][link]) 58 | 59 | [link]: ../../nomicon/exotic-sizes.html#dynamically-sized-types-dsts 60 | 61 | ### Expression 62 | 63 | In computer programming, an expression is a combination of values, constants, 64 | variables, operators and functions that evaluate to a single value. For example, 65 | `2 + (3 * 4)` is an expression that returns the value 14. It is worth noting 66 | that expressions can have side-effects. For example, a function included in an 67 | expression might perform actions other than simply returning a value. 68 | 69 | ### Expression-Oriented Language 70 | 71 | In early programming languages, [expressions][expression] and 72 | [statements][statement] were two separate syntactic categories: expressions had 73 | a value and statements did things. However, later languages blurred this 74 | distinction, allowing expressions to do things and statements to have a value. 75 | In an expression-oriented language, (nearly) every statement is an expression 76 | and therefore returns a value. Consequently, these expression statements can 77 | themselves form part of larger expressions. 78 | 79 | [expression]: glossary.html#expression 80 | [statement]: glossary.html#statement 81 | 82 | ### Statement 83 | 84 | In computer programming, a statement is the smallest standalone element of a 85 | programming language that commands a computer to perform an action. 86 | -------------------------------------------------------------------------------- /second-edition/src/img/trpl15-01.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | %3 11 | 12 | 13 | table0 14 | 15 | Cons 16 | 17 | i32 18 | 19 | 20 | Cons 21 | 22 | i32 23 | 24 | 25 | Cons 26 | 27 | i32 28 | 29 | 30 | Cons 31 | 32 | i32 33 | 34 | 35 | Cons 36 | 37 | i32 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /first-edition/src/borrow-and-asref.md: -------------------------------------------------------------------------------- 1 | # Borrow and AsRef 2 | 3 | The [`Borrow`][borrow] and [`AsRef`][asref] traits are very similar, but 4 | different. Here’s a quick refresher on what these two traits mean. 5 | 6 | [borrow]: ../../std/borrow/trait.Borrow.html 7 | [asref]: ../../std/convert/trait.AsRef.html 8 | 9 | # Borrow 10 | 11 | The `Borrow` trait is used when you’re writing a data structure, and you want to 12 | use either an owned or borrowed type as synonymous for some purpose. 13 | 14 | For example, [`HashMap`][hashmap] has a [`get` method][get] which uses `Borrow`: 15 | 16 | ```rust,ignore 17 | fn get(&self, k: &Q) -> Option<&V> 18 | where K: Borrow, 19 | Q: Hash + Eq 20 | ``` 21 | 22 | [hashmap]: ../../std/collections/struct.HashMap.html 23 | [get]: ../../std/collections/struct.HashMap.html#method.get 24 | 25 | This signature is pretty complicated. The `K` parameter is what we’re interested 26 | in here. It refers to a parameter of the `HashMap` itself: 27 | 28 | ```rust,ignore 29 | struct HashMap { 30 | ``` 31 | 32 | The `K` parameter is the type of _key_ the `HashMap` uses. So, looking at 33 | the signature of `get()` again, we can use `get()` when the key implements 34 | `Borrow`. That way, we can make a `HashMap` which uses `String` keys, 35 | but use `&str`s when we’re searching: 36 | 37 | ```rust 38 | use std::collections::HashMap; 39 | 40 | let mut map = HashMap::new(); 41 | map.insert("Foo".to_string(), 42); 42 | 43 | assert_eq!(map.get("Foo"), Some(&42)); 44 | ``` 45 | 46 | This is because the standard library has `impl Borrow for String`. 47 | 48 | For most types, when you want to take an owned or borrowed type, a `&T` is 49 | enough. But one area where `Borrow` is effective is when there’s more than one 50 | kind of borrowed value. This is especially true of references and slices: you 51 | can have both an `&T` or a `&mut T`. If we wanted to accept both of these types, 52 | `Borrow` is up for it: 53 | 54 | ```rust 55 | use std::borrow::Borrow; 56 | use std::fmt::Display; 57 | 58 | fn foo + Display>(a: T) { 59 | println!("a is borrowed: {}", a); 60 | } 61 | 62 | let mut i = 5; 63 | 64 | foo(&i); 65 | foo(&mut i); 66 | ``` 67 | 68 | This will print out `a is borrowed: 5` twice. 69 | 70 | # AsRef 71 | 72 | The `AsRef` trait is a conversion trait. It’s used for converting some value to 73 | a reference in generic code. Like this: 74 | 75 | ```rust 76 | let s = "Hello".to_string(); 77 | 78 | fn foo>(s: T) { 79 | let slice = s.as_ref(); 80 | } 81 | ``` 82 | 83 | # Which should I use? 84 | 85 | We can see how they’re kind of the same: they both deal with owned and borrowed 86 | versions of some type. However, they’re a bit different. 87 | 88 | Choose `Borrow` when you want to abstract over different kinds of borrowing, or 89 | when you’re building a data structure that treats owned and borrowed values in 90 | equivalent ways, such as hashing and comparison. 91 | 92 | Choose `AsRef` when you want to convert something to a reference directly, and 93 | you’re writing generic code. 94 | -------------------------------------------------------------------------------- /second-edition/src/ch12-00-an-io-project.md: -------------------------------------------------------------------------------- 1 | # An I/O Project Building a Small Grep 2 | 3 | 7 | 8 | 16 | 17 | This chapter is both a recap of the many skills you've learned so far and an 18 | exploration of a few more standard library features. We're going to build a 19 | command-line tool that interacts with file and command line input/output to 20 | practice some of the Rust you now have under your belt. 21 | 22 | Rust's speed, safety, 'single binary' output, and cross-platform support make 23 | it a good language for creating command line tools, so for our project we'll 24 | make our own version of the classic command line tool `grep`. Grep is an 25 | acronym for "Globally search a Regular Expression and Print." In the simplest 26 | use case, `grep` searches a specified file for a specified string using the 27 | following steps: 28 | 29 | - Take as arguments a filename and a string. 30 | - Read the file. 31 | - Find lines in the file that contain the string argument. 32 | - Print out those lines. 33 | 34 | We'll also show how to use environment variables and print to standard error 35 | instead of standard out; these techniques are commonly used in command line 36 | tools. 37 | 38 | One Rust community member, Andrew Gallant, has already created a 39 | fully-featured, very fast version of `grep`, called `ripgrep`. By comparison, 40 | our version of `grep` will be fairly simple, this chapter will give you some of 41 | the background knowledge to help you understand a real-world project like 42 | `ripgrep`. 43 | 44 | This project will bring together a number of concepts you've learned so far: 45 | 46 | - Organizing code (using what we learned in modules, Chapter 7) 47 | - Using vectors and strings (collections, Chapter 8) 48 | - Handling errors (Chapter 9) 49 | - Using traits and lifetimes where appropriate (Chapter 10) 50 | - Writing tests (Chapter 11) 51 | 52 | We'll also briefly introduce closures, iterators, and trait objects, which 53 | Chapters 13 and 17 will cover in detail. 54 | 55 | Let's create a new project with, as always, `cargo new`. We're calling our 56 | project `greprs` to distinguish from the `grep` tool that you may already have 57 | on your system: 58 | 59 | ```text 60 | $ cargo new --bin greprs 61 | Created binary (application) `greprs` project 62 | $ cd greprs 63 | ``` 64 | -------------------------------------------------------------------------------- /first-edition/src/deref-coercions.md: -------------------------------------------------------------------------------- 1 | # `Deref` coercions 2 | 3 | The standard library provides a special trait, [`Deref`][deref]. It’s normally 4 | used to overload `*`, the dereference operator: 5 | 6 | ```rust 7 | use std::ops::Deref; 8 | 9 | struct DerefExample { 10 | value: T, 11 | } 12 | 13 | impl Deref for DerefExample { 14 | type Target = T; 15 | 16 | fn deref(&self) -> &T { 17 | &self.value 18 | } 19 | } 20 | 21 | fn main() { 22 | let x = DerefExample { value: 'a' }; 23 | assert_eq!('a', *x); 24 | } 25 | ``` 26 | 27 | [deref]: ../../std/ops/trait.Deref.html 28 | 29 | This is useful for writing custom pointer types. However, there’s a language 30 | feature related to `Deref`: ‘deref coercions’. Here’s the rule: If you have a 31 | type `U`, and it implements `Deref`, values of `&U` will 32 | automatically coerce to a `&T`. Here’s an example: 33 | 34 | ```rust 35 | fn foo(s: &str) { 36 | // Borrow a string for a second. 37 | } 38 | 39 | // String implements Deref. 40 | let owned = "Hello".to_string(); 41 | 42 | // Therefore, this works: 43 | foo(&owned); 44 | ``` 45 | 46 | Using an ampersand in front of a value takes a reference to it. So `owned` is a 47 | `String`, `&owned` is an `&String`, and since `impl Deref for 48 | String`, `&String` will deref to `&str`, which `foo()` takes. 49 | 50 | That’s it. This rule is one of the only places in which Rust does an automatic 51 | conversion for you, but it adds a lot of flexibility. For example, the `Rc` 52 | type implements `Deref`, so this works: 53 | 54 | ```rust 55 | use std::rc::Rc; 56 | 57 | fn foo(s: &str) { 58 | // Borrow a string for a second. 59 | } 60 | 61 | // String implements Deref. 62 | let owned = "Hello".to_string(); 63 | let counted = Rc::new(owned); 64 | 65 | // Therefore, this works: 66 | foo(&counted); 67 | ``` 68 | 69 | All we’ve done is wrap our `String` in an `Rc`. But we can now pass the 70 | `Rc` around anywhere we’d have a `String`. The signature of `foo` 71 | didn’t change, but works just as well with either type. This example has two 72 | conversions: `&Rc` to `&String` and then `&String` to `&str`. Rust will do 73 | this as many times as possible until the types match. 74 | 75 | Another very common implementation provided by the standard library is: 76 | 77 | ```rust 78 | fn foo(s: &[i32]) { 79 | // Borrow a slice for a second. 80 | } 81 | 82 | // Vec implements Deref. 83 | let owned = vec![1, 2, 3]; 84 | 85 | foo(&owned); 86 | ``` 87 | 88 | Vectors can `Deref` to a slice. 89 | 90 | ## Deref and method calls 91 | 92 | `Deref` will also kick in when calling a method. Consider the following 93 | example. 94 | 95 | ```rust 96 | struct Foo; 97 | 98 | impl Foo { 99 | fn foo(&self) { println!("Foo"); } 100 | } 101 | 102 | let f = &&Foo; 103 | 104 | f.foo(); 105 | ``` 106 | 107 | Even though `f` is a `&&Foo` and `foo` takes `&self`, this works. That’s 108 | because these things are the same: 109 | 110 | ```rust,ignore 111 | f.foo(); 112 | (&f).foo(); 113 | (&&f).foo(); 114 | (&&&&&&&&f).foo(); 115 | ``` 116 | 117 | A value of type `&&&&&&&&&&&&&&&&Foo` can still have methods defined on `Foo` 118 | called, because the compiler will insert as many * operations as necessary to 119 | get it right. And since it’s inserting `*`s, that uses `Deref`. 120 | -------------------------------------------------------------------------------- /second-edition/src/img/trpl15-04.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | 7 | 8 | %3 9 | 10 | 11 | table0 12 | 13 | a 14 | 15 | 16 | table1 17 | 18 | 5 19 | 20 | 21 | 22 | 23 | table2 24 | 25 | b 26 | 27 | 28 | table3 29 | 30 | 10 31 | 32 | 33 | 34 | 35 | table0:ref->table1:data 36 | 37 | 38 | 39 | 40 | table1:ref->table2:data 41 | 42 | 43 | 44 | 45 | table2:ref->table3:data 46 | 47 | 48 | 49 | 50 | table3:ref->table0:data 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /first-edition/src/ufcs.md: -------------------------------------------------------------------------------- 1 | # Universal Function Call Syntax 2 | 3 | Sometimes, functions can have the same names. Consider this code: 4 | 5 | ```rust 6 | trait Foo { 7 | fn f(&self); 8 | } 9 | 10 | trait Bar { 11 | fn f(&self); 12 | } 13 | 14 | struct Baz; 15 | 16 | impl Foo for Baz { 17 | fn f(&self) { println!("Baz’s impl of Foo"); } 18 | } 19 | 20 | impl Bar for Baz { 21 | fn f(&self) { println!("Baz’s impl of Bar"); } 22 | } 23 | 24 | let b = Baz; 25 | ``` 26 | 27 | If we were to try to call `b.f()`, we’d get an error: 28 | 29 | ```text 30 | error: multiple applicable methods in scope [E0034] 31 | b.f(); 32 | ^~~ 33 | note: candidate #1 is defined in an impl of the trait `main::Foo` for the type 34 | `main::Baz` 35 | fn f(&self) { println!("Baz’s impl of Foo"); } 36 | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 37 | note: candidate #2 is defined in an impl of the trait `main::Bar` for the type 38 | `main::Baz` 39 | fn f(&self) { println!("Baz’s impl of Bar"); } 40 | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 41 | 42 | ``` 43 | 44 | We need a way to disambiguate which method we need. This feature is called 45 | ‘universal function call syntax’, and it looks like this: 46 | 47 | ```rust 48 | # trait Foo { 49 | # fn f(&self); 50 | # } 51 | # trait Bar { 52 | # fn f(&self); 53 | # } 54 | # struct Baz; 55 | # impl Foo for Baz { 56 | # fn f(&self) { println!("Baz’s impl of Foo"); } 57 | # } 58 | # impl Bar for Baz { 59 | # fn f(&self) { println!("Baz’s impl of Bar"); } 60 | # } 61 | # let b = Baz; 62 | Foo::f(&b); 63 | Bar::f(&b); 64 | ``` 65 | 66 | Let’s break it down. 67 | 68 | ```rust,ignore 69 | Foo:: 70 | Bar:: 71 | ``` 72 | 73 | These halves of the invocation are the types of the two traits: `Foo` and 74 | `Bar`. This is what ends up actually doing the disambiguation between the two: 75 | Rust calls the one from the trait name you use. 76 | 77 | ```rust,ignore 78 | f(&b) 79 | ``` 80 | 81 | When we call a method like `b.f()` using [method syntax][methodsyntax], Rust 82 | will automatically borrow `b` if `f()` takes `&self`. In this case, Rust will 83 | not, and so we need to pass an explicit `&b`. 84 | 85 | [methodsyntax]: method-syntax.html 86 | 87 | # Angle-bracket Form 88 | 89 | The form of UFCS we just talked about: 90 | 91 | ```rust,ignore 92 | Trait::method(args); 93 | ``` 94 | 95 | Is a short-hand. There’s an expanded form of this that’s needed in some 96 | situations: 97 | 98 | ```rust,ignore 99 | ::method(args); 100 | ``` 101 | 102 | The `<>::` syntax is a means of providing a type hint. The type goes inside 103 | the `<>`s. In this case, the type is `Type as Trait`, indicating that we want 104 | `Trait`’s version of `method` to be called here. The `as Trait` part is 105 | optional if it’s not ambiguous. Same with the angle brackets, hence the 106 | shorter form. 107 | 108 | Here’s an example of using the longer form. 109 | 110 | ```rust 111 | trait Foo { 112 | fn foo() -> i32; 113 | } 114 | 115 | struct Bar; 116 | 117 | impl Bar { 118 | fn foo() -> i32 { 119 | 20 120 | } 121 | } 122 | 123 | impl Foo for Bar { 124 | fn foo() -> i32 { 125 | 10 126 | } 127 | } 128 | 129 | fn main() { 130 | assert_eq!(10, ::foo()); 131 | assert_eq!(20, Bar::foo()); 132 | } 133 | ``` 134 | 135 | Using the angle bracket syntax lets you call the trait method instead of the 136 | inherent one. 137 | -------------------------------------------------------------------------------- /first-edition/src/match.md: -------------------------------------------------------------------------------- 1 | # Match 2 | 3 | Often, a simple [`if`][if]/`else` isn’t enough, because you have more than two 4 | possible options. Also, conditions can get quite complex. Rust 5 | has a keyword, `match`, that allows you to replace complicated `if`/`else` 6 | groupings with something more powerful. Check it out: 7 | 8 | ```rust 9 | let x = 5; 10 | 11 | match x { 12 | 1 => println!("one"), 13 | 2 => println!("two"), 14 | 3 => println!("three"), 15 | 4 => println!("four"), 16 | 5 => println!("five"), 17 | _ => println!("something else"), 18 | } 19 | ``` 20 | 21 | [if]: if.html 22 | 23 | `match` takes an expression and then branches based on its value. Each ‘arm’ of 24 | the branch is of the form `val => expression`. When the value matches, that arm’s 25 | expression will be evaluated. It’s called `match` because of the term ‘pattern 26 | matching’, which `match` is an implementation of. There’s a [separate section on 27 | patterns][patterns] that covers all the patterns that are possible here. 28 | 29 | [patterns]: patterns.html 30 | 31 | One of the many advantages of `match` is it enforces ‘exhaustiveness checking’. 32 | For example if we remove the last arm with the underscore `_`, the compiler will 33 | give us an error: 34 | 35 | ```text 36 | error: non-exhaustive patterns: `_` not covered 37 | ``` 38 | 39 | Rust is telling us that we forgot some value. The compiler infers from `x` that it 40 | can have any 32bit integer value; for example -2,147,483,648 to 2,147,483,647. The `_` acts 41 | as a 'catch-all', and will catch all possible values that *aren't* specified in 42 | an arm of `match`. As you can see in the previous example, we provide `match` 43 | arms for integers 1-5, if `x` is 6 or any other value, then it is caught by `_`. 44 | 45 | `match` is also an expression, which means we can use it on the right-hand 46 | side of a `let` binding or directly where an expression is used: 47 | 48 | ```rust 49 | let x = 5; 50 | 51 | let number = match x { 52 | 1 => "one", 53 | 2 => "two", 54 | 3 => "three", 55 | 4 => "four", 56 | 5 => "five", 57 | _ => "something else", 58 | }; 59 | ``` 60 | 61 | Sometimes it’s a nice way of converting something from one type to another; in 62 | this example the integers are converted to `String`. 63 | 64 | # Matching on enums 65 | 66 | Another important use of the `match` keyword is to process the possible 67 | variants of an enum: 68 | 69 | ```rust 70 | enum Message { 71 | Quit, 72 | ChangeColor(i32, i32, i32), 73 | Move { x: i32, y: i32 }, 74 | Write(String), 75 | } 76 | 77 | fn quit() { /* ... */ } 78 | fn change_color(r: i32, g: i32, b: i32) { /* ... */ } 79 | fn move_cursor(x: i32, y: i32) { /* ... */ } 80 | 81 | fn process_message(msg: Message) { 82 | match msg { 83 | Message::Quit => quit(), 84 | Message::ChangeColor(r, g, b) => change_color(r, g, b), 85 | Message::Move { x, y: new_name_for_y } => move_cursor(x, new_name_for_y), 86 | Message::Write(s) => println!("{}", s), 87 | }; 88 | } 89 | ``` 90 | 91 | Again, the Rust compiler checks exhaustiveness, so it demands that you 92 | have a match arm for every variant of the enum. If you leave one off, it 93 | will give you a compile-time error unless you use `_` or provide all possible 94 | arms. 95 | 96 | Unlike the previous uses of `match`, you can’t use the normal `if` 97 | statement to do this. You can use the [`if let`][if-let] statement, 98 | which can be seen as an abbreviated form of `match`. 99 | 100 | [if-let]: if-let.html 101 | -------------------------------------------------------------------------------- /first-edition/src/enums.md: -------------------------------------------------------------------------------- 1 | # Enums 2 | 3 | An `enum` in Rust is a type that represents data that is one of 4 | several possible variants. Each variant in the `enum` can optionally 5 | have data associated with it: 6 | 7 | ```rust 8 | enum Message { 9 | Quit, 10 | ChangeColor(i32, i32, i32), 11 | Move { x: i32, y: i32 }, 12 | Write(String), 13 | } 14 | ``` 15 | 16 | The syntax for defining variants resembles the syntaxes used to define structs: 17 | you can have variants with no data (like unit-like structs), variants with named 18 | data, and variants with unnamed data (like tuple structs). Unlike 19 | separate struct definitions, however, an `enum` is a single type. A 20 | value of the enum can match any of the variants. For this reason, an 21 | enum is sometimes called a ‘sum type’: the set of possible values of the 22 | enum is the sum of the sets of possible values for each variant. 23 | 24 | We use the `::` syntax to use the name of each variant: they’re scoped by the name 25 | of the `enum` itself. This allows both of these to work: 26 | 27 | ```rust 28 | # enum Message { 29 | # Move { x: i32, y: i32 }, 30 | # } 31 | let x: Message = Message::Move { x: 3, y: 4 }; 32 | 33 | enum BoardGameTurn { 34 | Move { squares: i32 }, 35 | Pass, 36 | } 37 | 38 | let y: BoardGameTurn = BoardGameTurn::Move { squares: 1 }; 39 | ``` 40 | 41 | Both variants are named `Move`, but since they’re scoped to the name of 42 | the enum, they can both be used without conflict. 43 | 44 | A value of an `enum` type contains information about which variant it is, 45 | in addition to any data associated with that variant. This is sometimes 46 | referred to as a ‘tagged union’, since the data includes a ‘tag’ 47 | indicating what type it is. The compiler uses this information to 48 | enforce that you’re accessing the data in the enum safely. For instance, 49 | you can’t simply try to destructure a value as if it were one of the 50 | possible variants: 51 | 52 | ```rust,ignore 53 | fn process_color_change(msg: Message) { 54 | let Message::ChangeColor(r, g, b) = msg; // This causes a compile-time error. 55 | } 56 | ``` 57 | 58 | Not supporting these operations may seem rather limiting, but it’s a limitation 59 | which we can overcome. There are two ways: by implementing equality ourselves, 60 | or by pattern matching variants with [`match`][match] expressions, which you’ll 61 | learn in the next section. We don’t know enough about Rust to implement 62 | equality yet, but we’ll find out in the [`traits`][traits] section. 63 | 64 | [match]: match.html 65 | [traits]: traits.html 66 | 67 | # Constructors as functions 68 | 69 | An `enum` constructor can also be used like a function. For example: 70 | 71 | ```rust 72 | # enum Message { 73 | # Write(String), 74 | # } 75 | let m = Message::Write("Hello, world".to_string()); 76 | ``` 77 | 78 | is the same as 79 | 80 | ```rust 81 | # enum Message { 82 | # Write(String), 83 | # } 84 | fn foo(x: String) -> Message { 85 | Message::Write(x) 86 | } 87 | 88 | let x = foo("Hello, world".to_string()); 89 | ``` 90 | 91 | This is not immediately useful to us, but when we get to 92 | [`closures`][closures], we’ll talk about passing functions as arguments to 93 | other functions. For example, with [`iterators`][iterators], we can do this 94 | to convert a vector of `String`s into a vector of `Message::Write`s: 95 | 96 | ```rust 97 | # enum Message { 98 | # Write(String), 99 | # } 100 | 101 | let v = vec!["Hello".to_string(), "World".to_string()]; 102 | 103 | let v1: Vec = v.into_iter().map(Message::Write).collect(); 104 | ``` 105 | 106 | [closures]: closures.html 107 | [iterators]: iterators.html 108 | -------------------------------------------------------------------------------- /first-edition/src/operators-and-overloading.md: -------------------------------------------------------------------------------- 1 | # Operators and Overloading 2 | 3 | Rust allows for a limited form of operator overloading. There are certain 4 | operators that are able to be overloaded. To support a particular operator 5 | between types, there’s a specific trait that you can implement, which then 6 | overloads the operator. 7 | 8 | For example, the `+` operator can be overloaded with the `Add` trait: 9 | 10 | ```rust 11 | use std::ops::Add; 12 | 13 | #[derive(Debug)] 14 | struct Point { 15 | x: i32, 16 | y: i32, 17 | } 18 | 19 | impl Add for Point { 20 | type Output = Point; 21 | 22 | fn add(self, other: Point) -> Point { 23 | Point { x: self.x + other.x, y: self.y + other.y } 24 | } 25 | } 26 | 27 | fn main() { 28 | let p1 = Point { x: 1, y: 0 }; 29 | let p2 = Point { x: 2, y: 3 }; 30 | 31 | let p3 = p1 + p2; 32 | 33 | println!("{:?}", p3); 34 | } 35 | ``` 36 | 37 | In `main`, we can use `+` on our two `Point`s, since we’ve implemented 38 | `Add` for `Point`. 39 | 40 | There are a number of operators that can be overloaded this way, and all of 41 | their associated traits live in the [`std::ops`][stdops] module. Check out its 42 | documentation for the full list. 43 | 44 | [stdops]: ../../std/ops/index.html 45 | 46 | Implementing these traits follows a pattern. Let’s look at [`Add`][add] in more 47 | detail: 48 | 49 | ```rust 50 | # mod foo { 51 | pub trait Add { 52 | type Output; 53 | 54 | fn add(self, rhs: RHS) -> Self::Output; 55 | } 56 | # } 57 | ``` 58 | 59 | [add]: ../../std/ops/trait.Add.html 60 | 61 | There’s three types in total involved here: the type you `impl Add` for, `RHS`, 62 | which defaults to `Self`, and `Output`. For an expression `let z = x + y`, `x` 63 | is the `Self` type, `y` is the RHS, and `z` is the `Self::Output` type. 64 | 65 | ```rust 66 | # struct Point; 67 | # use std::ops::Add; 68 | impl Add for Point { 69 | type Output = f64; 70 | 71 | fn add(self, rhs: i32) -> f64 { 72 | // Add an i32 to a Point and get an f64. 73 | # 1.0 74 | } 75 | } 76 | ``` 77 | 78 | will let you do this: 79 | 80 | ```rust,ignore 81 | let p: Point = // ... 82 | let x: f64 = p + 2i32; 83 | ``` 84 | 85 | # Using operator traits in generic structs 86 | 87 | Now that we know how operator traits are defined, we can define our `HasArea` 88 | trait and `Square` struct from the [traits chapter][traits] more generically: 89 | 90 | [traits]: traits.html 91 | 92 | ```rust 93 | use std::ops::Mul; 94 | 95 | trait HasArea { 96 | fn area(&self) -> T; 97 | } 98 | 99 | struct Square { 100 | x: T, 101 | y: T, 102 | side: T, 103 | } 104 | 105 | impl HasArea for Square 106 | where T: Mul + Copy { 107 | fn area(&self) -> T { 108 | self.side * self.side 109 | } 110 | } 111 | 112 | fn main() { 113 | let s = Square { 114 | x: 0.0f64, 115 | y: 0.0f64, 116 | side: 12.0f64, 117 | }; 118 | 119 | println!("Area of s: {}", s.area()); 120 | } 121 | ``` 122 | 123 | For `HasArea` and `Square`, we declare a type parameter `T` and replace 124 | `f64` with it. The `impl` needs more involved modifications: 125 | 126 | ```rust,ignore 127 | impl HasArea for Square 128 | where T: Mul + Copy { ... } 129 | ``` 130 | 131 | The `area` method requires that we can multiply the sides, so we declare that 132 | type `T` must implement `std::ops::Mul`. Like `Add`, mentioned above, `Mul` 133 | itself takes an `Output` parameter: since we know that numbers don't change 134 | type when multiplied, we also set it to `T`. `T` must also support copying, so 135 | Rust doesn't try to move `self.side` into the return value. 136 | -------------------------------------------------------------------------------- /second-edition/src/ch01-01-installation.md: -------------------------------------------------------------------------------- 1 | ## Installation 2 | 3 | The first step to using Rust is to install it. You’ll need an internet 4 | connection to run the commands in this chapter, as we’ll be downloading Rust 5 | from the internet. 6 | 7 | We’ll be showing off a number of commands using a terminal, and those lines all 8 | start with `$`. You don't need to type in the `$` character; they are there to indicate 9 | the start of each command. You’ll see many tutorials and examples around the web 10 | that follow this convention: `$` for commands run as a regular user, and `#` 11 | for commands you should be running as an administrator. Lines that don't start 12 | with `$` are typically showing the output of the previous command. 13 | 14 | ### Installing on Linux or Mac 15 | 16 | If you're on Linux or a Mac, all you need to do is open a terminal and type 17 | this: 18 | 19 | ```text 20 | $ curl https://sh.rustup.rs -sSf | sh 21 | ``` 22 | 23 | This will download a script and start the installation. You may be prompted for 24 | your password. If it all goes well, you’ll see this appear: 25 | 26 | ```text 27 | Rust is installed now. Great! 28 | ``` 29 | 30 | Of course, if you disapprove of the `curl | sh` pattern, you can download, inspect 31 | and run the script however you like. 32 | 33 | ### Installing on Windows 34 | 35 | On Windows, go to [https://rustup.rs](https://rustup.rs/) and 36 | follow the instructions to download rustup-init.exe. Run that and follow the 37 | rest of the instructions it gives you. 38 | 39 | The rest of the Windows-specific commands in the book will assume that you are 40 | using `cmd` as your shell. If you use a different shell, you may be able to run 41 | the same commands that Linux and Mac users do. If neither work, consult the 42 | documentation for the shell you are using. 43 | 44 | ### Custom installations 45 | 46 | If you have reasons for preferring not to use rustup.rs, please see [the Rust 47 | installation page](https://www.rust-lang.org/install.html) for other options. 48 | 49 | ### Updating 50 | 51 | Once you have Rust installed, updating to the latest version is easy. 52 | From your shell, run the update script: 53 | 54 | ```text 55 | $ rustup update 56 | ``` 57 | 58 | ### Uninstalling 59 | 60 | Uninstalling Rust is as easy as installing it. From your shell, run 61 | the uninstall script: 62 | 63 | ```text 64 | $ rustup self uninstall 65 | ``` 66 | 67 | ### Troubleshooting 68 | 69 | If you've got Rust installed, you can open up a shell, and type this: 70 | 71 | ```text 72 | $ rustc --version 73 | ``` 74 | 75 | You should see the version number, commit hash, and commit date in a format 76 | similar to this for the latest stable version at the time you install: 77 | 78 | ```text 79 | rustc x.y.z (abcabcabc yyyy-mm-dd) 80 | ``` 81 | 82 | If you see this, Rust has been installed successfully! 83 | Congrats! 84 | 85 | If you don't and you're on Windows, check that Rust is in your `%PATH%` system 86 | variable. 87 | 88 | If it still isn't working, there are a number of places where you can get help. 89 | The easiest is [the #rust IRC channel on irc.mozilla.org][irc], 90 | which you can access through [Mibbit][mibbit]. Go to that address, and you'll 91 | be chatting with other Rustaceans (a silly nickname we call ourselves) who can 92 | help you out. Other great resources include [the Users forum][users] and 93 | [Stack Overflow][stackoverflow]. 94 | 95 | [irc]: irc://irc.mozilla.org/#rust 96 | [mibbit]: http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust 97 | [users]: https://users.rust-lang.org/ 98 | [stackoverflow]: http://stackoverflow.com/questions/tagged/rust 99 | 100 | ### Local documentation 101 | 102 | The installer also includes a copy of the documentation locally, so you can 103 | read it offline. Run `rustup doc` to open the local documentation in your 104 | browser. 105 | 106 | Any time there's a type or function provided by the standard library and you're 107 | not sure what it does, use the API documentation to find out! 108 | -------------------------------------------------------------------------------- /second-edition/spellcheck.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Copyright 2016 The Rust Project Developers. See the COPYRIGHT 3 | # file at the top-level directory of this distribution and at 4 | # http://rust-lang.org/COPYRIGHT. 5 | # 6 | # Licensed under the Apache License, Version 2.0 or the MIT license 8 | # , at your 9 | # option. This file may not be copied, modified, or distributed 10 | # except according to those terms. 11 | 12 | aspell --version 13 | 14 | # Checks project markdown files for spell errors 15 | 16 | # Notes: 17 | 18 | # This script needs dictionary file ($dict_filename) with project-specific 19 | # valid words. If this file is missing, first invocation of a script generates 20 | # a file of words considered typos at the moment. User should remove real typos 21 | # from this file and leave only valid words. When script generates false 22 | # positive after source modification, new valid word should be added 23 | # to dictionary file. 24 | 25 | # Default mode of this script is interactive. Each source file is scanned for 26 | # typos. aspell opens window, suggesting fixes for each found typo. Original 27 | # files with errors will be backed up to files with format "filename.md.bak". 28 | 29 | # When running in CI, this script should be run in "list" mode (pass "list" 30 | # as first argument). In this mode script scans all files and reports found 31 | # errors. Exit code in this case depends on scan result: 32 | # 1 if any errors found, 33 | # 0 if all is clear. 34 | 35 | # Script skips words with length less than or equal to 3. This helps to avoid 36 | # some false positives. 37 | 38 | # We can consider skipping source code in markdown files (```code```) to reduce 39 | # rate of false positives, but then we lose ability to detect typos in code 40 | # comments/strings etc. 41 | 42 | shopt -s nullglob 43 | 44 | dict_filename=./dictionary.txt 45 | markdown_sources=(./src/*.md) 46 | mode="check" 47 | 48 | # aspell repeatedly modifies personal dictionary for some purpose, 49 | # so we should use a copy of our dictionary 50 | dict_path="/tmp/$dict_filename" 51 | 52 | if [[ "$1" == "list" ]]; then 53 | mode="list" 54 | fi 55 | 56 | if [[ ! -f "$dict_filename" ]]; then 57 | # Pre-check mode: generates dictionary of words aspell consider typos. 58 | # After user validates that this file contains only valid words, we can 59 | # look for typos using this dictionary and some default aspell dictionary. 60 | echo "Scanning files to generate dictionary file '$dict_filename'." 61 | echo "Please check that it doesn't contain any misspellings." 62 | 63 | echo "personal_ws-1.1 en 0 utf-8" > "$dict_filename" 64 | cat "${markdown_sources[@]}" | aspell --ignore 3 list | sort -u >> "$dict_filename" 65 | elif [[ "$mode" == "list" ]]; then 66 | # List (default) mode: scan all files, report errors 67 | declare -i retval=0 68 | 69 | cp "$dict_filename" "$dict_path" 70 | 71 | if [ ! -f $dict_path ]; then 72 | retval=1 73 | exit "$retval" 74 | fi 75 | 76 | for fname in "${markdown_sources[@]}"; do 77 | command=$(aspell --ignore 3 --personal="$dict_path" "$mode" < "$fname") 78 | if [[ -n "$command" ]]; then 79 | for error in $command; do 80 | # FIXME: Find more correct way to get line number 81 | # (ideally from aspell). Now it can make some false positives, 82 | # because it is just a grep 83 | grep --with-filename --line-number --color=always "$error" "$fname" 84 | done 85 | retval=1 86 | fi 87 | done 88 | exit "$retval" 89 | elif [[ "$mode" == "check" ]]; then 90 | # Interactive mode: fix typos 91 | cp "$dict_filename" "$dict_path" 92 | 93 | if [ ! -f $dict_path ]; then 94 | retval=1 95 | exit "$retval" 96 | fi 97 | 98 | for fname in "${markdown_sources[@]}"; do 99 | aspell --ignore 3 --dont-backup --personal="$dict_path" "$mode" "$fname" 100 | done 101 | fi 102 | -------------------------------------------------------------------------------- /second-edition/tools/src/bin/concat_chapters.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT 2 | // file at the top-level directory of this distribution and at 3 | // http://rust-lang.org/COPYRIGHT. 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | 11 | #[macro_use] extern crate lazy_static; 12 | extern crate regex; 13 | 14 | use std::env; 15 | use std::io; 16 | use std::io::{Read, Write}; 17 | use std::process::exit; 18 | use std::fs::{create_dir, read_dir, File}; 19 | use std::path::{Path, PathBuf}; 20 | use std::collections::BTreeMap; 21 | 22 | use regex::Regex; 23 | 24 | static PATTERNS: &'static [(&'static str, &'static str)] = &[ 25 | (r"ch(\d\d)-\d\d-.*\.md", "chapter$1.md"), 26 | (r"appendix-(\d\d).*\.md", "appendix.md"), 27 | ]; 28 | 29 | lazy_static! { 30 | static ref MATCHERS: Vec<(Regex, &'static str)> = { 31 | PATTERNS.iter() 32 | .map(|&(expr, repl)| (Regex::new(expr).unwrap(), repl)) 33 | .collect() 34 | }; 35 | } 36 | 37 | fn main() { 38 | let args: Vec = env::args().collect(); 39 | 40 | if args.len() < 3 { 41 | println!("Usage: {} ", args[0]); 42 | exit(1); 43 | } 44 | 45 | let source_dir = ensure_dir_exists(&args[1]).unwrap(); 46 | let target_dir = ensure_dir_exists(&args[2]).unwrap(); 47 | 48 | let mut matched_files = match_files(source_dir, target_dir); 49 | matched_files.sort(); 50 | 51 | for (target_path, source_paths) in group_by_target(matched_files) { 52 | concat_files(source_paths, target_path).unwrap(); 53 | } 54 | } 55 | 56 | fn match_files(source_dir: &Path, target_dir: &Path) -> Vec<(PathBuf, PathBuf)> { 57 | read_dir(source_dir) 58 | .expect("Unable to read source directory") 59 | .filter_map(|maybe_entry| maybe_entry.ok()) 60 | .filter_map(|entry| { 61 | let source_filename = entry.file_name(); 62 | let source_filename = &source_filename.to_string_lossy().into_owned(); 63 | for &(ref regex, replacement) in MATCHERS.iter() { 64 | if regex.is_match(source_filename) { 65 | let target_filename = regex.replace_all(source_filename, replacement); 66 | let source_path = entry.path(); 67 | let mut target_path = PathBuf::from(&target_dir); 68 | target_path.push(target_filename); 69 | return Some((source_path, target_path)); 70 | } 71 | } 72 | None 73 | }) 74 | .collect() 75 | } 76 | 77 | fn group_by_target(matched_files: Vec<(PathBuf, PathBuf)>) -> BTreeMap> { 78 | let mut grouped: BTreeMap> = BTreeMap::new(); 79 | for (source, target) in matched_files { 80 | if let Some(source_paths) = grouped.get_mut(&target) { 81 | source_paths.push(source); 82 | continue; 83 | } 84 | let source_paths = vec![source]; 85 | grouped.insert(target.clone(), source_paths); 86 | } 87 | grouped 88 | } 89 | 90 | fn concat_files(source_paths: Vec, target_path: PathBuf) -> io::Result<()> { 91 | println!("Concatenating into {}:", target_path.to_string_lossy()); 92 | let mut target = try!(File::create(target_path)); 93 | try!(target.write_all(b"\n[TOC]\n")); 94 | 95 | for path in source_paths { 96 | println!(" {}", path.to_string_lossy()); 97 | let mut source = try!(File::open(path)); 98 | let mut contents: Vec = Vec::new(); 99 | try!(source.read_to_end(&mut contents)); 100 | 101 | try!(target.write_all(b"\n")); 102 | try!(target.write_all(&contents)); 103 | try!(target.write_all(b"\n")); 104 | } 105 | Ok(()) 106 | } 107 | 108 | fn ensure_dir_exists(dir_string: &str) -> io::Result<&Path> { 109 | let path = Path::new(dir_string); 110 | if !path.exists() { 111 | try!(create_dir(path)); 112 | } 113 | Ok(&path) 114 | } 115 | -------------------------------------------------------------------------------- /second-edition/src/ch06-03-if-let.md: -------------------------------------------------------------------------------- 1 | ## Concise Control Flow with `if let` 2 | 3 | The `if let` syntax lets you combine `if` and `let` into a less verbose way to 4 | handle values that match one pattern and ignore the rest. Consider the program 5 | in Listing 6-6 that matches on an `Option` value but only wants to execute 6 | code if the value is three: 7 | 8 | ```rust 9 | let some_u8_value = Some(0u8); 10 | match some_u8_value { 11 | Some(3) => println!("three"), 12 | _ => (), 13 | } 14 | ``` 15 | 16 | Listing 6-6: A `match` that only cares about executing 17 | code when the value is `Some(3)` 18 | 19 | We want to do something with the `Some(3)` match but do nothing with any other 20 | `Some` value or the `None` value. To satisfy the `match` expression, we 21 | have to add `_ => ()` after processing just one variant, which is a lot of 22 | boilerplate code to add. 23 | 24 | Instead, we could write this in a shorter way using `if let`. The following 25 | code behaves the same as the `match` in Listing 6-6: 26 | 27 | ```rust 28 | # let some_u8_value = Some(0u8); 29 | if let Some(3) = some_u8_value { 30 | println!("three"); 31 | } 32 | ``` 33 | 34 | `if let` takes a pattern and an expression separated by an `=`. It works the 35 | same way as a `match`, where the expression is given to the `match` and the 36 | pattern is its first arm. 37 | 38 | Using `if let` means you have less to type, less indentation, and less 39 | boilerplate code. However, we’ve lost the exhaustive checking that `match` 40 | enforces. Choosing between `match` and `if let` depends on what you’re doing in 41 | your particular situation and if gaining conciseness is an appropriate 42 | trade-off for losing exhaustive checking. 43 | 44 | In other words, you can think of `if let` as syntax sugar for a `match` that 45 | runs code when the value matches one pattern and then ignores all other values. 46 | 47 | We can include an `else` with an `if let`. The block of code that goes with the 48 | `else` is the same as the block of code that would go with the `_` case in the 49 | `match` expression that is equivalent to the `if let` and `else`. Recall the 50 | `Coin` enum definition in Listing 6-4, where the `Quarter` variant also held a 51 | `UsState` value. If we wanted to count all non-quarter coins we see while also 52 | announcing the state of the quarters, we could do that with a `match` 53 | expression like this: 54 | 55 | ```rust 56 | # #[derive(Debug)] 57 | # enum UsState { 58 | # Alabama, 59 | # Alaska, 60 | # } 61 | # 62 | # enum Coin { 63 | # Penny, 64 | # Nickel, 65 | # Dime, 66 | # Quarter(UsState), 67 | # } 68 | # let coin = Coin::Penny; 69 | let mut count = 0; 70 | match coin { 71 | Coin::Quarter(state) => println!("State quarter from {:?}!", state), 72 | _ => count += 1, 73 | } 74 | ``` 75 | 76 | Or we could use an `if let` and `else` expression like this: 77 | 78 | ```rust 79 | # #[derive(Debug)] 80 | # enum UsState { 81 | # Alabama, 82 | # Alaska, 83 | # } 84 | # 85 | # enum Coin { 86 | # Penny, 87 | # Nickel, 88 | # Dime, 89 | # Quarter(UsState), 90 | # } 91 | # let coin = Coin::Penny; 92 | let mut count = 0; 93 | if let Coin::Quarter(state) = coin { 94 | println!("State quarter from {:?}!", state); 95 | } else { 96 | count += 1; 97 | } 98 | ``` 99 | 100 | If you have a situation in which your program has logic that is too verbose to 101 | express using a `match`, remember that `if let` is in your Rust toolbox as well. 102 | 103 | ## Summary 104 | 105 | We’ve now covered how to use enums to create custom types that can be one of a 106 | set of enumerated values. We’ve shown how the standard library’s `Option` 107 | type helps you use the type system to prevent errors. When enum values have 108 | data inside them, you can use `match` or `if let` to extract and use those 109 | values, depending on how many cases you need to handle. 110 | 111 | Your Rust programs can now express concepts in your domain using structs and 112 | enums. Creating custom types to use in your API ensures type safety: the 113 | compiler will make certain your functions only get values of the type each 114 | function expects. 115 | 116 | In order to provide a well-organized API to your users that is straightforward 117 | to use and only exposes exactly what your users will need, let’s now turn to 118 | Rust’s modules. 119 | -------------------------------------------------------------------------------- /first-edition/src/raw-pointers.md: -------------------------------------------------------------------------------- 1 | # Raw Pointers 2 | 3 | Rust has a number of different smart pointer types in its standard library, but 4 | there are two types that are extra-special. Much of Rust’s safety comes from 5 | compile-time checks, but raw pointers don’t have such guarantees, and are 6 | [unsafe][unsafe] to use. 7 | 8 | `*const T` and `*mut T` are called ‘raw pointers’ in Rust. Sometimes, when 9 | writing certain kinds of libraries, you’ll need to get around Rust’s safety 10 | guarantees for some reason. In this case, you can use raw pointers to implement 11 | your library, while exposing a safe interface for your users. For example, `*` 12 | pointers are allowed to alias, allowing them to be used to write 13 | shared-ownership types, and even thread-safe shared memory types (the `Rc` 14 | and `Arc` types are both implemented entirely in Rust). 15 | 16 | Here are some things to remember about raw pointers that are different than 17 | other pointer types. They: 18 | 19 | - are not guaranteed to point to valid memory and are not even 20 | guaranteed to be non-NULL (unlike both `Box` and `&`); 21 | - do not have any automatic clean-up, unlike `Box`, and so require 22 | manual resource management; 23 | - are plain-old-data, that is, they don't move ownership, again unlike 24 | `Box`, hence the Rust compiler cannot protect against bugs like 25 | use-after-free; 26 | - lack any form of lifetimes, unlike `&`, and so the compiler cannot 27 | reason about dangling pointers; and 28 | - have no guarantees about aliasing or mutability other than mutation 29 | not being allowed directly through a `*const T`. 30 | 31 | # Basics 32 | 33 | Creating a raw pointer is perfectly safe: 34 | 35 | ```rust 36 | let x = 5; 37 | let raw = &x as *const i32; 38 | 39 | let mut y = 10; 40 | let raw_mut = &mut y as *mut i32; 41 | ``` 42 | 43 | However, dereferencing one is not. This won’t work: 44 | 45 | ```rust,ignore 46 | let x = 5; 47 | let raw = &x as *const i32; 48 | 49 | println!("raw points at {}", *raw); 50 | ``` 51 | 52 | It gives this error: 53 | 54 | ```text 55 | error: dereference of raw pointer requires unsafe function or block [E0133] 56 | println!("raw points at {}", *raw); 57 | ^~~~ 58 | ``` 59 | 60 | When you dereference a raw pointer, you’re taking responsibility that it’s not 61 | pointing somewhere that would be incorrect. As such, you need `unsafe`: 62 | 63 | ```rust 64 | let x = 5; 65 | let raw = &x as *const i32; 66 | 67 | let points_at = unsafe { *raw }; 68 | 69 | println!("raw points at {}", points_at); 70 | ``` 71 | 72 | For more operations on raw pointers, see [their API documentation][rawapi]. 73 | 74 | [unsafe]: unsafe.html 75 | [rawapi]: ../../std/primitive.pointer.html 76 | 77 | # FFI 78 | 79 | Raw pointers are useful for FFI: Rust’s `*const T` and `*mut T` are similar to 80 | C’s `const T*` and `T*`, respectively. For more about this use, consult the 81 | [FFI chapter][ffi]. 82 | 83 | [ffi]: ffi.html 84 | 85 | # References and raw pointers 86 | 87 | At runtime, a raw pointer `*` and a reference pointing to the same piece of 88 | data have an identical representation. In fact, an `&T` reference will 89 | implicitly coerce to an `*const T` raw pointer in safe code and similarly for 90 | the `mut` variants (both coercions can be performed explicitly with, 91 | respectively, `value as *const T` and `value as *mut T`). 92 | 93 | Going the opposite direction, from `*const` to a reference `&`, is not safe. A 94 | `&T` is always valid, and so, at a minimum, the raw pointer `*const T` has to 95 | point to a valid instance of type `T`. Furthermore, the resulting pointer must 96 | satisfy the aliasing and mutability laws of references. The compiler assumes 97 | these properties are true for any references, no matter how they are created, 98 | and so any conversion from raw pointers is asserting that they hold. The 99 | programmer *must* guarantee this. 100 | 101 | The recommended method for the conversion is: 102 | 103 | ```rust 104 | // Explicit cast: 105 | let i: u32 = 1; 106 | let p_imm: *const u32 = &i as *const u32; 107 | 108 | // Implicit coercion: 109 | let mut m: u32 = 2; 110 | let p_mut: *mut u32 = &mut m; 111 | 112 | unsafe { 113 | let ref_imm: &u32 = &*p_imm; 114 | let ref_mut: &mut u32 = &mut *p_mut; 115 | } 116 | ``` 117 | 118 | The `&*x` dereferencing style is preferred to using a `transmute`. The latter 119 | is far more powerful than necessary, and the more restricted operation is 120 | harder to use incorrectly; for example, it requires that `x` is a pointer 121 | (unlike `transmute`). 122 | -------------------------------------------------------------------------------- /second-edition/src/ch18-02-refutability.md: -------------------------------------------------------------------------------- 1 | ## Refutability: Whether a Pattern Might Fail to Match 2 | 3 | Patterns come in two forms: refutable and irrefutable. Patterns which cannot 4 | fail to match for any possible value are said to be *irrefutable*, and patterns 5 | which can fail to match for some possible value are said to be *refutable*. 6 | `let` statements, function parameters, and `for` loops are restricted to only 7 | accept irrefutable patterns, since there's nothing correct the program could do 8 | if the pattern fails to match. `if let`, and `while let` expressions are 9 | restricted to only accept refutable patterns, since they're made to handle 10 | possible failure and we wouldn't need their functionality if the pattern could 11 | never fail. 12 | 13 | In general, you shouldn't have to worry about the distinction between refutable 14 | and irrefutable patterns; just be familiar with the concept of refutability 15 | when you see it mentioned in an error message. When you get an error message 16 | involving refutability, you'll need to change either the pattern or the 17 | construct you're using the pattern with, depending on your intentions for the 18 | behavior of the code. 19 | 20 | Let's look at some examples. Earlier in this chapter, we had `let x = 5;`. `x` 21 | is indeed an irrefutable pattern we're allowed to use: since it matches 22 | anything, it can't fail to match. In contrast, consider trying to match one 23 | variant of an enum with `let`, such as matching only a `Some` value from the 24 | `Option` enum as shown in Listing 18-7: 25 | 26 | ```rust,ignore 27 | let Some(x) = some_option_value; 28 | ``` 29 | 30 | Listing 18-7: Attempting to use a refutable pattern with 31 | `let` 32 | 33 | If `some_option_value` was a `None` value, `some_option_value` would not match 34 | the pattern `Some(x)`. The pattern `Some(x)` is refutable since there exists a 35 | case in which it would fail to match a value. There's nothing valid that our 36 | code could do with this `let` statement if `some_option_value` was the `None` 37 | value. Therefore, Rust will complain at compile time that we've tried to use a 38 | refutable pattern where an irrefutable pattern is required: 39 | 40 | ```text 41 | error[E0005]: refutable pattern in local binding: `None` not covered 42 | --> :3:5 43 | | 44 | 3 | let Some(x) = some_option_value; 45 | | ^^^^^^^ pattern `None` not covered 46 | ``` 47 | 48 | We didn't cover (and couldn't cover!) every valid value with the pattern 49 | `Some(x)`, so Rust will rightfully complain. 50 | 51 | If we have a refutable pattern, instead of using `let`, we can use `if let`. 52 | That way, if the pattern doesn't match, the code inside the curly braces won't 53 | execute. That code will only make sense and run if the value matches the 54 | pattern. Listing 18-8 shows how to fix the code in Listing 18-7 with `Some(x)` 55 | matching `some_option_value`. Using the refutable pattern `Some(x)` is allowed, 56 | since this example uses `if let`: 57 | 58 | ```rust 59 | # let some_option_value: Option = None; 60 | if let Some(x) = some_option_value { 61 | println!("{}", x); 62 | } 63 | ``` 64 | 65 | Listing 18-8: Using `if let` and a block with refutable 66 | patterns instead of `let` 67 | 68 | Consequently, if we give `if let` an irrefutable pattern that will always match, 69 | such as `x` as shown in Listing 18-9: 70 | 71 | ```rust,ignore 72 | if let x = 5 { 73 | println!("{}", x); 74 | }; 75 | ``` 76 | 77 | Listing 18-9: Attempting to use an irrefutable pattern 78 | with `if let` 79 | 80 | Rust will complain that it doesn't make sense to use `if let` with an 81 | irrefutable pattern: 82 | 83 | ```text 84 | error[E0162]: irrefutable if-let pattern 85 | --> :2:8 86 | | 87 | 2 | if let x = 5 { 88 | | ^ irrefutable pattern 89 | ``` 90 | 91 | Generally, match arms use refutable patterns, except for the last arm that 92 | might match any remaining values with an irrefutable pattern. A `match` with 93 | only one arm whose pattern is irrefutable is allowed, but it's not particularly 94 | useful and could be replaced with a simpler `let` statement. Both the expressions 95 | associated with a `let` statement and a single arm irrefutable match will 96 | unconditionally be run, so the end result is the same if their expressions are. 97 | 98 | Now that we've discussed all the places that patterns can be used and the 99 | difference between refutable and irrefutable patterns, let's go over all the 100 | syntax we can use to create patterns. 101 | -------------------------------------------------------------------------------- /first-edition/src/vectors.md: -------------------------------------------------------------------------------- 1 | # Vectors 2 | 3 | A ‘vector’ is a dynamic or ‘growable’ array, implemented as the standard 4 | library type [`Vec`][vec]. The `T` means that we can have vectors 5 | of any type (see the chapter on [generics][generic] for more). 6 | Vectors always allocate their data on the heap. 7 | You can create them with the `vec!` macro: 8 | 9 | ```rust 10 | let v = vec![1, 2, 3, 4, 5]; // v: Vec 11 | ``` 12 | 13 | (Notice that unlike the `println!` macro we’ve used in the past, we use square 14 | brackets `[]` with `vec!` macro. Rust allows you to use either in either 15 | situation, this is just convention.) 16 | 17 | There’s an alternate form of `vec!` for repeating an initial value: 18 | 19 | ```rust 20 | let v = vec![0; 10]; // A vector of ten zeroes. 21 | ``` 22 | 23 | Vectors store their contents as contiguous arrays of `T` on the heap. This means 24 | that they must be able to know the size of `T` at compile time (that is, how 25 | many bytes are needed to store a `T`?). The size of some things can't be known 26 | at compile time. For these you'll have to store a pointer to that thing: 27 | thankfully, the [`Box`][box] type works perfectly for this. 28 | 29 | ## Accessing elements 30 | 31 | To get the value at a particular index in the vector, we use `[]`s: 32 | 33 | ```rust 34 | let v = vec![1, 2, 3, 4, 5]; 35 | 36 | println!("The third element of v is {}", v[2]); 37 | ``` 38 | 39 | The indices count from `0`, so the third element is `v[2]`. 40 | 41 | It’s also important to note that you must index with the `usize` type: 42 | 43 | ```rust,ignore 44 | let v = vec![1, 2, 3, 4, 5]; 45 | 46 | let i: usize = 0; 47 | let j: i32 = 0; 48 | 49 | // Works: 50 | v[i]; 51 | 52 | // Doesn’t: 53 | v[j]; 54 | ``` 55 | 56 | Indexing with a non-`usize` type gives an error that looks like this: 57 | 58 | ```text 59 | error: the trait bound `collections::vec::Vec<_> : core::ops::Index` 60 | is not satisfied [E0277] 61 | v[j]; 62 | ^~~~ 63 | note: the type `collections::vec::Vec<_>` cannot be indexed by `i32` 64 | error: aborting due to previous error 65 | ``` 66 | 67 | There’s a lot of punctuation in that message, but the core of it makes sense: 68 | you cannot index with an `i32`. 69 | 70 | ## Out-of-bounds Access 71 | 72 | If you try to access an index that doesn’t exist: 73 | 74 | ```rust,ignore 75 | let v = vec![1, 2, 3]; 76 | println!("Item 7 is {}", v[7]); 77 | ``` 78 | 79 | then the current thread will [panic] with a message like this: 80 | 81 | ```text 82 | thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 7' 83 | ``` 84 | 85 | If you want to handle out-of-bounds errors without panicking, you can use 86 | methods like [`get`][get] or [`get_mut`][get_mut] that return `None` when 87 | given an invalid index: 88 | 89 | ```rust 90 | let v = vec![1, 2, 3]; 91 | match v.get(7) { 92 | Some(x) => println!("Item 7 is {}", x), 93 | None => println!("Sorry, this vector is too short.") 94 | } 95 | ``` 96 | 97 | ## Iterating 98 | 99 | Once you have a vector, you can iterate through its elements with `for`. There 100 | are three versions: 101 | 102 | ```rust 103 | let mut v = vec![1, 2, 3, 4, 5]; 104 | 105 | for i in &v { 106 | println!("A reference to {}", i); 107 | } 108 | 109 | for i in &mut v { 110 | println!("A mutable reference to {}", i); 111 | } 112 | 113 | for i in v { 114 | println!("Take ownership of the vector and its element {}", i); 115 | } 116 | ``` 117 | 118 | Note: You cannot use the vector again once you have iterated by taking ownership of the vector. 119 | You can iterate the vector multiple times by taking a reference to the vector whilst iterating. 120 | For example, the following code does not compile. 121 | 122 | ```rust,ignore 123 | let v = vec![1, 2, 3, 4, 5]; 124 | 125 | for i in v { 126 | println!("Take ownership of the vector and its element {}", i); 127 | } 128 | 129 | for i in v { 130 | println!("Take ownership of the vector and its element {}", i); 131 | } 132 | ``` 133 | 134 | Whereas the following works perfectly, 135 | 136 | ```rust 137 | let v = vec![1, 2, 3, 4, 5]; 138 | 139 | for i in &v { 140 | println!("This is a reference to {}", i); 141 | } 142 | 143 | for i in &v { 144 | println!("This is a reference to {}", i); 145 | } 146 | ``` 147 | 148 | Vectors have many more useful methods, which you can read about in [their 149 | API documentation][vec]. 150 | 151 | [vec]: ../../std/vec/index.html 152 | [box]: ../../std/boxed/index.html 153 | [generic]: generics.html 154 | [panic]: concurrency.html#panics 155 | [get]: ../../std/vec/struct.Vec.html#method.get 156 | [get_mut]: ../../std/vec/struct.Vec.html#method.get_mut 157 | -------------------------------------------------------------------------------- /second-edition/src/ch12-02-reading-a-file.md: -------------------------------------------------------------------------------- 1 | ## Reading a File 2 | 3 | Next, we're going to read the file that we specify in the filename command line 4 | argument. First, we need a sample file to test it with---the best kind of file 5 | to use to make sure that `greprs` is working is one with a small amount of text 6 | over multiple lines with some repeated words. Listing 12-3 has an Emily 7 | Dickinson poem that will work well! Create a file called `poem.txt` at the root 8 | level of your project, and enter the poem "I'm nobody! Who are you?": 9 | 10 | Filename: poem.txt 11 | 12 | ```text 13 | I'm nobody! Who are you? 14 | Are you nobody, too? 15 | Then there's a pair of us — don't tell! 16 | They'd banish us, you know. 17 | 18 | How dreary to be somebody! 19 | How public, like a frog 20 | To tell your name the livelong day 21 | To an admiring bog! 22 | ``` 23 | 24 | Listing 12-3: The poem "I'm nobody! Who are you?" by 25 | Emily Dickinson that will make a good test case 26 | 27 | 31 | 32 | 33 | 34 | With that in place, edit *src/main.rs* and add code to open the file as shown 35 | in Listing 12-4: 36 | 37 | Filename: src/main.rs 38 | 39 | ```rust,should_panic 40 | use std::env; 41 | use std::fs::File; 42 | use std::io::prelude::*; 43 | 44 | fn main() { 45 | let args: Vec = env::args().collect(); 46 | 47 | let query = &args[1]; 48 | let filename = &args[2]; 49 | 50 | println!("Searching for {}", query); 51 | println!("In file {}", filename); 52 | 53 | let mut f = File::open(filename).expect("file not found"); 54 | 55 | let mut contents = String::new(); 56 | f.read_to_string(&mut contents).expect("something went wrong reading the file"); 57 | 58 | println!("With text:\n{}", contents); 59 | } 60 | ``` 61 | 62 | Listing 12-4: Reading the contents of the file specified by the second argument 63 | 64 | 65 | 66 | First, we add some more `use` statements to bring in relevant parts of the 67 | standard library: we need `std::fs::File` for dealing with files, and 68 | `std::io::prelude::*` contains various traits that are useful when doing I/O, 69 | including file I/O. In the same way that Rust has a general prelude that brings 70 | certain things into scope automatically, the `std::io` module has its own 71 | prelude of common things you'll need when working with I/O. Unlike the default 72 | prelude, we must explicitly `use` the prelude in `std::io`. 73 | 74 | In `main`, we've added three things: first, we get a mutable handle to the file 75 | by calling the `File::open` function and passing it the value of the `filename` 76 | variable. Second, we create a variable called `contents` and set it to a 77 | mutable, empty `String`. This will hold the content of the file after we read 78 | it in. Third, we call `read_to_string` on our file handle and pass a mutable 79 | reference to `contents` as an argument. 80 | 81 | After those lines, we've again added temporary `println!` that prints out the 82 | value in `contents` after we've read the file so we can check that our program 83 | is working so far. 84 | 85 | Let's try running this code with any string as the first command line argument 86 | (since we haven't implemented the searching part yet) and our *poem.txt* file 87 | as the second argument: 88 | 89 | ```text 90 | $ cargo run the poem.txt 91 | Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs 92 | Running `target/debug/greprs the poem.txt` 93 | Searching for the 94 | In file poem.txt 95 | With text: 96 | I'm nobody! Who are you? 97 | Are you nobody, too? 98 | Then there's a pair of us — don't tell! 99 | They'd banish us, you know. 100 | 101 | How dreary to be somebody! 102 | How public, like a frog 103 | To tell your name the livelong day 104 | To an admiring bog! 105 | ``` 106 | 107 | Great! Our code read in and printed out the content of the file. We've got a 108 | few flaws though: the `main` function has multiple responsibilities, and we're 109 | not handling errors as well as we could be. While our program is still small, 110 | these flaws aren't a big problem, but as our program grows, it will be harder 111 | to fix them cleanly. It's good practice to begin refactoring early on when 112 | developing a program, as it's much easier to refactor smaller amounts of code, 113 | so we'll do that now. 114 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ## First edition 4 | 5 | The first edition of the book is no longer actively being worked on, since 6 | we're concentrating our efforts on bringing the second edition to print. We 7 | will accept pull requests for small tweaks to the first edition; any larger 8 | work should be spent improving the second edition. Issues will likely be closed 9 | unless they are also issues in the second edition. 10 | 11 | ## Second edition 12 | 13 | We're currently working with No Starch Press to bring the second edition of the 14 | book to print. Each chapter goes through [a number of stages][project]: 15 | 16 | [project]: https://github.com/rust-lang/book/projects/1 17 | 18 | * We write and edit a chapter's initial content 19 | * No Starch provides a round of edits and questions 20 | * We revise, clarify, and check those edits 21 | * A Technical Reviewer checks for the accuracy of technical details 22 | * No Starch copyedits the chapter for spelling, grammar, wording, consistency 23 | * We revise, clarify, and check the copyedits 24 | * The chapter goes to layout, at which point only minor changes should be made 25 | 26 | ### Documenting newly stabilized features 27 | 28 | New features added to Rust will be documented in the ["Newest Features" 29 | Appendix][new] per [RFC 1636][rfc]. We'd love pull requests adding new 30 | sections! These sections may be incorporated into the book at some point, but 31 | we have no timeline for doing so; see the Post-publication section below for 32 | more details. 33 | 34 | [new]: https://github.com/rust-lang/book/blob/master/second-edition/src/appendix-07-newest-features.md 35 | [rfc]: https://github.com/rust-lang/rfcs/pull/1636#issuecomment-247325313 36 | 37 | ### Corrections and Modifications 38 | 39 | We would love issues and pull requests to the Markdown files in the src 40 | directory, up until the chapter goes to layout with No Starch. At that point, 41 | we will likely only be accepting changes that correct factual errors or major 42 | problems and not, for example, minor wording changes. 43 | 44 | You can check which chapters have gone to layout and are frozen on the [project 45 | page][project] by scrolling all the way to the right to find the column titled 46 | **Frozen**. 47 | 48 | ### Review 49 | 50 | Our [open pull requests][pulls] are new chapters or edits that we're currently 51 | working on. We would love if you would read through those and make comments for 52 | any suggestions or corrections! 53 | 54 | [pulls]: https://github.com/rust-lang/book/pulls 55 | 56 | ### Translations 57 | 58 | We'd especially love help translating the second edition of the book! See the 59 | [Translations] label to join in efforts that are currently in progress. Open 60 | a new issue to start working on a new language! We're waiting on [mdbook 61 | support] for multiple languages before we merge any in, but feel free to 62 | start! The chapters in [the frozen column] of the project won't see major 63 | changes, so if you start with those, you won't have to redo work :) 64 | 65 | [Translations]: https://github.com/rust-lang/book/issues?q=is%3Aopen+is%3Aissue+label%3ATranslations 66 | [mdbook support]: https://github.com/azerupi/mdBook/issues/5 67 | [the frozen column]: https://github.com/rust-lang/book/projects/1 68 | 69 | ### Help wanted 70 | 71 | If you're looking for ways to help that don't involve large amounts of reading 72 | or writing, check out the [open issues with the E-help-wanted 73 | label][help-wanted]. These might be small fixes to the text Rust code, frontend 74 | code, or shell scripts that would help us be more efficient or enhance the book 75 | in some way! 76 | 77 | [help-wanted]: https://github.com/rust-lang/book/issues?q=is%3Aopen+is%3Aissue+label%3AE-help-wanted 78 | 79 | ### Post-publication 80 | 81 | After the second edition of the book goes to print, here are our intentions for 82 | changes: 83 | 84 | * The online version should stay fairly close to the printed version. For 85 | example, you should be able to look at listing 10-3 in the book and find 86 | listing 10-3 in the online version and copy-paste the code if you want to 87 | play with it. Major changes to correct errors should get documented in 88 | errata. 89 | * There are multiple efforts starting to translate the online book into 90 | other languages. It would help the translations stay in sync if we're not 91 | constantly changing the text. 92 | * Someday there might be a third edition, once there are enough large, new 93 | features in Rust to warrant such a thing. We don't have any schedule in mind 94 | for that though, nor have we decided if it would be modifications to the 95 | second edition or a ground-up rewrite. Until we have plans for that, we won't 96 | be accepting pull requests that aren't fixing errors, for example, changing 97 | the way something is worded. 98 | 99 | This repository is under the same license as Rust itself, MIT/Apache2. 100 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # The Rust Programming Language 2 | 3 | [![Build Status](https://travis-ci.org/rust-lang/book.svg?branch=master)](https://travis-ci.org/rust-lang/book) 4 | 5 | This repo contains two editions of “The Rust Programming Language”. 6 | 7 | The second edition is a rewrite that will be printed by NoStarch Press, 8 | available around October 2017. 9 | 10 | [You can read it online][html]; the last few chapters aren't completed yet, but 11 | the first half of the book is much improved from the first edition. We recommend 12 | starting with the second edition. 13 | 14 | [html]: http://rust-lang.github.io/book/ 15 | 16 | [The first edition is still available to read online][first]. 17 | 18 | [first]: https://doc.rust-lang.org/book/ 19 | 20 | ## Requirements 21 | 22 | Building the book requires [mdBook] >= v0.0.13. To get it: 23 | 24 | [mdBook]: https://github.com/azerupi/mdBook 25 | 26 | ```bash 27 | $ cargo install mdbook 28 | ``` 29 | 30 | ## Building 31 | 32 | To build the book, first `cd` into either the `first-edition` or 33 | `second-edition` directory depending on which edition of the book you would 34 | like to build. Then type: 35 | 36 | ```bash 37 | $ mdbook build 38 | ``` 39 | 40 | The output will be in the `book` subdirectory. To check it out, open it in 41 | your web browser. 42 | 43 | _Firefox:_ 44 | ```bash 45 | $ firefox book/index.html # Linux 46 | $ open -a "Firefox" book/index.html # OS X 47 | $ Start-Process "firefox.exe" .\book\index.html # Windows (PowerShell) 48 | $ start firefox.exe .\book\index.html # Windows (Cmd) 49 | ``` 50 | 51 | _Chrome:_ 52 | ```bash 53 | $ google-chrome book/index.html # Linux 54 | $ open -a "Google Chrome" book/index.html # OS X 55 | $ Start-Process "chrome.exe" .\book\index.html # Windows (PowerShell) 56 | $ start chrome.exe .\book\index.html # Windows (Cmd) 57 | ``` 58 | 59 | To run the tests: 60 | 61 | ```bash 62 | $ mdbook test 63 | ``` 64 | 65 | ## Contributing 66 | 67 | We'd love your help! Please see [CONTRIBUTING.md][contrib] to learn about the 68 | kinds of contributions we're looking for. 69 | 70 | [contrib]: https://github.com/rust-lang/book/blob/master/CONTRIBUTING.md 71 | 72 | ### Translations 73 | 74 | We'd especially love help translating the second edition of the book! See the 75 | [Translations] label to join in efforts that are currently in progress. Open 76 | a new issue to start working on a new language! We're waiting on [mdbook 77 | support] for multiple languages before we merge any in, but feel free to 78 | start! The chapters in [the frozen column] of the project won't see major 79 | changes, so if you start with those, you won't have to redo work :) 80 | 81 | [Translations]: https://github.com/rust-lang/book/issues?q=is%3Aopen+is%3Aissue+label%3ATranslations 82 | [mdbook support]: https://github.com/azerupi/mdBook/issues/5 83 | [the frozen column]: https://github.com/rust-lang/book/projects/1 84 | 85 | ## No Starch 86 | 87 | As the second edition of the book will be published by No Starch, we first 88 | iterate here, then ship the text off to No Starch. Then they do editing, and we 89 | fold it back in. 90 | 91 | As such, there’s a directory, *nostarch*, which corresponds to the text in No 92 | Starch’s system. 93 | 94 | When we've started working with No Starch in a word doc, we will also check 95 | those into the repo in the *nostarch/odt* directory. To extract the text from 96 | the word doc as markdown in order to backport changes to the online book: 97 | 98 | 1. Open the doc file in LibreOffice 99 | 1. Accept all tracked changes 100 | 1. Save as Microsoft Word 2007-2013 XML (.docx) in the *tmp* directory 101 | 1. Run `./doc-to-md.sh` 102 | 1. Inspect changes made to the markdown file in the *nostarch* directory and 103 | copy the changes to the *src* directory as appropriate. 104 | 105 | ## Graphviz dot 106 | 107 | This is mostly for Carol's reference because she keeps having to look it up. 108 | 109 | We're using [Graphviz](http://graphviz.org/) for some of the diagrams in the 110 | book. The source for those files live in the `dot` directory. To turn a `dot` 111 | file, for example, `dot/trpl04-01.dot` into an `svg`, run: 112 | 113 | ```bash 114 | $ dot dot/trpl04-01.dot -Tsvg > src/img/trpl04-01.svg 115 | ``` 116 | 117 | In the generated SVG, remove the width and the height attributes from the `svg` 118 | element and set the `viewBox` attribute to `0.00 0.00 1000.00 1000.00` or other 119 | values that don't cut off the image. 120 | 121 | ## Spellchecking 122 | 123 | To scan source files for spelling errors, you can use the `spellcheck.sh` 124 | script. It needs a dictionary of valid words, which is provided in 125 | `dictionary.txt`. If the script produces a false positive (say, you used word 126 | `BTreeMap` which the script considers invalid), you need to add this word to 127 | `dictionary.txt` (keep the sorted order for consistency). 128 | -------------------------------------------------------------------------------- /second-edition/src/img/trpl04-01.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | %3 11 | 12 | 13 | table0 14 | 15 | s1 16 | 17 | name 18 | 19 | value 20 | 21 | ptr 22 | 23 | 24 | len 25 | 26 | 5 27 | 28 | capacity 29 | 30 | 5 31 | 32 | 33 | table1 34 | 35 | index 36 | 37 | value 38 | 39 | 0 40 | 41 | h 42 | 43 | 1 44 | 45 | e 46 | 47 | 2 48 | 49 | l 50 | 51 | 3 52 | 53 | l 54 | 55 | 4 56 | 57 | o 58 | 59 | 60 | table0:pointer:c->table1:pointee 61 | 62 | 63 | 64 | 65 | 66 | --------------------------------------------------------------------------------