diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..d56abbf304 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Set the default behavior, in case people don't have core.autocrlf set. +* text=auto eol=lf diff --git a/.gitignore b/.gitignore index c29ce06384..e82f879ba9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -bin/* -stage/* -node_modules/* -!node_modules/gitbook-plugin-rust-playpen +book + +# Auto-generated files from macOS +.DS_Store \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index acb9509a4d..17adda5b9c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,21 +1,23 @@ -language: node_js - -install: - - npm install gitbook@0.7.1 -g - - curl -s https://static.rust-lang.org/rustup.sh | sudo sh > /dev/null - -script: - - rustc --version - - make - - make test - - make book - -after_success: - - test $TRAVIS_PULL_REQUEST == "false" && test $TRAVIS_BRANCH == "master" && bash deploy.sh - +sudo: false +language: rust +rust: + - nightly branches: - only: master - -env: - global: - - secure: "oFD/tic8JAwpMXuMDBZXV4ot6w1NLWvHQTrDKmUHSMQJC1cbbrR1p5q8XayfjtmdqQdFQmIfM6YHEKeHw//ypgObWjYS8q00OaaMDXPTdmgr1Ee4nhgkkDihT+kVij0rn96W/QvyAVoaV5hJoyUr3Nhk+mnHEYm3M+Q3LAQglRg=" + only: + - master +before_script: + - | + set -ex + rustup --version + rustc -Vv + curl -sSL https://github.com/rust-lang/mdBook/releases/download/v0.4.5/mdbook-v0.4.5-x86_64-unknown-linux-gnu.tar.gz | tar -xz --directory=$HOME/.cargo/bin + mdbook --version + rustup toolchain update nightly -c rust-docs +script: + - mdbook build + - mdbook test + - | + set -e + curl -sSLo linkcheck.sh \ + https://raw.githubusercontent.com/rust-lang/rust/master/src/tools/linkchecker/linkcheck.sh + sh linkcheck.sh --all rust-by-example diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000..cdfd7cfe80 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,39 @@ +# The Rust Code of Conduct + +A version of this document [can be found online](https://www.rust-lang.org/conduct.html). + +## Conduct + +**Contact**: [rust-mods@rust-lang.org](mailto:rust-mods@rust-lang.org) + +* We are committed to providing a friendly, safe and welcoming environment for all, regardless of level of experience, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, nationality, or other similar characteristic. +* On IRC, please avoid using overtly sexual nicknames or other nicknames that might detract from a friendly, safe and welcoming environment for all. +* Please be kind and courteous. There's no need to be mean or rude. +* Respect that people have differences of opinion and that every design or implementation choice carries a trade-off and numerous costs. There is seldom a right answer. +* Please keep unstructured critique to a minimum. If you have solid ideas you want to experiment with, make a fork and see how it works. +* We will exclude you from interaction if you insult, demean or harass anyone. That is not welcome behavior. We interpret the term "harassment" as including the definition in the [Citizen Code of Conduct](http://citizencodeofconduct.org/); if you have any lack of clarity about what might be included in that concept, please read their definition. In particular, we don't tolerate behavior that excludes people in socially marginalized groups. +* Private harassment is also unacceptable. No matter who you are, if you feel you have been or are being harassed or made uncomfortable by a community member, please contact one of the channel ops or any of the [Rust moderation team][mod_team] immediately. Whether you're a regular contributor or a newcomer, we care about making this community a safe place for you and we've got your back. +* Likewise any spamming, trolling, flaming, baiting or other attention-stealing behavior is not welcome. + +## Moderation + +These are the policies for upholding our community's standards of conduct. If you feel that a thread needs moderation, please contact the [Rust moderation team][mod_team]. + +1. Remarks that violate the Rust standards of conduct, including hateful, hurtful, oppressive, or exclusionary remarks, are not allowed. (Cursing is allowed, but never targeting another user, and never in a hateful manner.) +2. Remarks that moderators find inappropriate, whether listed in the code of conduct or not, are also not allowed. +3. Moderators will first respond to such remarks with a warning. +4. If the warning is unheeded, the user will be "kicked," i.e., kicked out of the communication channel to cool off. +5. If the user comes back and continues to make trouble, they will be banned, i.e., indefinitely excluded. +6. Moderators may choose at their discretion to un-ban the user if it was a first offense and they offer the offended party a genuine apology. +7. If a moderator bans someone and you think it was unjustified, please take it up with that moderator, or with a different moderator, **in private**. Complaints about bans in-channel are not allowed. +8. Moderators are held to a higher standard than other community members. If a moderator creates an inappropriate situation, they should expect less leeway than others. + +In the Rust community we strive to go the extra step to look out for each other. Don't just aim to be technically unimpeachable, try to be your best self. In particular, avoid flirting with offensive or sensitive issues, particularly if they're off-topic; this all too often leads to unnecessary fights, hurt feelings, and damaged trust; worse, it can drive people away from the community entirely. + +And if someone takes issue with something you said or did, resist the urge to be defensive. Just stop doing what it was they complained about and apologize. Even if you feel you were misinterpreted or unfairly accused, chances are good there was something you could've communicated better — remember that it's your responsibility to make your fellow Rustaceans comfortable. Everyone wants to get along and we are all here first and foremost because we want to talk about cool technology. You will find that people will be eager to assume good intent and forgive as long as you earn their trust. + +The enforcement policies listed above apply to all official Rust venues; including official IRC channels (#rust, #rust-internals, #rust-tools, #rust-libs, #rustc, #rust-beginners, #rust-docs, #rust-community, #rust-lang, and #cargo); GitHub repositories under rust-lang, rust-lang-nursery, and rust-lang-deprecated; and all forums under rust-lang.org (users.rust-lang.org, internals.rust-lang.org). For other projects adopting the Rust Code of Conduct, please contact the maintainers of those projects for enforcement. If you wish to use this code of conduct for your own project, consider explicitly mentioning your moderation policy or making a copy with your own moderation policy so as to avoid confusion. + +*Adapted from the [Node.js Policy on Trolling](http://blog.izs.me/post/30036893703/policy-on-trolling) as well as the [Contributor Covenant v1.3.0](https://www.contributor-covenant.org/version/1/3/0/).* + +[mod_team]: https://www.rust-lang.org/team.html#Moderation-team diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3c98d95983..665a708c03 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,89 +1,69 @@ -# Opening an issue +# Rust by Example contribution guidelines -## I would like to see an example about $TOPIC +Thank you for your interest in making Rust by Example (also known as RBE) +better! We'd love to have your contribution. We expect all contributors to +abide by the [Rust code of conduct], which you can find at that link or in the +[`CODE_OF_CONDUCT.md`] file in this repository. -Please check if such topic is already part of our -[TODO list][issues-all]. If that's -not the case, leave your request as a comment on that issue. +[Rust code of conduct]: https://www.rust-lang.org/policies/code-of-conduct +[`CODE_OF_CONDUCT.md`]: https://github.com/rust-lang/rust-by-example/blob/master/CODE_OF_CONDUCT.md -## There's a typo/error in example $X -## Example $X is not clear -## I have an idea for example $X +## License -Please include the example id in the issue title, e.g. "variables/mut: concept -not clear". The example id is the relative path in the URL without the html -extension, e.g. URL: `http://rustbyexample.com/variables/scope.html` -> id: -`variables/scope` +RBE is dual licenced under the MIT and Apache 2.0 licenses, and so are all +contributions. Please see the [`LICENSE-MIT`] and [`LICENSE-APACHE`] files in +this directory for more details. -If its something simple like a typo, you can send a PR directly. +[`LICENSE-MIT`]: https://github.com/rust-lang/rust-by-example/blob/master/LICENSE-MIT +[`LICENSE-APACHE`]: https://github.com/rust-lang/rust-by-example/blob/master/LICENSE-APACHE -# Sending a PR for a small fix +## Pull Requests -If you are submitting a correction/modification to an existing chapter, please -start the commit message with the example id, e.g. "type/literals: fix typo". +To make changes to RBE, please send in pull requests on GitHub to the `master` +branch. We'll review them and either merge or request changes. Travis CI tests +everything as well, so you may get feedback from it too. -# I want to contribute an example about $TOPIC +If you make additions or other changes to a pull request, feel free to either amend +previous commits or only add new ones, however you prefer. We may ask you to squash +your commits before merging, depending. -## Check if there is an action plan for that topic +## Issue Tracker -Look for -[issues][issues-open] -that have a C-* label: +You can find the issue tracker [on +GitHub](https://github.com/rust-lang/rust-by-example/issues). If you've found a +problem with RBE, please open an issue there. -* C-new: A new chapter, there probably a lot to do here. +We use the following labels: -* C-expand: Expand an existing chapter, new examples are needed. +* `enhancement`: This is for any request for new sections or functionality. +* `bug`: This is for anything that's in RBE, but incorrect or not working. +* `discussion`: A discussion about improving something in RBE; this may lead to new + enhancement or bug issues. +* `E-mentor`: This issue has someone dedicated to helping a new contributor fix it! + Can apply to both enhancement or bug issues. -* C-split: The current chapter is too long, we want to split it into smaller - chunks. +## Development workflow -* C-taken: Someone is already working in this issue, but if there is a lot of - work to do, probably you can still help. +To build RBE, [install Rust], and then: -## Let us know what are you working on +```bash +$ git clone https://github.com/rust-lang/rust-by-example +$ cd rust-by-example +$ cargo install mdbook +$ mdbook build +``` -If an issue about the topic already exists, leave a comment there to let us -know that you'll help. Otherwise, open a new issue mentioning what topic you -plan to work on. +[install Rust]: http://rust-lang.org/install.html -## Hack away +The files will be in the `book` directory at the top-level; `mdbook serve` will +open the contents in your web browser. -See the [README][readme] for details about how the static site is generated. +To run the tests: -## Finally, send a PR +```bash +$ mdbook test +``` -* Don't forget to register the example in the `examples/structure.json` file. - -* Include the example id in the commit message header, e.g. for - `literals/string` use the message "literals: add example about strings" - -* Add a `Close #123` to the commit message, to close the issue that's been used - to track your work. - -# Code Style - -## Markdown (.md) - -* Lines should contain a maximum of 79 characters. -* Use reference style hyperlinks, for example: - -Instead of: - - [Goto my URL](http://www.myurl.com) - -Use: - - [Goto my URL][1] - - (Bottom of page) - [1]: http://www.myurl.com - -## Rust code (.rs) - -* Lines should contain a maximum of 79 characters. -* In comments, types, methods, macros and variables should be wrapped in - backticks, e.g. ``` `println!` ``` - -[issues-all]: https://github.com/rust-lang/rust-by-example/issues/ -[issues-open]: https://github.com/rust-lang/rust-by-example/issues?labels=&page=1&state=open -[readme]: README.md +If you're adding a new chapter, you'll need to edit `src\SUMMARY.md` to add it. If +you're tweaking an existing example, you'll need to edit the corresponding file; check +`src\SUMMARY.md` to see a mapping of where chapters go to files. diff --git a/Makefile b/Makefile deleted file mode 100644 index 501726ba69..0000000000 --- a/Makefile +++ /dev/null @@ -1,45 +0,0 @@ -GITBOOK = gitbook -RUSTC = rustc -STRICT = -D deprecated -QUIET = -A unused-variables -A dead-code -A unused-assignments -A experimental -RUSTC_NT = $(RUSTC) --no-trans --test $(QUIET) ${STRICT} -WHITELIST = examples/attribute/cfg/custom/custom.rs \ - examples/borrow/borrow.rs \ - examples/borrow/freeze/freeze.rs \ - examples/borrow/mut/mut.rs \ - examples/bounds/bounds.rs \ - examples/constants/constants.rs \ - examples/crates/link/executable.rs \ - examples/lifetime/borrow/borrow.rs \ - examples/mod/mod.rs \ - examples/print/print.rs \ - examples/type/cast/cast.rs \ - examples/type/type.rs \ - examples/variables/declare/declare.rs \ - examples/variables/mut/mut.rs \ - examples/variables/scope/scope.rs \ - examples/vec/vec.rs \ - -srcs = $(filter-out $(WHITELIST),$(shell find examples -name '*.rs')) - -.PHONY: all book clean test serve - -all: - ./setup-stage.sh - $(RUSTC) src/update.rs --out-dir bin - bin/update - -book: - cd stage && $(GITBOOK) build - ./fix-edit-button.sh - ./add-relinks.sh - -clean: - rm -rf bin stage - -test: - $(foreach src,$(srcs),$(RUSTC_NT) $(src) || exit;) - ./check-line-length.sh - -serve: - cd stage && $(GITBOOK) serve diff --git a/README.md b/README.md index e616dc7caa..a6886feec1 100644 --- a/README.md +++ b/README.md @@ -1,103 +1,56 @@ -[![Build Status][travis-image]][travis-link] -# Rust by Example +# Rust By Example -## What's this? +[![Build Status][travis-badge]][travis-repo] -This is the source code of the -[Rust by example][website] website! +[travis-badge]: https://travis-ci.com/rust-lang/rust-by-example.svg?branch=master +[travis-repo]: https://travis-ci.com/rust-lang/rust-by-example -## How to contribute +Learn Rust with examples (Live code editor included) -See [CONTRIBUTING.md][how-to-contribute]. +## Using -## How to generate the static site +If you'd like to read Rust by Example, you can visit +to read it online. -``` -npm install gitbook@0.7.1 -make all -make book GITBOOK=`pwd`/node_modules/.bin/gitbook -make test GITBOOK=`pwd`/node_modules/.bin/gitbook -``` - -View the results with ```make serve GITBOOK=`pwd`/node_modules/.bin/gitbook```. - -Note: on Ubuntu `node` may be called `nodejs`. I had to edit `.bin/gitbook` accordingly. - -### Details - -We use these tools to generate the static site: - -* [Rust][rust-lang] \o/ -* [gitbook][gitbook] +If you'd like to read it locally, [install Rust], and then: -`gitbook` will generate the site from markdown files (see details about how it -works [here][gitbook-format]). - -Before running `gitbook`, we do a preprocessing step using -[src/update.rs][update-rs]. - -This preprocessing has two steps: - -### Generating the `SUMMARY.md` - -`SUMMARY.md` is generated from the -[examples/structure.json][structure] file. This JSON file -contains a tree-like structure of "examples". - -Each example has: - -* an id, e.g. `hello` -* a title, e.g. `Hello World` -* optionally, children, which is a vector of sub-examples, e.g. `null` -* a directory under `examples`, e.g. [examples/hello][hello-folder] -* an entry in examples/structure.json, e.g. - `{ "id": "hello", "title": "Hello World", "children": null }` -* some source file(s), e.g. [examples/hello/hello.rs][hello-rs] -* an input markdown file, e.g. - [examples/hello/input.md][hello-md] +```bash +$ git clone https://github.com/rust-lang/rust-by-example +$ cd rust-by-example +$ cargo install mdbook +$ mdbook build +$ mdbook serve +``` -When dealing with a child example, the path will have to include the id of its -ancestors; e.g. `examples/variable/mut/input.md`, implies that a `mut` example -lives under the `variable` example. +[install Rust]: https://www.rust-lang.org/tools/install -### Processing `input.md` +To be able to run the examples, you must be connected to the internet; you can +read all content offline, however! -Instead of including the rust code directly in `input.md`, the code lives in -separate source files; and the preprocessing step will insert the source code -in the markdown file. +## Contributing -For example, to insert the source code of the `hello.rs` file, the following -syntax is used in the markdown file: +Please see the [CONTRIBUTING.md] file for more details. -* `{hello.play}` expands the source code embedded in a live code editor -* `{hello.rs}` expands to static/plain source code. -* `{hello.out}` expands to the output of executing the source code. +[CONTRIBUTING.md]: https://github.com/rust-lang/rust-by-example/blob/master/CONTRIBUTING.md -The Makefile provides the following recipes: +## Translations to other languages -* `make`: builds `update.rs` and does the preprocessing step -* `make book`: runs `gitbook` to generate the book -* `make serve`: runs `gitbook --serve` to generate the book and publishes it - under `localhost:4000` -* `make test`: will check all the rust source files for compilation errors +* [Chinese](https://github.com/rust-lang-cn/rust-by-example-cn) +* [Japanese](https://github.com/rust-lang-ja/rust-by-example-ja) +* [French](https://github.com/Songbird0/FR_RBE) +* [Russian](https://github.com/ruRust/rust-by-example) ## License -Rust by example is dual licensed under the Apache 2.0 license and the MIT -license. +Rust by Example is licensed under either of -See LICENSE-APACHE and LICENSE-MIT for more details. +* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or + ) +* MIT license ([LICENSE-MIT](LICENSE-MIT) or + ) -[travis-image]: https://travis-ci.org/rust-lang/rust-by-example.svg?branch=master -[travis-link]: https://travis-ci.org/rust-lang/rust-by-example -[website]: http://rustbyexample.com -[how-to-contribute]: CONTRIBUTING.md -[rust-lang]: http://www.rust-lang.org/ -[gitbook]: http://www.gitbook.io -[gitbook-dir]: https://github.com/GitbookIO/gitbook#book-format -[update-rs]: src/update.rs -[structure]: examples/structure.json -[hello-folder]: examples/hello -[hello-rs]: examples/hello/hello.rs -[hello-md]: examples/hello/input.md +at your option. +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in Rust by Example by you, as defined in the Apache-2.0 license, shall be +dually licensed as above, without any additional terms or conditions. diff --git a/add-relinks.sh b/add-relinks.sh deleted file mode 100755 index a77376bad9..0000000000 --- a/add-relinks.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/bash - -for example in $(ls examples); do - if [[ -d examples/${example} ]]; then - new_html=http://rustbyexample.com/${example}.html - - mkdir -p stage/_book/examples/${example} - echo ' - - - - - - -' > stage/_book/examples/${example}/README.html - fi -done diff --git a/book.json b/book.json deleted file mode 100644 index 365974f0d1..0000000000 --- a/book.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "plugins": ["rust-playpen"], - "pluginsConfig": { - "rust-playpen": {} - } -} diff --git a/book.toml b/book.toml new file mode 100644 index 0000000000..089d703286 --- /dev/null +++ b/book.toml @@ -0,0 +1,11 @@ +[book] +title = "Rust By Example" +description = "Rust by Example (RBE) is a collection of runnable examples that illustrate various Rust concepts and standard libraries." +author = "The Rust Community" + +[output.html.playpen] +editable = true +editor = "ace" + +[output.html.fold] +enable = true diff --git a/check-line-length.sh b/check-line-length.sh deleted file mode 100755 index 046f8643ae..0000000000 --- a/check-line-length.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/bash - -WHITELIST=( - ./examples/lifetime/borrow/borrow.rs - ./src/playpen.rs -) - -echo "Checking if any rust file has a line longer than 79 characters" - -suspects=$(find -name '*.rs' | xargs grep -Pl ".{80}") -status=$? - -any_offender=false -if [[ $status == 0 ]]; then - for suspect in $suspects; do - if [[ " ${WHITELIST[*]} " == *" ${suspect} "* ]]; then - continue - fi - any_offender=true - echo "> $suspect exceeds 79 chars" - awk 'length($0) > 79' $suspect - done - -fi - -if $any_offender; then - exit 1 -else - echo "All is good!" -fi diff --git a/deploy.sh b/deploy.sh deleted file mode 100644 index 8118df3e80..0000000000 --- a/deploy.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/bash - -rev=$(git rev-parse --short HEAD) - -cd stage/_book - -git init -git config user.name "Steve Klabnik" -git config user.email "steve@steveklabnik.com" -git remote add upstream "https://$GH_TOKEN@github.com/rust-lang/rust-by-example.git" -git fetch upstream && git reset upstream/gh-pages - -echo "rustbyexample.com" > CNAME -cp -r ../../vendor/gitbook/* gitbook/ - -touch . - -git add -A . - -git commit -m "rebuild pages at ${rev}" -git push -q upstream HEAD:gh-pages diff --git a/examples/README.md b/examples/README.md deleted file mode 100644 index 4b23e507b8..0000000000 --- a/examples/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# Rust by Example - -[Rust][rust] is a programming language with a focus on -type safety, memory safety, concurrency and performance. - -This book is a collection of bitesize examples that illustrate various rustic -concepts and the Rust distribution libraries. - -Be sure to have rust [installed][install] and the -[docs][std] at hand, let's -start! - -*Note*: This book will follow the nightly version of Rust until we reach -version 1.0, it's highly possible that some examples won't work with snapshot -versions like 0.10, be sure to use a nightly version! - -[rust]: http://www.rust-lang.org/ -[install]: http://www.rust-lang.org/install.html -[std]: http://doc.rust-lang.org/std/ diff --git a/examples/array/array.rs b/examples/array/array.rs deleted file mode 100644 index 25aa3eeb5f..0000000000 --- a/examples/array/array.rs +++ /dev/null @@ -1,36 +0,0 @@ -use std::mem; - -// This function borrows a slice -fn analyze_slice(slice: &[int]) { - println!("first element of the slice: {}", slice[0]); - println!("the slice has {} elements", slice.len()); -} - -fn main() { - // Fixed-size array (type signature is superfluous) - let xs: [int, ..5] = [1, 2, 3, 4, 5]; - - // All elements can be initialized to the same value - let ys: [int, ..500] = [0, ..500]; - - // Indexing starts at 0 - println!("first element of the array: {}", xs[0]); - println!("second element of the array: {}", xs[1]); - - // `len` returns the size of the array - println!("array size: {}", xs.len()); - - // Arrays are stack allocated - println!("array occupies {} bytes", mem::size_of_val(&xs)); - - // Arrays can be automatically borrowed as slices - println!("borrow the whole array as a slice"); - analyze_slice(&xs); - - // Slices can point to a section of an array - println!("borrow a section of the array as a slice"); - analyze_slice(ys.slice(1, 4)); - - // Out of bound indexing yields a task failure - println!("{}", xs[5]); -} diff --git a/examples/array/input.md b/examples/array/input.md deleted file mode 100644 index e60e8e5fc5..0000000000 --- a/examples/array/input.md +++ /dev/null @@ -1,10 +0,0 @@ -An array is a collection of objects of the same type `T`, stored in contiguous -memory. Arrays are created using brackets `[]`, and their size, which is known -at compile time, is part of their type signature `[T, ..size]`. - -Slices are similar to arrays, but their size is not known at compile time. -Instead, a slice is two-word object, the first word is a pointer to the data, -and the second word is the length of the slice. Slices can be used to borrow a -section of an array, and have `&[T]` as type signature. - -{array.play} diff --git a/examples/attribute/cfg/cfg.rs b/examples/attribute/cfg/cfg.rs deleted file mode 100644 index 95dd647bfa..0000000000 --- a/examples/attribute/cfg/cfg.rs +++ /dev/null @@ -1,15 +0,0 @@ -// This function only gets compiled if the target OS is linux -#[cfg(target_os = "linux")] -fn are_you_on_linux() { - println!("You are running linux!") -} - -// And this function only gets compiled if the target OS is *not* linux -#[cfg(not(target_os = "linux"))] -fn are_you_on_linux() { - println!("You are *not* running linux!") -} - -fn main() { - are_you_on_linux(); -} diff --git a/examples/attribute/cfg/custom/custom.rs b/examples/attribute/cfg/custom/custom.rs deleted file mode 100644 index 19ad641852..0000000000 --- a/examples/attribute/cfg/custom/custom.rs +++ /dev/null @@ -1,8 +0,0 @@ -#[cfg(some_condition)] -fn conditional_function() { - println!("condition met!") -} - -fn main() { - conditional_function(); -} diff --git a/examples/attribute/cfg/custom/input.md b/examples/attribute/cfg/custom/input.md deleted file mode 100644 index 75b04dd853..0000000000 --- a/examples/attribute/cfg/custom/input.md +++ /dev/null @@ -1,15 +0,0 @@ -Some conditionals like `target_os` are implicitly provided by `rustc`, but -custom conditionals must be passed to `rustc` using the `--cfg` flag. - -{custom.rs} - -Without the custom `cfg` flag: - -{custom.out} - -With the custom `cfg` flag: - -``` -$ rustc --cfg some_condition custom.rs && ./custom -condition met! -``` diff --git a/examples/attribute/cfg/input.md b/examples/attribute/cfg/input.md deleted file mode 100644 index 1d473f39f4..0000000000 --- a/examples/attribute/cfg/input.md +++ /dev/null @@ -1,3 +0,0 @@ -The `cfg` attribute can be use to achieve conditional compilation. - -{cfg.play} diff --git a/examples/attribute/crate/input.md b/examples/attribute/crate/input.md deleted file mode 100644 index 0464f24e54..0000000000 --- a/examples/attribute/crate/input.md +++ /dev/null @@ -1,14 +0,0 @@ -The `crate_type` attribute can be used to tell the compiler whether a crate is -a binary or a library (and even which type of library). And the `crate_name` -attribute can be used to set the name of the crate. - -{lib.rs} - -When the `crate_type` attribute is used, we no longer need to pass the -`--crate-type` flag to `rustc`. - -``` -$ rustc lib.rs -$ ls lib* -liberty.rlib -``` diff --git a/examples/attribute/crate/lib.rs b/examples/attribute/crate/lib.rs deleted file mode 100644 index 3fc52b6a34..0000000000 --- a/examples/attribute/crate/lib.rs +++ /dev/null @@ -1,18 +0,0 @@ -// This crate is a library -#![crate_type = "lib"] -// The library is named "erty" -#![crate_name = "erty"] - -pub fn public_function() { - println!("called erty's `public_function()`"); -} - -fn private_function() { - println!("called erty's `private_function()`"); -} - -pub fn indirect_access() { - print!("called erty's `indirect_access()`, that\n> "); - - private_function(); -} diff --git a/examples/borrow/alias/alias.rs b/examples/borrow/alias/alias.rs deleted file mode 100644 index a3510fa573..0000000000 --- a/examples/borrow/alias/alias.rs +++ /dev/null @@ -1,43 +0,0 @@ -struct Point { x: int, y: int, z: int } - -fn main() { - let mut point = Point { x: 0, y: 0, z: 0 }; - - { - let borrowed_point = &point; - let another_borrow = &point; - - // Data can be accessed via the references and the original owner - println!("Point has coordinates: ({}, {}, {})", - borrowed_point.x, another_borrow.y, point.z); - - // Error! Can't borrow point as mutable because it's currently - // borrowed as immutable - //let mutable_borrow = &mut point; - // TODO ^ Try uncommenting this line - - // Immutable references go out of scope - } - - { - let mutable_borrow = &mut point; - - // Change data via mutable reference - mutable_borrow.x = 5; - - // Error! Can't borrow `point` as immutable because it's currently - // borrowed as mutable - //let y = &point.y; - // TODO ^ Try uncommenting this line - - // Error! Can't print, because println! takes an immutable reference - //println!("Point Z coordinate is {}", point.z); - // TODO ^ Try uncommenting this line - - // Mutable reference goes out of scope - } - - // Immutable references to point are allowed again - println!("Point now has coordinates: ({}, {}, {})", - point.x, point.y, point.z); -} diff --git a/examples/borrow/alias/input.md b/examples/borrow/alias/input.md deleted file mode 100644 index 438029996d..0000000000 --- a/examples/borrow/alias/input.md +++ /dev/null @@ -1,6 +0,0 @@ -Data can be immutably borrowed any number of times, but while immutably -borrowed, the original data can't be mutably borrowed. On the other side, -only *one* mutable borrow is allowed at a time. The original data can be -borrowed again after the mutable reference goes out of scope. - -{alias.play} diff --git a/examples/borrow/borrow.rs b/examples/borrow/borrow.rs deleted file mode 100644 index 57bbcb8531..0000000000 --- a/examples/borrow/borrow.rs +++ /dev/null @@ -1,35 +0,0 @@ -// This function takes ownership of the box -fn eat_box(boxed_int: Box) { - println!("destroying box that contains {}", boxed_int); -} - -// This function borrows the box -fn peep_inside_box(borrowed_box: &Box) { - println!("This box contains {}", borrowed_box); -} - -fn main() { - // A boxed integer - let boxed_int = box 5; - - // Borrow the box, ownership is not taken - peep_inside_box(&boxed_int); - - // The box can be borrowed again - peep_inside_box(&boxed_int); - - { - // Take a reference to the data contained inside the box - let _ref_to_int: &int = &*boxed_int; - - // Error! Can't destroy boxed_int, while the inner value has been - // borrowed - eat_box(boxed_int); - // FIXME ^ Comment out this line - - // `_ref_to_int` goes out of scope - } - - // Give up ownership of the box - eat_box(boxed_int); -} diff --git a/examples/borrow/freeze/freeze.rs b/examples/borrow/freeze/freeze.rs deleted file mode 100644 index 60a919c7fb..0000000000 --- a/examples/borrow/freeze/freeze.rs +++ /dev/null @@ -1,17 +0,0 @@ -fn main() { - let mut _integer = 5i; - - { - // Borrow `integer` - let _ref_to_integer = &_integer; - - // Error! `integer` is frozen in this scope - _integer = 4; - // FIXME ^ Comment out this line - - // `ref_to_integer` goes out of scope - } - - // Ok! `integer` is not frozen in this scope - _integer = 4; -} diff --git a/examples/borrow/freeze/input.md b/examples/borrow/freeze/input.md deleted file mode 100644 index ca10763179..0000000000 --- a/examples/borrow/freeze/input.md +++ /dev/null @@ -1,4 +0,0 @@ -When data is borrowed, it also *freezes*. *Frozen* data can't be modified via -the original object, until all the references to it go out of scope. - -{freeze.play} diff --git a/examples/borrow/input.md b/examples/borrow/input.md deleted file mode 100644 index 622d478ce0..0000000000 --- a/examples/borrow/input.md +++ /dev/null @@ -1,9 +0,0 @@ -Most of the time we'll like to access some data, without taking ownership over -it. To accomplish this, Rust provides a *borrowing* mechanism. Instead of -passing objects by-value (`T`), objects can be passed by reference (`&T`). - -{borrow.play} - -The compiler statically guarantees that references *always* point to valid -objects, via its borrow checker. For example, the original object can't be -destroyed, while references to it exists. diff --git a/examples/borrow/mut/input.md b/examples/borrow/mut/input.md deleted file mode 100644 index c3370d6832..0000000000 --- a/examples/borrow/mut/input.md +++ /dev/null @@ -1,5 +0,0 @@ -`&T` borrows the data via an immutable reference, and the borrower can read the -data but not modify it. Mutable data can be mutably borrowed via a mutable -reference `&mut T`, giving read/write access to the borrower. - -{mut.play} diff --git a/examples/borrow/mut/mut.rs b/examples/borrow/mut/mut.rs deleted file mode 100644 index c6d9adc41d..0000000000 --- a/examples/borrow/mut/mut.rs +++ /dev/null @@ -1,44 +0,0 @@ -#[allow(dead_code)] -struct Book { - // `&'static str` is a reference to a string allocated in read only memory - author: &'static str, - title: &'static str, - year: uint, -} - -// This function takes a reference to a book -fn borrow_book(book: &Book) { - println!("I borrowed {} {} edition", book.title, book.year); -} - -// This function takes a reference to a mutable book -fn new_edition(book: &mut Book) { - // the fields of the book can be modified - book.year = 2014; -} - -fn main() { - // An immutable Book - let geb = Book { - // string literals have type `&'static str` - author: "Douglas Hofstadter", - title: "Gödel, Escher, Bach", - year: 1979, - }; - - // Immutably borrow `geb` - borrow_book(&geb); - - // Error! Can't borrow an immutable object as mutable - new_edition(&mut geb); - // FIXME ^ Comment out this line - - // `mutable_geb` is a mutable copy of `geb` - let mut mutable_geb = geb; - - // Borrow a mutable object as mutable - new_edition(&mut mutable_geb); - - // Mutable objects can be immutably borrowed - borrow_book(&mutable_geb); -} diff --git a/examples/borrow/ref/input.md b/examples/borrow/ref/input.md deleted file mode 100644 index 7eca8f7256..0000000000 --- a/examples/borrow/ref/input.md +++ /dev/null @@ -1,4 +0,0 @@ -When doing pattern matching or destructuring via the `let` binding, the `ref` -keyword can be used to take references to the fields of a struct/tuple. - -{ref.play} diff --git a/examples/borrow/ref/ref.rs b/examples/borrow/ref/ref.rs deleted file mode 100644 index 3cf7d0e7c4..0000000000 --- a/examples/borrow/ref/ref.rs +++ /dev/null @@ -1,40 +0,0 @@ -#[deriving(Copy)] -struct Point { x: int, y: int } - -fn main() { - let point = Point { x: 0, y: 0 }; - - let _copy_of_x = { - // `ref_to_x` is a reference to the `x` field of `point` - let Point { x: ref ref_to_x, y: _ } = point; - - // Return a copy of the `x` field of `point` - *ref_to_x - }; - - // A mutable copy of `point` - let mut mutable_point = point; - - { - // `ref` can be paired with `mut` to take mutable references - let Point { x: _, y: ref mut mut_ref_to_y } = mutable_point; - - // Mutate the `y` field of `mutable_point`, via a mutable reference - *mut_ref_to_y = 1; - } - - println!("point is ({}, {})", point.x, point.y); - println!("mutable_point is ({}, {})", mutable_point.x, mutable_point.y); - - let mut tuple = (box 5u, 3u); - - { - // `ref` can also be paired with `box` to take a mutable reference to - // the data contained in the box - let (box ref mut i, _) = tuple; - - *i = 3; - } - - println!("tuple is {}", tuple); -} diff --git a/examples/bounds/bounds.rs b/examples/bounds/bounds.rs deleted file mode 100644 index 3fc12fe4e8..0000000000 --- a/examples/bounds/bounds.rs +++ /dev/null @@ -1,57 +0,0 @@ -#[deriving(Show)] -struct Vec2 { - x: T, - y: T, -} - -impl< - // Bound: `T` must implement the `Add` trait - T: Add -> Add, Vec2> -for Vec2 { - fn add(&self, rhs: &Vec2) -> Vec2 { - Vec2 { - // `x` and `y` are of type `T`, and implement the `add` method - x: self.x.add(&rhs.x), - // The sugary `+` operator can also be used - y: self.y + rhs.y, - } - } -} - -impl< - // Bound: `T` must implement the `Sub` trait - T: Sub -> Sub, Vec2> -for Vec2 { - fn sub(&self, rhs: &Vec2) -> Vec2 { - Vec2 { - x: self.x - rhs.x, - y: self.y - rhs.y, - } - } -} - -impl< - // Bound: `T` must implement *both* the `Add` trait and the `Mul` trait - T: Add + Mul -> Mul, T> -for Vec2 { - fn mul(&self, rhs: &Vec2) -> T { - (self.x * rhs.x) + (self.y * rhs.y) - } -} - -fn main() { - // Floats implement the `Add`, `Mul` and `Sub` traits - let v1 = Vec2 { x: 1.2_f32, y: 3.4 }; - let v2 = Vec2 { x: 5.6_f32, y: 7.8 }; - - println!("{} + {} = {}", v1, v2, v1 + v2); - println!("{} - {} = {}", v1, v2, v1 - v2); - println!("{} . {} = {}", v1, v2, v1.dot(&v2)); - - // Error! `char` doesn't implement the `Add` trait - println!("{}", Vec2 { x: ' ', y: 'b' } + Vec2 { x: 'c', y: 'd' }); - // FIXME ^ Comment out this line -} diff --git a/examples/bounds/input.md b/examples/bounds/input.md deleted file mode 100644 index 0caf2845d9..0000000000 --- a/examples/bounds/input.md +++ /dev/null @@ -1,10 +0,0 @@ -When working with generics, the type parameters (e.g. `Ty`) may use traits -(e.g. `Tr`) as *bounds* (e.g. `Ty: Tr`, which reads as: `Ty` must implement the -`Tr` trait). Bounding has two effects: - -* Generics instances (`let ty: Ty = (...)`) can now access the methods - (`ty.tr()`) of the traits specified in the bounds. -* The generic can only be specialized for type parameters that conform to the - bounds. - -{bounds.play} diff --git a/examples/box/box.rs b/examples/box/box.rs deleted file mode 100644 index 0f6111a042..0000000000 --- a/examples/box/box.rs +++ /dev/null @@ -1,68 +0,0 @@ -use std::mem; - -#[allow(dead_code)] -#[deriving(Copy)] -struct Point { - x: f64, - y: f64, -} - -#[allow(dead_code)] -struct Rectangle { - p1: Point, - p2: Point, -} - -fn origin() -> Point { - Point { x: 0.0, y: 0.0 } -} - -fn boxed_origin() -> Box { - // Allocate this point in the heap, and return a pointer to it - box Point { x: 0.0, y: 0.0 } -} - -fn main() { - // (all the type annotations are superfluous) - // Stack allocated variables - let point: Point = origin(); - let rectangle: Rectangle = Rectangle { - p1: origin(), - p2: Point { x: 3.0, y: 4.0 } - }; - - // Heap allocated rectangle - let boxed_rectangle: Box = box Rectangle { - p1: origin(), - p2: origin() - }; - - // The output of functions can be boxed - let boxed_point: Box = box origin(); - - // Double indirection - let box_in_a_box: Box> = box boxed_origin(); - - println!("Point occupies {} bytes in the stack", - mem::size_of_val(&point)); - println!("Rectangle occupies {} bytes in the stack", - mem::size_of_val(&rectangle)); - - // box size = pointer size - println!("Boxed point occupies {} bytes in the stack", - mem::size_of_val(&boxed_point)); - println!("Boxed rectangle occupies {} bytes in the stack", - mem::size_of_val(&boxed_rectangle)); - println!("Boxed box occupies {} bytes in the stack", - mem::size_of_val(&box_in_a_box)); - - // Copy the data contained in `boxed_point` into `unboxed_point` - let unboxed_point: Point = *boxed_point; - println!("Unboxed point occupies {} bytes in the stack", - mem::size_of_val(&unboxed_point)); - - // Unboxing via a destructuring pattern - let box another_unboxed_point = boxed_point; - println!("Another unboxed point occupies {} bytes in the stack", - mem::size_of_val(&another_unboxed_point)); -} diff --git a/examples/box/input.md b/examples/box/input.md deleted file mode 100644 index ae4cb9bbb5..0000000000 --- a/examples/box/input.md +++ /dev/null @@ -1,11 +0,0 @@ -All values in Rust are stack allocated by default. Values can be *boxed* -(allocated in the heap) using the `box` construct. A box, with type signature -`Box`, is a smart pointer to a heap allocated value of type `T`. When a box -goes out of scope, its destructor is called, the inner object is destroyed, and -the memory in the heap is freed. - -Boxed values can be dereferenced using the `*` operator, this removes one layer -of indirection. Alternatively, the `let box x = y` pattern can be used to -"unbox" `y` into `x`. - -{box.play} diff --git a/examples/channels/channels.rs b/examples/channels/channels.rs deleted file mode 100644 index cd9a333dc4..0000000000 --- a/examples/channels/channels.rs +++ /dev/null @@ -1,37 +0,0 @@ -use std::comm; - -static NTASKS: uint = 3; - -fn main() { - // Channels have two endpoints: the `Sender` and the `Receiver`, - // where `T` is the type of the message to be transfer - // (type annotation is superfluous) - let (tx, rx): (Sender, Receiver) = comm::channel(); - - for id in range(0, NTASKS) { - // The sender endpoint can be copied - let task_tx = tx.clone(); - - // Each task will send its id via the channel - spawn(proc() { - // The task takes ownership over `task_tx` - // Each task queues a message in the channel - task_tx.send(id); - - // Sending is a non-blocking operation, the task will continue - // immediately after sending its message - println!("task {} finished", id); - }); - } - - // Here, all the messages are collected - let mut ids = Vec::with_capacity(NTASKS); - for _ in range(0, NTASKS) { - // The `recv` method picks a message from the channel - // `recv` will block the current task if there no messages available - ids.push(rx.recv()); - } - - // Show the order in which the messages were sent - println!("{}", ids); -} diff --git a/examples/channels/input.md b/examples/channels/input.md deleted file mode 100644 index 7e5186a247..0000000000 --- a/examples/channels/input.md +++ /dev/null @@ -1,5 +0,0 @@ -Rust provides asynchronous `channels` for communication between tasks. Channels -allow an unidirectional flow of information between two end-points: the -`Sender` and the `Receiver`. - -{channels.play} diff --git a/examples/clone/clone.rs b/examples/clone/clone.rs deleted file mode 100644 index f5ffba8f3a..0000000000 --- a/examples/clone/clone.rs +++ /dev/null @@ -1,43 +0,0 @@ -// A unit struct without resources -#[deriving(Show, Copy)] -struct Nil; - -// A tuple struct with resources that implements the `Clone` trait -#[deriving(Clone,Show)] -struct Pair(Box, Box); - -fn main() { - // Instantiate `Nil` - let nil = Nil; - // Copy `Nil`, there are no resources to move - let copied_nil = nil; - - // Both `Nil`s can be used independently - println!("original: {}", nil); - println!("copy: {}", copied_nil); - - // Instantiate a `Pair` - let pair = Pair(box 1, box 2); - println!("original: {}", pair); - - // Copy `pair` into `moved_pair`, moves resources - let moved_pair = pair; - println!("copy: {}", moved_pair); - - // Error! `pair` has lost it resources - //println!("original: {}", pair); - // TODO ^ Try uncommenting this line - - // "Clone" `moved_pair` into `cloned_pair` (resources included) - let cloned_pair = moved_pair.clone(); - - // `Drop` the original pair - drop(moved_pair); - - // Error! `moved_pair` has been `drop`ed - //println!("copy: {}", moved_pair); - // TODO ^ Try uncommenting this line - - // Clone can still be used - println!("clone: {}", cloned_pair); -} diff --git a/examples/clone/input.md b/examples/clone/input.md deleted file mode 100644 index 7372ce8b56..0000000000 --- a/examples/clone/input.md +++ /dev/null @@ -1,6 +0,0 @@ -When dealing with resources, the default behavior is to transfer them during -assignments or function calls. Sometimes the intention is to make a copy of the -resource, this can be accomplished by calling the `clone` method, defined in -the `Clone` trait. - -{clone.play} diff --git a/examples/closures/closures.rs b/examples/closures/closures.rs deleted file mode 100644 index 31c1b4758d..0000000000 --- a/examples/closures/closures.rs +++ /dev/null @@ -1,12 +0,0 @@ -fn main() { - let captured_value = 7u; - - let closure = |argument| { - println!("I captured this: {}", captured_value); - println!("Argument passed was: {}", argument); - - true - }; - - println!("Closure returned: {}", closure("a string")); -} diff --git a/examples/closures/input.md b/examples/closures/input.md deleted file mode 100644 index 835b824600..0000000000 --- a/examples/closures/input.md +++ /dev/null @@ -1,10 +0,0 @@ -Closures are special functions that can capture the variables available in the -surrounding scope. Closures consist of three parts: - -* A list of arguments enclosed by pipes `|`, these arguments can optionally be - type annotated, but usually the compiler will infer their types -* Optionally the return type using an arrow `->`, again this usually gets - inferred -* A block, the last expression is the return value - -{closures.play} diff --git a/examples/constants/constants.rs b/examples/constants/constants.rs deleted file mode 100644 index 6db121c1dd..0000000000 --- a/examples/constants/constants.rs +++ /dev/null @@ -1,28 +0,0 @@ -static LANGUAGE: &'static str = "Rust"; -static THRESHOLD: int = 10; - -fn is_big(n: int) -> bool { - // Access constant in some function - n > THRESHOLD -} - -fn main() { - let n = 16; - - // Access constant in the main task - println!("This is {}", LANGUAGE); - println!("The threshold is {}", THRESHOLD); - println!("{} is {}", n, if is_big(n) { "big" } else { "small" }); - - // Error! Cannot modify a static item - THRESHOLD = 5; - // FIXME ^ Comment out this line - - { - // String literals are references to read-only memory - let _static_string: &'static str = "In read-only memory"; - - // When `_static_string` goes out of scope, we can no longer refer to - // the underlying data, but the string remains in the read-only memory - } -} diff --git a/examples/constants/input.md b/examples/constants/input.md deleted file mode 100644 index d3f8eed72a..0000000000 --- a/examples/constants/input.md +++ /dev/null @@ -1,12 +0,0 @@ -Constants can be declared in the global scope using the `static` keyword, the -type annotation is obligatory in this case. These constants are placed in a -read-only section of the memory and can be accessed in any other part of the -program. - -String literals like `"string"` can also be assigned to static variables. These -variables have type signature `&'static str`, and are references to strings -allocated in read-only memory. `'static` is a special lifetime that outlives -all the other lifetimes, and indicates that the referenced data is available in -all the scopes. - -{constants.play} diff --git a/examples/crates/lib/erty.rs b/examples/crates/lib/erty.rs deleted file mode 100644 index 6104f64ea3..0000000000 --- a/examples/crates/lib/erty.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub fn public_function() { - println!("called erty's `public_function()`"); -} - -fn private_function() { - println!("called erty's `private_function()`"); -} - -pub fn indirect_access() { - print!("called erty's `indirect_access()`, that\n> "); - - private_function(); -} diff --git a/examples/crates/lib/input.md b/examples/crates/lib/input.md deleted file mode 100644 index 33b7114df5..0000000000 --- a/examples/crates/lib/input.md +++ /dev/null @@ -1,15 +0,0 @@ -Let's create a library, and then see how to link it to another crate. - -{erty.rs} - -``` -$ rustc --crate-type=lib erty.rs -$ ls lib* -liberty.rlib -``` - -Libraries get prefixed with "lib", and by default they get named after their -crate file, but this default name can be overridden using the -[`crate_name` attribute][crate-name]. - -[crate-name]: /attribute/crate.html diff --git a/examples/crates/link/executable.rs b/examples/crates/link/executable.rs deleted file mode 100644 index 42c83c39f5..0000000000 --- a/examples/crates/link/executable.rs +++ /dev/null @@ -1,11 +0,0 @@ -// Link to `liberty`, import items under the `erty` module -extern crate erty; - -fn main() { - erty::public_function(); - - // Error! `private_function` is private - //erty::private_function(); - - erty::indirect_access(); -} diff --git a/examples/crates/link/input.md b/examples/crates/link/input.md deleted file mode 100644 index 043852b79e..0000000000 --- a/examples/crates/link/input.md +++ /dev/null @@ -1,14 +0,0 @@ -To link a crate to this new library, the `extern crate` declaration must be -used. This will not only link the library, but also import all its items -under a module named the same as the library. The visibility rules that apply -to modules also apply to libraries. - -{executable.rs} - -``` -# The `-L .` argument adds the current directory to the library search path -$ rustc -L . executable.rs && ./executable -called erty's `public_function()` -called erty's `indirect_access()`, that -> called erty's `private_function()` -``` diff --git a/examples/drop/input.md b/examples/drop/input.md deleted file mode 100644 index 2e7b4c28d3..0000000000 --- a/examples/drop/input.md +++ /dev/null @@ -1,9 +0,0 @@ -The `Drop` trait only has one method: `drop`, and this method is called when -an object goes out of scope. The main use of the `Drop` trait is to free the -resources that the implementor instance owns. - -`Box`, `Vec`, `String`, `File` and `Process` are some examples of types that -implement the `Drop` trait to free resources. The `Drop` trait can be -implemented for any custom data type. - -{drop.play} diff --git a/examples/enum/c-like/c-like.rs b/examples/enum/c-like/c-like.rs deleted file mode 100644 index cff6396cf9..0000000000 --- a/examples/enum/c-like/c-like.rs +++ /dev/null @@ -1,53 +0,0 @@ -// If you'd like to refer to the days without saying -// `Day::Monday`, then you use the following notation -// use Day::{ -// Monday, -// Tuesday, -// Wednesday, -// Thursday, -// Friday, -// Saturday, -// Sunday, -// } -// -// And you can refer to enum variants just like in C - -// enum with implicit discriminator (starts at 0) -#[allow(dead_code)] -enum Day { - Monday, - Tuesday, - Wednesday, - Thursday, - Friday, - Saturday, - Sunday, -} - -impl Day { - fn mood(&self) { - println!("{}", match *self { - Day::Friday => "it's friday!", - Day::Saturday | Day::Sunday => "weekend :-)", - _ => "weekday...", - }) - } -} - -// enum with explicit discriminator -#[allow(dead_code)] -enum Color { - Red = 0xff0000, - Green = 0x00ff00, - Blue = 0x0000ff, -} - -fn main() { - let today = Day::Monday; - - today.mood(); - - // enums can be casted into integers - println!("roses are #{:06x}", Color::Red as int); - println!("violets are #{:06x}", Color::Blue as int); -} diff --git a/examples/enum/c-like/input.md b/examples/enum/c-like/input.md deleted file mode 100644 index be1e0cad2b..0000000000 --- a/examples/enum/c-like/input.md +++ /dev/null @@ -1,3 +0,0 @@ -`enum` can also be used as C-like enums. - -{c-like.play} diff --git a/examples/enum/input.md b/examples/enum/input.md deleted file mode 100644 index 4b5b001b83..0000000000 --- a/examples/enum/input.md +++ /dev/null @@ -1,9 +0,0 @@ -The `enum` keyword allows the creation of -[tagged unions][tag-union], which can be used -as algebraic data types -([ADT][adt]). - -{enum.play} - -[adt]: http://en.wikipedia.org/wiki/Algebraic_data_type -[tag-union]: http://en.wikipedia.org/wiki/Tagged_union diff --git a/examples/expression/expression.rs b/examples/expression/expression.rs deleted file mode 100644 index e06489ad27..0000000000 --- a/examples/expression/expression.rs +++ /dev/null @@ -1,20 +0,0 @@ -fn main() { - let x = 5u; - - let y = { - let x_squared = x * x; - let x_cube = x_squared * x; - - // This expression will be assigned to `y` - x_cube + x_squared + x - }; - - let z = { - // The semicolon suppresses this expression and `()` is assigned to `z` - 2 * x; - }; - - println!("x is {}", x); - println!("y is {}", y); - println!("z is {}", z); -} diff --git a/examples/expression/input.md b/examples/expression/input.md deleted file mode 100644 index ca8971f997..0000000000 --- a/examples/expression/input.md +++ /dev/null @@ -1,15 +0,0 @@ -In Rust, almost every statement is an expression, this means that the statement -returns a value. This may not always be desired, so the output can be -suppressed by ending the expression with a semicolon `;`. - -Blocks are expressions too, so they can be used as -[r-values][rvalue] -in assignments. The last expression in the block will be assigned to the -[l-value][lvalue]. -But, if the last expression of the block ends with a semicolon, the return -value will be `()`. - -{expression.play} - -[rvalue]: https://en.wikipedia.org/wiki/Value_%28computer_science%29#lrvalue -[lvalue]: https://en.wikipedia.org/wiki/Value_%28computer_science%29#lrvalue diff --git a/examples/file/create/create.rs b/examples/file/create/create.rs deleted file mode 100644 index 09d2d1088e..0000000000 --- a/examples/file/create/create.rs +++ /dev/null @@ -1,29 +0,0 @@ -use std::io::File; - -static LOREM_IPSUM: &'static str = -"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod -tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, -quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo -consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse -cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non -proident, sunt in culpa qui officia deserunt mollit anim id est laborum. -"; - -fn main() { - let path = Path::new("out/lorem_ipsum.txt"); - let display = path.display(); - - // Open a file in write-only mode, returns `IoResult` - let mut file = match File::create(&path) { - Err(why) => panic!("couldn't create {}: {}", display, why.desc), - Ok(file) => file, - }; - - // Write the `LOREM_IPSUM` string to `file`, returns `IoResult<()>` - match file.write_str(LOREM_IPSUM) { - Err(why) => { - panic!("couldn't write to {}: {}", display, why.desc) - }, - Ok(_) => println!("successfully wrote to {}", display), - } -} diff --git a/examples/file/create/input.md b/examples/file/create/input.md deleted file mode 100644 index 0452492503..0000000000 --- a/examples/file/create/input.md +++ /dev/null @@ -1,29 +0,0 @@ -The `create` static method opens a file in write-only mode. If the file already -existed, the old content is destroyed, otherwise a new file is created. - -{create.play} - -As in the previous example, the playpen won't allow file I/O, so you'll hit one -of the failure paths. Here's the expected successful output: - -``` -$ mkdir out -$ rustc create.rs && ./create -successfully wrote to out/lorem_ipsum.txt -$ cat out/lorem_ipsum.txt -Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod -tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, -quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo -consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse -cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non -proident, sunt in culpa qui officia deserunt mollit anim id est laborum. -``` - -(As in the previous example, you are encouraged to test this example under -failure conditions) - -There is also a more generic -[`open_mode`][open-mode] -method that can open files in other modes like: read+write, append, etc. - -[open-mode]: http://doc.rust-lang.org/std/io/fs/struct.File.html#method.open_mode diff --git a/examples/file/input.md b/examples/file/input.md deleted file mode 100644 index 5f2166bcf4..0000000000 --- a/examples/file/input.md +++ /dev/null @@ -1,9 +0,0 @@ -The `File` struct represents a file that has been opened (it wraps a file -descriptor), and gives read and/or write access to the underlying file. - -Since many things can go wrong when doing file I/O, all the `File` methods -return the `IoResult` type, which is an alias for `Result`. - -This makes the failure of all I/O operations *explicit*, thanks to -this the programmer can see all the failure paths, and is encouraged to handle -them in a proactive manner. diff --git a/examples/file/open/input.md b/examples/file/open/input.md deleted file mode 100644 index 8200b3a5bc..0000000000 --- a/examples/file/open/input.md +++ /dev/null @@ -1,20 +0,0 @@ -The `open` static method can be used to open a file in read-only mode. - -A `File` owns a resource, the file descriptor, and take cares of closing the -file when its `drop`ed. - -{open.play} - -The playpen doesn't allow file I/O, so you'll hit one of the failure paths. -Here's the expected successful output: - -``` -$ echo "Hello World!" > hello.txt -$ rustc open.rs && ./open -hello.txt contains: -Hello World! -``` - -(You are encouraged to test the previous example under different failure -conditions: `hello.txt` doesn't exist, or `hello.txt` is not readable, -etc.) diff --git a/examples/file/open/open.rs b/examples/file/open/open.rs deleted file mode 100644 index f857e74c82..0000000000 --- a/examples/file/open/open.rs +++ /dev/null @@ -1,22 +0,0 @@ -use std::io::File; - -fn main() { - // Create a path to the desired file - let path = Path::new("hello.txt"); - let display = path.display(); - - // Open the path in read-only mode, returns `IoResult` - let mut file = match File::open(&path) { - // The `desc` field of `IoError` is a string that describes the error - Err(why) => panic!("couldn't open {}: {}", display, why.desc), - Ok(file) => file, - }; - - // Read the file contents into a string, returns `IoResult` - match file.read_to_string() { - Err(why) => panic!("couldn't read {}: {}", display, why.desc), - Ok(string) => print!("{} contains:\n{}", display, string), - } - - // `file` goes out of scope, and the "hello.txt" file gets closed -} diff --git a/examples/fn/input.md b/examples/fn/input.md deleted file mode 100644 index b2de5ac5a2..0000000000 --- a/examples/fn/input.md +++ /dev/null @@ -1,11 +0,0 @@ -Functions are declared using the `fn` keyword. Its arguments are type -annotated, just like variables; and, if the function returns a value, the -return type must be specified after an arrow `->`. - -The final expression in the function will be used as return value. -Alternatively, the `return` statement can be used to return a value earlier -from within the function, even from inside loops or ifs. - -Let's rewrite fizzbuzz using functions! - -{fn.play} diff --git a/examples/fn/unused/unused.rs b/examples/fn/unused/unused.rs deleted file mode 100644 index bae5665576..0000000000 --- a/examples/fn/unused/unused.rs +++ /dev/null @@ -1,12 +0,0 @@ -fn used_function() {} - -// `#[allow(dead_code)]` is an attribute that disables the `dead_code` lint -#[allow(dead_code)] -fn unused_function() {} - -fn noisy_unused_function() {} -// FIXME ^ Add an attribute to suppress the warning - -fn main() { - used_function(); -} diff --git a/examples/for/for.rs b/examples/for/for.rs deleted file mode 100644 index 8aa29024a3..0000000000 --- a/examples/for/for.rs +++ /dev/null @@ -1,14 +0,0 @@ -fn main() { - // `n` will take the values: 1, 2, ..., 100 in each iteration - for n in range(1u, 101) { - if n % 15 == 0 { - println!("fizzbuzz"); - } else if n % 3 == 0 { - println!("fizz"); - } else if n % 5 == 0 { - println!("buzz"); - } else { - println!("{}", n); - } - } -} diff --git a/examples/for/input.md b/examples/for/input.md deleted file mode 100644 index 13662c44c0..0000000000 --- a/examples/for/input.md +++ /dev/null @@ -1,8 +0,0 @@ -The `for in` construct can be used to iterate an `Iterator`, a lazy value -generator (more details later). One of the most common iterators is the `range` -function. `range(a, b)` will yield values from `a` (inclusive) to `b` -(exclusive) in steps of one. - -Let's write fizzbuzz using `for` instead of `while`. - -{for.play} diff --git a/examples/fs/fs.rs b/examples/fs/fs.rs deleted file mode 100644 index 9dd7bbb849..0000000000 --- a/examples/fs/fs.rs +++ /dev/null @@ -1,92 +0,0 @@ -use std::io::fs; -use std::io::fs::PathExtensions; -use std::io::{File, IoResult, USER_RWX}; - -// A simple implementation of `$ cat path` -fn cat(path: &Path) -> IoResult { - File::open(path).and_then(|mut f| f.read_to_string()) -} - -// A simple implementation of `$ echo s > path` -fn echo(s: &str, path: &Path) -> IoResult<()> { - File::create(path).and_then(|mut f| f.write_str(s)) -} - -// A simple implementation of `$ touch path` (ignores existing files) -fn touch(path: &Path) -> IoResult<()> { - if !path.exists() { - File::create(path).and_then(|_| Ok(())) - } else { - Ok(()) - } -} - -fn main() { - println!("`mkdir a`"); - // Create a directory, returns `IoResult<()>` - match fs::mkdir(&Path::new("a"), USER_RWX) { - Err(why) => println!("! {}", why.kind), - Ok(_) => {}, - } - - println!("`echo hello > a/b.txt`"); - // The previous match can be simplified using the `unwrap_or_else` method - echo("hello", &Path::new("a/b.txt")).unwrap_or_else(|why| { - println!("! {}", why.kind); - }); - - println!("`mkdir -p a/c/d`"); - // Recursively create a directory, returns `IoResult<()>` - fs::mkdir_recursive(&Path::new("a/c/d"), USER_RWX).unwrap_or_else(|why| { - println!("! {}", why.kind); - }); - - println!("`touch a/c/e.txt`"); - touch(&Path::new("a/c/e.txt")).unwrap_or_else(|why| { - println!("! {}", why.kind); - }); - - println!("`ln -s ../b.txt a/c/b.txt`"); - // Create a symbolic link, returns `IoResult<()>` - fs::symlink(&Path::new("../b.txt"), - &Path::new("a/c/b.txt")).unwrap_or_else(|why| { - println!("! {}", why.kind); - }); - - println!("`cat a/c/b.txt`"); - match cat(&Path::new("a/c/b.txt")) { - Err(why) => println!("! {}", why.kind), - Ok(s) => println!("> {}", s), - } - - println!("`ls a`"); - // Read the contents of a directory, returns `IoResult>` - match fs::readdir(&Path::new("a")) { - Err(why) => println!("! {}", why.kind), - Ok(paths) => for path in paths.iter() { - println!("> {}", path.display()); - }, - } - - println!("`walk a`"); - // Recursively walk over the contents of a directory, returns - // `Directories`, which implements the `Iterator trait - match fs::walk_dir(&Path::new("a")) { - Err(why) => println!("! {}", why.kind), - Ok(mut paths) => for path in paths { - println!("> {}", path.display()); - }, - } - - println!("`rm a/c/e.txt`"); - // Remove a file, returns `IoResult<()>` - fs::unlink(&Path::new("a/c/e.txt")).unwrap_or_else(|why| { - println!("! {}", why.kind); - }); - - println!("`rmdir a/c/d`"); - // Remove an empty directory, returns `IoResult<()>` - fs::rmdir(&Path::new("a/c/d")).unwrap_or_else(|why| { - println!("! {}", why.kind); - }); -} diff --git a/examples/fs/input.md b/examples/fs/input.md deleted file mode 100644 index 6ca8ff49a4..0000000000 --- a/examples/fs/input.md +++ /dev/null @@ -1,43 +0,0 @@ -The [`std::io::fs`][std-fs] -module contains several functions that deal with the filesystem. - -{fs.play} - -You won't be able to run the previous code, because the playpen doesn't allow -file operations. Here's the expected successful output: - -``` -$ rustc fs.rs && ./fs -`mkdir a` -`echo hello > a/b.txt` -`mkdir -p a/c/d` -`touch a/c/e.txt` -`ln -s ../b.txt a/c/b.txt` -`cat a/c/b.txt` -> hello -`ls a` -> a/b.txt -> a/c -`walk a` -> a/c -> a/c/b.txt -> a/c/e.txt -> a/c/d -> a/b.txt -`rm a/c/e.txt` -`rmdir a/c/d` -``` - -And the final state of the `a` directory is: - -``` -$ tree a -a -|-- b.txt -`-- c - `-- b.txt -> ../b.txt - -1 directory, 2 files -``` - -[std-fs]: http://doc.rust-lang.org/std/io/fs/ diff --git a/examples/generics/generics.rs b/examples/generics/generics.rs deleted file mode 100644 index 796f881bb0..0000000000 --- a/examples/generics/generics.rs +++ /dev/null @@ -1,33 +0,0 @@ -// A generic struct -struct Pair { - first: T, - second: T, -} - -// A generic function -fn swap(pair: Pair) -> Pair { - let Pair { first, second } = pair; - - Pair { first: second, second: first } -} - -// Reimplementing a 2-element tuple as a tuple struct -struct Tuple2(T, U); - -fn main() { - // Explicitly specialize `Pair` - let pair_of_chars: Pair = Pair { first: 'a', second: 'b' }; - - // Implicitly specialize `Pair` - let pair_of_ints = Pair { first: 1i, second: 2 }; - - // Explicitly specialize `Tuple2` - let _tuple: Tuple2 = Tuple2('R', 2); - - // Explicitly specialize `swap` - let _swapped_pair_of_chars = swap::(pair_of_chars); - - // Implicitly specialize `swap` - let _swapped_pair_of_ints = swap(pair_of_ints); -} - diff --git a/examples/generics/impl/impl.rs b/examples/generics/impl/impl.rs deleted file mode 100644 index 61a4aed01f..0000000000 --- a/examples/generics/impl/impl.rs +++ /dev/null @@ -1,28 +0,0 @@ -struct Tup (f64,); -struct GenTup(T,); - -// impl of Tup -impl Tup { - fn value(&self) -> &f64 { - let &Tup ( ref val ) = self; - - val - } -} - -// impl of GenTup for a generic type `T` -impl GenTup { - fn value(&self) -> &T { - let &GenTup (ref val) = self; - - val - } -} - -fn main() { - let x = Tup(3.0); - let y = GenTup(3i32); - - println!("{}, {}", x.value(), y.value()); -} - diff --git a/examples/generics/impl/input.md b/examples/generics/impl/input.md deleted file mode 100644 index 5147a56408..0000000000 --- a/examples/generics/impl/input.md +++ /dev/null @@ -1,22 +0,0 @@ -Implementations can also be made generic. Generally `impl` is followed by -the type `` although it is not a strict requirement. - -```rust -struct T; // A null struct -struct GenericTup(T,); - -// impl of GenericTup we specifically specialize: -impl GenericTup {} // Specialize to `f32` -impl GenericTup {} // Specialize to `T` defined above - -// `` Must precede the type to remain generic -impl GenericTup {} -``` - -{impl.play} - -###See also: -[impl](http://rustbyexample.com/methods.html), -[struct](http://rustbyexample.com/structs.html), and -[functions returning references](http://rustbyexample.com/lifetime/fn.html), - diff --git a/examples/generics/input.md b/examples/generics/input.md deleted file mode 100644 index 6d713d6f1a..0000000000 --- a/examples/generics/input.md +++ /dev/null @@ -1,9 +0,0 @@ -Generic structs can be declared to hold generic types, and generic functions -can be declared to take generic types as arguments. - -Generics must be specialized when used; but, because of type inference, -annotation is usually not required. When that's not the case, structs can be -specialized via type annotation, and functions can be specialized passing the -generic arguments using this syntax `::`. - -{generics.play} diff --git a/examples/generics/phantom/input.md b/examples/generics/phantom/input.md deleted file mode 100644 index 6646fcdd09..0000000000 --- a/examples/generics/phantom/input.md +++ /dev/null @@ -1,11 +0,0 @@ -A Phantom type is a data type which contains extra hidden -generic parameters. These extra parameters hold no storage values. -They are checked statically at compile time and only -at compile time; they have no run-time behavior. - -{phantom.play} - -###See also: -[Deriving](http://rustbyexample.com/trait/deriving.html), -[struct](http://rustbyexample.com/structs.html), and -[TupleStructs](http://rustbyexample.com/structs.html) diff --git a/examples/generics/phantom/phantom.rs b/examples/generics/phantom/phantom.rs deleted file mode 100644 index 03b134ceda..0000000000 --- a/examples/generics/phantom/phantom.rs +++ /dev/null @@ -1,39 +0,0 @@ -// Generic tuplestruct with same types in both -// generic and definition (A,) -struct Tuple(A,); - -// This tuple is a phantom type. B is a hidden -// parameter. Storage is allocated for generic type A -// yet not for B. Therefore, B cannot be used in computations. -#[deriving(PartialEq)] // Allow equality test for this type -struct PhantomTuple(A,); - -// Similarly, a phantom type struct which is generic over A -// with hidden parameter B -#[deriving(PartialEq)] // Allow equality test for this type -struct PhantomStruct { first: A } - -fn main() { - // instantiate Tuple - let _tuple: Tuple = Tuple('R'); - - // We can create similar types without carrying around extra info - // PhantomTuple specialized to - let _tuple1: PhantomTuple = PhantomTuple('Q'); - // PhantomTuple specialized to - let _tuple2: PhantomTuple = PhantomTuple('Q'); - - // Error: type mismatch so these cannot be compared - //println!("_tuple1 == _tuple2 yields: {}", - // _tuple1 == _tuple2); - - // Specialized to - let _struct1: PhantomStruct = PhantomStruct { first: 'Q'}; - // Specialized to - let _struct2: PhantomStruct = PhantomStruct { first: 'Q'}; - - // Error: type mismatch so these cannot be compared - //println!("_struct1 == _struct2 yields: {}", - // _struct2 == _struct2); -} - diff --git a/examples/generics/phantom/units/input.md b/examples/generics/phantom/units/input.md deleted file mode 100644 index f445d51557..0000000000 --- a/examples/generics/phantom/units/input.md +++ /dev/null @@ -1,14 +0,0 @@ -A useful method of unit conversions: - -{units.play} - -###See also: -[Borrowing (`&`)](http://rustbyexample.com/borrow.html), -[Bounds (`X: Y`)](http://rustbyexample.com/bounds.html), -[enum](http://rustbyexample.com/enum.html), -[impl & self](http://rustbyexample.com/methods.html), -[Overloading](http://rustbyexample.com/ops.html), -[ref](http://rustbyexample.com/borrow/ref.html), -[Traits (`X for Y`)](http://rustbyexample.com/trait.html), and -[TupleStructs](http://rustbyexample.com/structs.html). - diff --git a/examples/generics/phantom/units/units.rs b/examples/generics/phantom/units/units.rs deleted file mode 100644 index 134f45ea28..0000000000 --- a/examples/generics/phantom/units/units.rs +++ /dev/null @@ -1,44 +0,0 @@ -// Null enumerations to define unit types -#[deriving(Show)] -enum Inch {} -#[deriving(Show)] -enum Mm {} - -// Length is phantom type with hidden parameter `Unit` -#[deriving(Show)] -struct Length(T,); - -// `impl X for Y {}` reads "implement `X` Trait for Type `Y`" -// So, this implements the `Add` Trait for Type `Length` -// The `Add` Trait overloads the addition operator -// so elements can be added together. -// `X: Y` applies a restriction to `X` and only allows operations -// to `X` if `X` implements the Trait `Y`. -// This means that this `impl` defines `Add` only for `T` when -// two `T's` can be added together and the result is of -// Type `T`: (`T: Add`) -impl > Add, - Length> for Length { - fn add(&self, r: &Length) -> Length { - let &Length(ref left) = self; - let &Length(ref right) = r; - - Length(*left + *right) - } -} - -fn main() { - // Specialize one_foot to have hidden parameter `Inch` - let one_foot: Length = Length(12.0); - // one_meter has hidden parameter `Mm` - let one_meter: Length = Length(1000.0); - - // Addition works - println!("one foot + one_foot = {}", one_foot + one_foot); - println!("one meter + one_meter = {}", one_meter + one_meter); - - // Nonsensical operations fail as they should - // Error: type mismatch - //let one_feter = one_foot + one_meter; -} - diff --git a/examples/hello/hello.rs b/examples/hello/hello.rs deleted file mode 100644 index 35763efe3f..0000000000 --- a/examples/hello/hello.rs +++ /dev/null @@ -1,14 +0,0 @@ -// This is a comment, and will be ignored by the compiler -// You can test this code by clicking the "Run" button over there -> -// or if prefer to use your keyboard, you can use the "Ctrl + Enter" shortcut - -// This code is editable, feel free to hack it! -// You can always return to the original code by clicking the "Reset" button -> - -// This is the main function -fn main() { - // The statements here will be executed when the compiled binary is called - - // Print text to the console - println!("Hello World!"); -} diff --git a/examples/hello/input.md b/examples/hello/input.md deleted file mode 100644 index 926ea7c897..0000000000 --- a/examples/hello/input.md +++ /dev/null @@ -1,19 +0,0 @@ -This is the source code of the traditional Hello World program. - -{hello.play} - -`println!` is a *macro* (we'll cover them later) that prints text to the -console. - -A binary can be generated using the rust compiler: `rustc`. - -``` -$ rustc hello.rs -``` - -`rustc` will produce a `hello` binary that can be executed. - -``` -$ ./hello -Hello World! -``` diff --git a/examples/hof/hof.rs b/examples/hof/hof.rs deleted file mode 100644 index 5ea39e6523..0000000000 --- a/examples/hof/hof.rs +++ /dev/null @@ -1,44 +0,0 @@ -// The `AdditiveIterator` trait adds the `sum` method to iterators -use std::iter::AdditiveIterator; -use std::iter; - -fn main() { - println!("Find the sum of all the squared odd numbers under 1000"); - let upper = 1000u; - - // Imperative approach - // Declare accumulator variable - let mut acc = 0; - // Iterate: 0, 1, 2, ... to infinity - for n in iter::count(0u, 1) { - // Square the number - let n_squared = n * n; - - if n_squared >= upper { - // Break loop if exceeded the upper limit - break; - } else if is_odd(n_squared) { - // Accumulate value, if it's odd - acc += n_squared; - } - } - println!("imperative style: {}", acc); - - // Functional approach - let sum_of_squared_odd_numbers = - // All natural numbers - iter::count(0u, 1). - // Squared - map(|n| n * n). - // Below upper limit - take_while(|&n| n < upper). - // That are odd - filter(|n| is_odd(*n)). - // Sum them - sum(); - println!("functional style: {}", sum_of_squared_odd_numbers); -} - -fn is_odd(n: uint) -> bool { - n % 2 == 1 -} diff --git a/examples/hof/input.md b/examples/hof/input.md deleted file mode 100644 index 02784bbe0e..0000000000 --- a/examples/hof/input.md +++ /dev/null @@ -1,13 +0,0 @@ -Rust provides Higher Order Functions (HOF), these are functions that take a -closure as argument to produce a more useful function. HOFs and lazy iterators -give Rust its functional flavor. - -{hof.play} - -[Option][option] -and -[Iterator][iter] -implement their fair share of HOFs. - -[option]: http://doc.rust-lang.org/core/option/type.Option.html -[iter]: http://doc.rust-lang.org/core/iter/trait.Iterator.html diff --git a/examples/if-else/if-else.rs b/examples/if-else/if-else.rs deleted file mode 100644 index 2982fefd10..0000000000 --- a/examples/if-else/if-else.rs +++ /dev/null @@ -1,28 +0,0 @@ -fn main() { - let n = 5i; - - if n < 0 { - print!("{} is negative", n); - } else if n > 0 { - print!("{} is positive", n); - } else { - print!("{} is zero", n); - } - - let big_n = - if n < 10 && n > -10 { - println!(", and is a small number, increase ten-fold"); - - // This expression returns an `int` - 10 * n - } else { - println!(", and is a big number, reduce by two"); - - // This expression must return an `int` as well - n / 2 - // TODO ^ Try suppressing this expression with a semicolon - }; - // ^ Don't forget to put a semicolon here! All the `let` bindings need it - - println!("{} -> {}", n, big_n); -} diff --git a/examples/if-else/input.md b/examples/if-else/input.md deleted file mode 100644 index 755ab1eb9f..0000000000 --- a/examples/if-else/input.md +++ /dev/null @@ -1,6 +0,0 @@ -Branching with if-else is similar to C. Unlike C, the boolean condition doesn't -need to be surrounded by parentheses, and each condition is followed by a -block. If-else conditionals are expressions too; and, because of Rust type -safety, all the branches must return the same type. - -{if-else.play} diff --git a/examples/iter/input.md b/examples/iter/input.md deleted file mode 100644 index cf9b3aa1ae..0000000000 --- a/examples/iter/input.md +++ /dev/null @@ -1,9 +0,0 @@ -The `Iterator` trait is used to implement iterators over collections (like -arrays) and lazy value generators. - -{iter.play} - -The `Iterator` trait gives access to -[several methods][iter]. - -[iter]: http://doc.rust-lang.org/core/iter/trait.Iterator.html diff --git a/examples/iter/iter.rs b/examples/iter/iter.rs deleted file mode 100644 index 8c8dbeff71..0000000000 --- a/examples/iter/iter.rs +++ /dev/null @@ -1,65 +0,0 @@ -use std::mem; - -struct Fibonacci { - curr: uint, - next: uint, -} - -// Implement 'Iterator' for 'Fibonacci' -impl Iterator for Fibonacci { - // The 'Iterator' trait only requires the 'next' method to be defined. The - // return type is 'Option', 'None' is returned when the 'Iterator' is - // over, otherwise the next value is returned wrapped in 'Some' - fn next(&mut self) -> Option { - let new_next = self.curr + self.next; - let new_curr = mem::replace(&mut self.next, new_next); - - // 'Some' is always returned, this is an infinite value generator - Some(mem::replace(&mut self.curr, new_curr)) - } -} - -// Returns a fibonacci sequence generator -fn fibonacci() -> Fibonacci { - Fibonacci { curr: 1, next: 1 } -} - -fn main() { - // Iterator that generates: 0, 1 and 2 - let mut sequence = range(0u, 3); - - println!("Four consecutive `next` calls on range(0, 3)"); - println!("> {}", sequence.next()); - println!("> {}", sequence.next()); - println!("> {}", sequence.next()); - println!("> {}", sequence.next()); - - // The for construct will iterate an 'Iterator' until it returns 'None'. - // Every 'Some' value is unwrapped and bound to a variable. - println!("Iterate over range(0, 3) using for"); - for i in range(0u, 3) { - println!("> {}", i); - } - - // The 'take(n)' method will reduce an iterator to its first 'n' terms, - // which is pretty useful for infinite value generators - println!("The first four terms of the Fibonacci sequence are: "); - for i in fibonacci().take(4) { - println!("> {}", i); - } - - // The 'skip(n)' method will shorten an iterator by dropping its first 'n' - // terms - println!("The next four terms of the Fibonacci sequence are: "); - for i in fibonacci().skip(4).take(4) { - println!("> {}", i); - } - - let array = [1u, 3, 3, 7]; - - // The 'iter' method produces an 'Iterator' over an array/slice - println!("Iterate the following array {}", array.as_slice()); - for i in array.iter() { - println!("> {}", i); - } -} diff --git a/examples/lifetime/borrow/borrow.rs b/examples/lifetime/borrow/borrow.rs deleted file mode 100644 index 3e4d20a225..0000000000 --- a/examples/lifetime/borrow/borrow.rs +++ /dev/null @@ -1,19 +0,0 @@ -// FIXME To see the "real" compiler error, change both `&'b` and `&'e` into `&` - -fn main() { // `'main` starts ────────────────────────────────────────────┐ - let stack_integer: int = 5; // `'a` starts ─────────────────────────┐ │ - let boxed_integer = box 4; // `'b` starts ────────────────────────┐ │ │ - // │ │ │ - // This is a valid operation │ │ │ - let ref_to_box: &'b int = &*boxed_integer; // `'c` starts ──────┐ │ │ │ - // │ │ │ │ - // The compiler forbids this operation, because │ │ │ │ - // `ref_to_another_box` would become a dangling pointer │ │ │ │ - let ref_to_another_box: &'e int = { // `'let` `'d` start ───┬─┐ │ │ │ │ - let another_boxed_integer = box 3; // `'e` starts ────┐ │ │ │ │ │ │ - // │ │ │ │ │ │ │ - &*another_boxed_integer // │ │ │ │ │ │ │ - }; // `'e` `'let` end ────────────────────────────────────┴─┘ │ │ │ │ │ - // │ │ │ │ │ - let invalid_dereference = *ref_to_another_box; // │ │ │ │ │ -} // `'d` `'c` `'b` `'a` `'main` end ─────────────────────────────┴─┴─┴─┴─┘ diff --git a/examples/lifetime/borrow/input.md b/examples/lifetime/borrow/input.md deleted file mode 100644 index a5c196801e..0000000000 --- a/examples/lifetime/borrow/input.md +++ /dev/null @@ -1,53 +0,0 @@ -Let's see how the compiler prevents the creation of dangling pointers via its -borrow checker. To simplify the analysis and explanation, we have two -additions: - -* Lifetimes has been explicitly annotated in the source code. -* We have drawn the lifetime "lines", which span from the creation of an object - to its destruction. The block scopes have also been drawn. - -Note that explicit lifetime annotation on references `&'foo T` is not allowed -by the compiler, so you must remove the lifetime part `'foo` to see the "real" -compiler error. - -{borrow.play} - -The "real" compiler error is: "`another_boxed_integer` does not live long -enough". Let's analyze why this happens: - -* `stack_integer` has lifetime `'a` -* `boxed_integer` has lifetime `'b` -* `ref_to_box` has lifetime `'c` -* `ref_to_another_box` has lifetime `'d` -* `another_boxed_integer` has lifetime `'e` -* `'main` and `'let` are the scopes of the blocks -* When a block scope ends, all the objects declared in it get destroyed - * `'let` ends, and so does `'e` - * `'main` ends, and so does `'a` `'b` `'c` and `'d` -* `ref_to_box` is a valid borrow, because - * `ref_to_box` has lifetime `'c` - * `ref_to_box` points to an object with lifetime `'b` - * `'c` will never *outlive* `'b` (this is expressed as `'c < 'b`) - * therefore `ref_to_box` will always point to valid data -* `ref_to_another_box` is an *invalid* borrow, because - * `ref_to_another_box` has lifetime `'d` - * `ref_to_another_box` points to an object with lifetime `'e` - * `'d` outlives `'e` - * therefore `ref_to_another_box` can become a dangling pointer (it can point - to destroyed data) - * creation of dangling pointers is forbidden, so this borrow is invalid - -The borrow checker will do this job for the programmer behind his/her back, to -prevent him/her from (unintentionally) creating dangling pointers. Although, -the programmer can be saved by the borrow checker without knowing what is a -lifetime. - -The programmer doesn't need to explicitly annotate lifetimes (nor understand -what are lifetimes), for the borrow checker to do its job in most cases. These -are the cases where explicit lifetimes are required: - -* [Functions that return references][lifetime] -* [Structs that hold references][structs] - -[lifetime]: /lifetime/fn.html -[structs]: /lifetime/struct.html diff --git a/examples/lifetime/explicit/explicit.rs b/examples/lifetime/explicit/explicit.rs deleted file mode 100644 index 0057b53cce..0000000000 --- a/examples/lifetime/explicit/explicit.rs +++ /dev/null @@ -1,24 +0,0 @@ -struct Book { - // `String` is a heap allocated string - title: String, - author: String, - year: uint, -} - -fn get_title<'a>(book: &'a Book) -> &'a str { - book.title.as_slice() -} - -fn main() { - let geb = Book { - // construct a `String` from a reference to a string (`&'static str`) - // by copying of the data - author: String::from_str("Douglas Hofstadter"), - title: String::from_str("Godel, Escher, Bach"), - year: 1979, - }; - - let title: &str = get_title(&geb); - - println!("I just read {}", title); -} diff --git a/examples/lifetime/explicit/input.md b/examples/lifetime/explicit/input.md deleted file mode 100644 index 7ad7450754..0000000000 --- a/examples/lifetime/explicit/input.md +++ /dev/null @@ -1,16 +0,0 @@ -When writing functions that return references, lifetimes must be explicitly -annotated. These functions are generic and we must tell the compiler what is -the relationship between the lifetimes of the objects that appear in the -arguments and the output. - -Let's illustrate with an example: we want a function that returns a reference -to the title field of a Book struct. The most generic function that we could -write would look like this: - -{explicit.play} - -The compiler can't tell how `'a` and `'b` are related, so we must supply this -information. The answer here is that `'a = 'b`, the reason is that the title -field will be destroyed when the book gets destroyed (same way with the -creation time), therefore the title field has the same lifetime as the book. - diff --git a/examples/lifetime/fn/fn.rs b/examples/lifetime/fn/fn.rs deleted file mode 100644 index ff462e64fa..0000000000 --- a/examples/lifetime/fn/fn.rs +++ /dev/null @@ -1,50 +0,0 @@ -#[deriving(Show)] -struct Triplet { - one: int, - two: int, - three: int, -} - -impl Triplet { - // First attempt: No explicit lifetimes - // The compiler infers that the field and the struct have the same lifetime - fn mut_one(&mut self) -> &mut int { - &mut self.one - } - - // Second attempt: We explicitly annotate the lifetimes on all the - // references - // Error! The compiler doesn't know what is the relationship between the - // lifetime `structure` and the lifetime `field` - //fn mut_two<'structure, 'field>(&'structure mut self) -> &'field mut int { - //&mut self.two - //} - // TODO ^ Try uncommenting this method - - // Third attempt: We think! What is the relationship between the lifetimes? - // Clearly `'field` *can't* outlive `'structure`, because the field will be - // destroyed when the struct gets destroyed - // If the fields get destroyed along with the struct, then that means that - // both the struct and its field have the same lifetime! - // Ok, so we need to tell the compiler that `'structure` = `'field` - // We can use a shorter name for the lifetime, it's common to use a single - // letter lifetime, let's use `'s`, because it's the first letter of - // structure - fn mut_three<'s>(&'s mut self) -> &'s mut int { - &mut self.three - } -} - -fn main() { - let mut triplet = Triplet { one: 1, two: 2, three: 3 }; - - println!("Before: {}", triplet); - - *triplet.mut_one() = 0; - println!("After: {}", triplet); - - // Use mutable reference to modify the original struct - *triplet.mut_three() = 0; - - println!("After: {}", triplet); -} diff --git a/examples/lifetime/fn/input.md b/examples/lifetime/fn/input.md deleted file mode 100644 index 991080c362..0000000000 --- a/examples/lifetime/fn/input.md +++ /dev/null @@ -1,4 +0,0 @@ -Explicit lifetimes are necessary when functions return references. Our case -study will be returning a reference to one of the fields of a struct. - -{fn.play} diff --git a/examples/lifetime/input.md b/examples/lifetime/input.md deleted file mode 100644 index 8456e0d6cf..0000000000 --- a/examples/lifetime/input.md +++ /dev/null @@ -1,35 +0,0 @@ -The compiler enforces valid borrowing using its borrow checker. To accomplish -this, it keeps track of two things: -* The *lifetime* of objects, and -* The scope of blocks - -The lifetime of an object starts when the object is created and ends when it -goes out of scope (i.e. it gets destroyed, because of the RAII discipline). - -A lifetime looks like this: `'burrito`, which reads as: "lifetime burrito". - -All references actually have a type signature of the form `&'a T`, where -`'a` is the lifetime of the *referenced* object. The compiler takes care of -inserting the lifetime part `'a` so we can simply type annotate references with -`&T`. - -For example: - -``` rust -let integer: int = 5; -let ref_to_int: &int = &integer; -``` - -* `integer` has lifetime `'i` (it could be any other name, like `'foo`) -* `ref_to_int` has lifetime `'r` (references also have lifetimes!) -* `ref_to_int` type signature actually is `&'i int` (the compiler inserts the - `'i` for us) -* The type signature `&'i int` reads as: - * `&`: reference to an - * `int`: integer with - * `'i`: lifetime `i` (`i` is the lifetime of `integer`!) - -Because the compiler keeps track of the lifetime of referenced objects in the -type system, it can avoid several memory bugs. - -Haven't grokked what a lifetime is yet? Don't dismay! See the next page. diff --git a/examples/lifetime/struct/input.md b/examples/lifetime/struct/input.md deleted file mode 100644 index a8fe7a8a4f..0000000000 --- a/examples/lifetime/struct/input.md +++ /dev/null @@ -1,3 +0,0 @@ -Explicit lifetimes are also required in structs that hold references. - -{struct.play} diff --git a/examples/lifetime/struct/struct.rs b/examples/lifetime/struct/struct.rs deleted file mode 100644 index 31d9211d71..0000000000 --- a/examples/lifetime/struct/struct.rs +++ /dev/null @@ -1,33 +0,0 @@ -// First attempt: No explicit lifetimes -// Error! Compiler needs explicit lifetime -//struct Singleton { - //one: &mut int, -//} -// TODO ^ Try uncommenting this struct - -// Second attempt: Add lifetimes to all the references -struct Pair<'a, 'b> { - one: &'a mut int, - two: &'b mut int, -} - -fn main() { - // Let's say that `one` has lifetime `o` - let mut one = 1; - - { - // And that `two` has lifetime `t` - // `two` has a shorter (and different) lifetime than `one` (`'t < 'o`) - let mut two = 2; - - println!("Before: ({}, {})", one, two); - - // `Pair` gets specialized for `'a = 'o` and `'b = 't` - let pair = Pair { one: &mut one, two: &mut two }; - - *pair.one = 2; - *pair.two = 1; - - println!("After: ({}, {})", pair.one, pair.two); - } -} diff --git a/examples/literals/input.md b/examples/literals/input.md deleted file mode 100644 index 22cc945393..0000000000 --- a/examples/literals/input.md +++ /dev/null @@ -1,23 +0,0 @@ -Integers `1`, floats `1.2`, characters `'a'`, strings `"abc"`, booleans `true` -and the unit type `()` can be expressed using literals. - -Integers can, alternatively, be expressed using hexadecimal, octal or binary -notation using either of these prefixes: `0x`, `0o` or `0b`. - -Underscores can be inserted in numeric literals to improve readability, e.g. -`1_000` is the same as `1000`, and `0.000_001` is the same as `0.000001`. - -We need to tell the compiler what is the type of the literals we use. For now, -we'll use the `u` suffix to indicate that the literal is an unsigned integer, -and the `i` suffix to indicate that it's a signed integer. We'll cover the type -system in [another chapter][type], and give more details about type -annotating literals in [their own section][type-literal]. - -The operators available and their precedence are similar to other -[C-like languages][op-prec]. - -{literals.play} - -[op-prec]: https://en.wikipedia.org/wiki/Operator_precedence#Programming_languages -[type]: /type.html -[type-literal]: /type/literals.html diff --git a/examples/literals/literals.rs b/examples/literals/literals.rs deleted file mode 100644 index 46cfdc512b..0000000000 --- a/examples/literals/literals.rs +++ /dev/null @@ -1,23 +0,0 @@ -fn main() { - // Integer addition - println!("1 + 2 = {}", 1u + 2); - - // Integer subtraction - println!("1 - 2 = {}", 1i - 2); - // TODO ^ Try changing `1i` to `1u` to see why the type is important - - // Short-circuiting boolean logic - println!("true AND false is {}", true && false); - println!("true OR false is {}", true || false); - println!("NOT true is {}", !true); - - // Bitwise operations - println!("0011 AND 0101 is {:04b}", 0b0011u & 0b0101); - println!("0011 OR 0101 is {:04b}", 0b0011u | 0b0101); - println!("0011 XOR 0101 is {:04b}", 0b0011u ^ 0b0101); - println!("1 << 5 is {}", 1u << 5); - println!("0x80 >> 2 is 0x{:x}", 0x80u >> 2); - - // Use underscores to improve readability! - println!("One million is written as {}", 1_000_000u); -} diff --git a/examples/loop/input.md b/examples/loop/input.md deleted file mode 100644 index d79667783c..0000000000 --- a/examples/loop/input.md +++ /dev/null @@ -1,7 +0,0 @@ -Rust provides a `loop` keyword to indicate an infinite loop. - -The `break` statement can be used to exit a loop at anytime, whereas the -`continue` statement can be used to skip the rest of the iteration and start a -new one. - -{loop.play} diff --git a/examples/loop/nested/input.md b/examples/loop/nested/input.md deleted file mode 100644 index f128b7ad34..0000000000 --- a/examples/loop/nested/input.md +++ /dev/null @@ -1,5 +0,0 @@ -It's possible to `break` or `continue` outer loops when dealing with nested -loops. In these cases, the loops must be annotated with some `'label`, and the -label must be passed to the `break`/`continue` statement. - -{nested.play} diff --git a/examples/match/guard/guard.rs b/examples/match/guard/guard.rs deleted file mode 100644 index dd8d184e9e..0000000000 --- a/examples/match/guard/guard.rs +++ /dev/null @@ -1,16 +0,0 @@ -fn main() { - let pair = (2i, -2); - // TODO ^ Try different values for `pair` - - println!("Tell me about {}", pair); - // Match can be used to destructure a tuple - match pair { - // Destructure the tuple - (x, y) if x == y => println!("These are twins"), - // The ^ `if condition` part is a guard - (x, y) if x + y == 0 => println!("Antimatter, kaboom!"), - // `_` means don't bind the value to a variable - (x, _) if x % 2 == 1 => println!("The first one is odd"), - _ => println!("No correlation..."), - } -} diff --git a/examples/match/guard/input.md b/examples/match/guard/input.md deleted file mode 100644 index 8803a7b274..0000000000 --- a/examples/match/guard/input.md +++ /dev/null @@ -1,4 +0,0 @@ -The arms of a `match` block can be destructured, and a *guard* can be added to -further filter the arm. - -{guard.play} diff --git a/examples/match/input.md b/examples/match/input.md deleted file mode 100644 index 53c52a8959..0000000000 --- a/examples/match/input.md +++ /dev/null @@ -1,4 +0,0 @@ -Rust provides pattern matching via the `match` keyword, which can be used like -a C `switch`. - -{match.play} diff --git a/examples/match/struct/input.md b/examples/match/struct/input.md deleted file mode 100644 index a9e6b3b7d1..0000000000 --- a/examples/match/struct/input.md +++ /dev/null @@ -1,3 +0,0 @@ -A `struct` can be destructured with pattern matching. - -{struct.play} diff --git a/examples/match/struct/struct.rs b/examples/match/struct/struct.rs deleted file mode 100644 index 7e1d5d3194..0000000000 --- a/examples/match/struct/struct.rs +++ /dev/null @@ -1,22 +0,0 @@ -fn main() { - struct Foo { x: (uint, uint), y: uint } - - // destructure members of the struct - let foo = Foo { x: (1, 2), y: 3 }; - let Foo { x: (a, b), y } = foo; - - println!("a = {}, b = {}, y = {} ", a, b, y); - - // you can destructure structs and rename the variables, - // the order is not important - - let Foo { y: i, x: j } = foo; - println!("i = {}, j = {}", i, j); - - // and you can also ignore some variables: - let Foo { y, .. } = foo; - println!("y = {}", y); - - // this will give an error: pattern does not mention field `x` - // let Foo { y } = foo; -} diff --git a/examples/methods/input.md b/examples/methods/input.md deleted file mode 100644 index c2bde12242..0000000000 --- a/examples/methods/input.md +++ /dev/null @@ -1,5 +0,0 @@ -Methods are functions attached to objects, these methods have access to the -data of the object and its other methods via the `self` keyword. Methods are -defined under a `impl` block. - -{methods.play} diff --git a/examples/mod/mod.rs b/examples/mod/mod.rs deleted file mode 100644 index 849bbe9576..0000000000 --- a/examples/mod/mod.rs +++ /dev/null @@ -1,34 +0,0 @@ -fn function() { - println!("called `function()`"); -} - -// A module named `my` -mod my { - // A module can contain items like functions - #[allow(dead_code)] - fn function() { - println!("called `my::function()`"); - } - - // Modules can be nested - mod nested { - #[allow(dead_code)] - fn function() { - println!("called `my::nested::function()`"); - } - } -} - -fn main() { - function(); - - // Items inside a module can be called using their full path - // The `println` function lives in the `stdio` module - // The `stdio` module lives in the `io` module - // And the `io` module lives in the `std` crate - std::io::stdio::println("Hello World!"); - - // Error! `my::function` is private - my::function(); - // TODO ^ Comment out this line -} diff --git a/examples/mod/split/input.md b/examples/mod/split/input.md deleted file mode 100644 index d2a7d2c237..0000000000 --- a/examples/mod/split/input.md +++ /dev/null @@ -1,33 +0,0 @@ -Modules can be mapped to a file/directory hierarchy. Let's break down the -[visibility example][visibility] in files: - -``` -$ tree . -. -|-- my -| |-- inaccessible.rs -| |-- mod.rs -| `-- nested.rs -`-- split.rs -``` - -{split.rs} - -{my/mod.rs} - -{my/nested.rs} - -{my/inaccessible.rs} - -Let's check that things still work as before: - -``` -$ rustc split.rs && ./split -called `my::function()` -called `function()` -called `my::indirect_access()`, that -> called `my::private_function()` -called `my::nested::function()` -``` - -[visibility]: /mod/visibility.html diff --git a/examples/mod/split/my/inaccessible.rs b/examples/mod/split/my/inaccessible.rs deleted file mode 100644 index 487a10e468..0000000000 --- a/examples/mod/split/my/inaccessible.rs +++ /dev/null @@ -1,4 +0,0 @@ -#[allow(dead_code)] -pub fn public_function() { - println!("called `my::inaccessible::public_function()`"); -} diff --git a/examples/mod/split/my/mod.rs b/examples/mod/split/my/mod.rs deleted file mode 100644 index 5851229632..0000000000 --- a/examples/mod/split/my/mod.rs +++ /dev/null @@ -1,19 +0,0 @@ -// Similarly `mod inaccessible` and `mod nested` will locate the `nested.rs` -// and `inaccessible.rs` files and insert them here under their respective -// modules -mod inaccessible; -pub mod nested; - -pub fn function() { - println!("called `my::function()`"); -} - -fn private_function() { - println!("called `my::private_function()`"); -} - -pub fn indirect_access() { - print!("called `my::indirect_access()`, that\n> "); - - private_function(); -} diff --git a/examples/mod/split/my/nested.rs b/examples/mod/split/my/nested.rs deleted file mode 100644 index e47cf9b07b..0000000000 --- a/examples/mod/split/my/nested.rs +++ /dev/null @@ -1,8 +0,0 @@ -pub fn function() { - println!("called `my::nested::function()`"); -} - -#[allow(dead_code)] -fn private_function() { - println!("called `my::nested::private_function()`"); -} diff --git a/examples/mod/split/split.rs b/examples/mod/split/split.rs deleted file mode 100644 index 812ff8042a..0000000000 --- a/examples/mod/split/split.rs +++ /dev/null @@ -1,17 +0,0 @@ -// This declaration will look for a file named `my.rs` or `my/mod.rs` and will -// insert its contents inside a module named `my` under this scope -mod my; - -fn function() { - println!("called `function()`"); -} - -fn main() { - my::function(); - - function(); - - my::indirect_access(); - - my::nested::function(); -} diff --git a/examples/mod/super/input.md b/examples/mod/super/input.md deleted file mode 100644 index 05b1415fa3..0000000000 --- a/examples/mod/super/input.md +++ /dev/null @@ -1,4 +0,0 @@ -The `super` and `self` keywords can be used in the path, to remove ambiguity -when accessing items. - -{super.play} diff --git a/examples/mod/super/super.rs b/examples/mod/super/super.rs deleted file mode 100644 index 6fe3482053..0000000000 --- a/examples/mod/super/super.rs +++ /dev/null @@ -1,59 +0,0 @@ -fn function() { - println!("called `function()`"); -} - -mod my { - pub fn indirect_call() { - // Let's access all the functions named `function` from this scope - print!("called `my::indirect_call()`, that\n> "); - - // `my::function` can be called directly - function(); - - { - // This will bind to the `cool::function` in the *crate* scope - // In this case the crate scope is the outermost scope - use cool::function as root_cool_function; - - print!("> "); - root_cool_function(); - } - - { - // `self` refers to the current module scope, in this case: `my` - use self::cool::function as my_cool_function; - - print!("> ") - my_cool_function(); - } - - { - // `super` refers to the parent scope, i.e. outside of the `my` - // module - use super::function as root_function; - - print!("> "); - root_function(); - } - } - - fn function() { - println!("called `my::function()`"); - } - - mod cool { - pub fn function() { - println!("called `my::cool::function()`"); - } - } -} - -mod cool { - pub fn function() { - println!("called `cool::function()`"); - } -} - -fn main() { - my::indirect_call(); -} diff --git a/examples/mod/use/input.md b/examples/mod/use/input.md deleted file mode 100644 index 05b3657427..0000000000 --- a/examples/mod/use/input.md +++ /dev/null @@ -1,4 +0,0 @@ -The `use` declaration can be used to bind a full path to a new name, for easier -access. - -{use.play} diff --git a/examples/mod/use/use.rs b/examples/mod/use/use.rs deleted file mode 100644 index 3903739c5e..0000000000 --- a/examples/mod/use/use.rs +++ /dev/null @@ -1,35 +0,0 @@ -// Bind the `deeply::nested::function` path to `other_function` -use deeply::nested::function as other_function; - -fn function() { - println!("called `function()`"); -} - -mod deeply { - pub mod nested { - pub fn function() { - println!("called `deeply::nested::function()`") - } - } -} - -fn main() { - // Easier access to `deeply::nested::function` - other_function(); - - println!("Entering block"); - { - // This is equivalent to `use deeply::nested::function as function` - // This `function` will shadow the outer one - use deeply::nested::function; - - function(); - - println!("Leaving block"); - - // `use` bindings have a local scope, in this case the `function` - // shadowing is only available in this scope - } - - function(); -} diff --git a/examples/mod/visibility/input.md b/examples/mod/visibility/input.md deleted file mode 100644 index b334d7625e..0000000000 --- a/examples/mod/visibility/input.md +++ /dev/null @@ -1,5 +0,0 @@ -By default, the items in a module have private visibility, but this can be -overridden with the `pub` modifier. Only the public items of a module can be -accessed from outside the module scope. - -{visibility.play} diff --git a/examples/mod/visibility/visibility.rs b/examples/mod/visibility/visibility.rs deleted file mode 100644 index 8081b1b8d2..0000000000 --- a/examples/mod/visibility/visibility.rs +++ /dev/null @@ -1,73 +0,0 @@ -fn function() { - println!("called `function()`"); -} - -mod my { - // A public function - pub fn function() { - println!("called `my::function()`"); - } - - // A private function - fn private_function() { - println!("called `my::private_function()`"); - } - - // Items can access other items in the same module - pub fn indirect_access() { - print!("called `my::indirect_access()`, that\n> "); - - // regardless of their visibility - private_function(); - } - - // A public module - pub mod nested { - pub fn function() { - println!("called `my::nested::function()`"); - } - - #[allow(dead_code)] - fn private_function() { - println!("called `my::nested::private_function()`"); - } - } - - // A private module - mod inaccessible { - #[allow(dead_code)] - pub fn public_function() { - println!("called `my::inaccessible::public_function()`"); - } - } -} - -fn main() { - // The public items of a module can be accessed - my::function(); - - // modules allow disambiguation between items that have the same name - function(); - - // The private items of a module can't be directly accessed - // Error! `private_function` is private - //my::private_function(); - // TODO ^ Try uncommenting this line - - my::indirect_access(); - - // Public items inside public nested modules can be accessed from outside - // the parent module - my::nested::function(); - - // but private items inside public nested modules can't be accessed - // Error! `private_function` is private - //my::nested::private_function(); - // TODO ^ Try uncommenting this line - - // Items inside private nested modules can't be accessed, regardless of - // their visibility - // Error! `inaccessible` is a private module - //my::inaccessible::public_function(); - // TODO ^ Try uncommenting this line -} diff --git a/examples/move/input.md b/examples/move/input.md deleted file mode 100644 index c551bb017c..0000000000 --- a/examples/move/input.md +++ /dev/null @@ -1,11 +0,0 @@ -Because variables are in charge of freeing their resources (if any), resources -can only have *one* owner, otherwise resources would get freed more than once. - -When doing assignments `let x = y`, or passing function arguments by value -`foo(x)`, the *ownership* of the resources, if any, is transferred; this is -known as a "move" in Rust-speak. - -After moving resources, the previous owner can no longer be used. This avoids -the creation of *dangling pointers*. - -{move.play} diff --git a/examples/move/move.rs b/examples/move/move.rs deleted file mode 100644 index 4da44ff5a7..0000000000 --- a/examples/move/move.rs +++ /dev/null @@ -1,44 +0,0 @@ -// This function takes ownership of the heap allocated memory -fn destroy_box(c: Box) { - println!("destroying a box that contains {}", c); - - // `c` will be destroyed in this scope, and the memory will be freed -} - -fn main() { - // Stack allocated integer - let x = 5u; - - // "Copy" `x` into `y`, there are no resources to move - let y = x; - - // Both values can be independently used - println!("x is {}, and y is {}", x, y); - - // `a` is a pointer to a heap allocated integer - let a = box 5; - - println!("a contains: {}", a); - - // "Move" `a` into `b` - // Here's what happens under the hood: the pointer `a` gets copied (*not* - // the data on the heap, just its address) into `b`. Now both are pointers - // to the *same* heap allocated data. But now, `b` *owns* the heap - // allocated data; `b` is now in charge of freeing the memory in the heap. - let b = a; - - // After the previous move, `a` can no longer be used - // Error! `a` can no longer access the data, because it no longer owns the - // heap memory - //println!("a contains: {}", a); - // TODO ^ Try uncommenting this line - - // "Move" `b` into the function; `b` gives up ownership of the heap data - destroy_box(b); - - // Since the heap memory has been freed at this point, this action would - // result in dereferencing freed memory, but it's forbidden by the compiler - // Error! Same reason as the previous Error - //println!("b contains: {}", b); - // TODO ^ Try uncommenting this line -} diff --git a/examples/move/mut/input.md b/examples/move/mut/input.md deleted file mode 100644 index 239187aa28..0000000000 --- a/examples/move/mut/input.md +++ /dev/null @@ -1,3 +0,0 @@ -Mutability of data can be changed when ownership is transferred. - -{mut.play} diff --git a/examples/ops/input.md b/examples/ops/input.md deleted file mode 100644 index 8c0c066d73..0000000000 --- a/examples/ops/input.md +++ /dev/null @@ -1,11 +0,0 @@ -In Rust, many of the operators can be overloaded via traits. This is possible -because operators are just sugar for method calls. For example, `a + b` -desugars to `a.add(&b)`. This `add` method is part of the `Add` trait, hence -any implementor of the `Add` trait will be able to use the `+` operator. - -{operator.play} - -Here is a [list][ops] of -the traits that overload operators. - -[ops]: http://doc.rust-lang.org/core/ops/ diff --git a/examples/ops/operator.rs b/examples/ops/operator.rs deleted file mode 100644 index 7efb7839ab..0000000000 --- a/examples/ops/operator.rs +++ /dev/null @@ -1,35 +0,0 @@ -struct Foo; -struct Bar; - -#[deriving(Show)] -struct FooBar; - -#[deriving(Show)] -struct BarFoo; - -// The `Add` trait needs two generic parameters: -// * T is the type of the RHS summand, and -// * U is the type of the sum -// This block implements the operation: Foo + Bar = FooBar -impl Add for Foo { - fn add(&self, _rhs: &Bar) -> FooBar { - println!("> Foo.add(&Bar) was called"); - - FooBar - } -} - -// Addition can be implemented in a non-commutative way -// This block implements the operation: Bar + Foo = BarFoo -impl Add for Bar { - fn add(&self, _rhs: &Foo) -> BarFoo { - println!("> Bar.add(&Foo) was called"); - - BarFoo - } -} - -fn main() { - println!("Foo + Bar = {}", Foo + Bar); - println!("Bar + Foo = {}", Bar + Foo); -} diff --git a/examples/option/input.md b/examples/option/input.md deleted file mode 100644 index 25548903ed..0000000000 --- a/examples/option/input.md +++ /dev/null @@ -1,9 +0,0 @@ -Sometimes it's desirable to catch the failure of some parts of a program -instead of calling `panic!`, this can be accomplished using the `Option` enum. - -The `Option` enum has two variants: - -* `None`, to indicate failure or lack of value, and -* `Some(value)`, a tuple struct that wraps a `value` with type `T`. - -{option.play} diff --git a/examples/option/option.rs b/examples/option/option.rs deleted file mode 100644 index fd89338c6b..0000000000 --- a/examples/option/option.rs +++ /dev/null @@ -1,37 +0,0 @@ -// An integer division that doesn't `panic!` -fn checked_division(dividend: int, divisor: int) -> Option { - if divisor == 0 { - // Failure is represented as the `None` variant - None - } else { - // Result is wrapped in a `Some` variant - Some(dividend / divisor) - } -} - -// This function handles a division that may not succeed -fn try_division(dividend: int, divisor: int) { - // `Option` values can be pattern matched, just like other enums - match checked_division(dividend, divisor) { - None => println!("{} / {} failed!", dividend, divisor), - Some(quotient) => { - println!("{} / {} = {}", dividend, divisor, quotient) - }, - } -} - -fn main() { - try_division(4, 2); - try_division(1, 0); - - // Binding `None` to a variable needs to be type annotated - let none: Option = None; - let _equivalent_none = None::; - - let optional_float = Some(0f32); - - // The `unwrap` method will extract the value wrapped in a `Some` variant, - // or will `panic!` if called on a `None` variant - println!("{} unwraps to {}", optional_float, optional_float.unwrap()); - println!("{} unwraps to {}", none, none.unwrap()); -} diff --git a/examples/panic/input.md b/examples/panic/input.md deleted file mode 100644 index a9241ad24c..0000000000 --- a/examples/panic/input.md +++ /dev/null @@ -1,29 +0,0 @@ -The `panic!` macro can be used to generate a *task* panic and start unwinding -its stack. While unwinding, the runtime will take care of freeing all the -resources *owned* by the task by calling the destructor of all its objects. - -Since we are dealing with programs with only one task, `panic!` will cause the -program to report the panic message and exit. - -{panic.play} - -Let's check that `panic!` doesn't leak memory. - -``` -$ rustc panic.rs && valgrind ./panic -==4401== Memcheck, a memory error detector -==4401== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al. -==4401== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info -==4401== Command: ./panic -==4401== -task '
' panicked at 'division by zero', panic.rs:5 -==4401== -==4401== HEAP SUMMARY: -==4401== in use at exit: 0 bytes in 0 blocks -==4401== total heap usage: 18 allocs, 18 frees, 1,648 bytes allocated -==4401== -==4401== All heap blocks were freed -- no leaks are possible -==4401== -==4401== For counts of detected and suppressed errors, rerun with: -v -==4401== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) -``` diff --git a/examples/panic/panic.rs b/examples/panic/panic.rs deleted file mode 100644 index 3c69b04b44..0000000000 --- a/examples/panic/panic.rs +++ /dev/null @@ -1,22 +0,0 @@ -// Re-implementation of integer division (/) -fn division(dividend: int, divisor: int) -> int { - if divisor == 0 { - // Division by zero triggers a task panic - panic!("division by zero"); - } else { - dividend / divisor - } -} - -// The `main` task -fn main() { - // Heap allocated integer - let _x = box 0i; - - // This operation will trigger a task failure - division(3, 0); - - println!("This point won't be reached!"); - - // `_x` should get destroyed at this point -} diff --git a/examples/path/input.md b/examples/path/input.md deleted file mode 100644 index b6330a01db..0000000000 --- a/examples/path/input.md +++ /dev/null @@ -1,25 +0,0 @@ -The `Path` struct represents file paths in the underlying filesystem. There are -two flavors of `Path`: `posix::Path`, for UNIX-like systems, and -`windows::Path`, for Windows. The prelude exports the appropriate -platform-specific `Path` variant. - -A `Path` can be created from almost any type that implements the -`BytesContainer` trait, like a string, and provides several methods to get -information from the file/directory the path points to. - -Note that a `Path` is *not* internally represented as an UTF-8 string, but -instead is stored as a vector of bytes (`Vec`). Therefore, converting a -`Path` to a `&str` is *not* free and may fail (an `Option` is returned). - -{path.play} - -Be sure to check at other `Path` methods -([`posix::Path`][posix-path] -or [`windows::Path`][windows-path]) -and the -[`FileStat`][file-stat] -struct. - -[posix-path]: http://doc.rust-lang.org/std/path/posix/struct.Path.html -[windows-path]: http://doc.rust-lang.org/std/path/windows/struct.Path.html -[file-stat]: http://doc.rust-lang.org/std/io/struct.FileStat.html diff --git a/examples/path/path.rs b/examples/path/path.rs deleted file mode 100644 index 0e5ffa67d5..0000000000 --- a/examples/path/path.rs +++ /dev/null @@ -1,42 +0,0 @@ -use std::io::fs::PathExtensions; - -fn main() { - // Create a `Path` from an `&'static str` - let path = Path::new("."); - - // The `display` method returns a `Show`able structure - let display = path.display(); - - // Check if the path exists - if path.exists() { - println!("{} exists", display); - } - - // Check if the path is a file - if path.is_file() { - println!("{} is a file", display); - } - - // Check if the path is a directory - if path.is_dir() { - println!("{} is a directory", display); - } - - // `stat` returns an IoResult === Result - let stat = match path.stat() { - Err(why) => panic!("{}", why.desc), - Ok(stat) => stat, - }; - - println!("{} size is {} bytes", display, stat.size); - - // `join` merges a path with a byte container using the OS specific - // separator, and returns the new path - let new_path = path.join("a").join("b"); - - // Convert the path into a string slice - match new_path.as_str() { - None => panic!("new path is not a valid UTF-8 sequence"), - Some(s) => println!("new path is {}", s), - } -} diff --git a/examples/print/input.md b/examples/print/input.md deleted file mode 100644 index 7640dbfefa..0000000000 --- a/examples/print/input.md +++ /dev/null @@ -1,10 +0,0 @@ -The `println!` macro not only prints to the console, but is also capable of -formatting text and stringifying values. Plus, the formatting correctness will -be checked at compile time. - -{print.play} - -For more information about formatting, take a look at -[std::fmt][fmt]. - -[fmt]: http://doc.rust-lang.org/std/fmt/ diff --git a/examples/print/print.rs b/examples/print/print.rs deleted file mode 100644 index 49cb454f57..0000000000 --- a/examples/print/print.rs +++ /dev/null @@ -1,25 +0,0 @@ -fn main() { - // `print!` is like `println!` but it doesn't add a newline at the end - print!("January has "); - - // `{}` are placeholders for arguments that will be stringified - println!("{} days", 31i); - // The `i` suffix indicates the compiler that this literal has type: signed - // pointer size integer, see next chapter for more details - - // The positional arguments can be reused along the template - println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob"); - - // Named arguments can also be used - println!("{subject} {verb} {predicate}", - predicate="over the lazy dog", - subject="the quick brown fox", - verb="jumps"); - - // Special formatting can be specified in the placeholder after a `:` - println!("{} of {:b} people know binary, the other half don't", 1i, 2i); - - // Error! You are missing an argument - println!("My name is {0}, {1} {0}", "Bond"); - // FIXME ^ Add the missing argument: "James" -} diff --git a/examples/process/input.md b/examples/process/input.md deleted file mode 100644 index 671388d83d..0000000000 --- a/examples/process/input.md +++ /dev/null @@ -1,7 +0,0 @@ -The `ProcessOutput` struct represents the output of a finished child process. -And the `Command` struct is a process builder. - -{process.play} - -(You are encouraged to try the previous example with an incorrect flag passed -to `rustc`) diff --git a/examples/process/pipe/input.md b/examples/process/pipe/input.md deleted file mode 100644 index a24924510b..0000000000 --- a/examples/process/pipe/input.md +++ /dev/null @@ -1,5 +0,0 @@ -The `Process` struct represents a running child process, and exposes the -`stdin`, `stdout` and `stderr` handles for interaction with the underlying -process via pipes. - -{pipe.play} diff --git a/examples/process/pipe/pipe.rs b/examples/process/pipe/pipe.rs deleted file mode 100644 index b2d24e5f02..0000000000 --- a/examples/process/pipe/pipe.rs +++ /dev/null @@ -1,37 +0,0 @@ -use std::io::process::Command; - -static PANGRAM: &'static str = -"the quick brown fox jumped over the lazy dog\n"; - -fn main() { - // Spawn the `wc` command - let mut process = match Command::new("wc").spawn() { - Err(why) => panic!("couldn't spawn wc: {}", why.desc), - Ok(process) => process, - }; - - { - // The `stdin` field has type `Option` - // `take_unwrap` will take the value wrapped in a `Some` variant - // Note that we take ownership of `stdin` here - let mut stdin = process.stdin.take().unwrap(); - - // Write a string to the stdin of `wc` - match stdin.write_str(PANGRAM) { - Err(why) => panic!("couldn't write to wc stdin: {}", why.desc), - Ok(_) => println!("sent pangram to wc"), - } - - // `stdin` gets `drop`ed her, and the pipe is closed - // This is very important, otherwise `wc` wouldn't start processing the - // input we just sent - } - - // The `stdout` field also has type `Option` - // the `get_mut_ref` method will return a mutable reference to the value - // wrapped in a `Some` variant - match process.stdout.as_mut().unwrap().read_to_string() { - Err(why) => panic!("couldn't read wc stdout: {}", why.desc), - Ok(string) => print!("wc responded with:\n{}", string), - } -} diff --git a/examples/process/process.rs b/examples/process/process.rs deleted file mode 100644 index 34e0a130f0..0000000000 --- a/examples/process/process.rs +++ /dev/null @@ -1,29 +0,0 @@ -use std::io::process::{Command,ProcessOutput}; - -fn main() { - // Initial command `rustc` - let mut cmd = Command::new("rustc"); - // append the "--version" flag to the command - cmd.arg("--version"); - - // The `output` method will spawn `rustc --version`, wait until the process - // finishes and return the output of the process - match cmd.output() { - Err(why) => panic!("couldn't spawn rustc: {}", why.desc), - // Destructure `ProcessOutput` - Ok(ProcessOutput { error: err, output: out, status: exit }) => { - // Check if the process succeeded, i.e. the exit code was 0 - if exit.success() { - // `out` has type `Vec`, convert it to a UTF-8 `$str` - let s = String::from_utf8_lossy(out.as_slice()); - - print!("rustc succeeded and stdout was:\n{}", s); - } else { - // `err` also has type `Vec` - let s = String::from_utf8_lossy(err.as_slice()); - - print!("rustc failed and stderr was:\n{}", s); - } - }, - } -} diff --git a/examples/process/wait/input.md b/examples/process/wait/input.md deleted file mode 100644 index cdf87be219..0000000000 --- a/examples/process/wait/input.md +++ /dev/null @@ -1,11 +0,0 @@ -When a `Process` goes out of scope, its `drop` method will *wait* until the -child process finishes before releasing the resource. - -{wait.rs} - -``` -$ rustc wait.rs && ./wait -reached end of main -# `wait` keeps running for 5 seconds -# `sleep 5` command ends, and then our `wait` program finishes -``` diff --git a/examples/process/wait/wait.rs b/examples/process/wait/wait.rs deleted file mode 100644 index 714cc1fd06..0000000000 --- a/examples/process/wait/wait.rs +++ /dev/null @@ -1,7 +0,0 @@ -use std::io::process::Command; - -fn main() { - let _process = Command::new("sleep").arg("5").spawn(); - - println!("reached end of main"); -} diff --git a/examples/raii/input.md b/examples/raii/input.md deleted file mode 100644 index 6b1e25c2a8..0000000000 --- a/examples/raii/input.md +++ /dev/null @@ -1,32 +0,0 @@ -Variables in Rust do more than just hold data in the stack, they can also *own* -resources, e.g. `Box` owns memory in the heap. Because Rust enforces the -[RAII][raii] -discipline, whenever an object goes out of scope, its destructor is called -and the resources *owned* by it are freed. This behavior shields against -*resource leak* bugs. - -{raii.play} - -Don't take my word for it, let's check using `valgrind` - -``` -$ rustc raii.rs && valgrind ./raii -==26873== Memcheck, a memory error detector -==26873== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al. -==26873== Using Valgrind-3.9.0 and LibVEX; rerun with -h for copyright info -==26873== Command: ./raii -==26873== -==26873== -==26873== HEAP SUMMARY: -==26873== in use at exit: 0 bytes in 0 blocks -==26873== total heap usage: 1,013 allocs, 1,013 frees, 8,696 bytes allocated -==26873== -==26873== All heap blocks were freed -- no leaks are possible -==26873== -==26873== For counts of detected and suppressed errors, rerun with: -v -==26873== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2) -``` - -You'll never have to manually free memory again or worry about memory leaks! - -[raii]: http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization diff --git a/examples/raii/raii.rs b/examples/raii/raii.rs deleted file mode 100644 index 99e6fabbc6..0000000000 --- a/examples/raii/raii.rs +++ /dev/null @@ -1,26 +0,0 @@ -fn create_box() { - // Allocate an integer in the heap - let _function_box = box 3i; - - // `_function_box` gets destroyed here, memory gets freed -} - -fn main() { - // Allocate an integer in the heap - let _boxed_int = box 5i; - - // new (smaller) scope - { - // Another heap allocated integer - let _short_lived_box = box 4i; - - // `_short_lived_box` gets destroyed here, memory gets freed - } - - // Create lots of boxes - for _ in range(0u, 1_000) { - create_box(); - } - - // `_boxed_int` gets destroyed here, memory gets freed -} diff --git a/examples/result/input.md b/examples/result/input.md deleted file mode 100644 index 5a8edab985..0000000000 --- a/examples/result/input.md +++ /dev/null @@ -1,13 +0,0 @@ -We've seen that the `Option` enum can be used as a return value from functions -that may fail, where `None` can be returned to indicate failure. However, -sometimes is important to express *why* an operation failed. To do this we have -the `Result` enum. - -The `Result` enum has two variants: - -* `Ok(value)` which indicates that the operation succeeded, and wraps the - `value` returned by the operation. (`value` has type `T`) -* `Err(why)`, which indicates that the operation failed, and wraps `why`, - which (hopefully) explains the cause of the failure. (`why` has type `E`) - -{result.play} diff --git a/examples/result/try/input.md b/examples/result/try/input.md deleted file mode 100644 index a6b15c8239..0000000000 --- a/examples/result/try/input.md +++ /dev/null @@ -1,11 +0,0 @@ -Chaining results using match can get pretty untidy; luckily, the `try!` macro -can be used to make things pretty again. The `try!` macro expands to a match -expression, where the `Err(err)` branch expands to an early `return Err(err)`, -and the `Ok(ok)` branch expands to an `ok` expression. - -{try.play} - -Be sure to check the [documentation][docs], -as there are many methods to map/compose `Result`. - -[docs]: http://doc.rust-lang.org/std/result/index.html diff --git a/examples/sockets/client.rs b/examples/sockets/client.rs deleted file mode 100644 index a1bd4271a2..0000000000 --- a/examples/sockets/client.rs +++ /dev/null @@ -1,29 +0,0 @@ -use common::SOCKET_PATH; -use std::io::net::pipe::UnixStream; -use std::os; - -mod common; - -fn main() { - // `args` returns the arguments passed to the program - let args = os::args(); - let socket = Path::new(SOCKET_PATH); - - // First argument is the message to be sent - let message = match args.as_slice() { - [_, ref message] => message.as_slice(), - _ => panic!("wrong number of arguments"), - }; - - // Connect to socket - let mut stream = match UnixStream::connect(&socket) { - Err(_) => panic!("server is not running"), - Ok(stream) => stream, - }; - - // Send message - match stream.write_str(message) { - Err(_) => panic!("couldn't send message"), - Ok(_) => {} - } -} diff --git a/examples/sockets/common.rs b/examples/sockets/common.rs deleted file mode 100644 index 04b94028e8..0000000000 --- a/examples/sockets/common.rs +++ /dev/null @@ -1 +0,0 @@ -pub static SOCKET_PATH: &'static str = "loopback-socket"; diff --git a/examples/sockets/input.md b/examples/sockets/input.md deleted file mode 100644 index f88e85067a..0000000000 --- a/examples/sockets/input.md +++ /dev/null @@ -1,34 +0,0 @@ -Inter-Process Communication (IPC) for client-server applications can be -accomplished using -[UNIX sockets][unix-sockets]. - -Both client and server need to use the same path for the socket. - -{common.rs} - -The client program: - -{client.rs} - -The server program: - -{server.rs} - -Let's test the programs - -``` -$ rustc client.rs; rustc server.rs - -# Terminal 1 -$ ./server -Server started, waiting for clients - -# Terminal 2 -$ ./client hello - -# Terminal 1 -Server started, waiting for clients -Client said: hello -``` - -[unix-sockets]: http://en.wikipedia.org/wiki/Unix_domain_socket diff --git a/examples/sockets/server.rs b/examples/sockets/server.rs deleted file mode 100644 index 6107e00133..0000000000 --- a/examples/sockets/server.rs +++ /dev/null @@ -1,29 +0,0 @@ -use common::SOCKET_PATH; -use std::io::fs; -use std::io::fs::PathExtensions; -use std::io::net::pipe::UnixListener; -use std::io::{Acceptor,Listener}; - -mod common; - -fn main() { - let socket = Path::new(SOCKET_PATH); - - // Delete old socket if necessary - if socket.exists() { - fs::unlink(&socket).unwrap(); - } - - // Bind to socket - let stream = match UnixListener::bind(&socket) { - Err(_) => panic!("failed to bind socket"), - Ok(stream) => stream, - }; - - println!("Server started, waiting for clients"); - - // Iterate over clients, blocks if no client available - for mut client in stream.listen().incoming() { - println!("Client said: {}", client.read_to_string().unwrap()); - } -} diff --git a/examples/staging/arg/args.rs b/examples/staging/arg/args.rs deleted file mode 100644 index 448b040891..0000000000 --- a/examples/staging/arg/args.rs +++ /dev/null @@ -1,11 +0,0 @@ -use std::os; - -fn main() { - let args = os::args(); - // The first argument is the path that was used to call the program. - println!("My path is {}.", args[0]); - // The rest of the arguments are the passed command line parameters. - // Call the program like this: - // $ ./args arg1 arg2 - println!("I got {} arguments: {}.", args.len() - 1, args.tail()); -} diff --git a/examples/staging/arg/getopts/echo.rs b/examples/staging/arg/getopts/echo.rs deleted file mode 100644 index f47a9eadb2..0000000000 --- a/examples/staging/arg/getopts/echo.rs +++ /dev/null @@ -1,64 +0,0 @@ -extern crate getopts; - -use std::os; -use std::io::{print, println}; -use std::io::stdio; - -static VERSION: &'static str = "1.0.0"; - -fn main() { - let args = os::args(); - let ref program = args[0]; - - // Set possible flags. - // The first argument to `optflag` is the short flag name. - // The second argument is the long flag name. - // The third argument is the help text. - let opts = [ - getopts::optflag("n", "", "do not output the trailing newline"), - getopts::optflag("h", "help", "display this help and exit"), - getopts::optflag("V", "version", - "output version information and exit"), - ]; - - let matches = match getopts::getopts(args.tail(), &opts) { - Ok(m) => m, - Err(f) => { - println!("{}", f); - os::set_exit_status(1); - return; - // The exit code is 0 (success) by default. - // Any exit code other than 0 indicates failure. - } - }; - - if matches.opt_present("help") { - //^ We could as well have used the short name: "h" - println!("echo {} - display a line of text", VERSION); - println!(""); - println!("Usage:"); - println!(" {} [SHORT-OPTION]... [STRING]...", program); - println!(" {} LONG-OPTION", program); - println!(""); - println(getopts::usage("Echo the STRING(s) to standard output.", &opts) - .as_slice()); - return; - } - - if matches.opt_present("version") { - println!("echo version: {}", VERSION); - return; - } - - if !matches.free.is_empty() { - //^ `matches.free` contains all the arguments that are not options. - let string = matches.free.connect(" "); - print(string.as_slice()); - } - - if !matches.opt_present("n") { - println!("") - } else { - stdio::flush(); - } -} diff --git a/examples/staging/arg/getopts/input.md b/examples/staging/arg/getopts/input.md deleted file mode 100644 index 53a14d41ae..0000000000 --- a/examples/staging/arg/getopts/input.md +++ /dev/null @@ -1,70 +0,0 @@ -To build unix-style command line interfaces, you can use the [getopts](http://doc.rust-lang.org/getopts/index.html) crate. - -Here is a simple implementation of the `echo` unix program: - -{echo.play} - -``` -$ ./echo -h -echo 1.0.0 - display a line of text - -Usage: - ./echo [SHORT-OPTION]... [STRING]... - ./echo LONG-OPTION - -Echo the STRING(s) to standard output. - -Options: - -n do not output the trailing newline - -h --help display this help and exit - -V --version output version information and exit - -$ ./echo --version -echo version: 1.0.0 -$ ./echo Hello, World! -Hello, World! -``` - -This is a simplified version of the `echo` implementation by -[uutils](https://github.com/uutils/coreutils). - - -It is also possible to use *options* instead of *flags*, such that values can -be passed to the program: - -{testopt.rs} - -Here are some examples how the program behaves given different combinations of -arguments: - -``` -$ ./testopt -a=false, b=false, c="" -$ ./testopt -a -b -a=true, b=true, c="" -$ ./testopt -ab -a=true, b=true, c="" -$ ./testopt -c -Argument to option 'c' missing. -$ ./testopt -c value -a=false, b=false, c="value" -$ ./testopt -c=value -a=false, b=false, c="=value" -$ ./testopt -cvalue -a=false, b=false, c="value" -$ ./testopt arg -a=false, b=false, c="" -free arguments: [arg] -$ ./testopt -a arg -a=true, b=false, c="" -free arguments: [arg] -$ ./testopt -c value arg -a=false, b=false, c="value" -free arguments: [arg] -$ ./testopt -a -- -b -a=true, b=false, c="" -free arguments: [-b] -$ ./testopt -a - -a=true, b=false, c="" -free arguments: [-] -``` diff --git a/examples/staging/arg/getopts/test.sh b/examples/staging/arg/getopts/test.sh deleted file mode 100644 index 9beb289f1d..0000000000 --- a/examples/staging/arg/getopts/test.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/sh -# Generate the example output for input.md. - -function run { - echo '$' $1 - $1 -} - -run './testopt' -run './testopt -a -b' -run './testopt -ab' -run './testopt -c' -run './testopt -c value' -run './testopt -c=value' -run './testopt -cvalue' -run './testopt arg' -run './testopt -a arg' -run './testopt -c value arg' -run './testopt -a -- -b' -run './testopt -a -' diff --git a/examples/staging/arg/getopts/testopt.rs b/examples/staging/arg/getopts/testopt.rs deleted file mode 100644 index da488d249b..0000000000 --- a/examples/staging/arg/getopts/testopt.rs +++ /dev/null @@ -1,38 +0,0 @@ -extern crate getopts; - -use std::os; - -fn main() { - let args = os::args(); - let opts = [ - getopts::optflag("a", "long_a", ""), - getopts::optflag("b", "long_b", ""), - getopts::optopt("c", "long_c", "", "VALUE"), - //^ Use `optflagopt` if the argument should be optional. - // Use `reqopt` if the option is required. - // Use `optmulti`, `optflagmulti` if options can occur multiple times. - ]; - - let matches = match getopts::getopts(args.tail(), &opts) { - Ok(m) => m, - Err(f) => { - println!("{}", f); - os::set_exit_status(1); - return; - } - }; - let a = if matches.opt_present("a") {true} else {false}; - let b = if matches.opt_present("b") {true} else {false}; - let c = match matches.opt_str("c") { - Some(s) => s, - None => String::from_str(""), - }; - //^ Use `matches.opt_default` if you need a default (`opflagopt`). - // Use `matches.opt_count` if you need to count how many were matched - // (`*multi`). - - println!("a={}, b={}, c=\"{}\"", a, b, c); - if !matches.free.is_empty() { - println!("free arguments: {}", matches.free); - } -} diff --git a/examples/staging/arg/input.md b/examples/staging/arg/input.md deleted file mode 100644 index 8a2f0a2c06..0000000000 --- a/examples/staging/arg/input.md +++ /dev/null @@ -1,10 +0,0 @@ -The command line arguments can be accessed using `std::os::args`, which returns -a [vector](http://static.rust-lang.org/doc/master/std/vec/index.html) of strings: - -{args.play} - -``` -$ ./args 1 2 3 -My path is ./args. -I got 3 arguments: [1, 2, 3]. -``` diff --git a/examples/staging/arg/matching/input.md b/examples/staging/arg/matching/input.md deleted file mode 100644 index 0d97b55a57..0000000000 --- a/examples/staging/arg/matching/input.md +++ /dev/null @@ -1,30 +0,0 @@ -Matching can be used to parse simple arguments: - -{match_args.play} - -``` -$ ./match_args Rust -This is not the answer. -$ ./match_args 42 -This is the answer! -$ ./match_args do something -error: second argument not an integer -usage: -match_args - Check whether given string is the answer. -match_args {increase|decrease} - Increase or decrease given integer by one. -$ ./match_args do 42 -error: invalid command -usage: -match_args - Check whether given string is the answer. -match_args {increase|decrease} - Increase or decrease given integer by one. -$ ./match_args increase 42 -43 -``` - - -For implementing more complicated, unix-like command line interfaces see the `getopts` example. - diff --git a/examples/staging/arg/matching/match_args.rs b/examples/staging/arg/matching/match_args.rs deleted file mode 100644 index 037f1cab9f..0000000000 --- a/examples/staging/arg/matching/match_args.rs +++ /dev/null @@ -1,64 +0,0 @@ -use std::os; - -fn increase(number: int) { - println!("{}", number + 1); -} - -fn decrease(number: int) { - println!("{}", number - 1); -} - -fn help() { - println!("usage: -match_args - Check whether given string is the answer. -match_args {{increase|decrease}} - Increase or decrease given integer by one."); -} - -fn main() { - let args = os::args(); - - match args.as_slice() { - // no arguments passed - [ref name] => { - println!("My name is '{}'. Try passing some arguments!", name); - }, - // one argument passed - [_, ref string] => { - if string.as_slice() == "42" { - println!("This is the answer!"); - } else { - println!("This is not the answer."); - } - }, - // one command and one argument passed - [_, ref cmd, ref num] => { - // parse the number - let number: int = match from_str(num.as_slice()) { - Some(n) => { - n - }, - None => { - println!("error: second argument not an integer"); - help(); - return; - }, - }; - // parse the command - match cmd.as_slice() { - "increase" => increase(number), - "decrease" => decrease(number), - _ => { - println!("error: invalid command"); - help(); - }, - } - }, - // all the other cases - _ => { - // show a help message - help(); - } - } -} diff --git a/examples/staging/bench/bench.rs b/examples/staging/bench/bench.rs deleted file mode 100644 index dbcd4fc78d..0000000000 --- a/examples/staging/bench/bench.rs +++ /dev/null @@ -1,52 +0,0 @@ -extern crate test; - -use std::mem::replace; -use test::Bencher; - -// bench: find the `BENCH_SIZE` first terms of the fibonacci sequence -static BENCH_SIZE: uint = 20; - -// recursive fibonacci -fn fibonacci(n: uint) -> uint { - if n < 2 { - 1 - } else { - fibonacci(n - 1) + fibonacci(n - 2) - } -} - -// iterative fibonacci -struct Fibonacci { - curr: uint, - next: uint, -} - -impl Iterator for Fibonacci { - fn next(&mut self) -> Option { - let new_next = self.curr + self.next; - let new_curr = replace(&mut self.next, new_next); - - Some(replace(&mut self.curr, new_curr)) - } -} - -fn fibonacci_sequence() -> Fibonacci { - Fibonacci { curr: 1, next: 1 } -} - -// function to benchmark must be annotated with `#[bench]` -#[bench] -fn recursive_fibonacci(b: &mut Bencher) { - // exact code to benchmark must be passed as a closure to the iter - // method of Bencher - b.iter(|| { - range(0, BENCH_SIZE).map(fibonacci).collect::>() - }) -} - -#[bench] -fn iterative_fibonacci(b: &mut Bencher) { - b.iter(|| { - fibonacci_sequence().take(BENCH_SIZE).collect::>() - }) -} diff --git a/examples/staging/bench/input.md b/examples/staging/bench/input.md deleted file mode 100644 index 20c5e6517c..0000000000 --- a/examples/staging/bench/input.md +++ /dev/null @@ -1,17 +0,0 @@ -Rust provides infrastructure for benchmarking via the `Bencher` struct and -the `#[bench]` attribute. Details in the source code below. - -{bench.rs} - -The source needs to be compiled using the `--test` flag, and the `--bench` flag -must be passed to the resulting binary. - -``` bash -$ rustc --test -O bench.rs -$ ./bench --bench -running 2 tests -test iterative_fibonacci ... bench: 191 ns/iter (+/- 16) -test recursive_fibonacci ... bench: 49670 ns/iter (+/- 522) - -test result: ok. 0 passed; 0 failed; 0 ignored; 2 measured -``` diff --git a/examples/staging/comment/comment.rs b/examples/staging/comment/comment.rs deleted file mode 100644 index 4f291b934f..0000000000 --- a/examples/staging/comment/comment.rs +++ /dev/null @@ -1,14 +0,0 @@ -fn main() { - // This is an example of a line comment - // Notice how there are two slashes at the beginning of the line - // And that anything written inside these will not be read by the compiler - - // println!("Hello, world!"); - - // Run it. See? Now try deleting the two slashes, and run it again. - - /* - * This is another type of comment, the block comment. It's not used - * in Rust very often, and is against the Rust Style Guide. - */ -} diff --git a/examples/staging/comment/doc-comment/doc-comment.rs b/examples/staging/comment/doc-comment/doc-comment.rs deleted file mode 100644 index 2f912e9ba9..0000000000 --- a/examples/staging/comment/doc-comment/doc-comment.rs +++ /dev/null @@ -1,39 +0,0 @@ -/// A human being is represented here -pub struct Person { - /// A person must have a name, no matter how much Juliet may hate it - name: String, -} - -impl Person { - /// Returns a person with the name given them - /// - /// # Arguments - /// - /// * `name` - A string slice that holds the name of the person - /// - /// # Example - /// - /// ``` - /// // You can have rust code between fences inside the comments - /// // If you pass --test to Rustdoc, it will even test it for you! - /// let person = Person::new("name"); - /// ``` - pub fn new(name: &str) -> Person { - Person { - name: name.to_string(), - } - } - - /// Gives a friendly hello! - /// - /// Says "Hello, [name]" to the `Person` it is called on. - pub fn hello(& self) { - println!("Hello, {}!", self.name); - } -} - -fn main() { - let john = Person::new("John"); - - john.hello(); -} diff --git a/examples/staging/comment/doc-comment/input.md b/examples/staging/comment/doc-comment/input.md deleted file mode 100644 index 2e5e1515ac..0000000000 --- a/examples/staging/comment/doc-comment/input.md +++ /dev/null @@ -1,8 +0,0 @@ -Doc comments are very useful for big projects that require documentation. When -running [Rustdoc][1], these are the comments that get compiled into -documentation. They are denoted by a `///`, and support [Markdown][2]. - -{doc-comment.play} - -[1]: https://github.com/rust-lang/rust/blob/master/src/doc/rustdoc.md -[2]: https://en.wikipedia.org/wiki/Markdown diff --git a/examples/staging/comment/input.md b/examples/staging/comment/input.md deleted file mode 100644 index 273ef7734b..0000000000 --- a/examples/staging/comment/input.md +++ /dev/null @@ -1,11 +0,0 @@ -Comments are a necessary part of any serious program, and most non-serious -programs as well. - -There are two ways to write comments in Rust, "block" (`/**/`) and "line" -(`//`). However, the [Rust style guide][2] recommends only using the second. -There are also "Doc" comments, used for documentation. - -{comment.play} - -[1]: https://github.com/rust-lang/rust/blob/master/src/doc/rustdoc.md -[2]: https://aturon.github.io/style/comments.html diff --git a/examples/staging/ffi/ffi.rs b/examples/staging/ffi/ffi.rs deleted file mode 100644 index 7f0aa11ff9..0000000000 --- a/examples/staging/ffi/ffi.rs +++ /dev/null @@ -1,39 +0,0 @@ -use std::fmt; - -// this extern block links to the libm library -#[link(name = "m")] -extern { - // this is a foreign function - // that computes the square root of a single precision complex number - fn csqrtf(z: Complex) -> Complex; -} - -fn main() { - // z = -1 + 0i - let z = Complex { re: -1., im: 0. }; - - // calling a foreign function is an unsafe operation - let z_sqrt = unsafe { - csqrtf(z) - }; - - println!("the square root of {} is {}", z, z_sqrt); -} - -// Minimal implementation of single precision complex numbers -#[repr(C)] -#[deriving(Copy)] -struct Complex { - re: f32, - im: f32, -} - -impl fmt::Show for Complex { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if self.im < 0. { - write!(f, "{}-{}i", self.re, -self.im) - } else { - write!(f, "{}+{}i", self.re, self.im) - } - } -} diff --git a/examples/staging/ffi/input.md b/examples/staging/ffi/input.md deleted file mode 100644 index c68369df39..0000000000 --- a/examples/staging/ffi/input.md +++ /dev/null @@ -1,14 +0,0 @@ -Rust provides a Foreign Function Interface (FFI) to C libraries. Foreign -functions must be declared inside an `extern` block annotated with a `#[link]` -attribute containing the name of the foreign library. - -{ffi.rs} - -{ffi.out} - -Since calling foreign functions is considered unsafe, it's common to write safe -wrappers around them. - -{safe.rs} - -{safe.out} diff --git a/examples/staging/ffi/safe.rs b/examples/staging/ffi/safe.rs deleted file mode 100644 index f089733209..0000000000 --- a/examples/staging/ffi/safe.rs +++ /dev/null @@ -1,36 +0,0 @@ -use std::fmt; - -#[link(name = "m")] -extern { - fn ccosf(z: Complex) -> Complex; -} - -// safe wrapper -fn cos(z: Complex) -> Complex { - unsafe { ccosf(z) } -} - -fn main() { - // z = 0 + 1i - let z = Complex { re: 0., im: 1. }; - - println!("cos({}) = {}", z, cos(z)); -} - -// Minimal implementation of single precision complex numbers -#[repr(C)] -#[deriving(Copy)] -struct Complex { - re: f32, - im: f32, -} - -impl fmt::Show for Complex { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if self.im < 0. { - write!(f, "{}-{}i", self.re, -self.im) - } else { - write!(f, "{}+{}i", self.re, self.im) - } - } -} diff --git a/examples/staging/fmt/input.md b/examples/staging/fmt/input.md deleted file mode 100644 index 4929ac063f..0000000000 --- a/examples/staging/fmt/input.md +++ /dev/null @@ -1,35 +0,0 @@ -We've seen that formatting is specified via a *format string*: - -* `format!("{}", foo)` -> `"3735928559"` -* `format!("0x{:X}", foo)` -> - [`"0xDEADBEEF"`][deadbeef] -* `format!("0o{:o}", foo)` -> `"0o33653337357"` - -The same variable (`foo`) can be formatted differently depending on which -*argument type* is used: `X` vs `o` vs *unspecified*. - -This formatting functionality is implemented via traits, and there is one trait -for each argument type. The most common formatting trait is `Show`, which -handles cases where the argument type is left unspecified: `{}` for instance. - -{show.play} - -Here's the full list of formatting traits and their respective argument types: - -* *unspecified* -> `Show` -* `d` and `i` -> `Signed` -* `u` -> `Unsigned` -* `b` -> `Bool` -* `c` -> `Char` -* `o` -> `Octal` -* `x` -> `LowerHex` -* `X` -> `UpperHex` -* `s` -> `String` -* `p` -> `Pointer` -* `t` -> `Binary` -* `f` -> `Float` -* `e` -> `LowerExp` -* `E` -> `UpperExp` -* `?` -> `Poly` - -[deadbeef]: https://en.wikipedia.org/wiki/Deadbeef#Magic_debug_values diff --git a/examples/staging/fmt/show.rs b/examples/staging/fmt/show.rs deleted file mode 100644 index 4dee713351..0000000000 --- a/examples/staging/fmt/show.rs +++ /dev/null @@ -1,35 +0,0 @@ -use std::fmt::{mod,Formatter,Show}; -// For .abs() -use std::num::Float; - -struct City { - name: &'static str, - // Latitude - lat: f32, - // Longitude - lon: f32, -} - -impl Show for City { - // `f` is a buffer, this method must write the formatted string into it - fn fmt(&self, f: &mut Formatter) -> fmt::Result { - let lat_c = if self.lat >= 0.0 { 'N' } else { 'S' }; - let lon_c = if self.lon >= 0.0 { 'E' } else { 'W' }; - - // `write!` is like `format!`, but it will write the formatted string - // into a buffer (the first argument) - write!(f, "{}: {:.3}°{} {:.3}°{}", - self.name, self.lat.abs(), lat_c, self.lon.abs(), lon_c) - } -} - -fn main() { - for city in [ - City { name: "Dublin", lat: 53.347778, lon: -6.259722 }, - City { name: "Oslo", lat: 59.95, lon: 10.75 }, - City { name: "Vancouver", lat: 49.25, lon: -123.1 }, - ].iter() { - println!("{}", city); - } -} - diff --git a/examples/staging/hash/alt-key-types/alt-key-types.rs b/examples/staging/hash/alt-key-types/alt-key-types.rs deleted file mode 100644 index fb5fdce145..0000000000 --- a/examples/staging/hash/alt-key-types/alt-key-types.rs +++ /dev/null @@ -1,56 +0,0 @@ -use std::collections::HashMap; - -// Eq requires that you derive PartialEq on the type. -#[deriving(PartialEq, Eq, Hash)] -struct Account<'a>{ - username: &'a str, - password: &'a str, -} - -struct AccountInfo<'a>{ - name: &'a str, - email: &'a str, -} - -type Accounts<'a> = HashMap, AccountInfo<'a>>; - -fn try_logon<'a>(accounts: &Accounts<'a>, - username: &'a str, password: &'a str){ - println!("Username: {}", username); - println!("Password: {}", password); - println!("Attempting logon..."); - - let logon = Account { - username: username, - password: password, - }; - - match accounts.get(&logon) { - Some(account_info) => { - println!("Successful logon!"); - println!("Name: {}", account_info.name); - println!("Email: {}", account_info.email); - }, - _ => println!("Login failed!"), - } -} - -fn main(){ - let mut accounts: Accounts = HashMap::new(); - - let account = Account { - username: "j.everyman", - password: "password123", - }; - - let account_info = AccountInfo { - name: "John Everyman", - email: "j.everyman@email.com", - }; - - accounts.insert(account, account_info); - - try_logon(&accounts, "j.everyman", "psasword123"); - - try_logon(&accounts, "j.everyman", "password123"); -} diff --git a/examples/staging/hash/alt-key-types/input.md b/examples/staging/hash/alt-key-types/input.md deleted file mode 100644 index af43d97438..0000000000 --- a/examples/staging/hash/alt-key-types/input.md +++ /dev/null @@ -1,32 +0,0 @@ -Any type that implements the `Eq` and `Hash` traits can be a key in `HashMap`. -This includes: - -* `bool` (though not very useful since there is only two possible keys) -* `int`, `uint`, and all variations thereof -(see [`VecMap`][vecmap] for a more streamlined map implementation keyed by `uint`) -* `String` and `&str` (protip: you can have a `HashMap` keyed by `String` -and call `.get()` with an `&str`) - -Note that `f32` and `f64` do *not* implement `Hash`, -likely because [floating-point precision errors][floating] -would make using them as hashmap keys horribly error-prone. - -All collection classes implement `Eq` and `Hash` -if their contained type also respectively implements `Eq` and `Hash`. -For example, `Vec` will implement `Hash` if `T` implements `Hash`. - -You can easily implement `Eq` and `Hash` for a custom type with just one line: -`#[deriving(PartialEq, Eq, Hash)]` - -The compiler will do the rest. If you want more control over the details, -you can implement `Eq` and/or `Hash` yourself. -This guide will not cover the specifics of implementing `Hash`. - -To play around with using a `struct` in `HashMap`, -let's try making a very simple user logon system: - -{alt-key-types.play} - -[vecmap]: http://doc.rust-lang.org/std/collections/struct.VecMap.html -[hash]: http://en.wikipedia.org/wiki/Hash_function -[floating]: http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems diff --git a/examples/staging/hash/hashset/hashset.rs b/examples/staging/hash/hashset/hashset.rs deleted file mode 100644 index 3c7e82eefa..0000000000 --- a/examples/staging/hash/hashset/hashset.rs +++ /dev/null @@ -1,36 +0,0 @@ -use std::collections::HashSet; - -fn main() { - let mut a: HashSet = vec!(1i, 2, 3).into_iter().collect(); - let mut b: HashSet = vec!(2i, 3, 4).into_iter().collect(); - - assert!(a.insert(4)); - assert!(a.contains(&4)); - - // `HashSet::insert()` returns false if - // there was a value already present. - assert!(b.insert(4), "Value 4 is already in set B!"); - // FIXME ^ Comment out this line - - b.insert(5); - - // If a collection's element type implements `Show`, - // then the collection implements `Show`. - // It usually prints its elements in the format `[elem1, elem2, ...]` - println!("A: {}", a); - println!("B: {}", b); - - // Print [1, 2, 3, 4, 5] in arbitrary order - println!("Union: {}", a.union(&b).collect::>()); - - // This should print [1] - println!("Difference: {}", a.difference(&b).collect::>()); - - // Print [2, 3, 4] in arbitrary order. - println!("Intersection: {}", a.intersection(&b).collect::>()); - - // Print [1, 5] - println!("Symmetric Difference: {}", - a.symmetric_difference(&b).collect::>()); -} - diff --git a/examples/staging/hash/hashset/input.md b/examples/staging/hash/hashset/input.md deleted file mode 100644 index 535c43414b..0000000000 --- a/examples/staging/hash/hashset/input.md +++ /dev/null @@ -1,38 +0,0 @@ -Consider a `HashSet` as a `HashMap` where we just care about the keys ( -`HashSet` is, in actuality, just a wrapper around `HashMap`). - -"What's the point of that?" you ask. "I could just store the keys in a `Vec`." - -A `HashSet`'s unique feature is that -it is guaranteed to not have duplicate elements. -That's the contract that any set collection fulfills. -`HashSet` is just one implementation. (see also: [`TreeSet`][treeset]) - -If you insert a value that is already present in the `HashSet`, -(i.e. the new value is equal to the existing and they both have the same hash), -then the new value will replace the old. - -This is great for when you never want more than one of something, -or when you want to know if you've already got something. - -But sets can do more than that. - -Sets have 4 primary operations (all of the following calls return an iterator): - -* `union`: get all the unique elements in both sets. - -* `difference`: get all the elements that are in the first set but not the second. - -* `intersection`: get all the elements that are only in *both* sets. - -* `symmetric_difference`: -get all the elements that are in one set or the other, but *not* both. - -Try all of these in the following example. - -{hashset.play} - -(Examples adapted from the [documentation.][hash-set]) - -[treeset]: http://doc.rust-lang.org/std/collections/struct.TreeSet.html -[hash-set]: http://doc.rust-lang.org/std/collections/hashmap/struct.HashSet.html#method.difference diff --git a/examples/staging/hash/input.md b/examples/staging/hash/input.md deleted file mode 100644 index 55dccb0aa2..0000000000 --- a/examples/staging/hash/input.md +++ /dev/null @@ -1,18 +0,0 @@ -Where vectors store values by an integer index, `HashMap`s store values by key. -`HashMap` keys can be booleans, integers, strings, -or any other type that implements the `Eq` and `Hash` traits. -More on this in the next section. - -Like vectors, `HashMap`s are growable, but HashMaps can also shrink themselves -when they have excess space. -You can create a HashMap with a certain starting capacity using -`HashMap::with_capacity(uint)`, or use `HashMap::new()` to get a HashMap -with a default initial capacity (recommended). - -{hash.play} - -For more information on how hashing and hash maps -(sometimes called hash tables) work, have a look at -[Wikipedia][wiki-hash] - -[wiki-hash]: (http://en.wikipedia.org/wiki/Hash_table) diff --git a/examples/staging/input.md b/examples/staging/input.md deleted file mode 100644 index cfeef30906..0000000000 --- a/examples/staging/input.md +++ /dev/null @@ -1,3 +0,0 @@ -The chapters in this section are being worked on. These chapters are likely to -contain valid information, but may be unsorted or some of the concepts used -in them may have not been explained yet. diff --git a/examples/staging/json/decodable/decodable.rs b/examples/staging/json/decodable/decodable.rs deleted file mode 100644 index d4f6cbef9a..0000000000 --- a/examples/staging/json/decodable/decodable.rs +++ /dev/null @@ -1,48 +0,0 @@ -extern crate serialize; - -use serialize::{json, Decodable}; - -#[deriving(Decodable)] -struct City { - name: String, - // Latitude - lat: f32, - // Longitude - lon: f32, -} - -fn main() { - for &json_str in [ - r#"{"name": "Cape Town", "lat": -33.925, "lon": 18.424}"#, - - // Any extra fields will be ignored: - r#"{"name": "Tokyo", "country": "Japan", "lat": -33.925, - "lon": 18.424}"#, - - // However, a missing field will cause an error: - r#"{"lat": -33.86, "lon": 151.209}"#, - // FIXME ^ fill in the missing field: "name": "Sydney" - ].iter() { - let json_object = match json::from_str(json_str) { - Ok(json) => json, - Err(err) => { - println!("json::from_str: {}", err); - continue; - }, - }; - - // A `Decoder` object is created based on the `json_object` - // using which a `City` struct can be decoded: - let mut decoder = json::Decoder::new(json_object); - let city: City = match Decodable::decode(&mut decoder) { - Ok(city) => city, - Err(err) => { - println!("Decodable::decode: {}", err); - continue; - }, - }; - - println!("City: {} ({:.2}° N, {:.2}° E)", - city.name, city.lat, city.lon); - } -} diff --git a/examples/staging/json/decodable/input.md b/examples/staging/json/decodable/input.md deleted file mode 100644 index 80f895e5e5..0000000000 --- a/examples/staging/json/decodable/input.md +++ /dev/null @@ -1,13 +0,0 @@ -`serialize::Decodable` is a trait implemented for types to make them decodable -by the `serialize` module. - -To deserialize a type from a `Json` enum, a `serialize::json::Decoder` is first -created for this `Json`. It can then be used to decode data into `Decodable`s. - -To make this task easier, `Decodable` can be automatically derived for a struct -using `#[deriving(Decodable)]`. This creates a default implementation -in which key-value pairs of a JSON object are mapped to -fields of a `struct`. The keys are expected to have exactly the same -names as the `struct` fields, including case. - -{decodable.play} diff --git a/examples/staging/json/encodable/encodable.rs b/examples/staging/json/encodable/encodable.rs deleted file mode 100644 index c6be8b8245..0000000000 --- a/examples/staging/json/encodable/encodable.rs +++ /dev/null @@ -1,23 +0,0 @@ -extern crate serialize; - -use serialize::{json, Encodable}; - -#[deriving(Encodable)] -struct City { - name: &'static str, - // Latitude - lat: f32, - // Longitude - lon: f32, -} - -fn main() { - for city in [ - City { name: "São Paulo", lat: -23.55, lon: -46.633333 }, - City { name: "Lima", lat: -12.043333, lon: -77.028333 }, - City { name: "Santiago", lat: -33.45, lon: -70.666667 }, - ].iter() { - // `encode` encodes an `Encodable` implementor into a `String` - println!("{}", json::encode(city)); - } -} diff --git a/examples/staging/json/encodable/input.md b/examples/staging/json/encodable/input.md deleted file mode 100644 index 18371ed423..0000000000 --- a/examples/staging/json/encodable/input.md +++ /dev/null @@ -1,9 +0,0 @@ -`serialize::Encodable` is a trait implemented for types to make them encodable -by the `serialize` module. - -`Encodable` types can be serialized into JSON using `json::encode`. - -Just like `Decodable`, `Encodable` can be automatically derived for a struct -using `#[deriving(Encodable)]`. - -{encodable.play} diff --git a/examples/staging/json/input.md b/examples/staging/json/input.md deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/examples/staging/json/json-enum/input.md b/examples/staging/json/json-enum/input.md deleted file mode 100644 index 1e9fd16c14..0000000000 --- a/examples/staging/json/json-enum/input.md +++ /dev/null @@ -1,6 +0,0 @@ -`serialize::json::Json` is an enum capable of containing all of the -JSON value types. It is Rust's way of representing JSON documents. - -`Json` can be decoded from a JSON string using `seralize::json::from_str`: - -{json-enum.play} diff --git a/examples/staging/json/json-enum/json-enum.rs b/examples/staging/json/json-enum/json-enum.rs deleted file mode 100644 index 811dd5c541..0000000000 --- a/examples/staging/json/json-enum/json-enum.rs +++ /dev/null @@ -1,21 +0,0 @@ -extern crate serialize; - -use serialize::json; - -fn main() { - for &json_str in [ - // Valid JSON - r#"{"name": "London", "lat": 51.507222, "lon": -0.1275}"#, - - // Not a valid JSON, will produce an error - r#"{"name": "Prague" "lat": 50.082542, "lon": 14.425992}"#, - // FIXME ^ a comma is missing here - ].iter() { - // `from_str` decodes JSON from a string and returns a `Result` - // containing either a `Json` enum or an error - match json::from_str(json_str) { - Ok(json) => println!("json::from_str(): {}", json), - Err(err) => println!("json::from_str(): {}", err), - }; - } -} diff --git a/examples/staging/macros/designators.rs b/examples/staging/macros/designators.rs deleted file mode 100644 index 0b88855b19..0000000000 --- a/examples/staging/macros/designators.rs +++ /dev/null @@ -1,41 +0,0 @@ -#![feature(macro_rules)] - -macro_rules! create_function { - // this macro takes an argument of "type" `ident` - // the `ident` designator is used for variable/function names - ($func_name:ident) => { - // this macro creates a function with name `$func_name` - fn $func_name() { - // the stringify! macro converts an `ident` into a string - println!("You called {}()", - stringify!($func_name)) - } - } -} - -create_function!(foo) -create_function!(bar) - -macro_rules! print_result { - // the `expr` designator is used for expressions - ($expression:expr) => { - // stringify! will convert the expression *as it is* into a string - println!("{} = {}", - stringify!($expression), - $expression) - } -} - -fn main() { - foo(); - bar(); - - print_result!(1u + 1); - - // remember that blocks are expressions - print_result!({ - let x = 1u; - - x * x + 2 * x - 1 - }); -} diff --git a/examples/staging/macros/dry.rs b/examples/staging/macros/dry.rs deleted file mode 100644 index 20ea95add8..0000000000 --- a/examples/staging/macros/dry.rs +++ /dev/null @@ -1,61 +0,0 @@ -#![feature(macro_rules)] - -macro_rules! assert_equal_len { - ($a:ident, $b: ident, $func:ident, $op:tt) => { - assert!($a.len() == $b.len(), - "{}: dimension mismatch: {} {} {}", - stringify!($func), - ($a.len(),), - stringify!($op), - ($b.len(),)); - } -} - -macro_rules! op { - ($func:ident, $bound:ident, $op:tt, $method:ident) => { - fn $func>(xs: &mut Vec, ys: &Vec) { - assert_equal_len!(xs, ys, $func, $op); - - for (x, y) in xs.iter_mut().zip(ys.iter()) { - *x = x.$method(y); - } - } - } -} - -// implement add_assign, mul_assign, and sub_assign functions -op!(add_assign, Add, +=, add) -op!(mul_assign, Mul, *=, mul) -op!(sub_assign, Sub, -=, sub) - -fn main() { - let mut xs = Vec::from_elem(5, 0f64); - let ys = Vec::from_elem(6, 1f64); - - // this operation will fail at runtime - add_assign(&mut xs, &ys); -} - -mod test { - macro_rules! test { - ($func: ident, $x:expr, $y:expr, $z:expr) => { - #[test] - fn $func() { - for size in range(0u, 10) { - let mut x = Vec::from_elem(size, $x); - let y = Vec::from_elem(size, $y); - let z = Vec::from_elem(size, $z); - - super::$func(&mut x, &y); - - assert_eq!(x, z); - } - } - } - } - - // test add_assign, mul_assign and sub_assign - test!(add_assign, 1u, 2u, 3u) - test!(mul_assign, 2u, 3u, 6u) - test!(sub_assign, 3u, 2u, 1u) -} diff --git a/examples/staging/macros/input.md b/examples/staging/macros/input.md deleted file mode 100644 index 729882d652..0000000000 --- a/examples/staging/macros/input.md +++ /dev/null @@ -1,49 +0,0 @@ -Rust provides a powerful macro system that allows metaprogramming. As you've -seen in previous chapters, macros look like functions, except that their name -ends with a bang `!`, but instead of generating a function call, macros are -expanded into source code that gets compiled with the rest of the program. - -Macros are created using the `macro_rules!` macro. - -{simple.rs} - -{simple.out} - -The arguments of a macro are prefixed by a dollar sign `$` and type annotated -with a *designator*. - -{designators.rs} - -{designators.out} - -Macros can be overloaded to accept different combinations of arguments. - -{overload.rs} - -{overload.out} - -Macros can use `+` in the argument list, to indicate that an argument may -repeat at least once, or `*`, to indicate that the argument may repeat zero or -more times. - -{repeat.rs} - -{repeat.out} - -Macros allow writing DRY code, by factoring out the common parts of functions -and/or test suites. Here is an example that implements and tests the `+=`, `*=` -and `-=` operators on `Vec`. - -{dry.rs} - -{dry.out} - -``` -$ rustc --test dry.rs && ./dry -running 3 tests -test test::mul_assign ... ok -test test::add_assign ... ok -test test::sub_assign ... ok - -test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured -``` diff --git a/examples/staging/macros/overload.rs b/examples/staging/macros/overload.rs deleted file mode 100644 index e1e04b20fe..0000000000 --- a/examples/staging/macros/overload.rs +++ /dev/null @@ -1,25 +0,0 @@ -#![feature(macro_rules)] - -// macro_rules! is similar to a match block -macro_rules! test { - // the arguments don't need to be separated by a comma - // any template can be used - ($left:expr and $right:expr) => { - println!("{} and {} is {}", - stringify!($left), - stringify!($right), - $left && $right) - }; - // ^ each arm must be ended with a semicolon - ($left:expr or $right:expr) => { - println!("{} or {} is {}", - stringify!($left), - stringify!($right), - $left || $right) - }; -} - -fn main() { - test!(1i + 1 == 2i and 2i * 2 == 4i); - test!(true or false); -} diff --git a/examples/staging/macros/repeat.rs b/examples/staging/macros/repeat.rs deleted file mode 100644 index dbe6258b2e..0000000000 --- a/examples/staging/macros/repeat.rs +++ /dev/null @@ -1,20 +0,0 @@ -#![feature(macro_rules)] - -// min! will calculate the minimum of any number of arguments -macro_rules! min { - // base case - ($x:expr) => { - $x - }; - // `$x` followed by at least one `$y,` - ($x:expr, $($y:expr),+) => { - // call min! on the tail `$y` - std::cmp::min($x, min!($($y),+)) - } -} - -fn main() { - println!("{}", min!(1u)); - println!("{}", min!(1u + 2 , 2u)); - println!("{}", min!(5u, 2u * 3, 4u)); -} diff --git a/examples/staging/macros/simple.rs b/examples/staging/macros/simple.rs deleted file mode 100644 index 648bc07295..0000000000 --- a/examples/staging/macros/simple.rs +++ /dev/null @@ -1,16 +0,0 @@ -// macros are behind a feature gate -#![feature(macro_rules)] - -// This is the simplest macro, `say_hello` is the name of the macro -macro_rules! say_hello { - // `()` indicates that the macro takes no argument - () => { - // the macro will expand into the contents of this block - println!("Hello!"); - } -} - -fn main() { - // this call will expand into `println!("Hello");` - say_hello!() -} diff --git a/examples/staging/rand/deriving.rs b/examples/staging/rand/deriving.rs deleted file mode 100644 index 809b7bf9e8..0000000000 --- a/examples/staging/rand/deriving.rs +++ /dev/null @@ -1,21 +0,0 @@ -use std::rand; -use std::rand::Rng; - -#[deriving(Rand,Show)] -struct Point { - x: f64, - y: f64, -} - -#[deriving(Rand,Show)] -struct Rectangle { - p1: Point, - p2: Point, -} - -fn main() { - let mut rng = rand::task_rng(); - - println!("random point\n{}", rng.gen::()); - println!("random rectangle\n{}", rng.gen::()); -} diff --git a/examples/staging/rand/distributions.rs b/examples/staging/rand/distributions.rs deleted file mode 100644 index e1021d5fa5..0000000000 --- a/examples/staging/rand/distributions.rs +++ /dev/null @@ -1,18 +0,0 @@ -use std::rand::distributions::{IndependentSample,Normal,StudentT}; -use std::rand; - -fn main() { - let mut rng = rand::task_rng(); - - let normal = Normal::new(0.0, 1.0); - println!("10 samples from a normal distribution with mean 0.0 and SD 1.0"); - for _ in range(0u, 10) { - println!("{}", normal.ind_sample(&mut rng)); - } - - let student = StudentT::new(5.0); - println!("10 samples from a T distribution with 5 degrees of freedom"); - for _ in range(0u, 10) { - println!("{}", student.ind_sample(&mut rng)); - } -} diff --git a/examples/staging/rand/gen.rs b/examples/staging/rand/gen.rs deleted file mode 100644 index e599426892..0000000000 --- a/examples/staging/rand/gen.rs +++ /dev/null @@ -1,40 +0,0 @@ -use std::rand::Rng; -use std::rand; - -fn main() { - // create a task-local Random Number Generator - let mut rng = rand::task_rng(); - - // the `gen` methods generates values in the full range of each type using - // a uniform distribution - println!("randomly generate some values for different primitive types"); - println!("u8: {}", rng.gen::()); - println!("i8: {}", rng.gen::()); - println!("u16: {}", rng.gen::()); - println!("i16: {}", rng.gen::()); - // except for floats which get generated in the range [0, 1> - println!("f32: {}", rng.gen::()); - println!("f64: {}", rng.gen::()); - - // `gen_iter` returns an iterator that yields a infinite number of randomly - // generated numbers - let mut v: Vec = rng.gen_iter::().take(10).collect(); - - println!("10 randomly generated u8 values"); - println!("{}", v.as_slice()); - - // `shuffle` shuffles a mutable slice in place - rng.shuffle(v.as_mut_slice()); - println!("shuffle previous slice"); - println!("{}", v.as_slice()); - - // `choose` will sample an slice *with* replacement - // i.e. the same element can be chosen more than one time - println!("sample previous slice *with* replacement 10 times"); - for _ in range(0u, 10) { - match rng.choose(v.as_slice()) { - None => panic!("slice was empty"), - Some(x) => println!("{}", x), - } - } -} diff --git a/examples/staging/rand/input.md b/examples/staging/rand/input.md deleted file mode 100644 index 76419077f1..0000000000 --- a/examples/staging/rand/input.md +++ /dev/null @@ -1,22 +0,0 @@ -The `std::rand` module provides access to the Random Number Generators (RNG) -provided by the OS, which can then be used to generate random values of any -type that implements the `Rand` trait (which includes all the primitive types). - -{gen.rs} - -{gen.out} - -Several structs are available under the `std::rand::distributions` module, that -can be used to generate values using different probability distributions like: -normal, uniform, Student's T, Chi squared, Gamma, etc. - -{distributions.rs} - -{distributions.out} - -The `deriving` attribute can be used to implement the `Rand` trait for custom -types, this allows generation of random values of custom types. - -{deriving.rs} - -{deriving.out} diff --git a/examples/staging/simd/input.md b/examples/staging/simd/input.md deleted file mode 100644 index b58c4e2e98..0000000000 --- a/examples/staging/simd/input.md +++ /dev/null @@ -1,25 +0,0 @@ -Rust provides experimental support for SIMD vectors. These SIMD vectors are -exposed as structs (`f32x4`, `u8x16`, etc.), that implement basic operations -(`+`, `-`, `*`, etc) using SIMD instructions under the hood. - -{simd.rs} - -{simd.out} - -Here's a more complex example that sums two `Vec`, using the `f32x4` type -to operate on 4-element chunks at a time. - -{simd_add.rs} - -And here's the result of the benchmark: - -``` -$ rustc -O --test simd_add.rs && ./simd_add --bench -running 4 tests -test test::simd ... ignored -test test::vanilla ... ignored -test bench::simd ... bench: 1852 ns/iter (+/- 17) -test bench::vanilla ... bench: 8346 ns/iter (+/- 103) - -test result: ok. 0 passed; 0 failed; 2 ignored; 2 measured -``` diff --git a/examples/staging/simd/simd.rs b/examples/staging/simd/simd.rs deleted file mode 100644 index e702374f13..0000000000 --- a/examples/staging/simd/simd.rs +++ /dev/null @@ -1,15 +0,0 @@ -use std::simd::f32x4; - -fn main() { - // create simd vectors - let x = f32x4(1.0, 2.0, 3.0, 4.0); - let y = f32x4(4.0, 3.0, 2.0, 1.0); - - // simd product - let z = x * y; - - // like any struct, the simd vector can be destructured using `let` - let f32x4(a, b, c, d) = z; - - println!("{}", (a, b, c, d)); -} diff --git a/examples/staging/simd/simd_add.rs b/examples/staging/simd/simd_add.rs deleted file mode 100644 index 8c154a8aaf..0000000000 --- a/examples/staging/simd/simd_add.rs +++ /dev/null @@ -1,76 +0,0 @@ -#![feature(macro_rules)] - -use std::simd::f32x4; - -macro_rules! assert_equal_len { - ($a:ident, $b: ident) => { - assert!($a.len() == $b.len(), - "add_assign: dimension mismatch: {} += {}", - ($a.len(),), - ($b.len(),)); - } -} - -// element-wise addition -fn add_assign(xs: &mut Vec, ys: &Vec) { - assert_equal_len!(xs, ys); - - for (x, y) in xs.iter_mut().zip(ys.iter()) { - *x += *y; - } -} - -// simd accelerated addition -fn simd_add_assign(xs: &mut Vec, ys: &Vec) { - assert_equal_len!(xs, ys); - - let size = xs.len() as int; - let chunks = size / 4; - - // pointer to the start of the vector data - let p_x: *mut f32 = xs.as_mut_ptr(); - let p_y: *const f32 = ys.as_ptr(); - - // sum excess elements that don't fit in the simd vector - for i in range(4 * chunks, size) { - // dereferencing a raw pointer requires an unsafe block - unsafe { - // offset by i elements - *p_x.offset(i) += *p_y.offset(i); - } - } - - // treat f32 vector as an simd f32x4 vector - let simd_p_x = p_x as *mut f32x4; - let simd_p_y = p_y as *const f32x4; - - // sum "simd vector" - for i in range(0, chunks) { - unsafe { - *simd_p_x.offset(i) += *simd_p_y.offset(i); - } - } -} - -mod bench { - extern crate test; - use self::test::Bencher; - static BENCH_SIZE: uint = 10_000; - - macro_rules! bench { - ($name:ident, $func:ident) => { - #[bench] - fn $name(b: &mut Bencher) { - let mut x = Vec::from_elem(BENCH_SIZE, 1.0f32); - let y = Vec::from_elem(BENCH_SIZE, 0.1f32); - - b.iter(|| { - super::$func(&mut x, &y); - }) - } - } - } - - bench!(vanilla, add_assign) - bench!(simd, simd_add_assign) -} diff --git a/examples/staging/test/fail.rs b/examples/staging/test/fail.rs deleted file mode 100644 index f90df143c6..0000000000 --- a/examples/staging/test/fail.rs +++ /dev/null @@ -1,5 +0,0 @@ -#[test] -#[should_fail] -fn failing_test() { - assert!(1i == 2i); -} diff --git a/examples/staging/test/input.md b/examples/staging/test/input.md deleted file mode 100644 index ecbaa0d715..0000000000 --- a/examples/staging/test/input.md +++ /dev/null @@ -1,36 +0,0 @@ -To mark a function as a unit test, place `#[test]` (equivalent -to `#[cfg(test)]`) above any function. The function must take -no parameters and return nothing. - -{unit-test.rs} - -If you want the test to fail, just put `#[should_fail]` under `#[test]`. - -{fail.rs} - -To run unit tests, add either the `--test` or `--cfg test` flag to the -command. When using either flag, you do not need a `main()` function -as the executable will only include and run the functions flagged with -`#[test]` or `#[cfg(test)]`. If you don't pass the `--test` flag, `rustc` will -ignore any functions flagged with `#[test]`. That means calling any function -flagged with `#[test]` will result in `rustc: unresolved name` if it is not -compiled with `--test`. - -**note**: programs compiled with `--test` *ignore* information passed to stdout - -``` -$ rustc --test unit-test.rs -$ ./unit-test -running 1 test -test distance_test ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured -``` - -If `--test` were not included, then this would happen - -``` -$ rustc unit-test.rs -$ ./unit-test -If you see this, the tests were not compiled nor ran! -``` \ No newline at end of file diff --git a/examples/staging/test/unit-test.rs b/examples/staging/test/unit-test.rs deleted file mode 100644 index 14a9ff7f03..0000000000 --- a/examples/staging/test/unit-test.rs +++ /dev/null @@ -1,19 +0,0 @@ -// For .powi() -use std::num::Float; - - -fn distance(a: (f32, f32), b: (f32, f32)) -> f32 { - ( - (b.val0().powi(2) - a.val0().powi(2)) + - (b.val1().powi(2) - a.val1().powi(2)) - ).sqrt() -} - -fn main() { - println!("If you see this, the tests were not compiled nor ran!"); -} - -#[test] -fn distance_test() { - assert!(distance((0f32, 0f32), (1f32, 1f32)) == (2f32).sqrt()); -} diff --git a/examples/staging/unsafe/asm.rs b/examples/staging/unsafe/asm.rs deleted file mode 100644 index bc34dd086c..0000000000 --- a/examples/staging/unsafe/asm.rs +++ /dev/null @@ -1,9 +0,0 @@ -#![feature(asm)] - -fn add(a: i32, b: i32) -> i32 { - let sum: i32; - unsafe { - asm!("add $2, $1; mov $1, $0" : "=r"(sum) : "r"(a), "r"(b)); - } - sum -} diff --git a/examples/staging/unsafe/input.md b/examples/staging/unsafe/input.md deleted file mode 100644 index eb4c828b24..0000000000 --- a/examples/staging/unsafe/input.md +++ /dev/null @@ -1,42 +0,0 @@ -As an introduction to this section, to borrow from [the official docs]( -http://doc.rust-lang.org/master/guide-unsafe.html), "one should try to -minimize the amount of unsafe code in a code base." With that in mind, let's -get started! -Unsafe blocks in Rust are used to bypass protections put in place by the -compiler; specifically, there are four primary things that unsafe blocks are -used for: - -* dereferencing raw pointers -* calling a function over FFI (but this is covered in a different part of the - book) -* changing types through `std::cast::transmute` -* inline assembly - -### Raw Pointers -Raw pointers `*` and references `&T` function similarly, but references are -always safe because they are guaranteed to point to valid data due to the -borrow checker. Dereferencing a raw pointer can only be done through an unsafe -block. - -{pointer.rs} - -### Transmute -Allows simple conversion from one type to another, however both types must have -the same size and alignment - -{transmute.rs} - -### Inline Assembly -Inline assembly functions very similarly to the inline assembly of c, which -makes sense considering its implementation is not handled by rust, rather by -the LLVM. It allows for direct access to assembly manipulation, which can -massively increase speed, but it can also decrease portability and stability. -In most cases the compiler will optimize your rust code to better assembly than -you could write, so in most instances it is not worth it. The first parameter -of asm!() is the format of the assembly, the parameter following the colon is -the output variable, and the parameter(s) following that are the input -variables. - -**Note**: `#![feature(asm)]` is currently required to use inline assembly. - -{asm.rs} diff --git a/examples/staging/unsafe/pointer.rs b/examples/staging/unsafe/pointer.rs deleted file mode 100644 index ba494622cc..0000000000 --- a/examples/staging/unsafe/pointer.rs +++ /dev/null @@ -1,7 +0,0 @@ -fn main() { - let raw_p: *const u32 = &10; - - unsafe { - assert!(*raw_p == 10); - } -} diff --git a/examples/staging/unsafe/transmute.rs b/examples/staging/unsafe/transmute.rs deleted file mode 100644 index 27ba8a5b31..0000000000 --- a/examples/staging/unsafe/transmute.rs +++ /dev/null @@ -1,7 +0,0 @@ -fn main() { - let u: &[u8] = &[49, 50, 51]; - - unsafe { - assert!(u == std::mem::transmute::<&str, &[u8]>("123")); - } -} diff --git a/examples/str/input.md b/examples/str/input.md deleted file mode 100644 index cbb2c1658c..0000000000 --- a/examples/str/input.md +++ /dev/null @@ -1,18 +0,0 @@ -There are two types of strings in Rust: `String` and `&str`. - -A `String` is stored as a vector of bytes (`Vec`), but guaranteed to -always be a valid UTF-8 sequence. `String` is heap allocated, growable and not -null terminated. - -`&str` is a slice (`&[u8]`) that always points to a valid UTF-8 sequence, and -can be used to view into a `String`, just like `&[T]` is a view into `Vec`. - -{str.play} - -More `str`/`String` methods can be found under the -[std::str][str] and -[std::string][string] -modules - -[str]: http://doc.rust-lang.org/std/str/ -[string]: http://doc.rust-lang.org/std/string/ diff --git a/examples/str/str.rs b/examples/str/str.rs deleted file mode 100644 index e0743a5b5c..0000000000 --- a/examples/str/str.rs +++ /dev/null @@ -1,40 +0,0 @@ -fn main() { - // (all the type annotations are superfluous) - // A reference to a string allocated in read only memory - let pangram: &'static str = "the quick brown fox jumps over the lazy dog"; - println!("Pangram: {}", pangram); - - // Iterate over words in reverse, no new string is allocated - println!("Words in reverse"); - for word in pangram.words().rev() { - println!("> {}", word); - } - - // Copy chars into a vector, sort and remove duplicates - let mut chars: Vec = pangram.chars().collect(); - chars.sort(); - chars.dedup(); - - // Create an empty and growable `String` - let mut string = String::new(); - for c in chars.into_iter() { - // Insert a char at the end of string - string.push(c); - // Insert a string at the end of string - string.push_str(", "); - } - - // The trimmed string is a slice to the original string, hence no new - // allocation is performed - let chars_to_trim: &[char] = &[' ', ',']; - let trimmed_str: &str = string.as_slice().trim_chars(chars_to_trim); - println!("Used characters: {}", trimmed_str); - - // Heap allocate a string - let alice = String::from_str("I like dogs"); - // Allocate new memory and store the modified string there - let bob: String = alice.replace("dog", "cat"); - - println!("Alice says: {}", alice); - println!("Bob says: {}", bob); -} diff --git a/examples/structs/input.md b/examples/structs/input.md deleted file mode 100644 index 903a625f4e..0000000000 --- a/examples/structs/input.md +++ /dev/null @@ -1,10 +0,0 @@ -There are three types of structures ("structs") that can be created using the -`struct` keyword: - -* Tuple structs, which are, basically, named tuples. -* The classic [C structs][1] -* Unit structs, which are field-less structs. - -{structs.play} - -[1]:http://en.wikipedia.org/wiki/Struct_(C_programming_language) diff --git a/examples/structs/structs.rs b/examples/structs/structs.rs deleted file mode 100644 index 10e194ee0f..0000000000 --- a/examples/structs/structs.rs +++ /dev/null @@ -1,46 +0,0 @@ -// A unit struct -struct Nil; - -// A tuple struct -struct Pair(int, f64); - -// A struct with two fields -struct Point { - x: f64, - y: f64, -} - -// Structs can be reused as fields of another struct -#[allow(dead_code)] -struct Rectangle { - p1: Point, - p2: Point, -} - -fn main() { - // Instantiate a `Point` - let point: Point = Point { x: 0.3, y: 0.4 }; - - // Access the fields of the point - println!("point coordinates: ({}, {})", point.x, point.y); - - // Destructure the point using a `let` binding - let Point { x: my_x, y: my_y } = point; - - let _rectangle = Rectangle { - // struct instantiation is an expression too - p1: Point { x: my_y, y: my_x }, - p2: point, - }; - - // Instantiate a unit struct - let _nil = Nil; - - // Instantiate a tuple struct - let pair = Pair(1, 0.1); - - // Destructure a tuple struct - let Pair(integer, decimal) = pair; - - println!("pair contains {} and {}", integer, decimal); -} diff --git a/examples/structs/visibility/input.md b/examples/structs/visibility/input.md deleted file mode 100644 index 7d4b11e647..0000000000 --- a/examples/structs/visibility/input.md +++ /dev/null @@ -1,6 +0,0 @@ -Structs have an extra level of visibility, their fields can be public or -private (which is the default). This visibility only matters when a -struct is accessed from outside the module where it is defined, and its -goal is information hiding (encapsulation). - -{struct.play} diff --git a/examples/structs/visibility/struct.rs b/examples/structs/visibility/struct.rs deleted file mode 100644 index 581fe76de8..0000000000 --- a/examples/structs/visibility/struct.rs +++ /dev/null @@ -1,43 +0,0 @@ -mod my { - // A public struct with public fields - pub struct WhiteBox { - pub contents: T, - } - - // A public struct with private fields - #[allow(dead_code)] - pub struct BlackBox { - contents: T, - } - - impl BlackBox { - // A public constructor - pub fn new(contents: T) -> BlackBox { - BlackBox { - contents: contents, - } - } - } -} - -fn main() { - // Public structs with public fields can be constructed as usual - let white_box = my::WhiteBox { contents: "public information" }; - - // and their fields can be normally accessed - println!("The white box contains: {}", white_box.contents); - - // but public structs with private fields can't be constructed - // Error! `BlackBox` has private fields - //let black_box = my::BlackBox { contents: "classified information" }; - // TODO ^ Try uncommenting this line - - // However, structs with private fields can still be created using - // constructors - let _black_box = my::BlackBox::new("classified information"); - - // The private fields of a struct can't be accessed - // Error! The `contents` field is private - //println!("The black box contains: {}", _black_box.contents); - // TODO ^ Try uncommenting this line -} diff --git a/examples/structure.json b/examples/structure.json deleted file mode 100644 index 372e74722c..0000000000 --- a/examples/structure.json +++ /dev/null @@ -1,145 +0,0 @@ -[ - { "id": "hello", "title": "Hello World", "children": null }, - { "id": "print", "title": "Formatted print", "children": null }, - { "id": "literals", "title": "Literals and operators", "children": null }, - { "id": "variables", "title": "Variables", "children": [ - { "id": "mut", "title": "Mutability", "children": null }, - { "id": "scope", "title": "Scope and shadowing", "children": null }, - { "id": "declare", "title": "Declare first", "children": null } - ] }, - { "id": "type", "title": "Types", "children": [ - { "id": "cast", "title": "Casting", "children": null }, - { "id": "literals", "title": "Literals", "children": null }, - { "id": "inference", "title": "Inference", "children": null }, - { "id": "alias", "title": "Alias", "children": null } - ] }, - { "id": "expression", "title": "Expressions", "children": null }, - { "id": "if-else", "title": "If/else", "children": null }, - { "id": "loop", "title": "Loop", "children": [ - { "id": "nested", "title": "Nesting and labels", "children": null } - ] }, - { "id": "while", "title": "While", "children": null }, - { "id": "for", "title": "For and range", "children": null }, - { "id": "fn", "title": "Functions", "children": [ - { "id": "unused", "title": "Unused", "children": null } - ] }, - { "id": "mod", "title": "Modules", "children": [ - { "id": "visibility", "title": "Visibility", "children": null }, - { "id": "use", "title": "The `use` import", "children": null }, - { "id": "super", "title": "`super` and `self`", "children": null }, - { "id": "split", "title": "File hierarchy", "children": null } - ] }, - { "id": "crates", "title": "Crates", "children": [ - { "id": "lib", "title": "Library", "children": null }, - { "id": "link", "title": "`extern crate`", "children": null } - ] }, - { "id": "attribute", "title": "Attributes", "children": [ - { "id": "crate", "title": "Crates", "children": null }, - { "id": "cfg", "title": "`cfg`", "children": [ - { "id": "custom", "title": "Custom", "children": null } - ] } - ] }, - { "id": "tuples", "title": "Tuples", "children": null }, - { "id": "match", "title": "Pattern matching", "children": [ - { "id": "guard", "title": "Destructuring and guards", "children": null }, - { "id": "struct", "title": "Destructuring structs", "children": null } - ] }, - { "id": "structs", "title": "Structures", "children": [ - { "id": "visibility", "title": "Visibility", "children": null } - ] }, - { "id": "generics", "title": "Generics", "children": [ - { "id": "impl", "title": "Implementation", "children": null }, - { "id": "phantom", "title": "Phantom types", "children": [ - { "id": "units", "title": "Unit conversions", "children": null } - ] } - ] }, - { "id": "box", "title": "Box, stack and heap", "children": null }, - { "id": "raii", "title": "RAII", "children": null }, - { "id": "move", "title": "Ownership and moves", "children": [ - { "id": "mut", "title": "Mutability", "children": null } - ] }, - { "id": "borrow", "title": "Borrowing", "children": [ - { "id": "mut", "title": "Mutability", "children": null }, - { "id": "freeze", "title": "Freezing", "children": null }, - { "id": "alias", "title": "Aliasing", "children": null }, - { "id": "ref", "title": "The ref pattern", "children": null } - ] }, - { "id": "lifetime", "title": "Lifetimes", "children": [ - { "id": "borrow", "title": "The borrow checker", "children": null }, - { "id": "fn", "title": "Functions", "children": null }, - { "id": "struct", "title": "Structs", "children": null } - ] }, - { "id": "constants", "title": "Global constants", "children": null }, - { "id": "methods", "title": "Methods", "children": null }, - { "id": "enum", "title": "Enums", "children": [ - { "id": "c-like", "title": "C-like", "children": null } - ] }, - { "id": "panic", "title": "`panic!`", "children": null }, - { "id": "option", "title": "`Option`", "children": null }, - { "id": "array", "title": "Arrays and Slices", "children": null }, - { "id": "trait", "title": "Traits", "children": [ - { "id": "deriving", "title": "Deriving", "children": null } - ] }, - { "id": "ops", "title": "Operator Overloading", "children": null }, - { "id": "bounds", "title": "Bounds", "children": null }, - { "id": "drop", "title": "Drop", "children": null }, - { "id": "iter", "title": "Iterators", "children": null }, - { "id": "closures", "title": "Closures", "children": null }, - { "id": "hof", "title": "Higher Order Functions", "children": null }, - { "id": "vec", "title": "Vectors", "children": null }, - { "id": "str", "title": "Strings", "children": null }, - { "id": "clone", "title": "Clone", "children": null }, - { "id": "tasks", "title": "Tasks", "children": null }, - { "id": "channels", "title": "Channels", "children": null }, - { "id": "timers", "title": "Timers", "children": null }, - { "id": "sockets", "title": "Unix sockets", "children": null }, - { "id": "result", "title": "`Result`", "children": [ - { "id": "try", "title": "`try!`", "children": null } - ] }, - { "id": "path", "title": "Path", "children": null }, - { "id": "file", "title": "File I/O", "children": [ - { "id": "open", "title": "`open`", "children": null }, - { "id": "create", "title": "`create`", "children": null } - ] }, - { "id": "process", "title": "Child processes", "children": [ - { "id": "pipe", "title": "Pipes", "children": null }, - { "id": "wait", "title": "Wait", "children": null } - ] }, - { "id": "fs", "title": "Filesystem Operations", "children": null }, - { "id": "staging", "title": "Staging Area", "children": [ - { "id": "bench", "title": "Benchmarking", "children": null }, - { "id": "comment", "title": "Comments", "children": [ - { "id": "doc-comment", "title": "Doc Comments", "children": null } - ] }, - { "id": "ffi", "title": "Foreign Function Interface", "children": null }, - { "id": "macros", "title": "macro_rules!", "children": null }, - { "id": "arg", "title": "Program arguments", "children": [ - { "id": "matching", "title": "Argument parsing", "children": null }, - { "id": "getopts", "title": "`getopts`", "children": null } - ] }, - { "id": "rand", "title": "Random", "children": null }, - { "id": "simd", "title": "SIMD", "children": null }, - { "id": "test", "title": "Testing", "children": null }, - { "id": "unsafe", "title": "Unsafe operations", "children": null }, - { "id": "json", "title": "JSON parsing", "children": [ - { "id": "json-enum", "title": "`Json`", "children": null }, - { "id": "decodable", "title": "`Decodable`", "children": null }, - { "id": "encodable", "title": "`Encodable`", "children": null } - ] }, - { "id": "fmt", "title": "Formatting", "children": null }, - { "id": "hash", "title": "HashMap", "children": [ - { "id": "alt-key-types", "title": "Alternate/custom key types", "children": null}, - { "id": "hashset", "title": "HashSet", "children": null } - ] } - ] }, - { "id": "todo", "title": "TODO", "children": [ - { "id": "assert", "title": "assert! and debug_assert!", "children": null }, - { "id": "green", "title": "Green threads", "children": null }, - { "id": "log", "title": "Logging", "children": null }, - { "id": "rc", "title": "Reference counting", "children": null }, - { "id": "regex", "title": "Regex", "children": null }, - { "id": "rustdoc", "title": "rustdoc", "children": null }, - { "id": "select", "title": "select!", "children": null }, - { "id": "stdio", "title": "Standard I/O", "children": null } - ] } -] diff --git a/examples/tasks/input.md b/examples/tasks/input.md deleted file mode 100644 index a326cd9441..0000000000 --- a/examples/tasks/input.md +++ /dev/null @@ -1,11 +0,0 @@ -Rust provides a mechanism for spawning lightweight tasks via the `spawn` -function, the argument of this function is an owned closure named `proc`. - -{tasks.play} - -These tasks will be scheduled by the Rust runtime and the order of execution of -these tasks will be non-deterministic. - -(By default, Rust uses its *native* runtime, which maps each Rust task to a -native thread. Rust also provides a *green* runtime that provides green threads -and maps M Rust tasks to N native threads.) diff --git a/examples/tasks/tasks.rs b/examples/tasks/tasks.rs deleted file mode 100644 index d1cafaaf63..0000000000 --- a/examples/tasks/tasks.rs +++ /dev/null @@ -1,11 +0,0 @@ -static NTASKS: int = 10; - -// This is the `main` task -fn main() { - for i in range(0, NTASKS) { - // Spin up another task - spawn(proc() { - println!("this is task number {}", i) - }); - } -} diff --git a/examples/timers/input.md b/examples/timers/input.md deleted file mode 100644 index 1cf24cd382..0000000000 --- a/examples/timers/input.md +++ /dev/null @@ -1,23 +0,0 @@ -A `Timer` represents an underlying OS timer, and can generate *one-shot* and -*periodic* notifications via the `Receiver` endpoint of a channel. - -{timers.play} - -The playpen has a time limit, so you won't be able to see the (full) output in -the editor. Here's the output you should see, if you run this in a computer. - -``` -$ rustc timers.rs && time ./timers -Wait 1000 ms... -Done -Sleep for 1000 ms... -Done -Countdown -5 -4 -3 -2 -1 -Ignition! -./timers 0.00s user 0.00s system 0% cpu 8.003 total -``` diff --git a/examples/timers/timers.rs b/examples/timers/timers.rs deleted file mode 100644 index 4fbc9ac81c..0000000000 --- a/examples/timers/timers.rs +++ /dev/null @@ -1,42 +0,0 @@ -use std::io::Timer; -use std::io::timer; -use std::time::duration::Duration; -use std::iter; - -fn main() { - let interval = Duration::milliseconds(1000); - // Create a timer object - let mut timer = Timer::new().unwrap(); - - // Create a one-shot notification - // (superfluous type annotation) - let oneshot: Receiver<()> = timer.oneshot(interval); - - println!("Wait {} ms...", interval.num_milliseconds()); - - // Block the task until notification arrives - oneshot.recv(); - - println!("Done"); - - println!("Sleep for {} ms...", interval.num_milliseconds()); - - // This is equivalent to `timer.oneshot(interval).recv()` - timer::sleep(interval); - - println!("Done"); - - // The same timer can be used to generate periodic notifications - // (superfluous type annotation) - let metronome: Receiver<()> = timer.periodic(interval); - - println!("Countdown"); - for i in iter::range_step(5i, 0, -1) { - // This loop will run once every second - metronome.recv(); - - println!("{}", i); - } - metronome.recv(); - println!("Ignition!"); -} diff --git a/examples/todo/input.md b/examples/todo/input.md deleted file mode 100644 index 8b254a0fc1..0000000000 --- a/examples/todo/input.md +++ /dev/null @@ -1,4 +0,0 @@ -If you would like to see a chapter about some concept or library, please drop a -comment in [issue #1][issue-1] - -[issue-1]: https://github.com/rust-lang/rust-by-example/issues/1 diff --git a/examples/trait/deriving/deriving.rs b/examples/trait/deriving/deriving.rs deleted file mode 100644 index 7b2bd9abf9..0000000000 --- a/examples/trait/deriving/deriving.rs +++ /dev/null @@ -1,47 +0,0 @@ -// A tuple struct that can be compared -#[deriving(PartialEq, PartialOrd)] -struct Centimeters(f64); - -// A tuple struct that can be printed -#[deriving(Show)] -struct Inches(int); - -impl Inches { - fn to_centimeters(&self) -> Centimeters { - let &Inches(inches) = self; - - Centimeters(inches as f64 * 2.54) - } -} - -// A vanilla tuple struct -struct Seconds(int); - -fn main() { - let _one_second = Seconds(1); - - // Error! `Seconds` can't be printed, because it doesn't implement the - // `Show` trait - //println!("One second looks like: {}", _one_second); - // TODO ^ Try uncommenting this line - - // Error: `Seconds` can't be compared, because it doesn't implement the - // `PartialEq` trait - //let _this_is_true = _one_second == _one_second; - // TODO ^ Try uncommenting this line - - let foot = Inches(12); - - println!("One foot === {}", foot); - - let meter = Centimeters(100.0); - - let cmp = - if foot.to_centimeters() < meter { - "smaller" - } else { - "bigger" - }; - - println!("one foot is {} than one meter", cmp); -} diff --git a/examples/trait/deriving/input.md b/examples/trait/deriving/input.md deleted file mode 100644 index 8a4b3a5bab..0000000000 --- a/examples/trait/deriving/input.md +++ /dev/null @@ -1,44 +0,0 @@ -The compiler is capable of providing basic implementations for some traits via -the `#[deriving]` [attribute][attribute]. These traits can still be -manually implemented if a more complex behavior is required. - -{deriving.play} - -This is a list of the "derivable" traits: -* Comparison traits: - [`Eq`][eq], - [`PartialEq`][partial-eq], - [`Ord`][ord], - [`PartialOrd`][partial-ord] -* Serialization: - [`Encodable`][encodable], - [`Decodable`][decodable] -* [`Clone`][clone], - to create `T` from `&T` via a copy. -* [`Hash`][hash], to - compute a hash from `&T`. -* [`Rand`][rand], to - create a random instance of a data type. -* [`Default`][default], - to create an empty instance of a data type. -* [`Zero`][zero], to - create a zero instance of a numeric data type. -* [`FromPrimitive`][from-primitive], - to create an instance from a numeric primitive. -* [`Show`][show], to - format a value using the `{}` formatter. - -[attribute]: /attribute.html -[eq]: http://doc.rust-lang.org/std/cmp/trait.Eq.html -[partial-eq]: http://doc.rust-lang.org/std/cmp/trait.PartialEq.html -[ord]: http://doc.rust-lang.org/std/cmp/trait.Ord.html -[partial-ord]: http://doc.rust-lang.org/std/cmp/trait.PartialOrd.html -[encodable]: http://doc.rust-lang.org/serialize/trait.Encodable.html -[decodable]: http://doc.rust-lang.org/serialize/trait.Decodable.html -[clone]: http://doc.rust-lang.org/std/clone/trait.Clone.html -[hash]: http://doc.rust-lang.org/std/hash/trait.Hash.html -[rand]: http://doc.rust-lang.org/rand/trait.Rand.html -[default]: http://doc.rust-lang.org/std/default/trait.Default.html -[zero]: http://doc.rust-lang.org/std/num/trait.Zero.html -[from-primitive]: http://doc.rust-lang.org/std/num/trait.FromPrimitive.html -[show]: http://doc.rust-lang.org/std/fmt/trait.Show.html diff --git a/examples/trait/input.md b/examples/trait/input.md deleted file mode 100644 index a47bb8bbf8..0000000000 --- a/examples/trait/input.md +++ /dev/null @@ -1,4 +0,0 @@ -A `trait` is a collection of methods declared/defined for an unknown type: -`Self`. Traits can be implemented for any data type. - -{trait.play} diff --git a/examples/trait/trait.rs b/examples/trait/trait.rs deleted file mode 100644 index bd9e02c070..0000000000 --- a/examples/trait/trait.rs +++ /dev/null @@ -1,97 +0,0 @@ -trait Animal { - // Static method signature; `Self` refers to the implementor type - fn new(name: &'static str) -> Self; - - // Instance methods, only signatures - fn name(&self) -> &'static str; - fn noise(&self) -> &'static str; - - // A trait can provide default method definitions - fn talk(&self) { - // These definitions can access other methods declared in the same - // trait - println!("{} says {}", self.name(), self.noise()); - } -} - -struct Dog { name: &'static str } - -impl Dog { - fn wag_tail(&self) { - println!("{} wags tail", self.name); - } -} - -// Implement the `Animal` trait for `Dog` -impl Animal for Dog { - // Replace `Self` with the implementor type: `Dog` - fn new(name: &'static str) -> Dog { - Dog { name: name } - } - - fn name(&self) -> &'static str { - self.name - } - - fn noise(&self) -> &'static str { - "woof!" - } - - // Default trait methods can be overridden - fn talk(&self) { - // Traits methods can access the implementor methods - self.wag_tail(); - - println!("{} says {}", self.name, self.noise()); - } -} - -struct Sheep { naked: bool, name: &'static str } - -impl Sheep { - fn is_naked(&self) -> bool { - self.naked - } - - fn shear(&mut self) { - if self.is_naked() { - // Implementor methods can use the implementor's trait methods - println!("{} is already naked!", self.name()); - } else { - println!("{} gets a haircut", self.name); - - self.talk(); - self.naked = true; - } - } -} - -impl Animal for Sheep { - fn new(name: &'static str) -> Sheep { - Sheep { name: name, naked: false } - } - - fn name(&self) -> &'static str { - self.name - } - - fn noise(&self) -> &'static str { - if self.is_naked() { - "baaah" - } else { - "baaaaaaaaaaaah" - } - } -} - -fn main() { - // Type annotation is necessary in this case - let mut dolly: Sheep = Animal::new("Dolly"); - let spike: Dog = Animal::new("Spike"); - // TODO ^ Try removing the type annotations - - dolly.shear(); - - spike.talk(); - dolly.talk(); -} diff --git a/examples/tuples/input.md b/examples/tuples/input.md deleted file mode 100644 index a541373979..0000000000 --- a/examples/tuples/input.md +++ /dev/null @@ -1,6 +0,0 @@ -A tuple is a collection of values of different types. Tuples are constructed -using parentheses `()`, and each tuple itself is a value with type signature -`(T1, T2, ...)`, where `T1`, `T2` are the types of its members. Functions can -use tuples to return multiple values, as tuples can hold any number of values. - -{tuples.play} diff --git a/examples/tuples/tuples.rs b/examples/tuples/tuples.rs deleted file mode 100644 index 1721294e5c..0000000000 --- a/examples/tuples/tuples.rs +++ /dev/null @@ -1,35 +0,0 @@ -// Tuples can be used as function arguments and as return values -fn reverse(pair: (int, bool)) -> (bool, int) { - // `let` can be used to bind the members of a tuple to variables - let (integer, boolean) = pair; - - (boolean, integer) -} - -fn main() { - // A tuple with a bunch of different types - let long_tuple = (1u8, 2u16, 3u32, 4u64, - -1i8, -2i16, -3i32, -4i64, - 0.1f32, 0.2f64, - 'a', true); - - // Values can be extracted from the tuple using the `valN` methods - println!("long tuple first value: {}", long_tuple.val0()); - println!("long tuple second value: {}", long_tuple.val1()); - - // Tuples can be tuple members - let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16); - - // Tuples are printable - println!("tuple of tuples: {}", tuple_of_tuples); - - let pair = (1, true); - println!("pair is {}", pair); - - println!("the reversed pair is {}", reverse(pair)); - - // To create one element tuples, the comma is required to tell them apart - // from a literal surrounded by parentheses - println!("one element tuple: {}", (5u,)); - println!("just an integer: {}", (5u)); -} diff --git a/examples/type/alias/alias.rs b/examples/type/alias/alias.rs deleted file mode 100644 index 3d5bd0fb9f..0000000000 --- a/examples/type/alias/alias.rs +++ /dev/null @@ -1,21 +0,0 @@ -// `NanoSecond` is a new name for `u64` -type NanoSecond = u64; -type Inch = u64; - -// Use an attribute to silence warning -#[allow(non_camel_case_types)] -type uint64_t = u64; -// TODO ^ Try removing the attribute - -fn main() { - // `NanoSecond` = `Inch` = `uint64_t` = `u64` - let nanoseconds: NanoSecond = 5 as uint64_t; - let inches: Inch = 2 as uint64_t; - - // Note that type aliases *don't* provide any extra type safety, because - // aliases are *not* new types - println!("{} nanoseconds + {} inches = {} unit?", - nanoseconds, - inches, - nanoseconds + inches); -} diff --git a/examples/type/alias/input.md b/examples/type/alias/input.md deleted file mode 100644 index c9e16c7ae8..0000000000 --- a/examples/type/alias/input.md +++ /dev/null @@ -1,11 +0,0 @@ -The `type` statement can be used to give a new name to an existing type. Types -must have `CamelCase` names, or the compiler will raise a warning. The -exception to this rule are the primitive types: `uint`, `f32`, etc. - -{alias.play} - -The main use of aliases is to reduce typing, for example the -[`IoResult`][io-result] -type is an alias for the `Result` type. - -[io-result]: http://doc.rust-lang.org/std/io/type.IoResult.html diff --git a/examples/type/cast/cast.rs b/examples/type/cast/cast.rs deleted file mode 100644 index 845506bf2f..0000000000 --- a/examples/type/cast/cast.rs +++ /dev/null @@ -1,13 +0,0 @@ -fn main() { - let decimal = 65.4321_f32; - - // Error! No implicit conversion - let integer: u8 = decimal; - // FIXME ^ Comment out this line - - // Explicit conversion - let integer = decimal as u8; - let character = integer as char; - - println!("Casting: {} -> {} -> {}", decimal, integer, character); -} diff --git a/examples/type/cast/input.md b/examples/type/cast/input.md deleted file mode 100644 index 7a792d4ee5..0000000000 --- a/examples/type/cast/input.md +++ /dev/null @@ -1,4 +0,0 @@ -Rust provides no implicit type conversion (coercion) between primitive types. -But, explicit type conversion (casting) can be achieved using the `as` keyword. - -{cast.play} diff --git a/examples/type/inference/inference.rs b/examples/type/inference/inference.rs deleted file mode 100644 index 54131a2e38..0000000000 --- a/examples/type/inference/inference.rs +++ /dev/null @@ -1,16 +0,0 @@ -fn main() { - // Using local inference, the compiler knows that `elem` has type u8 - let elem = 5u8; - - // Create an empty vector (a growable array) - let mut vec = Vec::new(); - // At this point the compiler doesn't know the exact type of `vec`, it - // just knows that it's a vector of something (`Vec<_>`) - - // Insert `elem` in the vector - vec.push(elem); - // Aha! Now the compiler knows that `vec` is a vector of `u8`s (`Vec`) - // TODO ^ Try commenting out the `vec.push(elem)` line - - println!("{}", vec); -} diff --git a/examples/type/inference/input.md b/examples/type/inference/input.md deleted file mode 100644 index 93670a7a94..0000000000 --- a/examples/type/inference/input.md +++ /dev/null @@ -1,12 +0,0 @@ -The type inference engine is pretty smart. It does more than looking at the -type of the -[r-value][rvalue] -during an initialization. It also looks how the variable is used afterwards to -infer its type. Here's an advanced example of type inference: - -{inference.play} - -No type annotation of variables was needed, the compiler is happy and so is the -programmer! - -[rvalue]: https://en.wikipedia.org/wiki/Value_%28computer_science%29#lrvalue diff --git a/examples/type/input.md b/examples/type/input.md deleted file mode 100644 index 7920fb803f..0000000000 --- a/examples/type/input.md +++ /dev/null @@ -1,15 +0,0 @@ -Rust provides type safety via its static type-checker. Variables can be type -annotated when declared. However, in most cases, the compiler will be able to -infer the type of the variable from the context, heavily reducing the -annotation burden. - -{type.play} - -This is a summary of the primitive types in Rust: - -* signed integers: `i8`, `i16`, `i32`, `i64` and `int` (machine word size) -* unsigned integers: `u8`, `u16`, `u32`, `u64` and `uint` (machine word size) -* floating point: `f32`, `f64` -* `char` Unicode scalar values like `'a'`, `'α'` and `'∞'` (4 bytes each) -* `bool` either `true` or `false` -* and the unit type `()`, whose only value is also `()` diff --git a/examples/type/literals/input.md b/examples/type/literals/input.md deleted file mode 100644 index b971dbf684..0000000000 --- a/examples/type/literals/input.md +++ /dev/null @@ -1,23 +0,0 @@ -Numeric literals can be type annotated by adding the type as a suffix, with the -exception of `uint` that uses the `u` suffix and `int` that uses the `i` -suffix. - -The type of unsuffixed literals will depend on how they are used. If no -constraint exists, the compiler will raise an error. - -{literals.play} - -There are some concepts used in the previous code that haven't been explained -yet, here's a brief explanation for the impatient readers: - -* `fun(&foo)` is used to pass an argument to a function *by reference*, rather - than by value (`fun(foo)`). For more details see [borrowing][borrow]. -* `std::mem::size_of_val` is a function, but called with its *full path*. Code - can be split in logical units called *modules*. In this case the - `size_of_val` function is defined in the `mem` module, and the `mem` module - is defined in the `std` *crate*. For more details see - [modules][mod] and [crates][crate]. - -[borrow]: /borrow.html -[mod]: /mod.html -[crate]: /crates.html diff --git a/examples/type/literals/literals.rs b/examples/type/literals/literals.rs deleted file mode 100644 index f06230db83..0000000000 --- a/examples/type/literals/literals.rs +++ /dev/null @@ -1,22 +0,0 @@ -fn main() { - // Suffixed literals, their types are known at initialization - let x = 1u8; - let y = 2u; - let z = 3f32; - - // Unsuffixed literal, their types depend on how they are used - let i = 1; - let f = 1.0; - - // `size_of_val` returns the size of a variable in bytes - println!("size of `x` in bytes: {}", std::mem::size_of_val(&x)); - println!("size of `y` in bytes: {}", std::mem::size_of_val(&y)); - println!("size of `z` in bytes: {}", std::mem::size_of_val(&z)); - println!("size of `i` in bytes: {}", std::mem::size_of_val(&i)); - println!("size of `f` in bytes: {}", std::mem::size_of_val(&f)); - - // Constraints (summands must have the same type) for `i` and `f` - let _constraint_i = x + i; - let _constraint_f = z + f; - // TODO ^ Try commenting out these two lines -} diff --git a/examples/type/type.rs b/examples/type/type.rs deleted file mode 100644 index deda1c2a3c..0000000000 --- a/examples/type/type.rs +++ /dev/null @@ -1,10 +0,0 @@ -fn main() { - // Type annotated variable - let a_float: f64 = 1.0; - - // This variable is an `int` - let mut an_integer = 5i; - - // Error! The type of a variable can't be changed - an_integer = true; -} diff --git a/examples/variables/declare/declare.rs b/examples/variables/declare/declare.rs deleted file mode 100644 index ec54714807..0000000000 --- a/examples/variables/declare/declare.rs +++ /dev/null @@ -1,23 +0,0 @@ -fn main() { - // Declare a variable - let a_variable; - - { - let x = 2i; - - // Initialize the variable - a_variable = x * x; - } - - println!("a variable: {}", a_variable); - - let another_variable; - - // Error! Use of uninitialized variable - println!("another variable: {}", another_variable); - // FIXME ^ Comment out this line - - another_variable = 1i; - - println!("another variable: {}", another_variable); -} diff --git a/examples/variables/declare/input.md b/examples/variables/declare/input.md deleted file mode 100644 index 2bad0e6677..0000000000 --- a/examples/variables/declare/input.md +++ /dev/null @@ -1,7 +0,0 @@ -It's possible to declare variables first, and initialize them later. But, this -form is seldom used, as it may lead to the use of uninitialized variables. - -{declare.play} - -The compiler forbids use of uninitialized variables, as this would lead to -undefined behavior. diff --git a/examples/variables/input.md b/examples/variables/input.md deleted file mode 100644 index 22358bb6cf..0000000000 --- a/examples/variables/input.md +++ /dev/null @@ -1,3 +0,0 @@ -Values (like literals) can be bound to variables, using the `let` binding. - -{variables.play} diff --git a/examples/variables/mut/input.md b/examples/variables/mut/input.md deleted file mode 100644 index 309d762dd3..0000000000 --- a/examples/variables/mut/input.md +++ /dev/null @@ -1,6 +0,0 @@ -Variables are immutable by default, but this can be overridden using the `mut` -modifier. - -{mut.play} - -The compiler will throw a detailed diagnostic about mutability errors. diff --git a/examples/variables/mut/mut.rs b/examples/variables/mut/mut.rs deleted file mode 100644 index 023aa69fb0..0000000000 --- a/examples/variables/mut/mut.rs +++ /dev/null @@ -1,15 +0,0 @@ -fn main() { - let _immutable_variable = 1i; - let mut mutable_variable = 1i; - - println!("Before mutation: {}", mutable_variable); - - // Ok - mutable_variable += 1; - - println!("After mutation: {}", mutable_variable); - - // Error! - _immutable_variable += 1; - // FIXME ^ Comment out this line -} diff --git a/examples/variables/scope/input.md b/examples/variables/scope/input.md deleted file mode 100644 index fe781b9af0..0000000000 --- a/examples/variables/scope/input.md +++ /dev/null @@ -1,7 +0,0 @@ -Variables have local scope, and are constrained to live in a *block* (a block -is a collection of statements enclosed by braces `{}`). Also, -[variable shadowing][variable-shadow] is allowed. - -{scope.play} - -[variable-shadow]: https://en.wikipedia.org/wiki/Variable_shadowing diff --git a/examples/variables/scope/scope.rs b/examples/variables/scope/scope.rs deleted file mode 100644 index 7cb1624380..0000000000 --- a/examples/variables/scope/scope.rs +++ /dev/null @@ -1,24 +0,0 @@ -fn main() { - // This variable lives in the main function - let long_lived_variable = 1i; - - // This is a block, and has a smaller scope than the main function - { - // This variable only exists in this block - let short_lived_variable = 2i; - - println!("inner short: {}", short_lived_variable); - - // This variable *shadows* the outer one - let long_lived_variable = 5_f32; - - println!("inner long: {}", long_lived_variable); - } - // End of the block - - // Error! `short_lived_variable` doesn't exist in this scope - println!("outer short: {}", short_lived_variable); - // FIXME ^ Comment out this line - - println!("outer long: {}", long_lived_variable); -} diff --git a/examples/variables/variables.rs b/examples/variables/variables.rs deleted file mode 100644 index 59067e75e6..0000000000 --- a/examples/variables/variables.rs +++ /dev/null @@ -1,18 +0,0 @@ -fn main() { - let an_integer = 1u; - let a_boolean = true; - let unit = (); - - // copy `an_integer` into `copied_integer` - let copied_integer = an_integer; - - println!("An integer: {}", copied_integer); - println!("A boolean: {}", a_boolean); - println!("Meet the unit value: {}", unit); - - // The compiler warns about unused variables; these warnings can be - // silenced by prefixing the variable name with an underscore - let _unused_variable = 3u; - let noisy_unused_variable = 2u; - // FIXME ^ Prefix with an underscore to suppress the warning -} diff --git a/examples/vec/input.md b/examples/vec/input.md deleted file mode 100644 index 0c0bc5ad13..0000000000 --- a/examples/vec/input.md +++ /dev/null @@ -1,13 +0,0 @@ -Vectors are re-sizable arrays, like slices their size is not known at compile -time, but they can grow or shrink at anytime. A vector is represented using -3 words: a pointer to the data, its length and its capacity. The capacity -indicates how much memory is reserved for the vector, the vector can grow as -long as the length is smaller than the capacity, when this threshold needs to -be surpassed, the vector gets reallocated with a bigger capacity. - -{vec.play} - -More `Vec` methods can be found under the -[std::vec][vec] module - -[vec]: http://doc.rust-lang.org/std/vec/ diff --git a/examples/vec/vec.rs b/examples/vec/vec.rs deleted file mode 100644 index eece857b64..0000000000 --- a/examples/vec/vec.rs +++ /dev/null @@ -1,30 +0,0 @@ -fn main() { - // Iterators can be collected into vectors - let collected_iterator: Vec = range(0i, 10).collect(); - println!("Collected range(0, 10) into: {}", collected_iterator); - - // The `vec!` macro can be used to initialize a vector - let mut xs = vec![1i, 2, 3]; - println!("Initial vector: {}", xs); - - // Insert new element at the end of the vector - println!("Push 4 into the vector") - xs.push(4); - println!("Vector: {}", xs); - - // Error! Immutable vectors can't grow - collected_iterator.push(0); - // FIXME ^ Comment out this line - - // The `len` method yields the current size of the vector - println!("Vector size: {}", xs.len()); - - // Indexing is done using the square brackets (indexing starts at 0) - println!("Second element: {}", xs[1]); - - // `pop` removes the last element from the vector and returns it - println!("Pop last element: {}", xs.pop()); - - // Out of bounds indexing yields a task failure - println!("Fourth element: {}", xs[3]); -} diff --git a/examples/while/input.md b/examples/while/input.md deleted file mode 100644 index b7d0cf842e..0000000000 --- a/examples/while/input.md +++ /dev/null @@ -1,5 +0,0 @@ -The `while` keyword can be used to loop until a condition is met. - -Let's write the infamous fizzbuzz using a `while` loop. - -{while.play} diff --git a/fix-edit-button.sh b/fix-edit-button.sh deleted file mode 100755 index 06c292071e..0000000000 --- a/fix-edit-button.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash - -for example in $(find examples -type d -name "*"); do - html=stage/_book/${example#examples/}.html - if [[ -f ${html} ]]; then - echo ${html} - - sed -i s:${example#examples/}.md:${example}/input.md: ${html} - fi -done diff --git a/node_modules/gitbook-plugin-rust-playpen/book/editor.css b/node_modules/gitbook-plugin-rust-playpen/book/editor.css deleted file mode 100644 index 6471ce2dc5..0000000000 --- a/node_modules/gitbook-plugin-rust-playpen/book/editor.css +++ /dev/null @@ -1,84 +0,0 @@ -/* the style here follows graydon/rust-www */ - -#active-code { - position: relative; - display: block; - padding: 10px; - border-radius: 4px; - background-color: #FDFDFD; - border: 1px solid #CCC; -} - -#editor { - padding: none; - margin: none; - width: 100%; - min-height: 72px; - font-size: 13px; - font-family: Menlo, Monaco, Consolas, "Courier New", monospace; -} - -#result { - color: #333; - background-color: #E2EEF6; - margin-top: 10px; - padding: 10px; - display: none; - border-radius: 4px; - font-family: Menlo, Monaco, Consolas, "Courier New", monospace; -} - -#reset-code { - position: absolute; - z-index: 10; - float: right; - right: 8px; - top: 50px; - outline: none; -} - -#run-code { - position: absolute; - z-index: 10; - float: right; - right: 8px; - top: 8px; - outline: none; -} - -.ace-error-text, .ace-error-line, .ace-warning-text, .ace-warning-line { - position: absolute; -} - -.ace-error-text { - background-color: #e9abab; -} - -.ace-error-line { - background-color: #F6E2E2; -} - -.ace-warning-text { - background-color: #FFEF00; -} - -.ace-warning-line { - background-color: #FFFBCB; -} - -.btn-primary { - color: #fff; - background-color: #428bca; - border-color: #357ebd; - border-radius: 4px; -} -.btn-primary:hover, -.btn-primary:focus, -.btn-primary:active { - color: #fff; - background-color: #3276b1; - border-color: #285e8e; -} -.btn-primary:active { - background-image: none; -} diff --git a/node_modules/gitbook-plugin-rust-playpen/book/editor.js b/node_modules/gitbook-plugin-rust-playpen/book/editor.js deleted file mode 100644 index 0772db4265..0000000000 --- a/node_modules/gitbook-plugin-rust-playpen/book/editor.js +++ /dev/null @@ -1,269 +0,0 @@ -// this is mostly the editor implemented by @SergioBenitez for graydon/rust-www -// plus small modifications to accommodate a "Reset" button - -// ECMAScript 6 Backwards compatability -if (typeof String.prototype.startsWith != 'function') { - String.prototype.startsWith = function(str) { - return this.slice(0, str.length) == str; - }; -} - -// Regex for finding new lines -var newLineRegex = /(?:\r\n|\r|\n)/g; - -// DOM items -var editorDiv; -var resetButton; -var runButton; -var resultDiv; - -// Background colors for program result on success/error -var successColor = "#E2EEF6"; -var errorColor = "#F6E2E2"; -var warningColor = "#FFFBCB"; - -// Error message to return when there's a server failure -var errMsg = "The server encountered an error while running the program."; - -// Stores ACE editor markers (highights) for errors -var markers = []; - -// Status codes, because there are no enums in Javascript -var SUCCESS = 0; -var ERROR = 1; -var WARNING = 2; - -// Ace editor -var editor; -var Range; - -// Original source code -var originalCode; - -function initEditor() { - // Fetching DOM items - editorDiv = document.getElementById("editor"); - resetButton = document.getElementById("reset-code"); - runButton = document.getElementById("run-code"); - resultDiv = document.getElementById("result"); - - if (editorDiv === null) - return; // No editor on this page - - // Setup ace editor - editor = ace.edit("editor"); - Range = ace.require('ace/range').Range; - - var executeCode = function(ev) { - resultDiv.style.display = "block"; - resultDiv.innerHTML = "Running..."; - - // Clear previous markers, if any - markers.map(function(id) { editor.getSession().removeMarker(id); }); - - // Get the code, run the program - var program = editor.getValue(); - runProgram(program, handleResult); - }; - - editor.setTheme("ace/theme/tomorrow"); - editor.getSession().setMode("ace/mode/rust"); - editor.setShowPrintMargin(false); - editor.renderer.setShowGutter(false); - editor.setHighlightActiveLine(false); - editor.commands.addCommand({ - name: "run", - bindKey: { - win: "Ctrl-Enter", - mac: "Ctrl-Enter" - }, - exec: executeCode - }) - - originalCode = editor.getSession().getValue(); - - // Set initial size to match initial content - updateEditorHeight(); - - // Registering handler for run button click - runButton.addEventListener("click", executeCode); - - // Registering handler for reset button click - resetButton.addEventListener("click", function(ev) { - // Clear previous markers, if any - markers.map(function(id) { editor.getSession().removeMarker(id); }); - - editor.getSession().setValue(originalCode); - resultDiv.style.display = "none"; - }); - - editor.on('change', updateEditorHeight); - - // Highlight active line when focused - editor.on('focus', function() { - editor.setHighlightActiveLine(true); - }); - - // Don't when not - editor.on('blur', function() { - editor.setHighlightActiveLine(false); - }); -} - -initEditor(); - -require(["gitbook"], function(gitbook) { - gitbook.events.bind("page.change", function() { - initEditor(); - }) -}); - -// Changes the height of the editor to match its contents -function updateEditorHeight() { - // http://stackoverflow.com/questions/11584061/ - var newHeight = editor.getSession().getScreenLength() - * editor.renderer.lineHeight - + editor.renderer.scrollBar.getWidth(); - - editorDiv.style.height = Math.ceil(newHeight).toString() + "px"; - editor.resize(); -}; - -function escapeHTML(unsafe) { - return unsafe - .replace(/&/g, "&") - .replace(//g, ">") - .replace(/"/g, """) - .replace(/'/g, "'") - .replace(newLineRegex, '
'); -} - -// Dispatches a XMLHttpRequest to the Rust playpen, running the program, and -// issues a callback to `callback` with the result (or null on error) -function runProgram(program, callback) { - var req = new XMLHttpRequest(); - var data = JSON.stringify({ - version: "master", - optimize: "0", - code: program - }); - - // console.log("Sending", data); - req.open('POST', "http://play.rust-lang.org/evaluate.json", true); - req.onload = function(e) { - if (req.readyState === 4 && req.status === 200) { - var result = JSON.parse(req.response).result; - - // Need server support to get an accurate version of this. - var statusCode = SUCCESS; - if (result.indexOf("error:") !== -1) { - statusCode = ERROR; - } else if (result.indexOf("warning:") !== -1) { - statusCode = WARNING; - } - - callback(statusCode, result); - } else { - callback(false, null); - } - }; - - req.onerror = function(e) { - callback(false, null); - } - - req.setRequestHeader("Content-Type", "application/json"); - req.send(data); -} - -// The callback to runProgram -function handleResult(statusCode, message) { - // Dispatch depending on result type - if (result == null) { - resultDiv.style.backgroundColor = errorColor; - resultDiv.innerHTML = errMsg; - } else if (statusCode == SUCCESS) { - handleSuccess(message); - } else if (statusCode == WARNING) { - handleWarning(message); - } else { - handleError(message); - } -} - -// Called on successful program run -function handleSuccess(message) { - resultDiv.style.backgroundColor = successColor; - resultDiv.innerHTML = escapeHTML(message); -} - -// Called when program run results in warning(s) -function handleWarning(message) { - resultDiv.style.backgroundColor = warningColor; - handleProblem(message, "warning"); -} - -// Called when program run results in error(s) -function handleError(message) { - resultDiv.style.backgroundColor = errorColor; - handleProblem(message, "error"); -} - -// Called on unsuccessful program run. Detects and prints problems (either -// warnings or errors) in program output and highlights relevant lines and text -// in the code. -function handleProblem(message, problem) { - // Getting list of ranges with problems - var lines = message.split(newLineRegex); - - // Cleaning up the message: keeps only relevant problem output - var cleanMessage = lines.map(function(line) { - if (line.startsWith("") || line.indexOf("^") !== -1) { - var errIndex = line.indexOf(problem + ": "); - if (errIndex !== -1) return line.slice(errIndex); - return ""; - } - - // Discard playpen messages, keep the rest - if (line.startsWith("playpen:")) return ""; - return line; - }).filter(function(line) { - return line !== ""; - }).map(function(line) { - return escapeHTML(line); - }).join("
"); - - // Setting message - resultDiv.innerHTML = cleanMessage; - - // Highlighting the lines - var ranges = parseProblems(lines); - markers = ranges.map(function(range) { - return editor.getSession().addMarker(range, "ace-" + problem + "-line", - "fullLine", false); - }); - - // Highlighting the specific text - markers = markers.concat(ranges.map(function(range) { - return editor.getSession().addMarker(range, "ace-" + problem + "-text", - "text", false); - })); -} - -// Parses a problem message returning a list of ranges (row:col, row:col) where -// problems in the code have occured. -function parseProblems(lines) { - var ranges = []; - for (var i in lines) { - var line = lines[i]; - if (line.startsWith(":") && line.indexOf(": ") !== -1) { - var parts = line.split(/:\s?|\s+/, 5).slice(1, 5); - var ip = parts.map(function(p) { return parseInt(p, 10) - 1; }); - // console.log("line:", line, parts, ip); - ranges.push(new Range(ip[0], ip[1], ip[2], ip[3])); - } - } - - return ranges; -} diff --git a/node_modules/gitbook-plugin-rust-playpen/book/mode-rust.js b/node_modules/gitbook-plugin-rust-playpen/book/mode-rust.js deleted file mode 100644 index f43a904c74..0000000000 --- a/node_modules/gitbook-plugin-rust-playpen/book/mode-rust.js +++ /dev/null @@ -1 +0,0 @@ -ace.define("ace/mode/rust",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/rust_highlight_rules","ace/mode/folding/cstyle"],function(e,t,n){var r=e("../lib/oop"),i=e("./text").Mode,s=e("../tokenizer").Tokenizer,o=e("./rust_highlight_rules").RustHighlightRules,u=e("./folding/cstyle").FoldMode,a=function(){this.HighlightRules=o,this.foldingRules=new u};r.inherits(a,i),function(){this.lineCommentStart="/\\*",this.blockComment={start:"/*",end:"*/"},this.$id="ace/mode/rust"}.call(a.prototype),t.Mode=a}),ace.define("ace/mode/rust_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(e,t,n){var r=e("../lib/oop"),i=e("./text_highlight_rules").TextHighlightRules,s=function(){this.$rules={start:[{token:"variable.other.source.rust",regex:"'[a-zA-Z_][a-zA-Z0-9_]*[^\\']"},{token:"string.quoted.single.source.rust",regex:"'",push:[{token:"string.quoted.single.source.rust",regex:"'",next:"pop"},{include:"#rust_escaped_character"},{defaultToken:"string.quoted.single.source.rust"}]},{token:"string.quoted.double.source.rust",regex:'"',push:[{token:"string.quoted.double.source.rust",regex:'"',next:"pop"},{include:"#rust_escaped_character"},{defaultToken:"string.quoted.double.source.rust"}]},{token:["keyword.source.rust","meta.function.source.rust","entity.name.function.source.rust","meta.function.source.rust"],regex:"\\b(fn)(\\s+)([a-zA-Z_][a-zA-Z0-9_][\\w\\:,+ \\'<>]*)(\\s*\\()"},{token:"support.constant",regex:"\\b[a-zA-Z_][\\w\\d]*::"},{token:"keyword.source.rust",regex:"\\b(?:as|assert|break|claim|const|copy|Copy|do|drop|else|extern|fail|for|if|impl|in|let|log|loop|match|mod|module|move|mut|Owned|priv|pub|pure|ref|return|unchecked|unsafe|use|while|mod|Send|static|trait|class|struct|enum|type)\\b"},{token:"storage.type.source.rust",regex:"\\b(?:Self|m32|m64|m128|f80|f16|f128|int|uint|float|char|bool|u8|u16|u32|u64|f32|f64|i8|i16|i32|i64|str|option|either|c_float|c_double|c_void|FILE|fpos_t|DIR|dirent|c_char|c_schar|c_uchar|c_short|c_ushort|c_int|c_uint|c_long|c_ulong|size_t|ptrdiff_t|clock_t|time_t|c_longlong|c_ulonglong|intptr_t|uintptr_t|off_t|dev_t|ino_t|pid_t|mode_t|ssize_t)\\b"},{token:"variable.language.source.rust",regex:"\\bself\\b"},{token:"keyword.operator",regex:"!|\\$|\\*|\\-\\-|\\-|\\+\\+|\\+|-->|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|/=|%=|\\+=|\\-=|&=|\\^=|,|;"},{token:"constant.language.source.rust",regex:"\\b(?:true|false|Some|None|Left|Right|Ok|Err)\\b"},{token:"support.constant.source.rust",regex:"\\b(?:EXIT_FAILURE|EXIT_SUCCESS|RAND_MAX|EOF|SEEK_SET|SEEK_CUR|SEEK_END|_IOFBF|_IONBF|_IOLBF|BUFSIZ|FOPEN_MAX|FILENAME_MAX|L_tmpnam|TMP_MAX|O_RDONLY|O_WRONLY|O_RDWR|O_APPEND|O_CREAT|O_EXCL|O_TRUNC|S_IFIFO|S_IFCHR|S_IFBLK|S_IFDIR|S_IFREG|S_IFMT|S_IEXEC|S_IWRITE|S_IREAD|S_IRWXU|S_IXUSR|S_IWUSR|S_IRUSR|F_OK|R_OK|W_OK|X_OK|STDIN_FILENO|STDOUT_FILENO|STDERR_FILENO)\\b"},{token:"meta.preprocessor.source.rust",regex:"\\b\\w\\(\\w\\)*!|#\\[[\\w=\\(\\)_]+\\]\\b"},{token:"constant.numeric.integer.source.rust",regex:"\\b(?:[0-9][0-9_]*|[0-9][0-9_]*(?:u|u8|u16|u32|u64)|[0-9][0-9_]*(?:i|i8|i16|i32|i64))\\b"},{token:"constant.numeric.hex.source.rust",regex:"\\b(?:0x[a-fA-F0-9_]+|0x[a-fA-F0-9_]+(?:u|u8|u16|u32|u64)|0x[a-fA-F0-9_]+(?:i|i8|i16|i32|i64))\\b"},{token:"constant.numeric.binary.source.rust",regex:"\\b(?:0b[01_]+|0b[01_]+(?:u|u8|u16|u32|u64)|0b[01_]+(?:i|i8|i16|i32|i64))\\b"},{token:"constant.numeric.float.source.rust",regex:"[0-9][0-9_]*(?:f32|f64|f)|[0-9][0-9_]*[eE][+-]=[0-9_]+|[0-9][0-9_]*[eE][+-]=[0-9_]+(?:f32|f64|f)|[0-9][0-9_]*\\.[0-9_]+|[0-9][0-9_]*\\.[0-9_]+(?:f32|f64|f)|[0-9][0-9_]*\\.[0-9_]+%[eE][+-]=[0-9_]+|[0-9][0-9_]*\\.[0-9_]+%[eE][+-]=[0-9_]+(?:f32|f64|f)"},{token:"comment.line.documentation.source.rust",regex:"//!.*$",push_:[{token:"comment.line.documentation.source.rust",regex:"$",next:"pop"},{defaultToken:"comment.line.documentation.source.rust"}]},{token:"comment.line.double-dash.source.rust",regex:"//.*$",push_:[{token:"comment.line.double-dash.source.rust",regex:"$",next:"pop"},{defaultToken:"comment.line.double-dash.source.rust"}]},{token:"comment.block.source.rust",regex:"/\\*",push:[{token:"comment.block.source.rust",regex:"\\*/",next:"pop"},{defaultToken:"comment.block.source.rust"}]}],"#rust_escaped_character":[{token:"constant.character.escape.source.rust",regex:"\\\\(?:x[\\da-fA-F]{2}|[0-2][0-7]{,2}|3[0-6][0-7]?|37[0-7]?|[4-7][0-7]?|.)"}]},this.normalizeRules()};s.metaData={fileTypes:["rs","rc"],foldingStartMarker:"^.*\\bfn\\s*(\\w+\\s*)?\\([^\\)]*\\)(\\s*\\{[^\\}]*)?\\s*$",foldingStopMarker:"^\\s*\\}",name:"Rust",scopeName:"source.rust"},r.inherits(s,i),t.RustHighlightRules=s}),ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(e,t,n){var r=e("../../lib/oop"),i=e("../../range").Range,s=e("./fold_mode").FoldMode,o=t.FoldMode=function(e){e&&(this.foldingStartMarker=new RegExp(this.foldingStartMarker.source.replace(/\|[^|]*?$/,"|"+e.start)),this.foldingStopMarker=new RegExp(this.foldingStopMarker.source.replace(/\|[^|]*?$/,"|"+e.end)))};r.inherits(o,s),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(e,t,n,r){var i=e.getLine(n),s=i.match(this.foldingStartMarker);if(s){var o=s.index;if(s[1])return this.openingBracketBlock(e,s[1],n,o);var u=e.getCommentFoldRange(n,o+s[0].length,1);return u&&!u.isMultiLine()&&(r?u=this.getSectionRange(e,n):t!="all"&&(u=null)),u}if(t==="markbegin")return;var s=i.match(this.foldingStopMarker);if(s){var o=s.index+s[0].length;return s[1]?this.closingBracketBlock(e,s[1],n,o):e.getCommentFoldRange(n,o,-1)}},this.getSectionRange=function(e,t){var n=e.getLine(t),r=n.search(/\S/),s=t,o=n.length;t+=1;var u=t,a=e.getLength();while(++tf)break;var l=this.getFoldWidgetRange(e,"all",t);if(l){if(l.start.row<=s)break;if(l.isMultiLine())t=l.end.row;else if(r==f)break}u=t}return new i(s,o,u,e.getLine(u).length)}}.call(o.prototype)}) \ No newline at end of file diff --git a/node_modules/gitbook-plugin-rust-playpen/index.js b/node_modules/gitbook-plugin-rust-playpen/index.js deleted file mode 100644 index 19cf6b464f..0000000000 --- a/node_modules/gitbook-plugin-rust-playpen/index.js +++ /dev/null @@ -1,12 +0,0 @@ -module.exports = { - book: { - assets: "./book", - css: [ - "editor.css" - ], - js: [ - "editor.js", - "mode-rust.js" - ] - } -}; diff --git a/node_modules/gitbook-plugin-rust-playpen/package.json b/node_modules/gitbook-plugin-rust-playpen/package.json deleted file mode 100644 index 34040733f9..0000000000 --- a/node_modules/gitbook-plugin-rust-playpen/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "description": "Integrate Rust playpen with gitbook", - "engines": { - "gitbook": "*" - }, - "main": "index.js", - "name": "gitbook-plugin-rust-playpen" -} diff --git a/setup-stage.sh b/setup-stage.sh deleted file mode 100755 index 8d4ff232fd..0000000000 --- a/setup-stage.sh +++ /dev/null @@ -1,4 +0,0 @@ -mkdir -p bin -mkdir -p stage/node_modules -ln -sf ../book.json stage -ln -sf ../examples/README.md stage diff --git a/src/SUMMARY.md b/src/SUMMARY.md new file mode 100644 index 0000000000..216bceadfe --- /dev/null +++ b/src/SUMMARY.md @@ -0,0 +1,218 @@ +# Summary + +[Introduction](index.md) + +- [Hello World](hello.md) + - [Comments](hello/comment.md) + - [Formatted print](hello/print.md) + - [Debug](hello/print/print_debug.md) + - [Display](hello/print/print_display.md) + - [Testcase: List](hello/print/print_display/testcase_list.md) + - [Formatting](hello/print/fmt.md) + +- [Primitives](primitives.md) + - [Literals and operators](primitives/literals.md) + - [Tuples](primitives/tuples.md) + - [Arrays and Slices](primitives/array.md) + +- [Custom Types](custom_types.md) + - [Structures](custom_types/structs.md) + - [Enums](custom_types/enum.md) + - [use](custom_types/enum/enum_use.md) + - [C-like](custom_types/enum/c_like.md) + - [Testcase: linked-list](custom_types/enum/testcase_linked_list.md) + - [constants](custom_types/constants.md) + +- [Variable Bindings](variable_bindings.md) + - [Mutability](variable_bindings/mut.md) + - [Scope and Shadowing](variable_bindings/scope.md) + - [Declare first](variable_bindings/declare.md) + - [Freezing](variable_bindings/freeze.md) + +- [Types](types.md) + - [Casting](types/cast.md) + - [Literals](types/literals.md) + - [Inference](types/inference.md) + - [Aliasing](types/alias.md) + +- [Conversion](conversion.md) + - [`From` and `Into`](conversion/from_into.md) + - [`TryFrom` and `TryInto`](conversion/try_from_try_into.md) + - [To and from `String`s](conversion/string.md) + +- [Expressions](expression.md) + +- [Flow of Control](flow_control.md) + - [if/else](flow_control/if_else.md) + - [loop](flow_control/loop.md) + - [Nesting and labels](flow_control/loop/nested.md) + - [Returning from loops](flow_control/loop/return.md) + - [while](flow_control/while.md) + - [for and range](flow_control/for.md) + - [match](flow_control/match.md) + - [Destructuring](flow_control/match/destructuring.md) + - [tuples](flow_control/match/destructuring/destructure_tuple.md) + - [enums](flow_control/match/destructuring/destructure_enum.md) + - [pointers/ref](flow_control/match/destructuring/destructure_pointers.md) + - [structs](flow_control/match/destructuring/destructure_structures.md) + - [Guards](flow_control/match/guard.md) + - [Binding](flow_control/match/binding.md) + - [if let](flow_control/if_let.md) + - [while let](flow_control/while_let.md) + +- [Functions](fn.md) + - [Methods](fn/methods.md) + - [Closures](fn/closures.md) + - [Capturing](fn/closures/capture.md) + - [As input parameters](fn/closures/input_parameters.md) + - [Type anonymity](fn/closures/anonymity.md) + - [Input functions](fn/closures/input_functions.md) + - [As output parameters](fn/closures/output_parameters.md) + - [Examples in `std`](fn/closures/closure_examples.md) + - [Iterator::any](fn/closures/closure_examples/iter_any.md) + - [Searching through iterators](fn/closures/closure_examples/iter_find.md) + - [Higher Order Functions](fn/hof.md) + - [Diverging functions](fn/diverging.md) + +- [Modules](mod.md) + - [Visibility](mod/visibility.md) + - [Struct visibility](mod/struct_visibility.md) + - [The `use` declaration](mod/use.md) + - [`super` and `self`](mod/super.md) + - [File hierarchy](mod/split.md) + +- [Crates](crates.md) + - [Creating a Library](crates/lib.md) + - [Using a Library](crates/using_lib.md) + +- [Cargo](cargo.md) + - [Dependencies](cargo/deps.md) + - [Conventions](cargo/conventions.md) + - [Tests](cargo/test.md) + - [Build Scripts](cargo/build_scripts.md) + +- [Attributes](attribute.md) + - [`dead_code`](attribute/unused.md) + - [Crates](attribute/crate.md) + - [`cfg`](attribute/cfg.md) + - [Custom](attribute/cfg/custom.md) + +- [Generics](generics.md) + - [Functions](generics/gen_fn.md) + - [Implementation](generics/impl.md) + - [Traits](generics/gen_trait.md) + - [Bounds](generics/bounds.md) + - [Testcase: empty bounds](generics/bounds/testcase_empty.md) + - [Multiple bounds](generics/multi_bounds.md) + - [Where clauses](generics/where.md) + - [New Type Idiom](generics/new_types.md) + - [Associated items](generics/assoc_items.md) + - [The Problem](generics/assoc_items/the_problem.md) + - [Associated types](generics/assoc_items/types.md) + - [Phantom type parameters](generics/phantom.md) + - [Testcase: unit clarification](generics/phantom/testcase_units.md) + +- [Scoping rules](scope.md) + - [RAII](scope/raii.md) + - [Ownership and moves](scope/move.md) + - [Mutability](scope/move/mut.md) + - [Partial moves](scope/move/partial_move.md) + - [Borrowing](scope/borrow.md) + - [Mutability](scope/borrow/mut.md) + - [Aliasing](scope/borrow/alias.md) + - [The ref pattern](scope/borrow/ref.md) + - [Lifetimes](scope/lifetime.md) + - [Explicit annotation](scope/lifetime/explicit.md) + - [Functions](scope/lifetime/fn.md) + - [Methods](scope/lifetime/methods.md) + - [Structs](scope/lifetime/struct.md) + - [Traits](scope/lifetime/trait.md) + - [Bounds](scope/lifetime/lifetime_bounds.md) + - [Coercion](scope/lifetime/lifetime_coercion.md) + - [Static](scope/lifetime/static_lifetime.md) + - [Elision](scope/lifetime/elision.md) + +- [Traits](trait.md) + - [Derive](trait/derive.md) + - [Returning Traits with `dyn`](trait/dyn.md) + - [Operator Overloading](trait/ops.md) + - [Drop](trait/drop.md) + - [Iterators](trait/iter.md) + - [`impl Trait`](trait/impl_trait.md) + - [Clone](trait/clone.md) + - [Supertraits](trait/supertraits.md) + - [Disambiguating overlapping traits](trait/disambiguating.md) + +- [macro_rules!](macros.md) + - [Syntax](macros/syntax.md) + - [Designators](macros/designators.md) + - [Overload](macros/overload.md) + - [Repeat](macros/repeat.md) + - [DRY (Don't Repeat Yourself)](macros/dry.md) + - [DSL (Domain Specific Languages)](macros/dsl.md) + - [Variadics](macros/variadics.md) + +- [Error handling](error.md) + - [`panic`](error/panic.md) + - [`Option` & `unwrap`](error/option_unwrap.md) + - [Unpacking options with `?`](error/option_unwrap/question_mark.md) + - [Combinators: `map`](error/option_unwrap/map.md) + - [Combinators: `and_then`](error/option_unwrap/and_then.md) + - [`Result`](error/result.md) + - [`map` for `Result`](error/result/result_map.md) + - [aliases for `Result`](error/result/result_alias.md) + - [Early returns](error/result/early_returns.md) + - [Introducing `?`](error/result/enter_question_mark.md) + - [Multiple error types](error/multiple_error_types.md) + - [Pulling `Result`s out of `Option`s](error/multiple_error_types/option_result.md) + - [Defining an error type](error/multiple_error_types/define_error_type.md) + - [`Box`ing errors](error/multiple_error_types/boxing_errors.md) + - [Other uses of `?`](error/multiple_error_types/reenter_question_mark.md) + - [Wrapping errors](error/multiple_error_types/wrap_error.md) + - [Iterating over `Result`s](error/iter_result.md) + +- [Std library types](std.md) + - [Box, stack and heap](std/box.md) + - [Vectors](std/vec.md) + - [Strings](std/str.md) + - [`Option`](std/option.md) + - [`Result`](std/result.md) + - [`?`](std/result/question_mark.md) + - [`panic!`](std/panic.md) + - [HashMap](std/hash.md) + - [Alternate/custom key types](std/hash/alt_key_types.md) + - [HashSet](std/hash/hashset.md) + - [`Rc`](std/rc.md) + - [`Arc`](std/arc.md) + +- [Std misc](std_misc.md) + - [Threads](std_misc/threads.md) + - [Testcase: map-reduce](std_misc/threads/testcase_mapreduce.md) + - [Channels](std_misc/channels.md) + - [Path](std_misc/path.md) + - [File I/O](std_misc/file.md) + - [`open`](std_misc/file/open.md) + - [`create`](std_misc/file/create.md) + - [`read lines`](std_misc/file/read_lines.md) + - [Child processes](std_misc/process.md) + - [Pipes](std_misc/process/pipe.md) + - [Wait](std_misc/process/wait.md) + - [Filesystem Operations](std_misc/fs.md) + - [Program arguments](std_misc/arg.md) + - [Argument parsing](std_misc/arg/matching.md) + - [Foreign Function Interface](std_misc/ffi.md) + +- [Testing](testing.md) + - [Unit testing](testing/unit_testing.md) + - [Documentation testing](testing/doc_testing.md) + - [Integration testing](testing/integration_testing.md) + - [Dev-dependencies](testing/dev_dependencies.md) + +- [Unsafe Operations](unsafe.md) + +- [Compatibility](compatibility.md) + - [Raw identifiers](compatibility/raw_identifiers.md) + +- [Meta](meta.md) + - [Documentation](meta/doc.md) + - [Playpen](meta/playpen.md) diff --git a/examples/attribute/input.md b/src/attribute.md similarity index 70% rename from examples/attribute/input.md rename to src/attribute.md index cf7f90fff1..13b0a60b46 100644 --- a/examples/attribute/input.md +++ b/src/attribute.md @@ -1,9 +1,12 @@ +# Attributes + An attribute is metadata applied to some module, crate or item. This metadata can be used to/for: + * [conditional compilation of code][cfg] -* [set crate name, version and type (binary or library)][config] +* [set crate name, version and type (binary or library)][crate] * disable [lints][lint] (warnings) * enable compiler features (macros, glob imports, etc.) * link to a foreign library @@ -20,6 +23,16 @@ Attributes can take arguments with different syntaxes: * `#[attribute(key = "value")]` * `#[attribute(value)]` -[cfg]: /attribute/cfg.html -[crate]: /attribute/crate.html +Attributes can have multiple values and can be separated over multiple lines, too: + +```rust,ignore +#[attribute(value, value2)] + + +#[attribute(value, value2, value3, + value4, value5)] +``` + +[cfg]: attribute/cfg.md +[crate]: attribute/crate.md [lint]: https://en.wikipedia.org/wiki/Lint_%28software%29 diff --git a/src/attribute/cfg.md b/src/attribute/cfg.md new file mode 100644 index 0000000000..d0a4a10b73 --- /dev/null +++ b/src/attribute/cfg.md @@ -0,0 +1,43 @@ +# `cfg` + +Configuration conditional checks are possible through two different operators: + +* the `cfg` attribute: `#[cfg(...)]` in attribute position +* the `cfg!` macro: `cfg!(...)` in boolean expressions + +While the former enables conditional compilation, the latter conditionally +evaluates to `true` or `false` literals allowing for checks at run-time. Both +utilize identical argument syntax. + +```rust,editable +// This function only gets compiled if the target OS is linux +#[cfg(target_os = "linux")] +fn are_you_on_linux() { + println!("You are running linux!"); +} + +// And this function only gets compiled if the target OS is *not* linux +#[cfg(not(target_os = "linux"))] +fn are_you_on_linux() { + println!("You are *not* running linux!"); +} + +fn main() { + are_you_on_linux(); + + println!("Are you sure?"); + if cfg!(target_os = "linux") { + println!("Yes. It's definitely linux!"); + } else { + println!("Yes. It's definitely *not* linux!"); + } +} +``` + +### See also: + +[the reference][ref], [`cfg!`][cfg], and [macros][macros]. + +[cfg]: https://doc.rust-lang.org/std/macro.cfg!.html +[macros]: ../macros.md +[ref]: https://doc.rust-lang.org/reference/attributes.html#conditional-compilation diff --git a/src/attribute/cfg/custom.md b/src/attribute/cfg/custom.md new file mode 100644 index 0000000000..182d33654c --- /dev/null +++ b/src/attribute/cfg/custom.md @@ -0,0 +1,24 @@ +# Custom + +Some conditionals like `target_os` are implicitly provided by `rustc`, but +custom conditionals must be passed to `rustc` using the `--cfg` flag. + +```rust,editable,ignore,mdbook-runnable +#[cfg(some_condition)] +fn conditional_function() { + println!("condition met!"); +} + +fn main() { + conditional_function(); +} +``` + +Try to run this to see what happens without the custom `cfg` flag. + +With the custom `cfg` flag: + +```shell +$ rustc --cfg some_condition custom.rs && ./custom +condition met! +``` diff --git a/src/attribute/crate.md b/src/attribute/crate.md new file mode 100644 index 0000000000..1539c63988 --- /dev/null +++ b/src/attribute/crate.md @@ -0,0 +1,40 @@ +# Crates + +The `crate_type` attribute can be used to tell the compiler whether a crate is +a binary or a library (and even which type of library), and the `crate_name` +attribute can be used to set the name of the crate. + +However, it is important to note that both the `crate_type` and `crate_name` +attributes have **no** effect whatsoever when using Cargo, the Rust package +manager. Since Cargo is used for the majority of Rust projects, this means +real-world uses of `crate_type` and `crate_name` are relatively limited. + +```rust,editable +// This crate is a library +#![crate_type = "lib"] +// The library is named "rary" +#![crate_name = "rary"] + +pub fn public_function() { + println!("called rary's `public_function()`"); +} + +fn private_function() { + println!("called rary's `private_function()`"); +} + +pub fn indirect_access() { + print!("called rary's `indirect_access()`, that\n> "); + + private_function(); +} +``` + +When the `crate_type` attribute is used, we no longer need to pass the +`--crate-type` flag to `rustc`. + +```shell +$ rustc lib.rs +$ ls lib* +library.rlib +``` diff --git a/examples/fn/unused/input.md b/src/attribute/unused.md similarity index 55% rename from examples/fn/unused/input.md rename to src/attribute/unused.md index 9295a087f1..1eab374808 100644 --- a/examples/fn/unused/input.md +++ b/src/attribute/unused.md @@ -1,8 +1,23 @@ +# `dead_code` + The compiler provides a `dead_code` [*lint*][lint] that will warn about unused functions. An *attribute* can be used to disable the lint. -{unused.play} +```rust,editable +fn used_function() {} + +// `#[allow(dead_code)]` is an attribute that disables the `dead_code` lint +#[allow(dead_code)] +fn unused_function() {} + +fn noisy_unused_function() {} +// FIXME ^ Add an attribute to suppress the warning + +fn main() { + used_function(); +} +``` Note that in real programs, you should eliminate dead code. In these examples we'll allow dead code in some places because of the interactive nature of the diff --git a/src/cargo.md b/src/cargo.md new file mode 100644 index 0000000000..0f57c13698 --- /dev/null +++ b/src/cargo.md @@ -0,0 +1,12 @@ +# Cargo + +`cargo` is the official Rust package management tool. It has lots of really +useful features to improve code quality and developer velocity! These include + +- Dependency management and integration with [crates.io](https://crates.io) (the + official Rust package registry) +- Awareness of unit tests +- Awareness of benchmarks + +This chapter will go through some quick basics, but you can find the +comprehensive docs in [The Cargo Book](https://doc.rust-lang.org/cargo/). diff --git a/src/cargo/build_scripts.md b/src/cargo/build_scripts.md new file mode 100644 index 0000000000..6db3afe90a --- /dev/null +++ b/src/cargo/build_scripts.md @@ -0,0 +1,39 @@ +# Build Scripts + +Sometimes a normal build from `cargo` is not enough. Perhaps your crate needs +some pre-requisites before `cargo` will successfully compile, things like code +generation, or some native code that needs to be compiled. To solve this problem +we have build scripts that Cargo can run. + +To add a build script to your package it can either be specified in the +`Cargo.toml` as follows: + +```toml +[package] +... +build = "build.rs" +``` + +Otherwise Cargo will look for a `build.rs` file in the project directory by +default. + +## How to use a build script + +The build script is simply another Rust file that will be compiled and invoked +prior to compiling anything else in the package. Hence it can be used to fulfill +pre-requisites of your crate. + +Cargo provides the script with inputs via environment variables [specified +here] that can be used. + +The script provides output via stdout. All lines printed are written to +`target/debug/build//output`. Further, lines prefixed with `cargo:` will be +interpreted by Cargo directly and hence can be used to define parameters for the +package's compilation. + +For further specification and examples have a read of the +[Cargo specification][cargo_specification]. + +[specified here]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts + +[cargo_specification]: https://doc.rust-lang.org/cargo/reference/build-scripts.html diff --git a/src/cargo/conventions.md b/src/cargo/conventions.md new file mode 100644 index 0000000000..6e8196608e --- /dev/null +++ b/src/cargo/conventions.md @@ -0,0 +1,37 @@ +# Conventions + +In the previous chapter, we saw the following directory hierarchy: + +```txt +foo +├── Cargo.toml +└── src + └── main.rs +``` + +Suppose that we wanted to have two binaries in the same project, though. What +then? + +It turns out that `cargo` supports this. The default binary name is `main`, as +we saw before, but you can add additional binaries by placing them in a `bin/` +directory: + +```txt +foo +├── Cargo.toml +└── src + ├── main.rs + └── bin + └── my_other_bin.rs +``` + +To tell `cargo` to compile or run this binary as opposed to the default or other +binaries, we just pass `cargo` the `--bin my_other_bin` flag, where `my_other_bin` +is the name of the binary we want to work with. + +In addition to extra binaries, `cargo` supports [more features] such as +benchmarks, tests, and examples. + +In the next chapter, we will look more closely at tests. + +[more features]: https://doc.rust-lang.org/cargo/guide/project-layout.html diff --git a/src/cargo/deps.md b/src/cargo/deps.md new file mode 100644 index 0000000000..8913e9e383 --- /dev/null +++ b/src/cargo/deps.md @@ -0,0 +1,91 @@ +# Dependencies + +Most programs have dependencies on some libraries. If you have ever managed +dependencies by hand, you know how much of a pain this can be. Luckily, the Rust +ecosystem comes standard with `cargo`! `cargo` can manage dependencies for a +project. + +To create a new Rust project, + +```sh +# A binary +cargo new foo + +# OR A library +cargo new --lib foo +``` + +For the rest of this chapter, let's assume we are making a binary, rather than +a library, but all of the concepts are the same. + +After the above commands, you should see a file hierarchy like this: + +```txt +foo +├── Cargo.toml +└── src + └── main.rs +``` + +The `main.rs` is the root source file for your new project -- nothing new there. +The `Cargo.toml` is the config file for `cargo` for this project (`foo`). If you +look inside it, you should see something like this: + +```toml +[package] +name = "foo" +version = "0.1.0" +authors = ["mark"] + +[dependencies] +``` + +The `name` field under `[package]` determines the name of the project. This is +used by `crates.io` if you publish the crate (more later). It is also the name +of the output binary when you compile. + +The `version` field is a crate version number using [Semantic +Versioning](http://semver.org/). + +The `authors` field is a list of authors used when publishing the crate. + +The `[dependencies]` section lets you add dependencies for your project. + +For example, suppose that we want our program to have a great CLI. You can find +lots of great packages on [crates.io](https://crates.io) (the official Rust +package registry). One popular choice is [clap](https://crates.io/crates/clap). +As of this writing, the most recent published version of `clap` is `2.27.1`. To +add a dependency to our program, we can simply add the following to our +`Cargo.toml` under `[dependencies]`: `clap = "2.27.1"`. And that's it! You can start using +`clap` in your program. + +`cargo` also supports [other types of dependencies][dependencies]. Here is just +a small sampling: + +```toml +[package] +name = "foo" +version = "0.1.0" +authors = ["mark"] + +[dependencies] +clap = "2.27.1" # from crates.io +rand = { git = "https://github.com/rust-lang-nursery/rand" } # from online repo +bar = { path = "../bar" } # from a path in the local filesystem +``` + +`cargo` is more than a dependency manager. All of the available +configuration options are listed in the [format specification][manifest] of +`Cargo.toml`. + +To build our project we can execute `cargo build` anywhere in the project +directory (including subdirectories!). We can also do `cargo run` to build and +run. Notice that these commands will resolve all dependencies, download crates +if needed, and build everything, including your crate. (Note that it only +rebuilds what it has not already built, similar to `make`). + +Voila! That's all there is to it! + + +[manifest]: https://doc.rust-lang.org/cargo/reference/manifest.html +[dependencies]: https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html diff --git a/src/cargo/test.md b/src/cargo/test.md new file mode 100644 index 0000000000..01884a09af --- /dev/null +++ b/src/cargo/test.md @@ -0,0 +1,154 @@ +# Testing + +As we know testing is integral to any piece of software! Rust has first-class +support for unit and integration testing ([see this +chapter](https://doc.rust-lang.org/book/ch11-00-testing.html) in +TRPL). + +From the testing chapters linked above, we see how to write unit tests and +integration tests. Organizationally, we can place unit tests in the modules they +test and integration tests in their own `tests/` directory: + +```txt +foo +├── Cargo.toml +├── src +│ └── main.rs +│ └── lib.rs +└── tests + ├── my_test.rs + └── my_other_test.rs +``` + +Each file in `tests` is a separate +[integration test](https://doc.rust-lang.org/book/ch11-03-test-organization.html#integration-tests), +i.e. a test that is meant to test your library as if it were being called from a dependent +crate. + +The [Testing][testing] chapter elaborates on the three different testing styles: +[Unit][unit_testing], [Doc][doc_testing], and [Integration][integration_testing]. + +`cargo` naturally provides an easy way to run all of your tests! + +```shell +$ cargo test +``` + +You should see output like this: + +```shell +$ cargo test + Compiling blah v0.1.0 (file:///nobackup/blah) + Finished dev [unoptimized + debuginfo] target(s) in 0.89 secs + Running target/debug/deps/blah-d3b32b97275ec472 + +running 3 tests +test test_bar ... ok +test test_baz ... ok +test test_foo_bar ... ok +test test_foo ... ok + +test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out +``` + +You can also run tests whose name matches a pattern: + +```shell +$ cargo test test_foo +``` + +```shell +$ cargo test test_foo + Compiling blah v0.1.0 (file:///nobackup/blah) + Finished dev [unoptimized + debuginfo] target(s) in 0.35 secs + Running target/debug/deps/blah-d3b32b97275ec472 + +running 2 tests +test test_foo ... ok +test test_foo_bar ... ok + +test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out +``` + +One word of caution: Cargo may run multiple tests concurrently, so make sure +that they don't race with each other. + +One example of this concurrency causing issues is if two tests output to a +file, such as below: + +```rust +#[cfg(test)] +mod tests { + // Import the necessary modules + use std::fs::OpenOptions; + use std::io::Write; + + // This test writes to a file + #[test] + fn test_file() { + // Opens the file ferris.txt or creates one if it doesn't exist. + let mut file = OpenOptions::new() + .append(true) + .create(true) + .open("ferris.txt") + .expect("Failed to open ferris.txt"); + + // Print "Ferris" 5 times. + for _ in 0..5 { + file.write_all("Ferris\n".as_bytes()) + .expect("Could not write to ferris.txt"); + } + } + + // This test tries to write to the same file + #[test] + fn test_file_also() { + // Opens the file ferris.txt or creates one if it doesn't exist. + let mut file = OpenOptions::new() + .append(true) + .create(true) + .open("ferris.txt") + .expect("Failed to open ferris.txt"); + + // Print "Corro" 5 times. + for _ in 0..5 { + file.write_all("Corro\n".as_bytes()) + .expect("Could not write to ferris.txt"); + } + } +} +``` + +Although the intent is to get the following: +```shell +$ cat ferris.txt +Ferris +Ferris +Ferris +Ferris +Ferris +Corro +Corro +Corro +Corro +Corro +``` +What actually gets put into `ferris.txt` is this: +```shell +$ cargo test test_foo +Corro +Ferris +Corro +Ferris +Corro +Ferris +Corro +Ferris +Corro +Ferris +``` + +[testing]: ../testing.md +[unit_testing]: ../testing/unit_testing.md +[integration_testing]: ../testing/unit_testing.md +[doc_testing]: ../testing/doc_testing.md diff --git a/src/compatibility.md b/src/compatibility.md new file mode 100644 index 0000000000..00424ceb22 --- /dev/null +++ b/src/compatibility.md @@ -0,0 +1,7 @@ +# Compatibility + +The Rust language is fastly evolving, and because of this certain compatibility +issues can arise, despite efforts to ensure forwards-compatibility wherever +possible. + +* [Raw identifiers](compatibility/raw_identifiers.md) diff --git a/src/compatibility/raw_identifiers.md b/src/compatibility/raw_identifiers.md new file mode 100644 index 0000000000..eb42cf645a --- /dev/null +++ b/src/compatibility/raw_identifiers.md @@ -0,0 +1,42 @@ +# Raw identifiers + +Rust, like many programming languages, has the concept of "keywords". +These identifiers mean something to the language, and so you cannot use them in +places like variable names, function names, and other places. +Raw identifiers let you use keywords where they would not normally be allowed. +This is particularly useful when Rust introduces new keywords, and a library +using an older edition of Rust has a variable or function with the same name +as a keyword introduced in a newer edition. + +For example, consider a crate `foo` compiled with the 2015 edition of Rust that +exports a function named `try`. This keyword is reserved for a new feature in +the 2018 edition, so without raw identifiers, we would have no way to name the +function. + +```rust,ignore +extern crate foo; + +fn main() { + foo::try(); +} +``` + +You'll get this error: + +```text +error: expected identifier, found keyword `try` + --> src/main.rs:4:4 + | +4 | foo::try(); + | ^^^ expected identifier, found keyword +``` + +You can write this with a raw identifier: + +```rust,ignore +extern crate foo; + +fn main() { + foo::r#try(); +} +``` diff --git a/src/conversion.md b/src/conversion.md new file mode 100644 index 0000000000..52a96d06c4 --- /dev/null +++ b/src/conversion.md @@ -0,0 +1,14 @@ +# Conversion + +Primitive types can be converted to each other through [casting]. + +Rust addresses conversion between custom types (i.e., `struct` and `enum`) +by the use of [traits]. The generic +conversions will use the [`From`] and [`Into`] traits. However there are more +specific ones for the more common cases, in particular when converting to and +from `String`s. + +[casting]: types/cast.md +[traits]: trait.md +[`From`]: https://doc.rust-lang.org/std/convert/trait.From.html +[`Into`]: https://doc.rust-lang.org/std/convert/trait.Into.html diff --git a/src/conversion/from_into.md b/src/conversion/from_into.md new file mode 100644 index 0000000000..266d10f285 --- /dev/null +++ b/src/conversion/from_into.md @@ -0,0 +1,76 @@ +# `From` and `Into` + +The [`From`] and [`Into`] traits are inherently linked, and this is actually part of +its implementation. If you are able to convert type A from type B, then it +should be easy to believe that we should be able to convert type B to type A. + +## `From` + +The [`From`] trait allows for a type to define how to create itself from another +type, hence providing a very simple mechanism for converting between several +types. There are numerous implementations of this trait within the standard +library for conversion of primitive and common types. + +For example we can easily convert a `str` into a `String` + +```rust +let my_str = "hello"; +let my_string = String::from(my_str); +``` + +We can do similar for defining a conversion for our own type. + +```rust,editable +use std::convert::From; + +#[derive(Debug)] +struct Number { + value: i32, +} + +impl From for Number { + fn from(item: i32) -> Self { + Number { value: item } + } +} + +fn main() { + let num = Number::from(30); + println!("My number is {:?}", num); +} +``` + +## `Into` + +The [`Into`] trait is simply the reciprocal of the `From` trait. That is, if you +have implemented the `From` trait for your type, `Into` will call it when +necessary. + +Using the `Into` trait will typically require specification of the type to +convert into as the compiler is unable to determine this most of the time. +However this is a small trade-off considering we get the functionality for free. + +```rust,editable +use std::convert::From; + +#[derive(Debug)] +struct Number { + value: i32, +} + +impl From for Number { + fn from(item: i32) -> Self { + Number { value: item } + } +} + +fn main() { + let int = 5; + // Try removing the type declaration + let num: Number = int.into(); + println!("My number is {:?}", num); +} +``` + +[`From`]: https://doc.rust-lang.org/std/convert/trait.From.html +[`Into`]: https://doc.rust-lang.org/std/convert/trait.Into.html diff --git a/src/conversion/string.md b/src/conversion/string.md new file mode 100644 index 0000000000..ab1452153a --- /dev/null +++ b/src/conversion/string.md @@ -0,0 +1,55 @@ +# To and from Strings + +## Converting to String + +To convert any type to a `String` is as simple as implementing the [`ToString`] +trait for the type. Rather than doing so directly, you should implement the +[`fmt::Display`][Display] trait which automagically provides [`ToString`] and +also allows printing the type as discussed in the section on [`print!`][print]. + +```rust,editable +use std::fmt; + +struct Circle { + radius: i32 +} + +impl fmt::Display for Circle { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Circle of radius {}", self.radius) + } +} + +fn main() { + let circle = Circle { radius: 6 }; + println!("{}", circle.to_string()); +} +``` + +## Parsing a String + +One of the more common types to convert a string into is a number. The idiomatic +approach to this is to use the [`parse`] function and either to arrange for +type inference or to specify the type to parse using the 'turbofish' syntax. +Both alternatives are shown in the following example. + +This will convert the string into the type specified so long as the [`FromStr`] +trait is implemented for that type. This is implemented for numerous types +within the standard library. To obtain this functionality on a user defined type +simply implement the [`FromStr`] trait for that type. + +```rust,editable +fn main() { + let parsed: i32 = "5".parse().unwrap(); + let turbo_parsed = "10".parse::().unwrap(); + + let sum = parsed + turbo_parsed; + println!("Sum: {:?}", sum); +} +``` + +[`ToString`]: https://doc.rust-lang.org/std/string/trait.ToString.html +[Display]: https://doc.rust-lang.org/std/fmt/trait.Display.html +[print]: ../hello/print.md +[`parse`]: https://doc.rust-lang.org/std/primitive.str.html#method.parse +[`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html diff --git a/src/conversion/try_from_try_into.md b/src/conversion/try_from_try_into.md new file mode 100644 index 0000000000..ac62ad154b --- /dev/null +++ b/src/conversion/try_from_try_into.md @@ -0,0 +1,45 @@ +# `TryFrom` and `TryInto` + +Similar to [`From` and `Into`][from-into], [`TryFrom`] and [`TryInto`] are +generic traits for converting between types. Unlike `From`/`Into`, the +`TryFrom`/`TryInto` traits are used for fallible conversions, and as such, +return [`Result`]s. + +[from-into]: from_into.html +[`TryFrom`]: https://doc.rust-lang.org/std/convert/trait.TryFrom.html +[`TryInto`]: https://doc.rust-lang.org/std/convert/trait.TryInto.html +[`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html + +```rust,editable +use std::convert::TryFrom; +use std::convert::TryInto; + +#[derive(Debug, PartialEq)] +struct EvenNumber(i32); + +impl TryFrom for EvenNumber { + type Error = (); + + fn try_from(value: i32) -> Result { + if value % 2 == 0 { + Ok(EvenNumber(value)) + } else { + Err(()) + } + } +} + +fn main() { + // TryFrom + + assert_eq!(EvenNumber::try_from(8), Ok(EvenNumber(8))); + assert_eq!(EvenNumber::try_from(5), Err(())); + + // TryInto + + let result: Result = 8i32.try_into(); + assert_eq!(result, Ok(EvenNumber(8))); + let result: Result = 5i32.try_into(); + assert_eq!(result, Err(())); +} +``` diff --git a/examples/crates/input.md b/src/crates.md similarity index 50% rename from examples/crates/input.md rename to src/crates.md index 1fa3ad9809..b954eec6cd 100644 --- a/examples/crates/input.md +++ b/src/crates.md @@ -1,9 +1,12 @@ +# Crates + A crate is a compilation unit in Rust. Whenever `rustc some_file.rs` is called, `some_file.rs` is treated as the *crate file*. If `some_file.rs` has `mod` -declarations in it, then the contents of the module files will get merged with -the crate file *before* running the compiler over it. In other words, modules -do *not* get compiled individually, only crates get compiled. +declarations in it, then the contents of the module files would be inserted in +places where `mod` declarations in the crate file are found, *before* running +the compiler over it. In other words, modules do *not* get compiled +individually, only crates get compiled. A crate can be compiled into a binary or into a library. By default, `rustc` will produce a binary from a crate. This behavior can be overridden by passing -the `--crate-type` flag to `rustc`. +the `--crate-type` flag to `lib`. diff --git a/src/crates/lib.md b/src/crates/lib.md new file mode 100644 index 0000000000..44593f3bb0 --- /dev/null +++ b/src/crates/lib.md @@ -0,0 +1,32 @@ +# Creating a Library + +Let's create a library, and then see how to link it to another crate. + +```rust,ignore +pub fn public_function() { + println!("called rary's `public_function()`"); +} + +fn private_function() { + println!("called rary's `private_function()`"); +} + +pub fn indirect_access() { + print!("called rary's `indirect_access()`, that\n> "); + + private_function(); +} +``` + +```shell +$ rustc --crate-type=lib rary.rs +$ ls lib* +library.rlib +``` + +Libraries get prefixed with "lib", and by default they get named after their +crate file, but this default name can be overridden by passing +the `--crate-name` option to `rustc` or by using the [`crate_name` +attribute][crate-name]. + +[crate-name]: ../attribute/crate.md \ No newline at end of file diff --git a/src/crates/using_lib.md b/src/crates/using_lib.md new file mode 100644 index 0000000000..102080700f --- /dev/null +++ b/src/crates/using_lib.md @@ -0,0 +1,27 @@ +# Using a Library + +To link a crate to this new library you may use `rustc`'s `--extern` flag. All +of its items will then be imported under a module named the same as the library. +This module generally behaves the same way as any other module. + +```rust,ignore +// extern crate rary; // May be required for Rust 2015 edition or earlier + +fn main() { + rary::public_function(); + + // Error! `private_function` is private + //rary::private_function(); + + rary::indirect_access(); +} +``` + +```txt +# Where library.rlib is the path to the compiled library, assumed that it's +# in the same directory here: +$ rustc executable.rs --extern rary=library.rlib --edition=2018 && ./executable +called rary's `public_function()` +called rary's `indirect_access()`, that +> called rary's `private_function()` +``` diff --git a/src/custom_types.md b/src/custom_types.md new file mode 100644 index 0000000000..20a408b2e0 --- /dev/null +++ b/src/custom_types.md @@ -0,0 +1,8 @@ +# Custom Types + +Rust custom data types are formed mainly through the two keywords: + +* `struct`: define a structure +* `enum`: define an enumeration + +Constants can also be created via the `const` and `static` keywords. \ No newline at end of file diff --git a/src/custom_types/constants.md b/src/custom_types/constants.md new file mode 100644 index 0000000000..8878ba834e --- /dev/null +++ b/src/custom_types/constants.md @@ -0,0 +1,42 @@ +# constants + +Rust has two different types of constants which can be declared in any scope +including global. Both require explicit type annotation: + +* `const`: An unchangeable value (the common case). +* `static`: A possibly `mut`able variable with [`'static`][static] lifetime. + The static lifetime is inferred and does not have to be specified. + Accessing or modifying a mutable static variable is [`unsafe`][unsafe]. + +```rust,editable,ignore,mdbook-runnable +// Globals are declared outside all other scopes. +static LANGUAGE: &str = "Rust"; +const THRESHOLD: i32 = 10; + +fn is_big(n: i32) -> bool { + // Access constant in some function + n > THRESHOLD +} + +fn main() { + let n = 16; + + // Access constant in the main thread + println!("This is {}", LANGUAGE); + println!("The threshold is {}", THRESHOLD); + println!("{} is {}", n, if is_big(n) { "big" } else { "small" }); + + // Error! Cannot modify a `const`. + THRESHOLD = 5; + // FIXME ^ Comment out this line +} +``` + +### See also: + +[The `const`/`static` RFC]( +https://github.com/rust-lang/rfcs/blob/master/text/0246-const-vs-static.md), +[`'static` lifetime][static] + +[static]: ../scope/lifetime/static_lifetime.md +[unsafe]: ../unsafe.md diff --git a/src/custom_types/enum.md b/src/custom_types/enum.md new file mode 100644 index 0000000000..e861df9bfd --- /dev/null +++ b/src/custom_types/enum.md @@ -0,0 +1,109 @@ +# Enums + +The `enum` keyword allows the creation of a type which may be one of a few +different variants. Any variant which is valid as a `struct` is also valid as +an `enum`. + +```rust,editable +// Create an `enum` to classify a web event. Note how both +// names and type information together specify the variant: +// `PageLoad != PageUnload` and `KeyPress(char) != Paste(String)`. +// Each is different and independent. +enum WebEvent { + // An `enum` may either be `unit-like`, + PageLoad, + PageUnload, + // like tuple structs, + KeyPress(char), + Paste(String), + // or c-like structures. + Click { x: i64, y: i64 }, +} + +// A function which takes a `WebEvent` enum as an argument and +// returns nothing. +fn inspect(event: WebEvent) { + match event { + WebEvent::PageLoad => println!("page loaded"), + WebEvent::PageUnload => println!("page unloaded"), + // Destructure `c` from inside the `enum`. + WebEvent::KeyPress(c) => println!("pressed '{}'.", c), + WebEvent::Paste(s) => println!("pasted \"{}\".", s), + // Destructure `Click` into `x` and `y`. + WebEvent::Click { x, y } => { + println!("clicked at x={}, y={}.", x, y); + }, + } +} + +fn main() { + let pressed = WebEvent::KeyPress('x'); + // `to_owned()` creates an owned `String` from a string slice. + let pasted = WebEvent::Paste("my text".to_owned()); + let click = WebEvent::Click { x: 20, y: 80 }; + let load = WebEvent::PageLoad; + let unload = WebEvent::PageUnload; + + inspect(pressed); + inspect(pasted); + inspect(click); + inspect(load); + inspect(unload); +} + +``` + +## Type aliases + +If you use a type alias, you can refer to each enum variant via its alias. +This might be useful if the enum's name is too long or too generic, and you +want to rename it. + +```rust,editable +enum VeryVerboseEnumOfThingsToDoWithNumbers { + Add, + Subtract, +} + +// Creates a type alias +type Operations = VeryVerboseEnumOfThingsToDoWithNumbers; + +fn main() { + // We can refer to each variant via its alias, not its long and inconvenient + // name. + let x = Operations::Add; +} +``` + +The most common place you'll see this is in `impl` blocks using the `Self` alias. + +```rust,editable +enum VeryVerboseEnumOfThingsToDoWithNumbers { + Add, + Subtract, +} + +impl VeryVerboseEnumOfThingsToDoWithNumbers { + fn run(&self, x: i32, y: i32) -> i32 { + match self { + Self::Add => x + y, + Self::Subtract => x - y, + } + } +} +``` + +To learn more about enums and type aliases, you can read the +[stabilization report][aliasreport] from when this feature was stabilized into +Rust. + +### See also: + +[`match`][match], [`fn`][fn], and [`String`][str], ["Type alias enum variants" RFC][type_alias_rfc] + +[c_struct]: https://en.wikipedia.org/wiki/Struct_(C_programming_language) +[match]: ../flow_control/match.md +[fn]: ../fn.md +[str]: ../std/str.md +[aliasreport]: https://github.com/rust-lang/rust/pull/61682/#issuecomment-502472847 +[type_alias_rfc]: https://rust-lang.github.io/rfcs/2338-type-alias-enum-variants.html diff --git a/src/custom_types/enum/c_like.md b/src/custom_types/enum/c_like.md new file mode 100644 index 0000000000..65f832bef8 --- /dev/null +++ b/src/custom_types/enum/c_like.md @@ -0,0 +1,37 @@ +# C-like + +`enum` can also be used as C-like enums. + +```rust,editable +// An attribute to hide warnings for unused code. +#![allow(dead_code)] + +// enum with implicit discriminator (starts at 0) +enum Number { + Zero, + One, + Two, +} + +// enum with explicit discriminator +enum Color { + Red = 0xff0000, + Green = 0x00ff00, + Blue = 0x0000ff, +} + +fn main() { + // `enums` can be cast as integers. + println!("zero is {}", Number::Zero as i32); + println!("one is {}", Number::One as i32); + + println!("roses are #{:06x}", Color::Red as i32); + println!("violets are #{:06x}", Color::Blue as i32); +} +``` + +### See also: + +[casting][cast] + +[cast]: ../../types/cast.md diff --git a/src/custom_types/enum/enum_use.md b/src/custom_types/enum/enum_use.md new file mode 100644 index 0000000000..cf75c67ba4 --- /dev/null +++ b/src/custom_types/enum/enum_use.md @@ -0,0 +1,50 @@ +# use + +The `use` declaration can be used so manual scoping isn't needed: + +```rust,editable +// An attribute to hide warnings for unused code. +#![allow(dead_code)] + +enum Status { + Rich, + Poor, +} + +enum Work { + Civilian, + Soldier, +} + +fn main() { + // Explicitly `use` each name so they are available without + // manual scoping. + use crate::Status::{Poor, Rich}; + // Automatically `use` each name inside `Work`. + use crate::Work::*; + + // Equivalent to `Status::Poor`. + let status = Poor; + // Equivalent to `Work::Civilian`. + let work = Civilian; + + match status { + // Note the lack of scoping because of the explicit `use` above. + Rich => println!("The rich have lots of money!"), + Poor => println!("The poor have no money..."), + } + + match work { + // Note again the lack of scoping. + Civilian => println!("Civilians work!"), + Soldier => println!("Soldiers fight!"), + } +} +``` + +### See also: + +[`match`][match] and [`use`][use] + +[use]: ../../mod/use.md +[match]: ../../flow_control/match.md diff --git a/examples/enum/enum.rs b/src/custom_types/enum/testcase_linked_list.md similarity index 69% rename from examples/enum/enum.rs rename to src/custom_types/enum/testcase_linked_list.md index d3a6171e23..b07adecf6b 100644 --- a/examples/enum/enum.rs +++ b/src/custom_types/enum/testcase_linked_list.md @@ -1,10 +1,13 @@ -// Allow Cons and Nil to be referred to without namespacing -use List::{Cons, Nil}; +# Testcase: linked-list + +A common use for `enums` is to create a linked-list: + +```rust,editable +use crate::List::*; -// A linked list node, which can take on any of these two variants enum List { // Cons: Tuple struct that wraps an element and a pointer to the next node - Cons(uint, Box), + Cons(u32, Box), // Nil: A node that signifies the end of the linked list Nil, } @@ -18,17 +21,20 @@ impl List { } // Consume a list, and return the same list with a new element at its front - fn prepend(self, elem: uint) -> List { - // `Cons` also has type Node - Cons(elem, box self) + fn prepend(self, elem: u32) -> List { + // `Cons` also has type List + Cons(elem, Box::new(self)) } // Return the length of the list - fn len(&self) -> uint { + fn len(&self) -> u32 { // `self` has to be matched, because the behavior of this method // depends on the variant of `self` - // `self` has type `&Node`, and `*self` has type `Node`, matching on a + // `self` has type `&List`, and `*self` has type `List`, matching on a // concrete type `T` is preferred over a match on a reference `&T` + // after Rust 2018 you can use self here and tail (with no ref) below as well, + // rust will infer &s and ref tail. + // See https://doc.rust-lang.org/edition-guide/rust-2018/ownership-and-lifetimes/default-match-bindings.html match *self { // Can't take ownership of the tail, because `self` is borrowed; // instead take a reference to the tail @@ -57,7 +63,7 @@ fn main() { // Create an empty linked list let mut list = List::new(); - // Append some elements + // Prepend some elements list = list.prepend(1); list = list.prepend(2); list = list.prepend(3); @@ -66,3 +72,11 @@ fn main() { println!("linked list has length: {}", list.len()); println!("{}", list.stringify()); } +``` + +### See also: + +[`Box`][box] and [methods][methods] + +[box]: ../../std/box.md +[methods]: ../../fn/methods.md diff --git a/src/custom_types/structs.md b/src/custom_types/structs.md new file mode 100644 index 0000000000..508cff2314 --- /dev/null +++ b/src/custom_types/structs.md @@ -0,0 +1,101 @@ +# Structures + +There are three types of structures ("structs") that can be created using the +`struct` keyword: + +* Tuple structs, which are, basically, named tuples. +* The classic [C structs][c_struct] +* Unit structs, which are field-less, are useful for generics. + +```rust,editable +#[derive(Debug)] +struct Person { + name: String, + age: u8, +} + +// A unit struct +struct Unit; + +// A tuple struct +struct Pair(i32, f32); + +// A struct with two fields +struct Point { + x: f32, + y: f32, +} + +// Structs can be reused as fields of another struct +#[allow(dead_code)] +struct Rectangle { + // A rectangle can be specified by where the top left and bottom right + // corners are in space. + top_left: Point, + bottom_right: Point, +} + +fn main() { + // Create struct with field init shorthand + let name = String::from("Peter"); + let age = 27; + let peter = Person { name, age }; + + // Print debug struct + println!("{:?}", peter); + + + // Instantiate a `Point` + let point: Point = Point { x: 10.3, y: 0.4 }; + + // Access the fields of the point + println!("point coordinates: ({}, {})", point.x, point.y); + + // Make a new point by using struct update syntax to use the fields of our + // other one + let bottom_right = Point { x: 5.2, ..point }; + + // `bottom_right.y` will be the same as `point.y` because we used that field + // from `point` + println!("second point: ({}, {})", bottom_right.x, bottom_right.y); + + // Destructure the point using a `let` binding + let Point { x: left_edge, y: top_edge } = point; + + let _rectangle = Rectangle { + // struct instantiation is an expression too + top_left: Point { x: left_edge, y: top_edge }, + bottom_right: bottom_right, + }; + + // Instantiate a unit struct + let _unit = Unit; + + // Instantiate a tuple struct + let pair = Pair(1, 0.1); + + // Access the fields of a tuple struct + println!("pair contains {:?} and {:?}", pair.0, pair.1); + + // Destructure a tuple struct + let Pair(integer, decimal) = pair; + + println!("pair contains {:?} and {:?}", integer, decimal); +} +``` + +### Activity + +1. Add a function `rect_area` which calculates the area of a `Rectangle` (try + using nested destructuring). +2. Add a function `square` which takes a `Point` and a `f32` as arguments, and + returns a `Rectangle` with its lower left corner on the point, and a width and + height corresponding to the `f32`. + +### See also + +[`attributes`][attributes], and [destructuring][destructuring] + +[attributes]: ../attribute.md +[c_struct]: https://en.wikipedia.org/wiki/Struct_(C_programming_language) +[destructuring]: ../flow_control/match/destructuring.md diff --git a/src/error.md b/src/error.md new file mode 100644 index 0000000000..ea6c1b17ff --- /dev/null +++ b/src/error.md @@ -0,0 +1,31 @@ +# Error handling + +Error handling is the process of handling the possibility of failure. For +example, failing to read a file and then continuing to use that *bad* input +would clearly be problematic. Noticing and explicitly managing those errors +saves the rest of the program from various pitfalls. + +There are various ways to deal with errors in Rust, which are described in the +following subchapters. They all have more or less subtle differences and different +use cases. As a rule of thumb: + +An explicit `panic` is mainly useful for tests and dealing with unrecoverable errors. +For prototyping it can be useful, for example when dealing with functions that +haven't been implemented yet, but in those cases the more descriptive `unimplemented` +is better. In tests `panic` is a reasonable way to explicitly fail. + +The `Option` type is for when a value is optional or when the lack of a value is +not an error condition. For example the parent of a directory - `/` and `C:` don't +have one. When dealing with `Option`s, `unwrap` is fine for prototyping and cases +where it's absolutely certain that there is guaranteed to be a value. However `expect` +is more useful since it lets you specify an error message in case something goes +wrong anyway. + +When there is a chance that things do go wrong and the caller has to deal with the +problem, use `Result`. You can `unwrap` and `expect` them as well (please don't +do that unless it's a test or quick prototype). + +For a more rigorous discussion of error handling, refer to the error +handling section in the [official book][book]. + +[book]: https://doc.rust-lang.org/book/ch09-00-error-handling.html diff --git a/src/error/iter_result.md b/src/error/iter_result.md new file mode 100644 index 0000000000..3b03090d5d --- /dev/null +++ b/src/error/iter_result.md @@ -0,0 +1,81 @@ +# Iterating over `Result`s + +An `Iter::map` operation might fail, for example: + +```rust,editable +fn main() { + let strings = vec!["tofu", "93", "18"]; + let numbers: Vec<_> = strings + .into_iter() + .map(|s| s.parse::()) + .collect(); + println!("Results: {:?}", numbers); +} +``` + +Let's step through strategies for handling this. + +## Ignore the failed items with `filter_map()` + +`filter_map` calls a function and filters out the results that are `None`. + +```rust,editable +fn main() { + let strings = vec!["tofu", "93", "18"]; + let numbers: Vec<_> = strings + .into_iter() + .filter_map(|s| s.parse::().ok()) + .collect(); + println!("Results: {:?}", numbers); +} +``` + +## Fail the entire operation with `collect()` + +`Result` implements `FromIter` so that a vector of results (`Vec>`) +can be turned into a result with a vector (`Result, E>`). Once an +`Result::Err` is found, the iteration will terminate. + +```rust,editable +fn main() { + let strings = vec!["tofu", "93", "18"]; + let numbers: Result, _> = strings + .into_iter() + .map(|s| s.parse::()) + .collect(); + println!("Results: {:?}", numbers); +} +``` + +This same technique can be used with `Option`. + +## Collect all valid values and failures with `partition()` + +```rust,editable +fn main() { + let strings = vec!["tofu", "93", "18"]; + let (numbers, errors): (Vec<_>, Vec<_>) = strings + .into_iter() + .map(|s| s.parse::()) + .partition(Result::is_ok); + println!("Numbers: {:?}", numbers); + println!("Errors: {:?}", errors); +} +``` + +When you look at the results, you'll note that everything is still wrapped in +`Result`. A little more boilerplate is needed for this. + +```rust,editable +fn main() { + let strings = vec!["tofu", "93", "18"]; + let (numbers, errors): (Vec<_>, Vec<_>) = strings + .into_iter() + .map(|s| s.parse::()) + .partition(Result::is_ok); + let numbers: Vec<_> = numbers.into_iter().map(Result::unwrap).collect(); + let errors: Vec<_> = errors.into_iter().map(Result::unwrap_err).collect(); + println!("Numbers: {:?}", numbers); + println!("Errors: {:?}", errors); +} +``` diff --git a/src/error/multiple_error_types.md b/src/error/multiple_error_types.md new file mode 100644 index 0000000000..610bbfcb84 --- /dev/null +++ b/src/error/multiple_error_types.md @@ -0,0 +1,36 @@ +# Multiple error types + +The previous examples have always been very convenient; `Result`s interact +with other `Result`s and `Option`s interact with other `Option`s. + +Sometimes an `Option` needs to interact with a `Result`, or a +`Result` needs to interact with a `Result`. In those +cases, we want to manage our different error types in a way that makes them +composable and easy to interact with. + +In the following code, two instances of `unwrap` generate different error +types. `Vec::first` returns an `Option`, while `parse::` returns a +`Result`: + +```rust,editable,ignore,mdbook-runnable +fn double_first(vec: Vec<&str>) -> i32 { + let first = vec.first().unwrap(); // Generate error 1 + 2 * first.parse::().unwrap() // Generate error 2 +} + +fn main() { + let numbers = vec!["42", "93", "18"]; + let empty = vec![]; + let strings = vec!["tofu", "93", "18"]; + + println!("The first doubled is {}", double_first(numbers)); + + println!("The first doubled is {}", double_first(empty)); + // Error 1: the input vector is empty + + println!("The first doubled is {}", double_first(strings)); + // Error 2: the element doesn't parse to a number +} +``` + +Over the next sections, we'll see several strategies for handling these kind of problems. diff --git a/src/error/multiple_error_types/boxing_errors.md b/src/error/multiple_error_types/boxing_errors.md new file mode 100644 index 0000000000..84b0c41e55 --- /dev/null +++ b/src/error/multiple_error_types/boxing_errors.md @@ -0,0 +1,64 @@ +# `Box`ing errors + +A way to write simple code while preserving the original errors is to [`Box`][box] +them. The drawback is that the underlying error type is only known at runtime and not +[statically determined][dynamic_dispatch]. + +The stdlib helps in boxing our errors by having `Box` implement conversion from +any type that implements the `Error` trait into the trait object `Box`, +via [`From`][from]. + +```rust,editable +use std::error; +use std::fmt; + +// Change the alias to `Box`. +type Result = std::result::Result>; + +#[derive(Debug, Clone)] +struct EmptyVec; + +impl fmt::Display for EmptyVec { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "invalid first item to double") + } +} + +impl error::Error for EmptyVec {} + +fn double_first(vec: Vec<&str>) -> Result { + vec.first() + .ok_or_else(|| EmptyVec.into()) // Converts to Box + .and_then(|s| { + s.parse::() + .map_err(|e| e.into()) // Converts to Box + .map(|i| 2 * i) + }) +} + +fn print(result: Result) { + match result { + Ok(n) => println!("The first doubled is {}", n), + Err(e) => println!("Error: {}", e), + } +} + +fn main() { + let numbers = vec!["42", "93", "18"]; + let empty = vec![]; + let strings = vec!["tofu", "93", "18"]; + + print(double_first(numbers)); + print(double_first(empty)); + print(double_first(strings)); +} +``` + +### See also: + +[Dynamic dispatch][dynamic_dispatch] and [`Error` trait][error] + +[box]: https://doc.rust-lang.org/std/boxed/struct.Box.html +[dynamic_dispatch]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html#trait-objects-perform-dynamic-dispatch +[error]: https://doc.rust-lang.org/std/error/trait.Error.html +[from]: https://doc.rust-lang.org/std/convert/trait.From.html diff --git a/src/error/multiple_error_types/define_error_type.md b/src/error/multiple_error_types/define_error_type.md new file mode 100644 index 0000000000..4c374276dc --- /dev/null +++ b/src/error/multiple_error_types/define_error_type.md @@ -0,0 +1,68 @@ +# Defining an error type + +Sometimes it simplifies the code to mask all of the different errors with a +single type of error. We'll show this with a custom error. + +Rust allows us to define our own error types. In general, a "good" error type: + +* Represents different errors with the same type +* Presents nice error messages to the user +* Is easy to compare with other types + - Good: `Err(EmptyVec)` + - Bad: `Err("Please use a vector with at least one element".to_owned())` +* Can hold information about the error + - Good: `Err(BadChar(c, position))` + - Bad: `Err("+ cannot be used here".to_owned())` +* Composes well with other errors + +```rust,editable +use std::fmt; + +type Result = std::result::Result; + +// Define our error types. These may be customized for our error handling cases. +// Now we will be able to write our own errors, defer to an underlying error +// implementation, or do something in between. +#[derive(Debug, Clone)] +struct DoubleError; + +// Generation of an error is completely separate from how it is displayed. +// There's no need to be concerned about cluttering complex logic with the display style. +// +// Note that we don't store any extra info about the errors. This means we can't state +// which string failed to parse without modifying our types to carry that information. +impl fmt::Display for DoubleError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "invalid first item to double") + } +} + +fn double_first(vec: Vec<&str>) -> Result { + vec.first() + // Change the error to our new type. + .ok_or(DoubleError) + .and_then(|s| { + s.parse::() + // Update to the new error type here also. + .map_err(|_| DoubleError) + .map(|i| 2 * i) + }) +} + +fn print(result: Result) { + match result { + Ok(n) => println!("The first doubled is {}", n), + Err(e) => println!("Error: {}", e), + } +} + +fn main() { + let numbers = vec!["42", "93", "18"]; + let empty = vec![]; + let strings = vec!["tofu", "93", "18"]; + + print(double_first(numbers)); + print(double_first(empty)); + print(double_first(strings)); +} +``` diff --git a/src/error/multiple_error_types/option_result.md b/src/error/multiple_error_types/option_result.md new file mode 100644 index 0000000000..d2273f698f --- /dev/null +++ b/src/error/multiple_error_types/option_result.md @@ -0,0 +1,56 @@ +# Pulling `Result`s out of `Option`s + +The most basic way of handling mixed error types is to just embed them in each +other. + +```rust,editable +use std::num::ParseIntError; + +fn double_first(vec: Vec<&str>) -> Option> { + vec.first().map(|first| { + first.parse::().map(|n| 2 * n) + }) +} + +fn main() { + let numbers = vec!["42", "93", "18"]; + let empty = vec![]; + let strings = vec!["tofu", "93", "18"]; + + println!("The first doubled is {:?}", double_first(numbers)); + + println!("The first doubled is {:?}", double_first(empty)); + // Error 1: the input vector is empty + + println!("The first doubled is {:?}", double_first(strings)); + // Error 2: the element doesn't parse to a number +} +``` + +There are times when we'll want to stop processing on errors (like with +[`?`][enter_question_mark]) but keep going when the `Option` is `None`. A +couple of combinators come in handy to swap the `Result` and `Option`. + +```rust,editable +use std::num::ParseIntError; + +fn double_first(vec: Vec<&str>) -> Result, ParseIntError> { + let opt = vec.first().map(|first| { + first.parse::().map(|n| 2 * n) + }); + + opt.map_or(Ok(None), |r| r.map(Some)) +} + +fn main() { + let numbers = vec!["42", "93", "18"]; + let empty = vec![]; + let strings = vec!["tofu", "93", "18"]; + + println!("The first doubled is {:?}", double_first(numbers)); + println!("The first doubled is {:?}", double_first(empty)); + println!("The first doubled is {:?}", double_first(strings)); +} +``` + +[enter_question_mark]: ../result/enter_question_mark.md diff --git a/src/error/multiple_error_types/reenter_question_mark.md b/src/error/multiple_error_types/reenter_question_mark.md new file mode 100644 index 0000000000..61f80fc3e3 --- /dev/null +++ b/src/error/multiple_error_types/reenter_question_mark.md @@ -0,0 +1,79 @@ +# Other uses of `?` + +Notice in the previous example that our immediate reaction to calling +`parse` is to `map` the error from a library error into a boxed +error: + +```rust,ignore +.and_then(|s| s.parse::() + .map_err(|e| e.into()) +``` + +Since this is a simple and common operation, it would be convenient if it +could be elided. Alas, because `and_then` is not sufficiently flexible, it +cannot. However, we can instead use `?`. + +`?` was previously explained as either `unwrap` or `return Err(err)`. +This is only mostly true. It actually means `unwrap` or +`return Err(From::from(err))`. Since `From::from` is a conversion utility +between different types, this means that if you `?` where the error is +convertible to the return type, it will convert automatically. + +Here, we rewrite the previous example using `?`. As a result, the +`map_err` will go away when `From::from` is implemented for our error type: + +```rust,editable +use std::error; +use std::fmt; + +// Change the alias to `Box`. +type Result = std::result::Result>; + +#[derive(Debug)] +struct EmptyVec; + +impl fmt::Display for EmptyVec { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "invalid first item to double") + } +} + +impl error::Error for EmptyVec {} + +// The same structure as before but rather than chain all `Results` +// and `Options` along, we `?` to get the inner value out immediately. +fn double_first(vec: Vec<&str>) -> Result { + let first = vec.first().ok_or(EmptyVec)?; + let parsed = first.parse::()?; + Ok(2 * parsed) +} + +fn print(result: Result) { + match result { + Ok(n) => println!("The first doubled is {}", n), + Err(e) => println!("Error: {}", e), + } +} + +fn main() { + let numbers = vec!["42", "93", "18"]; + let empty = vec![]; + let strings = vec!["tofu", "93", "18"]; + + print(double_first(numbers)); + print(double_first(empty)); + print(double_first(strings)); +} +``` + +This is actually fairly clean now. Compared with the original `panic`, it +is very similar to replacing the `unwrap` calls with `?` except that the +return types are `Result`. As a result, they must be destructured at the +top level. + +### See also: + +[`From::from`][from] and [`?`][q_mark] + +[from]: https://doc.rust-lang.org/std/convert/trait.From.html +[q_mark]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator diff --git a/src/error/multiple_error_types/wrap_error.md b/src/error/multiple_error_types/wrap_error.md new file mode 100644 index 0000000000..392b783aed --- /dev/null +++ b/src/error/multiple_error_types/wrap_error.md @@ -0,0 +1,96 @@ +# Wrapping errors + +An alternative to boxing errors is to wrap them in your own error type. + +```rust,editable +use std::error; +use std::error::Error as _; +use std::num::ParseIntError; +use std::fmt; + +type Result = std::result::Result; + +#[derive(Debug)] +enum DoubleError { + EmptyVec, + // We will defer to the parse error implementation for their error. + // Supplying extra info requires adding more data to the type. + Parse(ParseIntError), +} + +impl fmt::Display for DoubleError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + DoubleError::EmptyVec => + write!(f, "please use a vector with at least one element"), + // The wrapped error contains additional information and is available + // via the source() method. + DoubleError::Parse(..) => + write!(f, "the provided string could not be parsed as int"), + } + } +} + +impl error::Error for DoubleError { + fn source(&self) -> Option<&(dyn error::Error + 'static)> { + match *self { + DoubleError::EmptyVec => None, + // The cause is the underlying implementation error type. Is implicitly + // cast to the trait object `&error::Error`. This works because the + // underlying type already implements the `Error` trait. + DoubleError::Parse(ref e) => Some(e), + } + } +} + +// Implement the conversion from `ParseIntError` to `DoubleError`. +// This will be automatically called by `?` if a `ParseIntError` +// needs to be converted into a `DoubleError`. +impl From for DoubleError { + fn from(err: ParseIntError) -> DoubleError { + DoubleError::Parse(err) + } +} + +fn double_first(vec: Vec<&str>) -> Result { + let first = vec.first().ok_or(DoubleError::EmptyVec)?; + // Here we implicitly use the `ParseIntError` implementation of `From` (which + // we defined above) in order to create a `DoubleError`. + let parsed = first.parse::()?; + + Ok(2 * parsed) +} + +fn print(result: Result) { + match result { + Ok(n) => println!("The first doubled is {}", n), + Err(e) => { + println!("Error: {}", e); + if let Some(source) = e.source() { + println!(" Caused by: {}", source); + } + }, + } +} + +fn main() { + let numbers = vec!["42", "93", "18"]; + let empty = vec![]; + let strings = vec!["tofu", "93", "18"]; + + print(double_first(numbers)); + print(double_first(empty)); + print(double_first(strings)); +} +``` + +This adds a bit more boilerplate for handling errors and might not be needed in +all applications. There are some libraries that can take care of the boilerplate +for you. + +### See also: + +[`From::from`][from] and [`Enums`][enums] + +[from]: https://doc.rust-lang.org/std/convert/trait.From.html +[enums]: ../../custom_types/enum.md diff --git a/src/error/option_unwrap.md b/src/error/option_unwrap.md new file mode 100644 index 0000000000..5192767fcc --- /dev/null +++ b/src/error/option_unwrap.md @@ -0,0 +1,65 @@ +# `Option` & `unwrap` + +In the last example, we showed that we can induce program failure at will. +We told our program to `panic` if we drink a sugary lemonade. +But what if we expect _some_ drink but don't receive one? +That case would be just as bad, so it needs to be handled! + +We *could* test this against the null string (`""`) as we do with a lemonade. +Since we're using Rust, let's instead have the compiler point out cases +where there's no drink. + +An `enum` called `Option` in the `std` library is used when absence is a +possibility. It manifests itself as one of two "options": + +* `Some(T)`: An element of type `T` was found +* `None`: No element was found + +These cases can either be explicitly handled via `match` or implicitly with +`unwrap`. Implicit handling will either return the inner element or `panic`. + +Note that it's possible to manually customize `panic` with [expect][expect], +but `unwrap` otherwise leaves us with a less meaningful output than explicit +handling. In the following example, explicit handling yields a more +controlled result while retaining the option to `panic` if desired. + +```rust,editable,ignore,mdbook-runnable +// The adult has seen it all, and can handle any drink well. +// All drinks are handled explicitly using `match`. +fn give_adult(drink: Option<&str>) { + // Specify a course of action for each case. + match drink { + Some("lemonade") => println!("Yuck! Too sugary."), + Some(inner) => println!("{}? How nice.", inner), + None => println!("No drink? Oh well."), + } +} + +// Others will `panic` before drinking sugary drinks. +// All drinks are handled implicitly using `unwrap`. +fn drink(drink: Option<&str>) { + // `unwrap` returns a `panic` when it receives a `None`. + let inside = drink.unwrap(); + if inside == "lemonade" { panic!("AAAaaaaa!!!!"); } + + println!("I love {}s!!!!!", inside); +} + +fn main() { + let water = Some("water"); + let lemonade = Some("lemonade"); + let void = None; + + give_adult(water); + give_adult(lemonade); + give_adult(void); + + let coffee = Some("coffee"); + let nothing = None; + + drink(coffee); + drink(nothing); +} +``` + +[expect]: https://doc.rust-lang.org/std/option/enum.Option.html#method.expect diff --git a/src/error/option_unwrap/and_then.md b/src/error/option_unwrap/and_then.md new file mode 100644 index 0000000000..c065f2043e --- /dev/null +++ b/src/error/option_unwrap/and_then.md @@ -0,0 +1,76 @@ +# Combinators: `and_then` + +`map()` was described as a chainable way to simplify `match` statements. +However, using `map()` on a function that returns an `Option` results +in the nested `Option>`. Chaining multiple calls together can +then become confusing. That's where another combinator called `and_then()`, +known in some languages as flatmap, comes in. + +`and_then()` calls its function input with the wrapped value and returns the result. If the `Option` is `None`, then it returns `None` instead. + +In the following example, `cookable_v2()` results in an `Option`. +Using `map()` instead of `and_then()` would have given an +`Option>`, which is an invalid type for `eat()`. + +```rust,editable +#![allow(dead_code)] + +#[derive(Debug)] enum Food { CordonBleu, Steak, Sushi } +#[derive(Debug)] enum Day { Monday, Tuesday, Wednesday } + +// We don't have the ingredients to make Sushi. +fn have_ingredients(food: Food) -> Option { + match food { + Food::Sushi => None, + _ => Some(food), + } +} + +// We have the recipe for everything except Cordon Bleu. +fn have_recipe(food: Food) -> Option { + match food { + Food::CordonBleu => None, + _ => Some(food), + } +} + +// To make a dish, we need both the recipe and the ingredients. +// We can represent the logic with a chain of `match`es: +fn cookable_v1(food: Food) -> Option { + match have_recipe(food) { + None => None, + Some(food) => match have_ingredients(food) { + None => None, + Some(food) => Some(food), + }, + } +} + +// This can conveniently be rewritten more compactly with `and_then()`: +fn cookable_v2(food: Food) -> Option { + have_recipe(food).and_then(have_ingredients) +} + +fn eat(food: Food, day: Day) { + match cookable_v2(food) { + Some(food) => println!("Yay! On {:?} we get to eat {:?}.", day, food), + None => println!("Oh no. We don't get to eat on {:?}?", day), + } +} + +fn main() { + let (cordon_bleu, steak, sushi) = (Food::CordonBleu, Food::Steak, Food::Sushi); + + eat(cordon_bleu, Day::Monday); + eat(steak, Day::Tuesday); + eat(sushi, Day::Wednesday); +} +``` + +### See also: + +[closures][closures], [`Option`][option], and [`Option::and_then()`][and_then] + +[closures]: ../../fn/closures.md +[option]: https://doc.rust-lang.org/std/option/enum.Option.html +[and_then]: https://doc.rust-lang.org/std/option/enum.Option.html#method.and_then diff --git a/src/error/option_unwrap/map.md b/src/error/option_unwrap/map.md new file mode 100644 index 0000000000..6682e317a9 --- /dev/null +++ b/src/error/option_unwrap/map.md @@ -0,0 +1,86 @@ +# Combinators: `map` + +`match` is a valid method for handling `Option`s. However, you may +eventually find heavy usage tedious, especially with operations only valid +with an input. In these cases, [combinators][combinators] can be used to +manage control flow in a modular fashion. + +`Option` has a built in method called `map()`, a combinator for the simple +mapping of `Some -> Some` and `None -> None`. Multiple `map()` calls can be +chained together for even more flexibility. + +In the following example, `process()` replaces all functions previous +to it while staying compact. + +```rust,editable +#![allow(dead_code)] + +#[derive(Debug)] enum Food { Apple, Carrot, Potato } + +#[derive(Debug)] struct Peeled(Food); +#[derive(Debug)] struct Chopped(Food); +#[derive(Debug)] struct Cooked(Food); + +// Peeling food. If there isn't any, then return `None`. +// Otherwise, return the peeled food. +fn peel(food: Option) -> Option { + match food { + Some(food) => Some(Peeled(food)), + None => None, + } +} + +// Chopping food. If there isn't any, then return `None`. +// Otherwise, return the chopped food. +fn chop(peeled: Option) -> Option { + match peeled { + Some(Peeled(food)) => Some(Chopped(food)), + None => None, + } +} + +// Cooking food. Here, we showcase `map()` instead of `match` for case handling. +fn cook(chopped: Option) -> Option { + chopped.map(|Chopped(food)| Cooked(food)) +} + +// A function to peel, chop, and cook food all in sequence. +// We chain multiple uses of `map()` to simplify the code. +fn process(food: Option) -> Option { + food.map(|f| Peeled(f)) + .map(|Peeled(f)| Chopped(f)) + .map(|Chopped(f)| Cooked(f)) +} + +// Check whether there's food or not before trying to eat it! +fn eat(food: Option) { + match food { + Some(food) => println!("Mmm. I love {:?}", food), + None => println!("Oh no! It wasn't edible."), + } +} + +fn main() { + let apple = Some(Food::Apple); + let carrot = Some(Food::Carrot); + let potato = None; + + let cooked_apple = cook(chop(peel(apple))); + let cooked_carrot = cook(chop(peel(carrot))); + // Let's try the simpler looking `process()` now. + let cooked_potato = process(potato); + + eat(cooked_apple); + eat(cooked_carrot); + eat(cooked_potato); +} +``` + +### See also: + +[closures][closures], [`Option`][option], [`Option::map()`][map] + +[combinators]: https://doc.rust-lang.org/reference/glossary.html#combinator +[closures]: ../../fn/closures.md +[option]: https://doc.rust-lang.org/std/option/enum.Option.html +[map]: https://doc.rust-lang.org/std/option/enum.Option.html#method.map diff --git a/src/error/option_unwrap/question_mark.md b/src/error/option_unwrap/question_mark.md new file mode 100644 index 0000000000..7437ff6c84 --- /dev/null +++ b/src/error/option_unwrap/question_mark.md @@ -0,0 +1,58 @@ +# Unpacking options with `?` + +You can unpack `Option`s by using `match` statements, but it's often easier to +use the `?` operator. If `x` is an `Option`, then evaluating `x?` will return +the underlying value if `x` is `Some`, otherwise it will terminate whatever +function is being executed and return `None`. + +```rust,editable +fn next_birthday(current_age: Option) -> Option { + // If `current_age` is `None`, this returns `None`. + // If `current_age` is `Some`, the inner `u8` gets assigned to `next_age` + let next_age: u8 = current_age?; + Some(format!("Next year I will be {}", next_age)) +} +``` + +You can chain many `?`s together to make your code much more readable. + +```rust,editable +struct Person { + job: Option, +} + +#[derive(Clone, Copy)] +struct Job { + phone_number: Option, +} + +#[derive(Clone, Copy)] +struct PhoneNumber { + area_code: Option, + number: u32, +} + +impl Person { + + // Gets the area code of the phone number of the person's job, if it exists. + fn work_phone_area_code(&self) -> Option { + // This would need many nested `match` statements without the `?` operator. + // It would take a lot more code - try writing it yourself and see which + // is easier. + self.job?.phone_number?.area_code + } +} + +fn main() { + let p = Person { + job: Some(Job { + phone_number: Some(PhoneNumber { + area_code: Some(61), + number: 439222222, + }), + }), + }; + + assert_eq!(p.work_phone_area_code(), Some(61)); +} +``` diff --git a/src/error/panic.md b/src/error/panic.md new file mode 100644 index 0000000000..5524dbf6f2 --- /dev/null +++ b/src/error/panic.md @@ -0,0 +1,19 @@ +# `panic` + +The simplest error handling mechanism we will see is `panic`. It prints an +error message, starts unwinding the stack, and usually exits the program. +Here, we explicitly call `panic` on our error condition: + +```rust,editable,ignore,mdbook-runnable +fn drink(beverage: &str) { + // You shouldn't drink too much sugary beverages. + if beverage == "lemonade" { panic!("AAAaaaaa!!!!"); } + + println!("Some refreshing {} is all I need.", beverage); +} + +fn main() { + drink("water"); + drink("lemonade"); +} +``` diff --git a/src/error/result.md b/src/error/result.md new file mode 100644 index 0000000000..d779bfdad1 --- /dev/null +++ b/src/error/result.md @@ -0,0 +1,83 @@ +# `Result` + +[`Result`][result] is a richer version of the [`Option`][option] type that +describes possible *error* instead of possible *absence*. + +That is, `Result` could have one of two outcomes: + +* `Ok(T)`: An element `T` was found +* `Err(E)`: An error was found with element `E` + +By convention, the expected outcome is `Ok` while the unexpected outcome is `Err`. + +Like `Option`, `Result` has many methods associated with it. `unwrap()`, for +example, either yields the element `T` or `panic`s. For case handling, +there are many combinators between `Result` and `Option` that overlap. + +In working with Rust, you will likely encounter methods that return the +`Result` type, such as the [`parse()`][parse] method. It might not always +be possible to parse a string into the other type, so `parse()` returns a +`Result` indicating possible failure. + +Let's see what happens when we successfully and unsuccessfully `parse()` a string: + +```rust,editable,ignore,mdbook-runnable +fn multiply(first_number_str: &str, second_number_str: &str) -> i32 { + // Let's try using `unwrap()` to get the number out. Will it bite us? + let first_number = first_number_str.parse::().unwrap(); + let second_number = second_number_str.parse::().unwrap(); + first_number * second_number +} + +fn main() { + let twenty = multiply("10", "2"); + println!("double is {}", twenty); + + let tt = multiply("t", "2"); + println!("double is {}", tt); +} +``` + +In the unsuccessful case, `parse()` leaves us with an error for `unwrap()` +to `panic` on. Additionally, the `panic` exits our program and provides an +unpleasant error message. + +To improve the quality of our error message, we should be more specific +about the return type and consider explicitly handling the error. + +## Using `Result` in `main` + +The `Result` type can also be the return type of the `main` function if +specified explicitly. Typically the `main` function will be of the form: + +```rust +fn main() { + println!("Hello World!"); +} +``` + +However `main` is also able to have a return type of `Result`. If an error +occurs within the `main` function it will return an error code and print a debug +representation of the error (using the [`Debug`] trait). The following example +shows such a scenario and touches on aspects covered in [the following section]. + +```rust,editable +use std::num::ParseIntError; + +fn main() -> Result<(), ParseIntError> { + let number_str = "10"; + let number = match number_str.parse::() { + Ok(number) => number, + Err(e) => return Err(e), + }; + println!("{}", number); + Ok(()) +} +``` + + +[option]: https://doc.rust-lang.org/std/option/enum.Option.html +[result]: https://doc.rust-lang.org/std/result/enum.Result.html +[parse]: https://doc.rust-lang.org/std/primitive.str.html#method.parse +[`Debug`]: https://doc.rust-lang.org/std/fmt/trait.Debug.html +[the following section]: result/early_returns.md diff --git a/src/error/result/early_returns.md b/src/error/result/early_returns.md new file mode 100644 index 0000000000..e76615131f --- /dev/null +++ b/src/error/result/early_returns.md @@ -0,0 +1,46 @@ +# Early returns + +In the previous example, we explicitly handled the errors using combinators. +Another way to deal with this case analysis is to use a combination of +`match` statements and *early returns*. + +That is, we can simply stop executing the function and return the error if +one occurs. For some, this form of code can be easier to both read and +write. Consider this version of the previous example, rewritten using early returns: + +```rust,editable +use std::num::ParseIntError; + +fn multiply(first_number_str: &str, second_number_str: &str) -> Result { + let first_number = match first_number_str.parse::() { + Ok(first_number) => first_number, + Err(e) => return Err(e), + }; + + let second_number = match second_number_str.parse::() { + Ok(second_number) => second_number, + Err(e) => return Err(e), + }; + + Ok(first_number * second_number) +} + +fn print(result: Result) { + match result { + Ok(n) => println!("n is {}", n), + Err(e) => println!("Error: {}", e), + } +} + +fn main() { + print(multiply("10", "2")); + print(multiply("t", "2")); +} +``` + +At this point, we've learned to explicitly handle errors using combinators +and early returns. While we generally want to avoid panicking, explicitly +handling all of our errors is cumbersome. + +In the next section, we'll introduce `?` for the cases where we simply +need to `unwrap` without possibly inducing `panic`. diff --git a/src/error/result/enter_question_mark.md b/src/error/result/enter_question_mark.md new file mode 100644 index 0000000000..8101e3efd7 --- /dev/null +++ b/src/error/result/enter_question_mark.md @@ -0,0 +1,75 @@ +# Introducing `?` + +Sometimes we just want the simplicity of `unwrap` without the possibility of +a `panic`. Until now, `unwrap` has forced us to nest deeper and deeper when +what we really wanted was to get the variable *out*. This is exactly the purpose of `?`. + +Upon finding an `Err`, there are two valid actions to take: + +1. `panic!` which we already decided to try to avoid if possible +2. `return` because an `Err` means it cannot be handled + +`?` is *almost*[^†] exactly equivalent to an `unwrap` which `return`s +instead of `panic`king on `Err`s. Let's see how we can simplify the earlier +example that used combinators: + +```rust,editable +use std::num::ParseIntError; + +fn multiply(first_number_str: &str, second_number_str: &str) -> Result { + let first_number = first_number_str.parse::()?; + let second_number = second_number_str.parse::()?; + + Ok(first_number * second_number) +} + +fn print(result: Result) { + match result { + Ok(n) => println!("n is {}", n), + Err(e) => println!("Error: {}", e), + } +} + +fn main() { + print(multiply("10", "2")); + print(multiply("t", "2")); +} +``` + +## The `try!` macro + +Before there was `?`, the same functionality was achieved with the `try!` macro. +The `?` operator is now recommended, but you may still find `try!` when looking +at older code. The same `multiply` function from the previous example +would look like this using `try!`: + +```rust,editable +// To compile and run this example without errors, while using Cargo, change the value +// of the `edition` field, in the `[package]` section of the `Cargo.toml` file, to "2015". + +use std::num::ParseIntError; + +fn multiply(first_number_str: &str, second_number_str: &str) -> Result { + let first_number = try!(first_number_str.parse::()); + let second_number = try!(second_number_str.parse::()); + + Ok(first_number * second_number) +} + +fn print(result: Result) { + match result { + Ok(n) => println!("n is {}", n), + Err(e) => println!("Error: {}", e), + } +} + +fn main() { + print(multiply("10", "2")); + print(multiply("t", "2")); +} +``` + + +[^†]: See [re-enter ?][re_enter_?] for more details. + +[re_enter_?]: ../multiple_error_types/reenter_question_mark.md diff --git a/src/error/result/result_alias.md b/src/error/result/result_alias.md new file mode 100644 index 0000000000..c4073980fc --- /dev/null +++ b/src/error/result/result_alias.md @@ -0,0 +1,46 @@ +# aliases for `Result` + +How about when we want to reuse a specific `Result` type many times? +Recall that Rust allows us to create [aliases][typealias]. Conveniently, +we can define one for the specific `Result` in question. + +At a module level, creating aliases can be particularly helpful. Errors +found in a specific module often have the same `Err` type, so a single alias +can succinctly define *all* associated `Results`. This is so useful that the +`std` library even supplies one: [`io::Result`][io_result]! + +Here's a quick example to show off the syntax: + +```rust,editable +use std::num::ParseIntError; + +// Define a generic alias for a `Result` with the error type `ParseIntError`. +type AliasedResult = Result; + +// Use the above alias to refer to our specific `Result` type. +fn multiply(first_number_str: &str, second_number_str: &str) -> AliasedResult { + first_number_str.parse::().and_then(|first_number| { + second_number_str.parse::().map(|second_number| first_number * second_number) + }) +} + +// Here, the alias again allows us to save some space. +fn print(result: AliasedResult) { + match result { + Ok(n) => println!("n is {}", n), + Err(e) => println!("Error: {}", e), + } +} + +fn main() { + print(multiply("10", "2")); + print(multiply("t", "2")); +} +``` + +### See also: + +[`io::Result`][io_result] + +[typealias]: ../../types/alias.md +[io_result]: https://doc.rust-lang.org/std/io/type.Result.html diff --git a/src/error/result/result_map.md b/src/error/result/result_map.md new file mode 100644 index 0000000000..24537c3189 --- /dev/null +++ b/src/error/result/result_map.md @@ -0,0 +1,88 @@ +# `map` for `Result` + +Panicking in the previous example's `multiply` does not make for robust code. +Generally, we want to return the error to the caller so it can decide what is +the right way to respond to errors. + +We first need to know what kind of error type we are dealing with. To determine +the `Err` type, we look to [`parse()`][parse], which is implemented with the +[`FromStr`][from_str] trait for [`i32`][i32]. As a result, the `Err` type is +specified as [`ParseIntError`][parse_int_error]. + +In the example below, the straightforward `match` statement leads to code +that is overall more cumbersome. + +```rust,editable +use std::num::ParseIntError; + +// With the return type rewritten, we use pattern matching without `unwrap()`. +fn multiply(first_number_str: &str, second_number_str: &str) -> Result { + match first_number_str.parse::() { + Ok(first_number) => { + match second_number_str.parse::() { + Ok(second_number) => { + Ok(first_number * second_number) + }, + Err(e) => Err(e), + } + }, + Err(e) => Err(e), + } +} + +fn print(result: Result) { + match result { + Ok(n) => println!("n is {}", n), + Err(e) => println!("Error: {}", e), + } +} + +fn main() { + // This still presents a reasonable answer. + let twenty = multiply("10", "2"); + print(twenty); + + // The following now provides a much more helpful error message. + let tt = multiply("t", "2"); + print(tt); +} +``` + +Luckily, `Option`'s `map`, `and_then`, and many other combinators are also +implemented for `Result`. [`Result`][result] contains a complete listing. + +```rust,editable +use std::num::ParseIntError; + +// As with `Option`, we can use combinators such as `map()`. +// This function is otherwise identical to the one above and reads: +// Modify n if the value is valid, otherwise pass on the error. +fn multiply(first_number_str: &str, second_number_str: &str) -> Result { + first_number_str.parse::().and_then(|first_number| { + second_number_str.parse::().map(|second_number| first_number * second_number) + }) +} + +fn print(result: Result) { + match result { + Ok(n) => println!("n is {}", n), + Err(e) => println!("Error: {}", e), + } +} + +fn main() { + // This still presents a reasonable answer. + let twenty = multiply("10", "2"); + print(twenty); + + // The following now provides a much more helpful error message. + let tt = multiply("t", "2"); + print(tt); +} +``` + +[parse]: https://doc.rust-lang.org/std/primitive.str.html#method.parse +[from_str]: https://doc.rust-lang.org/std/str/trait.FromStr.html +[i32]: https://doc.rust-lang.org/std/primitive.i32.html +[parse_int_error]: https://doc.rust-lang.org/std/num/struct.ParseIntError.html +[result]: https://doc.rust-lang.org/std/result/enum.Result.html diff --git a/src/example.rs b/src/example.rs deleted file mode 100644 index acee6504e4..0000000000 --- a/src/example.rs +++ /dev/null @@ -1,93 +0,0 @@ -use file; -use markdown::Markdown; -use serialize::{Decodable,json}; -use std::iter::AdditiveIterator; - -#[deriving(Decodable)] -pub struct Example { - children: Option>, - id: String, - title: String, -} - -impl Example { - pub fn get_list() -> Vec { - match file::read(&Path::new("examples/structure.json")) { - Err(why) => panic!("{}", why), - Ok(string) => match json::from_str(string.as_slice()) { - Err(_) => panic!("structure.json is not valid json"), - Ok(json) => { - match Decodable::decode(&mut json::Decoder::new(json)) { - Err(_) => panic!("error decoding structure.json"), - Ok(examples) => examples, - } - } - } - } - } - - pub fn count(&self) -> uint { - match self.children { - None => 1, - Some(ref children) => 1 + children.iter().map(|c| c.count()).sum(), - } - } - - pub fn process(&self, - number: Vec, - tx: Sender<(Vec, String)>, - indent: uint, - prefix: String) - { - let id = self.id.as_slice(); - let prefix = prefix.as_slice(); - let title = self.title.as_slice(); - - let entry = - match Markdown::process(number.as_slice(), id, title, prefix) { - Ok(_) => { - let md = if prefix.as_slice().is_whitespace() { - format!("{}.md", id) - } else { - format!("{}/{}.md", prefix, id) - }; - - format!("{}* [{}]({})", - " ".repeat(indent), - title, - md) - }, - Err(why) => { - print!("{}: {}\n", id, why); - format!("{}* {}", " ".repeat(indent), title) - }, - }; - - tx.send((number.clone(), entry)); - - match self.children { - None => {}, - Some(ref children) => { - let path = Path::new(format!("stage/{}/{}", prefix, id)); - - file::mkdir(&path); - - for (i, example) in children.iter().enumerate() { - let tx = tx.clone(); - let prefix = if prefix.as_slice().is_whitespace() { - format!("{}", id) - } else { - format!("{}/{}", prefix, id) - }; - - let mut number = number.clone(); - number.push(i + 1); - example.process(number, - tx, - indent + 1, - prefix); - } - }, - } - } -} diff --git a/src/expression.md b/src/expression.md new file mode 100644 index 0000000000..27a278d027 --- /dev/null +++ b/src/expression.md @@ -0,0 +1,54 @@ +# Expressions + +A Rust program is (mostly) made up of a series of statements: + +```rust,editable +fn main() { + // statement + // statement + // statement +} +``` + +There are a few kinds of statements in Rust. The most common two are declaring +a variable binding, and using a `;` with an expression: + +```rust,editable +fn main() { + // variable binding + let x = 5; + + // expression; + x; + x + 1; + 15; +} +``` + +Blocks are expressions too, so they can be used as values in +assignments. The last expression in the block will be assigned to the +place expression such as a local variable. However, if the last expression of the block ends with a +semicolon, the return value will be `()`. + +```rust,editable +fn main() { + let x = 5u32; + + let y = { + let x_squared = x * x; + let x_cube = x_squared * x; + + // This expression will be assigned to `y` + x_cube + x_squared + x + }; + + let z = { + // The semicolon suppresses this expression and `()` is assigned to `z` + 2 * x; + }; + + println!("x is {:?}", x); + println!("y is {:?}", y); + println!("z is {:?}", z); +} +``` diff --git a/src/file.rs b/src/file.rs deleted file mode 100644 index d52300e8f2..0000000000 --- a/src/file.rs +++ /dev/null @@ -1,65 +0,0 @@ -use std::io::USER_RWX; -use std::io::fs; -use std::io::process::{Command,ProcessOutput}; -use std::io::{File,Truncate,Write}; -use std::os; - -pub fn mkdir(path: &Path) { - match fs::mkdir_recursive(path, USER_RWX) { - Err(_) => {}, - Ok(_) => {}, - } -} - -pub fn read(path: &Path) -> Result { - match File::open(path) { - Err(_) => Err(format!("couldn't open {}", path.display())), - Ok(mut file) => match file.read_to_string() { - Err(_) => Err(format!("couldn't read {}", path.display())), - Ok(string) => Ok(string), - } - } -} - -pub fn run(prefix: &str, id: &str, src: &str) -> Result { - let cwd = os::getcwd().unwrap(); - // Assume that the current working directory actually exists - let out_dir = cwd.join(format!("bin/{}/{}", prefix, id)); - - let mut cmd = Command::new("rustc"); - cmd.cwd(&Path::new(format!("examples/{}/{}", prefix, id))); - cmd.arg(format!("{}.rs", src)); - cmd.arg("--out-dir"); - cmd.arg(out_dir); - - match cmd.output() { - Err(_) => return Err(format!("couldn't find rustc")), - Ok(p) => if !p.status.success() { - return Ok(String::from_utf8(p.error).unwrap()); - }, - } - - let executable = Path::new(format!("./bin/{}/{}/{}", prefix, id, src)); - - match Command::new(&executable).output() { - Err(_) => Err(format!("couldn't find {}", executable.display())), - Ok(ProcessOutput { error, output, status }) => { - let mut s = String::from_utf8(output).unwrap(); - if !status.success() { - s.push_str(String::from_utf8(error).unwrap().as_slice()); - } - - Ok(s) - } - } -} - -pub fn write(path: &Path, string: &str) -> Result<(), String> { - match File::open_mode(path, Truncate, Write) { - Err(_) => Err(format!("couldn't open {}", path.display())), - Ok(mut file) => match file.write_str(string) { - Err(_) => Err(format!("couldn't write {}", path.display())), - Ok(_) => Ok(()), - } - } -} diff --git a/src/flow_control.md b/src/flow_control.md new file mode 100644 index 0000000000..c8a2f9ed87 --- /dev/null +++ b/src/flow_control.md @@ -0,0 +1,4 @@ +# Flow of Control + +An essential part of any programming languages are ways to modify control flow: +`if`/`else`, `for`, and others. Let's talk about them in Rust. diff --git a/src/flow_control/for.md b/src/flow_control/for.md new file mode 100644 index 0000000000..b5d5d62721 --- /dev/null +++ b/src/flow_control/for.md @@ -0,0 +1,125 @@ +# for loops + +## for and range + +The `for in` construct can be used to iterate through an `Iterator`. +One of the easiest ways to create an iterator is to use the range +notation `a..b`. This yields values from `a` (inclusive) to `b` +(exclusive) in steps of one. + +Let's write FizzBuzz using `for` instead of `while`. + +```rust,editable +fn main() { + // `n` will take the values: 1, 2, ..., 100 in each iteration + for n in 1..101 { + if n % 15 == 0 { + println!("fizzbuzz"); + } else if n % 3 == 0 { + println!("fizz"); + } else if n % 5 == 0 { + println!("buzz"); + } else { + println!("{}", n); + } + } +} +``` + +Alternatively, `a..=b` can be used for a range that is inclusive on both ends. +The above can be written as: + +```rust,editable +fn main() { + // `n` will take the values: 1, 2, ..., 100 in each iteration + for n in 1..=100 { + if n % 15 == 0 { + println!("fizzbuzz"); + } else if n % 3 == 0 { + println!("fizz"); + } else if n % 5 == 0 { + println!("buzz"); + } else { + println!("{}", n); + } + } +} +``` + +## for and iterators + +The `for in` construct is able to interact with an `Iterator` in several ways. +As discussed in the section on the [Iterator][iter] trait, by default the `for` +loop will apply the `into_iter` function to the collection. However, this is +not the only means of converting collections into iterators. + +`into_iter`, `iter` and `iter_mut` all handle the conversion of a collection +into an iterator in different ways, by providing different views on the data +within. + +* `iter` - This borrows each element of the collection through each iteration. + Thus leaving the collection untouched and available for reuse after the loop. + +```rust,editable +fn main() { + let names = vec!["Bob", "Frank", "Ferris"]; + + for name in names.iter() { + match name { + &"Ferris" => println!("There is a rustacean among us!"), + // TODO ^ Try deleting the & and matching just "Ferris" + _ => println!("Hello {}", name), + } + } + + println!("names: {:?}", names); +} +``` + +* `into_iter` - This consumes the collection so that on each iteration the exact + data is provided. Once the collection has been consumed it is no longer + available for reuse as it has been 'moved' within the loop. + +```rust,editable,ignore,mdbook-runnable +fn main() { + let names = vec!["Bob", "Frank", "Ferris"]; + + for name in names.into_iter() { + match name { + "Ferris" => println!("There is a rustacean among us!"), + _ => println!("Hello {}", name), + } + } + + println!("names: {:?}", names); + // FIXME ^ Comment out this line +} +``` + +* `iter_mut` - This mutably borrows each element of the collection, allowing for + the collection to be modified in place. + +```rust,editable +fn main() { + let mut names = vec!["Bob", "Frank", "Ferris"]; + + for name in names.iter_mut() { + *name = match name { + &mut "Ferris" => "There is a rustacean among us!", + _ => "Hello", + } + } + + println!("names: {:?}", names); +} +``` + +In the above snippets note the type of `match` branch, that is the key +difference in the types of iteration. The difference in type then of course +implies differing actions that are able to be performed. + +### See also: + +[Iterator][iter] + +[iter]: ../trait/iter.md diff --git a/src/flow_control/if_else.md b/src/flow_control/if_else.md new file mode 100644 index 0000000000..d761aa8388 --- /dev/null +++ b/src/flow_control/if_else.md @@ -0,0 +1,37 @@ +# if/else + +Branching with `if`-`else` is similar to other languages. Unlike many of them, +the boolean condition doesn't need to be surrounded by parentheses, and each +condition is followed by a block. `if`-`else` conditionals are expressions, +and, all branches must return the same type. + +```rust,editable +fn main() { + let n = 5; + + if n < 0 { + print!("{} is negative", n); + } else if n > 0 { + print!("{} is positive", n); + } else { + print!("{} is zero", n); + } + + let big_n = + if n < 10 && n > -10 { + println!(", and is a small number, increase ten-fold"); + + // This expression returns an `i32`. + 10 * n + } else { + println!(", and is a big number, halve the number"); + + // This expression must return an `i32` as well. + n / 2 + // TODO ^ Try suppressing this expression with a semicolon. + }; + // ^ Don't forget to put a semicolon here! All `let` bindings need it. + + println!("{} -> {}", n, big_n); +} +``` diff --git a/src/flow_control/if_let.md b/src/flow_control/if_let.md new file mode 100644 index 0000000000..3742b6f683 --- /dev/null +++ b/src/flow_control/if_let.md @@ -0,0 +1,128 @@ +# if let + +For some use cases, when matching enums, `match` is awkward. For example: + +```rust +// Make `optional` of type `Option` +let optional = Some(7); + +match optional { + Some(i) => { + println!("This is a really long string and `{:?}`", i); + // ^ Needed 2 indentations just so we could destructure + // `i` from the option. + }, + _ => {}, + // ^ Required because `match` is exhaustive. Doesn't it seem + // like wasted space? +}; + +``` + +`if let` is cleaner for this use case and in addition allows various +failure options to be specified: + +```rust,editable +fn main() { + // All have type `Option` + let number = Some(7); + let letter: Option = None; + let emoticon: Option = None; + + // The `if let` construct reads: "if `let` destructures `number` into + // `Some(i)`, evaluate the block (`{}`). + if let Some(i) = number { + println!("Matched {:?}!", i); + } + + // If you need to specify a failure, use an else: + if let Some(i) = letter { + println!("Matched {:?}!", i); + } else { + // Destructure failed. Change to the failure case. + println!("Didn't match a number. Let's go with a letter!"); + } + + // Provide an altered failing condition. + let i_like_letters = false; + + if let Some(i) = emoticon { + println!("Matched {:?}!", i); + // Destructure failed. Evaluate an `else if` condition to see if the + // alternate failure branch should be taken: + } else if i_like_letters { + println!("Didn't match a number. Let's go with a letter!"); + } else { + // The condition evaluated false. This branch is the default: + println!("I don't like letters. Let's go with an emoticon :)!"); + } +} +``` + +In the same way, `if let` can be used to match any enum value: + +```rust,editable +// Our example enum +enum Foo { + Bar, + Baz, + Qux(u32) +} + +fn main() { + // Create example variables + let a = Foo::Bar; + let b = Foo::Baz; + let c = Foo::Qux(100); + + // Variable a matches Foo::Bar + if let Foo::Bar = a { + println!("a is foobar"); + } + + // Variable b does not match Foo::Bar + // So this will print nothing + if let Foo::Bar = b { + println!("b is foobar"); + } + + // Variable c matches Foo::Qux which has a value + // Similar to Some() in the previous example + if let Foo::Qux(value) = c { + println!("c is {}", value); + } + + // Binding also works with `if let` + if let Foo::Qux(value @ 100) = c { + println!("c is one hundred"); + } +} +``` + +Another benefit is that `if let` allows us to match non-parameterized enum variants. This is true even in cases where the enum doesn't implement or derive `PartialEq`. In such cases `if Foo::Bar == a` would fail to compile, because instances of the enum cannot be equated, however `if let` will continue to work. + +Would you like a challenge? Fix the following example to use `if let`: + +```rust,editable,ignore,mdbook-runnable +// This enum purposely neither implements nor derives PartialEq. +// That is why comparing Foo::Bar == a fails below. +enum Foo {Bar} + +fn main() { + let a = Foo::Bar; + + // Variable a matches Foo::Bar + if Foo::Bar == a { + // ^-- this causes a compile-time error. Use `if let` instead. + println!("a is foobar"); + } +} +``` + +### See also: + +[`enum`][enum], [`Option`][option], and the [RFC][if_let_rfc] + +[enum]: ../custom_types/enum.md +[if_let_rfc]: https://github.com/rust-lang/rfcs/pull/160 +[option]: ../std/option.md diff --git a/examples/loop/loop.rs b/src/flow_control/loop.md similarity index 59% rename from examples/loop/loop.rs rename to src/flow_control/loop.md index 5341cff6a0..4a2405b7bf 100644 --- a/examples/loop/loop.rs +++ b/src/flow_control/loop.md @@ -1,5 +1,14 @@ +# loop + +Rust provides a `loop` keyword to indicate an infinite loop. + +The `break` statement can be used to exit a loop at anytime, whereas the +`continue` statement can be used to skip the rest of the iteration and start a +new one. + +```rust,editable fn main() { - let mut count = 0u; + let mut count = 0u32; println!("Let's count until infinity!"); @@ -24,3 +33,4 @@ fn main() { } } } +``` \ No newline at end of file diff --git a/examples/loop/nested/nested.rs b/src/flow_control/loop/nested.md similarity index 58% rename from examples/loop/nested/nested.rs rename to src/flow_control/loop/nested.md index 786fabab0e..01c55a5594 100644 --- a/examples/loop/nested/nested.rs +++ b/src/flow_control/loop/nested.md @@ -1,3 +1,12 @@ +# Nesting and labels + +It's possible to `break` or `continue` outer loops when dealing with nested +loops. In these cases, the loops must be annotated with some `'label`, and the +label must be passed to the `break`/`continue` statement. + +```rust,editable +#![allow(unreachable_code)] + fn main() { 'outer: loop { println!("Entered the outer loop"); @@ -17,3 +26,4 @@ fn main() { println!("Exited the outer loop"); } +``` \ No newline at end of file diff --git a/src/flow_control/loop/return.md b/src/flow_control/loop/return.md new file mode 100644 index 0000000000..8511b1e869 --- /dev/null +++ b/src/flow_control/loop/return.md @@ -0,0 +1,22 @@ +# Returning from loops + +One of the uses of a `loop` is to retry an operation until it succeeds. If the +operation returns a value though, you might need to pass it to the rest of the +code: put it after the `break`, and it will be returned by the `loop` +expression. + +```rust,editable +fn main() { + let mut counter = 0; + + let result = loop { + counter += 1; + + if counter == 10 { + break counter * 2; + } + }; + + assert_eq!(result, 20); +} +``` diff --git a/examples/match/match.rs b/src/flow_control/match.md similarity index 61% rename from examples/match/match.rs rename to src/flow_control/match.md index af15a7a03c..6beeea3668 100644 --- a/examples/match/match.rs +++ b/src/flow_control/match.md @@ -1,5 +1,12 @@ +# match + +Rust provides pattern matching via the `match` keyword, which can be used like +a C `switch`. The first matching arm is evaluated and all possible values must be +covered. + +```rust,editable fn main() { - let number: int = 13; + let number = 13; // TODO ^ Try different values for `number` println!("Tell me about {}", number); @@ -8,15 +15,17 @@ fn main() { 1 => println!("One!"), // Match several values 2 | 3 | 5 | 7 | 11 => println!("This is a prime"), + // TODO ^ Try adding 13 to the list of prime values // Match an inclusive range - 13...19 => println!("A teen"), + 13..=19 => println!("A teen"), // Handle the rest of cases _ => println!("Ain't special"), + // TODO ^ Try commenting out this catch-all arm } let boolean = true; // Match is an expression too - let binary: int = match boolean { + let binary = match boolean { // The arms of a match must cover all the possible values false => 0, true => 1, @@ -25,3 +34,4 @@ fn main() { println!("{} -> {}", boolean, binary); } +``` diff --git a/src/flow_control/match/binding.md b/src/flow_control/match/binding.md new file mode 100644 index 0000000000..ccbb7c2add --- /dev/null +++ b/src/flow_control/match/binding.md @@ -0,0 +1,54 @@ +# Binding + +Indirectly accessing a variable makes it impossible to branch and use that +variable without re-binding. `match` provides the `@` sigil for binding values to +names: + +```rust,editable +// A function `age` which returns a `u32`. +fn age() -> u32 { + 15 +} + +fn main() { + println!("Tell me what type of person you are"); + + match age() { + 0 => println!("I haven't celebrated my first birthday yet"), + // Could `match` 1 ..= 12 directly but then what age + // would the child be? Instead, bind to `n` for the + // sequence of 1 ..= 12. Now the age can be reported. + n @ 1 ..= 12 => println!("I'm a child of age {:?}", n), + n @ 13 ..= 19 => println!("I'm a teen of age {:?}", n), + // Nothing bound. Return the result. + n => println!("I'm an old person of age {:?}", n), + } +} +``` + +You can also use binding to "destructure" `enum` variants, such as `Option`: + +```rust,editable +fn some_number() -> Option { + Some(42) +} + +fn main() { + match some_number() { + // Got `Some` variant, match if its value, bound to `n`, + // is equal to 42. + Some(n @ 42) => println!("The Answer: {}!", n), + // Match any other number. + Some(n) => println!("Not interesting... {}", n), + // Match anything else (`None` variant). + _ => (), + } +} +``` + +### See also: +[`functions`][functions], [`enums`][enums] and [`Option`][option] + +[functions]: ../../fn.md +[enums]: ../../custom_types/enum.md +[option]: ../../std/option.md diff --git a/src/flow_control/match/destructuring.md b/src/flow_control/match/destructuring.md new file mode 100644 index 0000000000..5e82e6cf54 --- /dev/null +++ b/src/flow_control/match/destructuring.md @@ -0,0 +1,14 @@ +# Destructuring + +A `match` block can destructure items in a variety of ways. + +* [Destructuring Tuples][tuple] +* [Destructuring Enums][enum] +* [Destructuring Pointers][refs] +* [Destructuring Structures][struct] + + +[enum]: destructuring/destructure_enum.md +[refs]: destructuring/destructure_pointers.md +[struct]: destructuring/destructure_structures.md +[tuple]: destructuring/destructure_tuple.md diff --git a/src/flow_control/match/destructuring/destructure_enum.md b/src/flow_control/match/destructuring/destructure_enum.md new file mode 100644 index 0000000000..60d8969459 --- /dev/null +++ b/src/flow_control/match/destructuring/destructure_enum.md @@ -0,0 +1,54 @@ +# enums + +An `enum` is destructured similarly: + +```rust,editable +// `allow` required to silence warnings because only +// one variant is used. +#[allow(dead_code)] +enum Color { + // These 3 are specified solely by their name. + Red, + Blue, + Green, + // These likewise tie `u32` tuples to different names: color models. + RGB(u32, u32, u32), + HSV(u32, u32, u32), + HSL(u32, u32, u32), + CMY(u32, u32, u32), + CMYK(u32, u32, u32, u32), +} + +fn main() { + let color = Color::RGB(122, 17, 40); + // TODO ^ Try different variants for `color` + + println!("What color is it?"); + // An `enum` can be destructured using a `match`. + match color { + Color::Red => println!("The color is Red!"), + Color::Blue => println!("The color is Blue!"), + Color::Green => println!("The color is Green!"), + Color::RGB(r, g, b) => + println!("Red: {}, green: {}, and blue: {}!", r, g, b), + Color::HSV(h, s, v) => + println!("Hue: {}, saturation: {}, value: {}!", h, s, v), + Color::HSL(h, s, l) => + println!("Hue: {}, saturation: {}, lightness: {}!", h, s, l), + Color::CMY(c, m, y) => + println!("Cyan: {}, magenta: {}, yellow: {}!", c, m, y), + Color::CMYK(c, m, y, k) => + println!("Cyan: {}, magenta: {}, yellow: {}, key (black): {}!", + c, m, y, k), + // Don't need another arm because all variants have been examined + } +} +``` + +### See also: + +[`#[allow(...)]`][allow], [color models][color_models] and [`enum`][enum] + +[allow]: ../../../attribute/unused.md +[color_models]: https://en.wikipedia.org/wiki/Color_model +[enum]: ../../../custom_types/enum.md diff --git a/src/flow_control/match/destructuring/destructure_pointers.md b/src/flow_control/match/destructuring/destructure_pointers.md new file mode 100644 index 0000000000..43ca3bd281 --- /dev/null +++ b/src/flow_control/match/destructuring/destructure_pointers.md @@ -0,0 +1,65 @@ +# pointers/ref + +For pointers, a distinction needs to be made between destructuring +and dereferencing as they are different concepts which are used +differently from a language like `C`. + + * Dereferencing uses `*` + * Destructuring uses `&`, `ref`, and `ref mut` + +```rust,editable +fn main() { + // Assign a reference of type `i32`. The `&` signifies there + // is a reference being assigned. + let reference = &4; + + match reference { + // If `reference` is pattern matched against `&val`, it results + // in a comparison like: + // `&i32` + // `&val` + // ^ We see that if the matching `&`s are dropped, then the `i32` + // should be assigned to `val`. + &val => println!("Got a value via destructuring: {:?}", val), + } + + // To avoid the `&`, you dereference before matching. + match *reference { + val => println!("Got a value via dereferencing: {:?}", val), + } + + // What if you don't start with a reference? `reference` was a `&` + // because the right side was already a reference. This is not + // a reference because the right side is not one. + let _not_a_reference = 3; + + // Rust provides `ref` for exactly this purpose. It modifies the + // assignment so that a reference is created for the element; this + // reference is assigned. + let ref _is_a_reference = 3; + + // Accordingly, by defining 2 values without references, references + // can be retrieved via `ref` and `ref mut`. + let value = 5; + let mut mut_value = 6; + + // Use `ref` keyword to create a reference. + match value { + ref r => println!("Got a reference to a value: {:?}", r), + } + + // Use `ref mut` similarly. + match mut_value { + ref mut m => { + // Got a reference. Gotta dereference it before we can + // add anything to it. + *m += 10; + println!("We added 10. `mut_value`: {:?}", m); + }, + } +} +``` + +### See also: + +[The ref pattern](../../../scope/borrow/ref.md) diff --git a/src/flow_control/match/destructuring/destructure_structures.md b/src/flow_control/match/destructuring/destructure_structures.md new file mode 100644 index 0000000000..9e43b70c15 --- /dev/null +++ b/src/flow_control/match/destructuring/destructure_structures.md @@ -0,0 +1,32 @@ +# structs + +Similarly, a `struct` can be destructured as shown: + +```rust,editable +fn main() { + struct Foo { + x: (u32, u32), + y: u32, + } + + // Try changing the values in the struct to see what happens + let foo = Foo { x: (1, 2), y: 3 }; + + match foo { + Foo { x: (1, b), y } => println!("First of x is 1, b = {}, y = {} ", b, y), + + // you can destructure structs and rename the variables, + // the order is not important + Foo { y: 2, x: i } => println!("y is 2, i = {:?}", i), + + // and you can also ignore some variables: + Foo { y, .. } => println!("y = {}, we don't care about x", y), + // this will give an error: pattern does not mention field `x` + //Foo { y } => println!("y = {}", y), + } +} +``` + +### See also: + +[Structs](../../../custom_types/structs.md) diff --git a/src/flow_control/match/destructuring/destructure_tuple.md b/src/flow_control/match/destructuring/destructure_tuple.md new file mode 100644 index 0000000000..30ae68f95c --- /dev/null +++ b/src/flow_control/match/destructuring/destructure_tuple.md @@ -0,0 +1,25 @@ +# tuples + +Tuples can be destructured in a `match` as follows: + +```rust,editable +fn main() { + let triple = (0, -2, 3); + // TODO ^ Try different values for `triple` + + println!("Tell me about {:?}", triple); + // Match can be used to destructure a tuple + match triple { + // Destructure the second and third elements + (0, y, z) => println!("First is `0`, `y` is {:?}, and `z` is {:?}", y, z), + (1, ..) => println!("First is `1` and the rest doesn't matter"), + // `..` can be the used ignore the rest of the tuple + _ => println!("It doesn't matter what they are"), + // `_` means don't bind the value to a variable + } +} +``` + +### See also: + +[Tuples](../../../primitives/tuples.md) diff --git a/src/flow_control/match/guard.md b/src/flow_control/match/guard.md new file mode 100644 index 0000000000..9caa65aa00 --- /dev/null +++ b/src/flow_control/match/guard.md @@ -0,0 +1,39 @@ +# Guards + +A `match` *guard* can be added to filter the arm. + +```rust,editable +fn main() { + let pair = (2, -2); + // TODO ^ Try different values for `pair` + + println!("Tell me about {:?}", pair); + match pair { + (x, y) if x == y => println!("These are twins"), + // The ^ `if condition` part is a guard + (x, y) if x + y == 0 => println!("Antimatter, kaboom!"), + (x, _) if x % 2 == 1 => println!("The first one is odd"), + _ => println!("No correlation..."), + } +} +``` + +Note that the compiler does not check arbitrary expressions for whether all +possible conditions have been checked. Therefore, you must use the `_` pattern +at the end. + +```rust,editable +fn main() { + let number: u8 = 4; + + match number { + i if i == 0 => println!("Zero"), + i if i > 0 => println!("Greater than zero"), + _ => println!("Fell through"), // This should not be possible to reach + } +} +``` + +### See also: + +[Tuples](../../primitives/tuples.md) diff --git a/examples/while/while.rs b/src/flow_control/while.md similarity index 61% rename from examples/while/while.rs rename to src/flow_control/while.md index c0396d31df..01a8dc9ecb 100644 --- a/examples/while/while.rs +++ b/src/flow_control/while.md @@ -1,6 +1,13 @@ +# while + +The `while` keyword can be used to run a loop while a condition is true. + +Let's write the infamous [FizzBuzz][fizzbuzz] using a `while` loop. + +```rust,editable fn main() { // A counter variable - let mut n = 1u; + let mut n = 1; // Loop while `n` is less than 101 while n < 101 { @@ -18,3 +25,6 @@ fn main() { n += 1; } } +``` + +[fizzbuzz]: https://en.wikipedia.org/wiki/Fizz_buzz diff --git a/src/flow_control/while_let.md b/src/flow_control/while_let.md new file mode 100644 index 0000000000..897375a8e2 --- /dev/null +++ b/src/flow_control/while_let.md @@ -0,0 +1,62 @@ +# while let + +Similar to `if let`, `while let` can make awkward `match` sequences +more tolerable. Consider the following sequence that increments `i`: + +```rust +// Make `optional` of type `Option` +let mut optional = Some(0); + +// Repeatedly try this test. +loop { + match optional { + // If `optional` destructures, evaluate the block. + Some(i) => { + if i > 9 { + println!("Greater than 9, quit!"); + optional = None; + } else { + println!("`i` is `{:?}`. Try again.", i); + optional = Some(i + 1); + } + // ^ Requires 3 indentations! + }, + // Quit the loop when the destructure fails: + _ => { break; } + // ^ Why should this be required? There must be a better way! + } +} +``` + +Using `while let` makes this sequence much nicer: + +```rust,editable +fn main() { + // Make `optional` of type `Option` + let mut optional = Some(0); + + // This reads: "while `let` destructures `optional` into + // `Some(i)`, evaluate the block (`{}`). Else `break`. + while let Some(i) = optional { + if i > 9 { + println!("Greater than 9, quit!"); + optional = None; + } else { + println!("`i` is `{:?}`. Try again.", i); + optional = Some(i + 1); + } + // ^ Less rightward drift and doesn't require + // explicitly handling the failing case. + } + // ^ `if let` had additional optional `else`/`else if` + // clauses. `while let` does not have these. +} +``` + +### See also: + +[`enum`][enum], [`Option`][option], and the [RFC][while_let_rfc] + +[enum]: ../custom_types/enum.md +[option]: ../std/option.md +[while_let_rfc]: https://github.com/rust-lang/rfcs/pull/214 diff --git a/examples/fn/fn.rs b/src/fn.md similarity index 57% rename from examples/fn/fn.rs rename to src/fn.md index 01df12493b..3516066d54 100644 --- a/examples/fn/fn.rs +++ b/src/fn.md @@ -1,3 +1,16 @@ +# Functions + +Functions are declared using the `fn` keyword. Its arguments are type +annotated, just like variables, and, if the function returns a value, the +return type must be specified after an arrow `->`. + +The final expression in the function will be used as return value. +Alternatively, the `return` statement can be used to return a value earlier +from within the function, even from inside loops or `if` statements. + +Let's rewrite FizzBuzz using functions! + +```rust,editable // Unlike C/C++, there's no restriction on the order of function definitions fn main() { // We can use this function here, and define it somewhere later @@ -5,7 +18,7 @@ fn main() { } // Function that returns a boolean value -fn is_divisible_by(lhs: uint, rhs: uint) -> bool { +fn is_divisible_by(lhs: u32, rhs: u32) -> bool { // Corner case, early return if rhs == 0 { return false; @@ -16,7 +29,7 @@ fn is_divisible_by(lhs: uint, rhs: uint) -> bool { } // Functions that "don't" return a value, actually return the unit type `()` -fn fizzbuzz(n: uint) -> () { +fn fizzbuzz(n: u32) -> () { if is_divisible_by(n, 15) { println!("fizzbuzz"); } else if is_divisible_by(n, 3) { @@ -30,8 +43,9 @@ fn fizzbuzz(n: uint) -> () { // When a function returns `()`, the return type can be omitted from the // signature -fn fizzbuzz_to(n: uint) { - for n in range(1, n + 1) { +fn fizzbuzz_to(n: u32) { + for n in 1..n + 1 { fizzbuzz(n); } } +``` diff --git a/src/fn/closures.md b/src/fn/closures.md new file mode 100644 index 0000000000..68bfd8adf6 --- /dev/null +++ b/src/fn/closures.md @@ -0,0 +1,44 @@ +# Closures + +Closures are functions that can capture the enclosing environment. For +example, a closure that captures the x variable: + +```Rust +|val| val + x +``` + +The syntax and capabilities of closures make them very convenient for +on the fly usage. Calling a closure is exactly like calling a function. +However, both input and return types *can* be inferred and input +variable names *must* be specified. + +Other characteristics of closures include: +* using `||` instead of `()` around input variables. +* optional body delimination (`{}`) for a single expression (mandatory otherwise). +* the ability to capture the outer environment variables. + +```rust,editable +fn main() { + // Increment via closures and functions. + fn function(i: i32) -> i32 { i + 1 } + + // Closures are anonymous, here we are binding them to references + // Annotation is identical to function annotation but is optional + // as are the `{}` wrapping the body. These nameless functions + // are assigned to appropriately named variables. + let closure_annotated = |i: i32| -> i32 { i + 1 }; + let closure_inferred = |i | i + 1 ; + + let i = 1; + // Call the function and closures. + println!("function: {}", function(i)); + println!("closure_annotated: {}", closure_annotated(i)); + println!("closure_inferred: {}", closure_inferred(i)); + + // A closure taking no arguments which returns an `i32`. + // The return type is inferred. + let one = || 1; + println!("closure returning one: {}", one()); + +} +``` diff --git a/src/fn/closures/anonymity.md b/src/fn/closures/anonymity.md new file mode 100644 index 0000000000..7008a446b8 --- /dev/null +++ b/src/fn/closures/anonymity.md @@ -0,0 +1,56 @@ +# Type anonymity + +Closures succinctly capture variables from enclosing scopes. Does this have +any consequences? It surely does. Observe how using a closure as a function +parameter requires [generics], which is necessary because of how they are +defined: + +```rust +// `F` must be generic. +fn apply(f: F) where + F: FnOnce() { + f(); +} +``` + +When a closure is defined, the compiler implicitly creates a new +anonymous structure to store the captured variables inside, meanwhile +implementing the functionality via one of the `traits`: `Fn`, `FnMut`, or +`FnOnce` for this unknown type. This type is assigned to the variable which +is stored until calling. + +Since this new type is of unknown type, any usage in a function will require +generics. However, an unbounded type parameter `` would still be ambiguous +and not be allowed. Thus, bounding by one of the `traits`: `Fn`, `FnMut`, or +`FnOnce` (which it implements) is sufficient to specify its type. + +```rust,editable +// `F` must implement `Fn` for a closure which takes no +// inputs and returns nothing - exactly what is required +// for `print`. +fn apply(f: F) where + F: Fn() { + f(); +} + +fn main() { + let x = 7; + + // Capture `x` into an anonymous type and implement + // `Fn` for it. Store it in `print`. + let print = || println!("{}", x); + + apply(print); +} +``` + +### See also: + +[A thorough analysis][thorough_analysis], [`Fn`][fn], [`FnMut`][fn_mut], +and [`FnOnce`][fn_once] + +[generics]: ../../generics.md +[fn]: https://doc.rust-lang.org/std/ops/trait.Fn.html +[fn_mut]: https://doc.rust-lang.org/std/ops/trait.FnMut.html +[fn_once]: https://doc.rust-lang.org/std/ops/trait.FnOnce.html +[thorough_analysis]: https://huonw.github.io/blog/2015/05/finding-closure-in-rust/ diff --git a/src/fn/closures/capture.md b/src/fn/closures/capture.md new file mode 100644 index 0000000000..061ef1c7b2 --- /dev/null +++ b/src/fn/closures/capture.md @@ -0,0 +1,115 @@ +# Capturing + +Closures are inherently flexible and will do what the functionality requires +to make the closure work without annotation. This allows capturing to +flexibly adapt to the use case, sometimes moving and sometimes borrowing. +Closures can capture variables: + +* by reference: `&T` +* by mutable reference: `&mut T` +* by value: `T` + +They preferentially capture variables by reference and only go lower when +required. + +```rust,editable +fn main() { + use std::mem; + + let color = String::from("green"); + + // A closure to print `color` which immediately borrows (`&`) `color` and + // stores the borrow and closure in the `print` variable. It will remain + // borrowed until `print` is used the last time. + // + // `println!` only requires arguments by immutable reference so it doesn't + // impose anything more restrictive. + let print = || println!("`color`: {}", color); + + // Call the closure using the borrow. + print(); + + // `color` can be borrowed immutably again, because the closure only holds + // an immutable reference to `color`. + let _reborrow = &color; + print(); + + // A move or reborrow is allowed after the final use of `print` + let _color_moved = color; + + + let mut count = 0; + // A closure to increment `count` could take either `&mut count` or `count` + // but `&mut count` is less restrictive so it takes that. Immediately + // borrows `count`. + // + // A `mut` is required on `inc` because a `&mut` is stored inside. Thus, + // calling the closure mutates the closure which requires a `mut`. + let mut inc = || { + count += 1; + println!("`count`: {}", count); + }; + + // Call the closure using a mutable borrow. + inc(); + + // The closure still mutably borrows `count` because it is called later. + // An attempt to reborrow will lead to an error. + // let _reborrow = &count; + // ^ TODO: try uncommenting this line. + inc(); + + // The closure no longer needs to borrow `&mut count`. Therefore, it is + // possible to reborrow without an error + let _count_reborrowed = &mut count; + + + // A non-copy type. + let movable = Box::new(3); + + // `mem::drop` requires `T` so this must take by value. A copy type + // would copy into the closure leaving the original untouched. + // A non-copy must move and so `movable` immediately moves into + // the closure. + let consume = || { + println!("`movable`: {:?}", movable); + mem::drop(movable); + }; + + // `consume` consumes the variable so this can only be called once. + consume(); + // consume(); + // ^ TODO: Try uncommenting this line. +} +``` + +Using `move` before vertical pipes forces closure +to take ownership of captured variables: + +```rust,editable +fn main() { + // `Vec` has non-copy semantics. + let haystack = vec![1, 2, 3]; + + let contains = move |needle| haystack.contains(needle); + + println!("{}", contains(&1)); + println!("{}", contains(&4)); + + // println!("There're {} elements in vec", haystack.len()); + // ^ Uncommenting above line will result in compile-time error + // because borrow checker doesn't allow re-using variable after it + // has been moved. + + // Removing `move` from closure's signature will cause closure + // to borrow _haystack_ variable immutably, hence _haystack_ is still + // available and uncommenting above line will not cause an error. +} +``` + +### See also: + +[`Box`][box] and [`std::mem::drop`][drop] + +[box]: ../../std/box.md +[drop]: https://doc.rust-lang.org/std/mem/fn.drop.html diff --git a/src/fn/closures/closure_examples.md b/src/fn/closures/closure_examples.md new file mode 100644 index 0000000000..2455523ad9 --- /dev/null +++ b/src/fn/closures/closure_examples.md @@ -0,0 +1,3 @@ +# Examples in `std` + +This section contains a few examples of using closures from the `std` library. \ No newline at end of file diff --git a/src/fn/closures/closure_examples/iter_any.md b/src/fn/closures/closure_examples/iter_any.md new file mode 100644 index 0000000000..1fb64e9707 --- /dev/null +++ b/src/fn/closures/closure_examples/iter_any.md @@ -0,0 +1,46 @@ +# Iterator::any + +`Iterator::any` is a function which when passed an iterator, will return +`true` if any element satisfies the predicate. Otherwise `false`. Its +signature: + +```rust,ignore +pub trait Iterator { + // The type being iterated over. + type Item; + + // `any` takes `&mut self` meaning the caller may be borrowed + // and modified, but not consumed. + fn any(&mut self, f: F) -> bool where + // `FnMut` meaning any captured variable may at most be + // modified, not consumed. `Self::Item` states it takes + // arguments to the closure by value. + F: FnMut(Self::Item) -> bool {} +} +``` + +```rust,editable +fn main() { + let vec1 = vec![1, 2, 3]; + let vec2 = vec![4, 5, 6]; + + // `iter()` for vecs yields `&i32`. Destructure to `i32`. + println!("2 in vec1: {}", vec1.iter() .any(|&x| x == 2)); + // `into_iter()` for vecs yields `i32`. No destructuring required. + println!("2 in vec2: {}", vec2.into_iter().any(| x| x == 2)); + + let array1 = [1, 2, 3]; + let array2 = [4, 5, 6]; + + // `iter()` for arrays yields `&i32`. + println!("2 in array1: {}", array1.iter() .any(|&x| x == 2)); + // `into_iter()` for arrays unusually yields `&i32`. + println!("2 in array2: {}", array2.into_iter().any(|&x| x == 2)); +} +``` + +### See also: + +[`std::iter::Iterator::any`][any] + +[any]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.any diff --git a/src/fn/closures/closure_examples/iter_find.md b/src/fn/closures/closure_examples/iter_find.md new file mode 100644 index 0000000000..9eb5072e97 --- /dev/null +++ b/src/fn/closures/closure_examples/iter_find.md @@ -0,0 +1,78 @@ +# Searching through iterators + +`Iterator::find` is a function which iterates over an iterator and searches for the +first value which satisfies some condition. If none of the values satisfy the +condition, it returns `None`. Its signature: + +```rust,ignore +pub trait Iterator { + // The type being iterated over. + type Item; + + // `find` takes `&mut self` meaning the caller may be borrowed + // and modified, but not consumed. + fn find

(&mut self, predicate: P) -> Option where + // `FnMut` meaning any captured variable may at most be + // modified, not consumed. `&Self::Item` states it takes + // arguments to the closure by reference. + P: FnMut(&Self::Item) -> bool {} +} +``` + +```rust,editable +fn main() { + let vec1 = vec![1, 2, 3]; + let vec2 = vec![4, 5, 6]; + + // `iter()` for vecs yields `&i32`. + let mut iter = vec1.iter(); + // `into_iter()` for vecs yields `i32`. + let mut into_iter = vec2.into_iter(); + + // `iter()` for vecs yields `&i32`, and we want to reference one of its + // items, so we have to destructure `&&i32` to `i32` + println!("Find 2 in vec1: {:?}", iter .find(|&&x| x == 2)); + // `into_iter()` for vecs yields `i32`, and we want to reference one of + // its items, so we have to destructure `&i32` to `i32` + println!("Find 2 in vec2: {:?}", into_iter.find(| &x| x == 2)); + + let array1 = [1, 2, 3]; + let array2 = [4, 5, 6]; + + // `iter()` for arrays yields `&i32` + println!("Find 2 in array1: {:?}", array1.iter() .find(|&&x| x == 2)); + // `into_iter()` for arrays unusually yields `&i32` + println!("Find 2 in array2: {:?}", array2.into_iter().find(|&&x| x == 2)); +} +``` + +`Iterator::find` gives you a reference to the item. But if you want the _index_ of the +item, use `Iterator::position`. + +```rust,editable +fn main() { + let vec = vec![1, 9, 3, 3, 13, 2]; + + let index_of_first_even_number = vec.iter().position(|x| x % 2 == 0); + assert_eq!(index_of_first_even_number, Some(5)); + + + let index_of_first_negative_number = vec.iter().position(|x| x < &0); + assert_eq!(index_of_first_negative_number, None); +} +``` + +### See also: + +[`std::iter::Iterator::find`][find] + +[`std::iter::Iterator::find_map`][find_map] + +[`std::iter::Iterator::position`][position] + +[`std::iter::Iterator::rposition`][rposition] + +[find]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.find +[find_map]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.find_map +[position]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.position +[rposition]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.rposition diff --git a/src/fn/closures/input_functions.md b/src/fn/closures/input_functions.md new file mode 100644 index 0000000000..0cf9cd1cb1 --- /dev/null +++ b/src/fn/closures/input_functions.md @@ -0,0 +1,38 @@ +# Input functions + +Since closures may be used as arguments, you might wonder if the same can be said +about functions. And indeed they can! If you declare a function that takes a +closure as parameter, then any function that satisfies the trait bound of that +closure can be passed as a parameter. + +```rust,editable +// Define a function which takes a generic `F` argument +// bounded by `Fn`, and calls it +fn call_me(f: F) { + f(); +} + +// Define a wrapper function satisfying the `Fn` bound +fn function() { + println!("I'm a function!"); +} + +fn main() { + // Define a closure satisfying the `Fn` bound + let closure = || println!("I'm a closure!"); + + call_me(closure); + call_me(function); +} +``` + +As an additional note, the `Fn`, `FnMut`, and `FnOnce` `traits` dictate how +a closure captures variables from the enclosing scope. + +### See also: + +[`Fn`][fn], [`FnMut`][fn_mut], and [`FnOnce`][fn_once] + +[fn]: https://doc.rust-lang.org/std/ops/trait.Fn.html +[fn_mut]: https://doc.rust-lang.org/std/ops/trait.FnMut.html +[fn_once]: https://doc.rust-lang.org/std/ops/trait.FnOnce.html diff --git a/src/fn/closures/input_parameters.md b/src/fn/closures/input_parameters.md new file mode 100644 index 0000000000..be36c6d361 --- /dev/null +++ b/src/fn/closures/input_parameters.md @@ -0,0 +1,92 @@ +# As input parameters + +While Rust chooses how to capture variables on the fly mostly without type +annotation, this ambiguity is not allowed when writing functions. When +taking a closure as an input parameter, the closure's complete type must be +annotated using one of a few `traits`. In order of decreasing restriction, +they are: + +* `Fn`: the closure captures by reference (`&T`) +* `FnMut`: the closure captures by mutable reference (`&mut T`) +* `FnOnce`: the closure captures by value (`T`) + +On a variable-by-variable basis, the compiler will capture variables in the +least restrictive manner possible. + +For instance, consider a parameter annotated as `FnOnce`. This specifies +that the closure *may* capture by `&T`, `&mut T`, or `T`, but the compiler +will ultimately choose based on how the captured variables are used in the +closure. + +This is because if a move is possible, then any type of borrow should also +be possible. Note that the reverse is not true. If the parameter is +annotated as `Fn`, then capturing variables by `&mut T` or `T` are not +allowed. + +In the following example, try swapping the usage of `Fn`, `FnMut`, and +`FnOnce` to see what happens: + +```rust,editable +// A function which takes a closure as an argument and calls it. +// denotes that F is a "Generic type parameter" +fn apply(f: F) where + // The closure takes no input and returns nothing. + F: FnOnce() { + // ^ TODO: Try changing this to `Fn` or `FnMut`. + + f(); +} + +// A function which takes a closure and returns an `i32`. +fn apply_to_3(f: F) -> i32 where + // The closure takes an `i32` and returns an `i32`. + F: Fn(i32) -> i32 { + + f(3) +} + +fn main() { + use std::mem; + + let greeting = "hello"; + // A non-copy type. + // `to_owned` creates owned data from borrowed one + let mut farewell = "goodbye".to_owned(); + + // Capture 2 variables: `greeting` by reference and + // `farewell` by value. + let diary = || { + // `greeting` is by reference: requires `Fn`. + println!("I said {}.", greeting); + + // Mutation forces `farewell` to be captured by + // mutable reference. Now requires `FnMut`. + farewell.push_str("!!!"); + println!("Then I screamed {}.", farewell); + println!("Now I can sleep. zzzzz"); + + // Manually calling drop forces `farewell` to + // be captured by value. Now requires `FnOnce`. + mem::drop(farewell); + }; + + // Call the function which applies the closure. + apply(diary); + + // `double` satisfies `apply_to_3`'s trait bound + let double = |x| 2 * x; + + println!("3 doubled: {}", apply_to_3(double)); +} +``` + +### See also: + +[`std::mem::drop`][drop], [`Fn`][fn], [`FnMut`][fnmut], [Generics][generics], [where][where] and [`FnOnce`][fnonce] + +[drop]: https://doc.rust-lang.org/std/mem/fn.drop.html +[fn]: https://doc.rust-lang.org/std/ops/trait.Fn.html +[fnmut]: https://doc.rust-lang.org/std/ops/trait.FnMut.html +[fnonce]: https://doc.rust-lang.org/std/ops/trait.FnOnce.html +[generics]: ../../generics.md +[where]: ../../generics/where.md diff --git a/src/fn/closures/output_parameters.md b/src/fn/closures/output_parameters.md new file mode 100644 index 0000000000..6cad1735b9 --- /dev/null +++ b/src/fn/closures/output_parameters.md @@ -0,0 +1,56 @@ +# As output parameters + +Closures as input parameters are possible, so returning closures as +output parameters should also be possible. However, anonymous +closure types are, by definition, unknown, so we have to use +`impl Trait` to return them. + +The valid traits for returning a closure are: + +* `Fn` +* `FnMut` +* `FnOnce` + +Beyond this, the `move` keyword must be used, which signals that all captures +occur by value. This is required because any captures by reference would be +dropped as soon as the function exited, leaving invalid references in the +closure. + +```rust,editable +fn create_fn() -> impl Fn() { + let text = "Fn".to_owned(); + + move || println!("This is a: {}", text) +} + +fn create_fnmut() -> impl FnMut() { + let text = "FnMut".to_owned(); + + move || println!("This is a: {}", text) +} + +fn create_fnonce() -> impl FnOnce() { + let text = "FnOnce".to_owned(); + + move || println!("This is a: {}", text) +} + +fn main() { + let fn_plain = create_fn(); + let mut fn_mut = create_fnmut(); + let fn_once = create_fnonce(); + + fn_plain(); + fn_mut(); + fn_once(); +} +``` + +### See also: + +[`Fn`][fn], [`FnMut`][fnmut], [Generics][generics] and [impl Trait][impltrait]. + +[fn]: https://doc.rust-lang.org/std/ops/trait.Fn.html +[fnmut]: https://doc.rust-lang.org/std/ops/trait.FnMut.html +[generics]: ../../generics.md +[impltrait]: ../../trait/impl_trait.md diff --git a/src/fn/diverging.md b/src/fn/diverging.md new file mode 100644 index 0000000000..52e1f819ae --- /dev/null +++ b/src/fn/diverging.md @@ -0,0 +1,69 @@ +# Diverging functions + +Diverging functions never return. They are marked using `!`, which is an empty type. + +```rust +fn foo() -> ! { + panic!("This call never returns."); +} +``` + +As opposed to all the other types, this one cannot be instantiated, because the +set of all possible values this type can have is empty. Note that, it is +different from the `()` type, which has exactly one possible value. + +For example, this function returns as usual, although there is no information +in the return value. + +```rust +fn some_fn() { + () +} + +fn main() { + let a: () = some_fn(); + println!("This function returns and you can see this line.") +} +``` + +As opposed to this function, which will never return the control back to the caller. + +```rust,ignore +#![feature(never_type)] + +fn main() { + let x: ! = panic!("This call never returns."); + println!("You will never see this line!"); +} +``` + +Although this might seem like an abstract concept, it is in fact very useful and +often handy. The main advantage of this type is that it can be cast to any other +one and therefore used at places where an exact type is required, for instance +in `match` branches. This allows us to write code like this: + +```rust +fn main() { + fn sum_odd_numbers(up_to: u32) -> u32 { + let mut acc = 0; + for i in 0..up_to { + // Notice that the return type of this match expression must be u32 + // because of the type of the "addition" variable. + let addition: u32 = match i%2 == 1 { + // The "i" variable is of type u32, which is perfectly fine. + true => i, + // On the other hand, the "continue" expression does not return + // u32, but it is still fine, because it never returns and therefore + // does not violate the type requirements of the match expression. + false => continue, + }; + acc += addition; + } + acc + } + println!("Sum of odd numbers up to 9 (excluding): {}", sum_odd_numbers(9)); +} +``` + +It is also the return type of functions that loop forever (e.g. `loop {}`) like +network servers or functions that terminate the process (e.g. `exit()`). diff --git a/src/fn/hof.md b/src/fn/hof.md new file mode 100644 index 0000000000..568c79d413 --- /dev/null +++ b/src/fn/hof.md @@ -0,0 +1,50 @@ +# Higher Order Functions + +Rust provides Higher Order Functions (HOF). These are functions that +take one or more functions and/or produce a more useful function. HOFs +and lazy iterators give Rust its functional flavor. + +```rust,editable +fn is_odd(n: u32) -> bool { + n % 2 == 1 +} + +fn main() { + println!("Find the sum of all the squared odd numbers under 1000"); + let upper = 1000; + + // Imperative approach + // Declare accumulator variable + let mut acc = 0; + // Iterate: 0, 1, 2, ... to infinity + for n in 0.. { + // Square the number + let n_squared = n * n; + + if n_squared >= upper { + // Break loop if exceeded the upper limit + break; + } else if is_odd(n_squared) { + // Accumulate value, if it's odd + acc += n_squared; + } + } + println!("imperative style: {}", acc); + + // Functional approach + let sum_of_squared_odd_numbers: u32 = + (0..).map(|n| n * n) // All natural numbers squared + .take_while(|&n_squared| n_squared < upper) // Below upper limit + .filter(|&n_squared| is_odd(n_squared)) // That are odd + .fold(0, |acc, n_squared| acc + n_squared); // Sum them + println!("functional style: {}", sum_of_squared_odd_numbers); +} +``` + +[Option][option] +and +[Iterator][iter] +implement their fair share of HOFs. + +[option]: https://doc.rust-lang.org/core/option/enum.Option.html +[iter]: https://doc.rust-lang.org/core/iter/trait.Iterator.html diff --git a/examples/methods/methods.rs b/src/fn/methods.md similarity index 81% rename from examples/methods/methods.rs rename to src/fn/methods.md index 41b580ceb5..8e8c10ced4 100644 --- a/examples/methods/methods.rs +++ b/src/fn/methods.md @@ -1,6 +1,10 @@ -use std::num::Float; -// To be able to use .abs(), you must include this +# Methods +Methods are functions attached to objects. These methods have access to the +data of the object and its other methods via the `self` keyword. Methods are +defined under an `impl` block. + +```rust,editable struct Point { x: f64, y: f64, @@ -15,7 +19,7 @@ impl Point { Point { x: 0.0, y: 0.0 } } - // Another static method, that takes two arguments + // Another static method, taking two arguments: fn new(x: f64, y: f64) -> Point { Point { x: x, y: y } } @@ -44,7 +48,7 @@ impl Rectangle { let Point { x: x1, y: y1 } = self.p1; let Point { x: x2, y: y2 } = self.p2; - 2.0 * (x1 - x2).abs() + 2.0 * (y1 - y2).abs() + 2.0 * ((x1 - x2).abs() + (y1 - y2).abs()) } // This method requires the caller object to be mutable @@ -59,7 +63,7 @@ impl Rectangle { } // `Pair` owns resources: two heap allocated integers -struct Pair(Box, Box); +struct Pair(Box, Box); impl Pair { // This method "consumes" the resources of the caller object @@ -81,9 +85,9 @@ fn main() { p2: Point::new(3.0, 4.0), }; - // Instance method are called using the dot operator + // Instance methods are called using the dot operator // Note that the first argument `&self` is implicitly passed, i.e. - // `rectangle.perimeter()` === `perimeter(&rectangle)` + // `rectangle.perimeter()` === `Rectangle::perimeter(&rectangle)` println!("Rectangle perimeter: {}", rectangle.perimeter()); println!("Rectangle area: {}", rectangle.area()); @@ -97,10 +101,10 @@ fn main() { //rectangle.translate(1.0, 0.0); // TODO ^ Try uncommenting this line - // Ok, mutable object can call mutable methods + // Okay! Mutable objects can call mutable methods square.translate(1.0, 1.0); - let pair = Pair(box 1, box 2); + let pair = Pair(Box::new(1), Box::new(2)); pair.destroy(); @@ -108,3 +112,4 @@ fn main() { //pair.destroy(); // TODO ^ Try uncommenting this line } +``` \ No newline at end of file diff --git a/src/generics.md b/src/generics.md new file mode 100644 index 0000000000..86ecc581a9 --- /dev/null +++ b/src/generics.md @@ -0,0 +1,64 @@ +# Generics + +*Generics* is the topic of generalizing types and functionalities to broader +cases. This is extremely useful for reducing code duplication in many ways, +but can call for rather involving syntax. Namely, being generic requires +taking great care to specify over which types a generic type +is actually considered valid. The simplest and most common use of generics +is for type parameters. + +A type parameter is specified as generic by the use of angle brackets and upper +[camel case][camelcase]: ``. "Generic type parameters" are +typically represented as ``. In Rust, "generic" also describes anything that +accepts one or more generic type parameters ``. Any type specified as a +generic type parameter is generic, and everything else is concrete (non-generic). + +For example, defining a *generic function* named `foo` that takes an argument +`T` of any type: + +```rust,ignore +fn foo(arg: T) { ... } +``` + +Because `T` has been specified as a generic type parameter using ``, it +is considered generic when used here as `(arg: T)`. This is the case even if `T` +has previously been defined as a `struct`. + +This example shows some of the syntax in action: + +```rust,editable +// A concrete type `A`. +struct A; + +// In defining the type `Single`, the first use of `A` is not preceded by ``. +// Therefore, `Single` is a concrete type, and `A` is defined as above. +struct Single(A); +// ^ Here is `Single`s first use of the type `A`. + +// Here, `` precedes the first use of `T`, so `SingleGen` is a generic type. +// Because the type parameter `T` is generic, it could be anything, including +// the concrete type `A` defined at the top. +struct SingleGen(T); + +fn main() { + // `Single` is concrete and explicitly takes `A`. + let _s = Single(A); + + // Create a variable `_char` of type `SingleGen` + // and give it the value `SingleGen('a')`. + // Here, `SingleGen` has a type parameter explicitly specified. + let _char: SingleGen = SingleGen('a'); + + // `SingleGen` can also have a type parameter implicitly specified: + let _t = SingleGen(A); // Uses `A` defined at the top. + let _i32 = SingleGen(6); // Uses `i32`. + let _char = SingleGen('a'); // Uses `char`. +} +``` + +### See also: + +[`structs`][structs] + +[structs]: custom_types/structs.md +[camelcase]: https://en.wikipedia.org/wiki/CamelCase diff --git a/src/generics/assoc_items.md b/src/generics/assoc_items.md new file mode 100644 index 0000000000..7a3871bb76 --- /dev/null +++ b/src/generics/assoc_items.md @@ -0,0 +1,15 @@ +# Associated items + +"Associated Items" refers to a set of rules pertaining to [`item`][items]s +of various types. It is an extension to `trait` generics, and allows +`trait`s to internally define new items. + +One such item is called an *associated type*, providing simpler usage +patterns when the `trait` is generic over its container type. + +### See also: + +[RFC][RFC] + +[items]: https://doc.rust-lang.org/reference/items.html +[RFC]: https://github.com/rust-lang/rfcs/blob/master/text/0195-associated-items.md diff --git a/src/generics/assoc_items/the_problem.md b/src/generics/assoc_items/the_problem.md new file mode 100644 index 0000000000..bc6f7636b1 --- /dev/null +++ b/src/generics/assoc_items/the_problem.md @@ -0,0 +1,67 @@ +# The Problem + +A `trait` that is generic over its container type has type specification +requirements - users of the `trait` *must* specify all of its generic types. + +In the example below, the `Contains` `trait` allows the use of the generic +types `A` and `B`. The trait is then implemented for the `Container` type, +specifying `i32` for `A` and `B` so that it can be used with `fn difference()`. + +Because `Contains` is generic, we are forced to explicitly state *all* of the +generic types for `fn difference()`. In practice, we want a way to express that +`A` and `B` are determined by the *input* `C`. As you will see in the next +section, associated types provide exactly that capability. + +```rust,editable +struct Container(i32, i32); + +// A trait which checks if 2 items are stored inside of container. +// Also retrieves first or last value. +trait Contains { + fn contains(&self, _: &A, _: &B) -> bool; // Explicitly requires `A` and `B`. + fn first(&self) -> i32; // Doesn't explicitly require `A` or `B`. + fn last(&self) -> i32; // Doesn't explicitly require `A` or `B`. +} + +impl Contains for Container { + // True if the numbers stored are equal. + fn contains(&self, number_1: &i32, number_2: &i32) -> bool { + (&self.0 == number_1) && (&self.1 == number_2) + } + + // Grab the first number. + fn first(&self) -> i32 { self.0 } + + // Grab the last number. + fn last(&self) -> i32 { self.1 } +} + +// `C` contains `A` and `B`. In light of that, having to express `A` and +// `B` again is a nuisance. +fn difference(container: &C) -> i32 where + C: Contains { + container.last() - container.first() +} + +fn main() { + let number_1 = 3; + let number_2 = 10; + + let container = Container(number_1, number_2); + + println!("Does container contain {} and {}: {}", + &number_1, &number_2, + container.contains(&number_1, &number_2)); + println!("First number: {}", container.first()); + println!("Last number: {}", container.last()); + + println!("The difference is: {}", difference(&container)); +} +``` + +### See also: + +[`struct`s][structs], and [`trait`s][traits] + +[structs]: ../../custom_types/structs.md +[traits]: ../../trait.md diff --git a/src/generics/assoc_items/types.md b/src/generics/assoc_items/types.md new file mode 100644 index 0000000000..0358fcebca --- /dev/null +++ b/src/generics/assoc_items/types.md @@ -0,0 +1,85 @@ +# Associated types + +The use of "Associated types" improves the overall readability of code +by moving inner types locally into a trait as *output* types. Syntax +for the `trait` definition is as follows: + +```rust +// `A` and `B` are defined in the trait via the `type` keyword. +// (Note: `type` in this context is different from `type` when used for +// aliases). +trait Contains { + type A; + type B; + + // Updated syntax to refer to these new types generically. + fn contains(&self, &Self::A, &Self::B) -> bool; +} +``` + +Note that functions that use the `trait` `Contains` are no longer required +to express `A` or `B` at all: + +```rust,ignore +// Without using associated types +fn difference(container: &C) -> i32 where + C: Contains { ... } + +// Using associated types +fn difference(container: &C) -> i32 { ... } +``` + +Let's rewrite the example from the previous section using associated types: + +```rust,editable +struct Container(i32, i32); + +// A trait which checks if 2 items are stored inside of container. +// Also retrieves first or last value. +trait Contains { + // Define generic types here which methods will be able to utilize. + type A; + type B; + + fn contains(&self, _: &Self::A, _: &Self::B) -> bool; + fn first(&self) -> i32; + fn last(&self) -> i32; +} + +impl Contains for Container { + // Specify what types `A` and `B` are. If the `input` type + // is `Container(i32, i32)`, the `output` types are determined + // as `i32` and `i32`. + type A = i32; + type B = i32; + + // `&Self::A` and `&Self::B` are also valid here. + fn contains(&self, number_1: &i32, number_2: &i32) -> bool { + (&self.0 == number_1) && (&self.1 == number_2) + } + // Grab the first number. + fn first(&self) -> i32 { self.0 } + + // Grab the last number. + fn last(&self) -> i32 { self.1 } +} + +fn difference(container: &C) -> i32 { + container.last() - container.first() +} + +fn main() { + let number_1 = 3; + let number_2 = 10; + + let container = Container(number_1, number_2); + + println!("Does container contain {} and {}: {}", + &number_1, &number_2, + container.contains(&number_1, &number_2)); + println!("First number: {}", container.first()); + println!("Last number: {}", container.last()); + + println!("The difference is: {}", difference(&container)); +} +``` diff --git a/src/generics/bounds.md b/src/generics/bounds.md new file mode 100644 index 0000000000..86e54e670c --- /dev/null +++ b/src/generics/bounds.md @@ -0,0 +1,81 @@ +# Bounds + +When working with generics, the type parameters often must use traits as *bounds* to +stipulate what functionality a type implements. For example, the following +example uses the trait `Display` to print and so it requires `T` to be bound +by `Display`; that is, `T` *must* implement `Display`. + +```rust,ignore +// Define a function `printer` that takes a generic type `T` which +// must implement trait `Display`. +fn printer(t: T) { + println!("{}", t); +} +``` + +Bounding restricts the generic to types that conform to the bounds. That is: + +```rust,ignore +struct S(T); + +// Error! `Vec` does not implement `Display`. This +// specialization will fail. +let s = S(vec![1]); +``` + +Another effect of bounding is that generic instances are allowed to access the +[methods] of traits specified in the bounds. For example: + +```rust,editable +// A trait which implements the print marker: `{:?}`. +use std::fmt::Debug; + +trait HasArea { + fn area(&self) -> f64; +} + +impl HasArea for Rectangle { + fn area(&self) -> f64 { self.length * self.height } +} + +#[derive(Debug)] +struct Rectangle { length: f64, height: f64 } +#[allow(dead_code)] +struct Triangle { length: f64, height: f64 } + +// The generic `T` must implement `Debug`. Regardless +// of the type, this will work properly. +fn print_debug(t: &T) { + println!("{:?}", t); +} + +// `T` must implement `HasArea`. Any type which meets +// the bound can access `HasArea`'s function `area`. +fn area(t: &T) -> f64 { t.area() } + +fn main() { + let rectangle = Rectangle { length: 3.0, height: 4.0 }; + let _triangle = Triangle { length: 3.0, height: 4.0 }; + + print_debug(&rectangle); + println!("Area: {}", area(&rectangle)); + + //print_debug(&_triangle); + //println!("Area: {}", area(&_triangle)); + // ^ TODO: Try uncommenting these. + // | Error: Does not implement either `Debug` or `HasArea`. +} +``` + +As an additional note, [`where`][where] clauses can also be used to apply bounds in +some cases to be more expressive. + +### See also: + +[`std::fmt`][fmt], [`struct`s][structs], and [`trait`s][traits] + +[fmt]: ../hello/print.md +[methods]: ../fn/methods.md +[structs]: ../custom_types/structs.md +[traits]: ../trait.md +[where]: ../generics/where.md diff --git a/src/generics/bounds/testcase_empty.md b/src/generics/bounds/testcase_empty.md new file mode 100644 index 0000000000..e956a57e42 --- /dev/null +++ b/src/generics/bounds/testcase_empty.md @@ -0,0 +1,43 @@ +# Testcase: empty bounds + +A consequence of how bounds work is that even if a `trait` doesn't +include any functionality, you can still use it as a bound. `Eq` and +`Copy` are examples of such `trait`s from the `std` library. + +```rust,editable +struct Cardinal; +struct BlueJay; +struct Turkey; + +trait Red {} +trait Blue {} + +impl Red for Cardinal {} +impl Blue for BlueJay {} + +// These functions are only valid for types which implement these +// traits. The fact that the traits are empty is irrelevant. +fn red(_: &T) -> &'static str { "red" } +fn blue(_: &T) -> &'static str { "blue" } + +fn main() { + let cardinal = Cardinal; + let blue_jay = BlueJay; + let _turkey = Turkey; + + // `red()` won't work on a blue jay nor vice versa + // because of the bounds. + println!("A cardinal is {}", red(&cardinal)); + println!("A blue jay is {}", blue(&blue_jay)); + //println!("A turkey is {}", red(&_turkey)); + // ^ TODO: Try uncommenting this line. +} +``` + +### See also: + +[`std::cmp::Eq`][eq], [`std::marker::Copy`][copy], and [`trait`s][traits] + +[eq]: https://doc.rust-lang.org/std/cmp/trait.Eq.html +[copy]: https://doc.rust-lang.org/std/marker/trait.Copy.html +[traits]: ../../trait.md diff --git a/src/generics/gen_fn.md b/src/generics/gen_fn.md new file mode 100644 index 0000000000..264057687d --- /dev/null +++ b/src/generics/gen_fn.md @@ -0,0 +1,59 @@ +# Functions + +The same set of rules can be applied to functions: a type `T` becomes +generic when preceded by ``. + +Using generic functions sometimes requires explicitly specifying type +parameters. This may be the case if the function is called where the return type +is generic, or if the compiler doesn't have enough information to infer +the necessary type parameters. + +A function call with explicitly specified type parameters looks like: +`fun::()`. + +```rust,editable +struct A; // Concrete type `A`. +struct S(A); // Concrete type `S`. +struct SGen(T); // Generic type `SGen`. + +// The following functions all take ownership of the variable passed into +// them and immediately go out of scope, freeing the variable. + +// Define a function `reg_fn` that takes an argument `_s` of type `S`. +// This has no `` so this is not a generic function. +fn reg_fn(_s: S) {} + +// Define a function `gen_spec_t` that takes an argument `_s` of type `SGen`. +// It has been explicitly given the type parameter `A`, but because `A` has not +// been specified as a generic type parameter for `gen_spec_t`, it is not generic. +fn gen_spec_t(_s: SGen) {} + +// Define a function `gen_spec_i32` that takes an argument `_s` of type `SGen`. +// It has been explicitly given the type parameter `i32`, which is a specific type. +// Because `i32` is not a generic type, this function is also not generic. +fn gen_spec_i32(_s: SGen) {} + +// Define a function `generic` that takes an argument `_s` of type `SGen`. +// Because `SGen` is preceded by ``, this function is generic over `T`. +fn generic(_s: SGen) {} + +fn main() { + // Using the non-generic functions + reg_fn(S(A)); // Concrete type. + gen_spec_t(SGen(A)); // Implicitly specified type parameter `A`. + gen_spec_i32(SGen(6)); // Implicitly specified type parameter `i32`. + + // Explicitly specified type parameter `char` to `generic()`. + generic::(SGen('a')); + + // Implicitly specified type parameter `char` to `generic()`. + generic(SGen('c')); +} +``` + +### See also: + +[functions][fn] and [`struct`s][structs] + +[fn]: ../fn.md +[structs]: ../custom_types/structs.md diff --git a/src/generics/gen_trait.md b/src/generics/gen_trait.md new file mode 100644 index 0000000000..6847dfea81 --- /dev/null +++ b/src/generics/gen_trait.md @@ -0,0 +1,45 @@ +# Traits + +Of course `trait`s can also be generic. Here we define one which reimplements +the `Drop` `trait` as a generic method to `drop` itself and an input. + +```rust,editable +// Non-copyable types. +struct Empty; +struct Null; + +// A trait generic over `T`. +trait DoubleDrop { + // Define a method on the caller type which takes an + // additional single parameter `T` and does nothing with it. + fn double_drop(self, _: T); +} + +// Implement `DoubleDrop` for any generic parameter `T` and +// caller `U`. +impl DoubleDrop for U { + // This method takes ownership of both passed arguments, + // deallocating both. + fn double_drop(self, _: T) {} +} + +fn main() { + let empty = Empty; + let null = Null; + + // Deallocate `empty` and `null`. + empty.double_drop(null); + + //empty; + //null; + // ^ TODO: Try uncommenting these lines. +} +``` + +### See also: + +[`Drop`][Drop], [`struct`][structs], and [`trait`][traits] + +[Drop]: https://doc.rust-lang.org/std/ops/trait.Drop.html +[structs]: ../custom_types/structs.md +[traits]: ../trait.md diff --git a/src/generics/impl.md b/src/generics/impl.md new file mode 100644 index 0000000000..69554316e0 --- /dev/null +++ b/src/generics/impl.md @@ -0,0 +1,56 @@ +# Implementation + +Similar to functions, implementations require care to remain generic. + +```rust +struct S; // Concrete type `S` +struct GenericVal(T); // Generic type `GenericVal` + +// impl of GenericVal where we explicitly specify type parameters: +impl GenericVal {} // Specify `f32` +impl GenericVal {} // Specify `S` as defined above + +// `` Must precede the type to remain generic +impl GenericVal {} +``` + +```rust,editable +struct Val { + val: f64, +} + +struct GenVal { + gen_val: T, +} + +// impl of Val +impl Val { + fn value(&self) -> &f64 { + &self.val + } +} + +// impl of GenVal for a generic type `T` +impl GenVal { + fn value(&self) -> &T { + &self.gen_val + } +} + +fn main() { + let x = Val { val: 3.0 }; + let y = GenVal { gen_val: 3i32 }; + + println!("{}, {}", x.value(), y.value()); +} +``` + +### See also: + +[functions returning references][fn], [`impl`][methods], and [`struct`][structs] + + +[fn]: ../scope/lifetime/fn.md +[methods]: ../fn/methods.md +[specialization_plans]: https://blog.rust-lang.org/2015/05/11/traits.html#the-future +[structs]: ../custom_types/structs.md diff --git a/src/generics/multi_bounds.md b/src/generics/multi_bounds.md new file mode 100644 index 0000000000..969ba6417e --- /dev/null +++ b/src/generics/multi_bounds.md @@ -0,0 +1,37 @@ +# Multiple bounds + +Multiple bounds for a single type can be applied with a `+`. Like normal, different types are +separated with `,`. + +```rust,editable +use std::fmt::{Debug, Display}; + +fn compare_prints(t: &T) { + println!("Debug: `{:?}`", t); + println!("Display: `{}`", t); +} + +fn compare_types(t: &T, u: &U) { + println!("t: `{:?}`", t); + println!("u: `{:?}`", u); +} + +fn main() { + let string = "words"; + let array = [1, 2, 3]; + let vec = vec![1, 2, 3]; + + compare_prints(&string); + //compare_prints(&array); + // TODO ^ Try uncommenting this. + + compare_types(&array, &vec); +} +``` + +### See also: + +[`std::fmt`][fmt] and [`trait`s][traits] + +[fmt]: ../hello/print.md +[traits]: ../trait.md diff --git a/src/generics/new_types.md b/src/generics/new_types.md new file mode 100644 index 0000000000..c819002c28 --- /dev/null +++ b/src/generics/new_types.md @@ -0,0 +1,59 @@ +# New Type Idiom + +The `newtype` idiom gives compile time guarantees that the right type of value is supplied +to a program. + +For example, an age verification function that checks age in years, *must* be given +a value of type `Years`. + +```rust, editable +struct Years(i64); + +struct Days(i64); + +impl Years { + pub fn to_days(&self) -> Days { + Days(self.0 * 365) + } +} + + +impl Days { + /// truncates partial years + pub fn to_years(&self) -> Years { + Years(self.0 / 365) + } +} + +fn old_enough(age: &Years) -> bool { + age.0 >= 18 +} + +fn main() { + let age = Years(5); + let age_days = age.to_days(); + println!("Old enough {}", old_enough(&age)); + println!("Old enough {}", old_enough(&age_days.to_years())); + // println!("Old enough {}", old_enough(&age_days)); +} +``` + +Uncomment the last print statement to observe that the type supplied must be `Years`. + +To obtain the `newtype`'s value as the base type, you may use the tuple or destructuring syntax like so: +```rust, editable +struct Years(i64); + +fn main() { + let years = Years(42); + let years_as_primitive_1: i64 = years.0; // Tuple + let Years(years_as_primitive_2) = years; // Destructuring +} +``` + +### See also: + +[`structs`][struct] + +[struct]: ../custom_types/structs.md + diff --git a/src/generics/phantom.md b/src/generics/phantom.md new file mode 100644 index 0000000000..59cf125d11 --- /dev/null +++ b/src/generics/phantom.md @@ -0,0 +1,63 @@ +# Phantom type parameters + +A phantom type parameter is one that doesn't show up at runtime, +but is checked statically (and only) at compile time. + +Data types can use extra generic type parameters to act as markers +or to perform type checking at compile time. These extra parameters +hold no storage values, and have no runtime behavior. + +In the following example, we combine [std::marker::PhantomData] +with the phantom type parameter concept to create tuples containing +different data types. + +```rust,editable +use std::marker::PhantomData; + +// A phantom tuple struct which is generic over `A` with hidden parameter `B`. +#[derive(PartialEq)] // Allow equality test for this type. +struct PhantomTuple(A,PhantomData); + +// A phantom type struct which is generic over `A` with hidden parameter `B`. +#[derive(PartialEq)] // Allow equality test for this type. +struct PhantomStruct { first: A, phantom: PhantomData } + +// Note: Storage is allocated for generic type `A`, but not for `B`. +// Therefore, `B` cannot be used in computations. + +fn main() { + // Here, `f32` and `f64` are the hidden parameters. + // PhantomTuple type specified as ``. + let _tuple1: PhantomTuple = PhantomTuple('Q', PhantomData); + // PhantomTuple type specified as ``. + let _tuple2: PhantomTuple = PhantomTuple('Q', PhantomData); + + // Type specified as ``. + let _struct1: PhantomStruct = PhantomStruct { + first: 'Q', + phantom: PhantomData, + }; + // Type specified as ``. + let _struct2: PhantomStruct = PhantomStruct { + first: 'Q', + phantom: PhantomData, + }; + + // Compile-time Error! Type mismatch so these cannot be compared: + //println!("_tuple1 == _tuple2 yields: {}", + // _tuple1 == _tuple2); + + // Compile-time Error! Type mismatch so these cannot be compared: + //println!("_struct1 == _struct2 yields: {}", + // _struct1 == _struct2); +} +``` + +### See also: + +[Derive], [struct], and [TupleStructs] + +[Derive]: ../trait/derive.md +[struct]: ../custom_types/structs.md +[TupleStructs]: ../custom_types/structs.md +[std::marker::PhantomData]: https://doc.rust-lang.org/std/marker/struct.PhantomData.html \ No newline at end of file diff --git a/src/generics/phantom/testcase_units.md b/src/generics/phantom/testcase_units.md new file mode 100644 index 0000000000..00f59fe2de --- /dev/null +++ b/src/generics/phantom/testcase_units.md @@ -0,0 +1,88 @@ +# Testcase: unit clarification + +A useful method of unit conversions can be examined by implementing `Add` +with a phantom type parameter. The `Add` `trait` is examined below: + +```rust,ignore +// This construction would impose: `Self + RHS = Output` +// where RHS defaults to Self if not specified in the implementation. +pub trait Add { + type Output; + + fn add(self, rhs: RHS) -> Self::Output; +} + +// `Output` must be `T` so that `T + T = T`. +impl Add for T { + type Output = T; + ... +} +``` + +The whole implementation: + +```rust,editable +use std::ops::Add; +use std::marker::PhantomData; + +/// Create void enumerations to define unit types. +#[derive(Debug, Clone, Copy)] +enum Inch {} +#[derive(Debug, Clone, Copy)] +enum Mm {} + +/// `Length` is a type with phantom type parameter `Unit`, +/// and is not generic over the length type (that is `f64`). +/// +/// `f64` already implements the `Clone` and `Copy` traits. +#[derive(Debug, Clone, Copy)] +struct Length(f64, PhantomData); + +/// The `Add` trait defines the behavior of the `+` operator. +impl Add for Length { + type Output = Length; + + // add() returns a new `Length` struct containing the sum. + fn add(self, rhs: Length) -> Length { + // `+` calls the `Add` implementation for `f64`. + Length(self.0 + rhs.0, PhantomData) + } +} + +fn main() { + // Specifies `one_foot` to have phantom type parameter `Inch`. + let one_foot: Length = Length(12.0, PhantomData); + // `one_meter` has phantom type parameter `Mm`. + let one_meter: Length = Length(1000.0, PhantomData); + + // `+` calls the `add()` method we implemented for `Length`. + // + // Since `Length` implements `Copy`, `add()` does not consume + // `one_foot` and `one_meter` but copies them into `self` and `rhs`. + let two_feet = one_foot + one_foot; + let two_meters = one_meter + one_meter; + + // Addition works. + println!("one foot + one_foot = {:?} in", two_feet.0); + println!("one meter + one_meter = {:?} mm", two_meters.0); + + // Nonsensical operations fail as they should: + // Compile-time Error: type mismatch. + //let one_feter = one_foot + one_meter; +} +``` + +### See also: + +[Borrowing (`&`)], [Bounds (`X: Y`)], [enum], [impl & self], +[Overloading], [ref], [Traits (`X for Y`)], and [TupleStructs]. + +[Borrowing (`&`)]: ../../scope/borrow.md +[Bounds (`X: Y`)]: ../../generics/bounds.md +[enum]: ../../custom_types/enum.md +[impl & self]: ../../fn/methods.md +[Overloading]: ../../trait/ops.md +[ref]: ../../scope/borrow/ref.md +[Traits (`X for Y`)]: ../../trait.md +[TupleStructs]: ../../custom_types/structs.md +[std::marker::PhantomData]: https://doc.rust-lang.org/std/marker/struct.PhantomData.html diff --git a/src/generics/where.md b/src/generics/where.md new file mode 100644 index 0000000000..f35f03f928 --- /dev/null +++ b/src/generics/where.md @@ -0,0 +1,55 @@ +# Where clauses + +A bound can also be expressed using a `where` clause immediately +before the opening `{`, rather than at the type's first mention. +Additionally, `where` clauses can apply bounds to arbitrary types, +rather than just to type parameters. + +Some cases that a `where` clause is useful: + +* When specifying generic types and bounds separately is clearer: + +```rust,ignore +impl MyTrait for YourType {} + +// Expressing bounds with a `where` clause +impl MyTrait for YourType where + A: TraitB + TraitC, + D: TraitE + TraitF {} +``` + +* When using a `where` clause is more expressive than using normal syntax. +The `impl` in this example cannot be directly expressed without a `where` clause: + +```rust,editable +use std::fmt::Debug; + +trait PrintInOption { + fn print_in_option(self); +} + +// Because we would otherwise have to express this as `T: Debug` or +// use another method of indirect approach, this requires a `where` clause: +impl PrintInOption for T where + Option: Debug { + // We want `Option: Debug` as our bound because that is what's + // being printed. Doing otherwise would be using the wrong bound. + fn print_in_option(self) { + println!("{:?}", Some(self)); + } +} + +fn main() { + let vec = vec![1, 2, 3]; + + vec.print_in_option(); +} +``` + +### See also: + +[RFC][where], [`struct`][struct], and [`trait`][trait] + +[struct]: ../custom_types/structs.md +[trait]: ../trait.md +[where]: https://github.com/rust-lang/rfcs/blob/master/text/0135-where.md diff --git a/src/hello.md b/src/hello.md new file mode 100644 index 0000000000..2a8d3153f3 --- /dev/null +++ b/src/hello.md @@ -0,0 +1,49 @@ +# Hello World + +This is the source code of the traditional Hello World program. + +```rust,editable +// This is a comment, and is ignored by the compiler +// You can test this code by clicking the "Run" button over there -> +// or if you prefer to use your keyboard, you can use the "Ctrl + Enter" shortcut + +// This code is editable, feel free to hack it! +// You can always return to the original code by clicking the "Reset" button -> + +// This is the main function +fn main() { + // Statements here are executed when the compiled binary is called + + // Print text to the console + println!("Hello World!"); +} +``` + +`println!` is a [*macro*][macros] that prints text to the +console. + +A binary can be generated using the Rust compiler: `rustc`. + +```bash +$ rustc hello.rs +``` + +`rustc` will produce a `hello` binary that can be executed. + +```bash +$ ./hello +Hello World! +``` + +### Activity + +Click 'Run' above to see the expected output. Next, add a new +line with a second `println!` macro so that the output +shows: + +```text +Hello World! +I'm a Rustacean! +``` + +[macros]: macros.md diff --git a/src/hello/comment.md b/src/hello/comment.md new file mode 100644 index 0000000000..8cd1ccf553 --- /dev/null +++ b/src/hello/comment.md @@ -0,0 +1,51 @@ +# Comments + +Any program requires comments, and Rust supports +a few different varieties: + +* *Regular comments* which are ignored by the compiler: + * `// Line comments which go to the end of the line.` + * `/* Block comments which go to the closing delimiter. */` +* *Doc comments* which are parsed into HTML library + [documentation][docs]: + * `/// Generate library docs for the following item.` + * `//! Generate library docs for the enclosing item.` + +```rust,editable +fn main() { + // This is an example of a line comment + // There are two slashes at the beginning of the line + // And nothing written inside these will be read by the compiler + + // println!("Hello, world!"); + + // Run it. See? Now try deleting the two slashes, and run it again. + + /* + * This is another type of comment, a block comment. In general, + * line comments are the recommended comment style. But + * block comments are extremely useful for temporarily disabling + * chunks of code. /* Block comments can be /* nested, */ */ + * so it takes only a few keystrokes to comment out everything + * in this main() function. /*/*/* Try it yourself! */*/*/ + */ + + /* + Note: The previous column of `*` was entirely for style. There's + no actual need for it. + */ + + // You can manipulate expressions more easily with block comments + // than with line comments. Try deleting the comment delimiters + // to change the result: + let x = 5 + /* 90 + */ 5; + println!("Is `x` 10 or 100? x = {}", x); +} + +``` + +### See also: + +[Library documentation][docs] + +[docs]: ../meta/doc.md diff --git a/src/hello/print.md b/src/hello/print.md new file mode 100644 index 0000000000..89d2aa0de3 --- /dev/null +++ b/src/hello/print.md @@ -0,0 +1,94 @@ +# Formatted print + +Printing is handled by a series of [`macros`][macros] defined in [`std::fmt`][fmt] +some of which include: + +* `format!`: write formatted text to [`String`][string] +* `print!`: same as `format!` but the text is printed to the console (io::stdout). +* `println!`: same as `print!` but a newline is appended. +* `eprint!`: same as `format!` but the text is printed to the standard error (io::stderr). +* `eprintln!`: same as `eprint!`but a newline is appended. + +All parse text in the same fashion. As a plus, Rust checks formatting +correctness at compile time. + +```rust,editable,ignore,mdbook-runnable +fn main() { + // In general, the `{}` will be automatically replaced with any + // arguments. These will be stringified. + println!("{} days", 31); + + // Without a suffix, 31 becomes an i32. You can change what type 31 is + // by providing a suffix. The number 31i64 for example has the type i64. + + // There are various optional patterns this works with. Positional + // arguments can be used. + println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob"); + + // As can named arguments. + println!("{subject} {verb} {object}", + object="the lazy dog", + subject="the quick brown fox", + verb="jumps over"); + + // Special formatting can be specified after a `:`. + println!("{} of {:b} people know binary, the other half doesn't", 1, 2); + + // You can right-align text with a specified width. This will output + // " 1". 5 white spaces and a "1". + println!("{number:>width$}", number=1, width=6); + + // You can pad numbers with extra zeroes. This will output "000001". + println!("{number:0>width$}", number=1, width=6); + + // Rust even checks to make sure the correct number of arguments are + // used. + println!("My name is {0}, {1} {0}", "Bond"); + // FIXME ^ Add the missing argument: "James" + + // Create a structure named `Structure` which contains an `i32`. + #[allow(dead_code)] + struct Structure(i32); + + // However, custom types such as this structure require more complicated + // handling. This will not work. + println!("This struct `{}` won't print...", Structure(3)); + // FIXME ^ Comment out this line. +} +``` + +[`std::fmt`][fmt] contains many [`traits`][traits] which govern the display +of text. The base form of two important ones are listed below: + +* `fmt::Debug`: Uses the `{:?}` marker. Format text for debugging purposes. +* `fmt::Display`: Uses the `{}` marker. Format text in a more elegant, user +friendly fashion. + +Here, we used `fmt::Display` because the std library provides implementations +for these types. To print text for custom types, more steps are required. + +Implementing the `fmt::Display` trait automatically implements the +[`ToString`] trait which allows us to [convert] the type to [`String`][string]. + +### Activities + + * Fix the two issues in the above code (see FIXME) so that it runs without + error. + * Add a `println!` macro that prints: `Pi is roughly 3.142` by controlling + the number of decimal places shown. For the purposes of this exercise, + use `let pi = 3.141592` as an estimate for pi. (Hint: you may need to + check the [`std::fmt`][fmt] documentation for setting the number of + decimals to display) + +### See also: + +[`std::fmt`][fmt], [`macros`][macros], [`struct`][structs], +and [`traits`][traits] + +[fmt]: https://doc.rust-lang.org/std/fmt/ +[macros]: ../macros.md +[string]: ../std/str.md +[structs]: ../custom_types/structs.md +[traits]: https://doc.rust-lang.org/std/fmt/#formatting-traits +[`ToString`]: https://doc.rust-lang.org/std/string/trait.ToString.html +[convert]: ../conversion/string.md diff --git a/src/hello/print/fmt.md b/src/hello/print/fmt.md new file mode 100644 index 0000000000..dd698d29fc --- /dev/null +++ b/src/hello/print/fmt.md @@ -0,0 +1,93 @@ +# Formatting + +We've seen that formatting is specified via a *format string*: + +* `format!("{}", foo)` -> `"3735928559"` +* `format!("0x{:X}", foo)` -> + [`"0xDEADBEEF"`][deadbeef] +* `format!("0o{:o}", foo)` -> `"0o33653337357"` + +The same variable (`foo`) can be formatted differently depending on which +*argument type* is used: `X` vs `o` vs *unspecified*. + +This formatting functionality is implemented via traits, and there is one trait +for each argument type. The most common formatting trait is `Display`, which +handles cases where the argument type is left unspecified: `{}` for instance. + +```rust,editable +use std::fmt::{self, Formatter, Display}; + +struct City { + name: &'static str, + // Latitude + lat: f32, + // Longitude + lon: f32, +} + +impl Display for City { + // `f` is a buffer, and this method must write the formatted string into it + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + let lat_c = if self.lat >= 0.0 { 'N' } else { 'S' }; + let lon_c = if self.lon >= 0.0 { 'E' } else { 'W' }; + + // `write!` is like `format!`, but it will write the formatted string + // into a buffer (the first argument) + write!(f, "{}: {:.3}°{} {:.3}°{}", + self.name, self.lat.abs(), lat_c, self.lon.abs(), lon_c) + } +} + +#[derive(Debug)] +struct Color { + red: u8, + green: u8, + blue: u8, +} + +fn main() { + for city in [ + City { name: "Dublin", lat: 53.347778, lon: -6.259722 }, + City { name: "Oslo", lat: 59.95, lon: 10.75 }, + City { name: "Vancouver", lat: 49.25, lon: -123.1 }, + ].iter() { + println!("{}", *city); + } + for color in [ + Color { red: 128, green: 255, blue: 90 }, + Color { red: 0, green: 3, blue: 254 }, + Color { red: 0, green: 0, blue: 0 }, + ].iter() { + // Switch this to use {} once you've added an implementation + // for fmt::Display. + println!("{:?}", *color); + } +} +``` + +You can view a [full list of formatting traits][fmt_traits] and their argument +types in the [`std::fmt`][fmt] documentation. + +### Activity +Add an implementation of the `fmt::Display` trait for the `Color` struct above +so that the output displays as: + +```text +RGB (128, 255, 90) 0x80FF5A +RGB (0, 3, 254) 0x0003FE +RGB (0, 0, 0) 0x000000 +``` + +Two hints if you get stuck: + * You [may need to list each color more than once][named_parameters], + * You can [pad with zeros to a width of 2][fmt_width] with `:02`. + +### See also: + +[`std::fmt`][fmt] + +[named_parameters]: https://doc.rust-lang.org/std/fmt/#named-parameters +[deadbeef]: https://en.wikipedia.org/wiki/Deadbeef#Magic_debug_values +[fmt]: https://doc.rust-lang.org/std/fmt/ +[fmt_traits]: https://doc.rust-lang.org/std/fmt/#formatting-traits +[fmt_width]: https://doc.rust-lang.org/std/fmt/#width diff --git a/src/hello/print/print_debug.md b/src/hello/print/print_debug.md new file mode 100644 index 0000000000..161b0b7729 --- /dev/null +++ b/src/hello/print/print_debug.md @@ -0,0 +1,84 @@ +# Debug + +All types which want to use `std::fmt` formatting `traits` require an +implementation to be printable. Automatic implementations are only provided +for types such as in the `std` library. All others *must* be manually +implemented somehow. + +The `fmt::Debug` `trait` makes this very straightforward. *All* types can +`derive` (automatically create) the `fmt::Debug` implementation. This is +not true for `fmt::Display` which must be manually implemented. + +```rust +// This structure cannot be printed either with `fmt::Display` or +// with `fmt::Debug`. +struct UnPrintable(i32); + +// The `derive` attribute automatically creates the implementation +// required to make this `struct` printable with `fmt::Debug`. +#[derive(Debug)] +struct DebugPrintable(i32); +``` + +All `std` library types are automatically printable with `{:?}` too: + +```rust,editable +// Derive the `fmt::Debug` implementation for `Structure`. `Structure` +// is a structure which contains a single `i32`. +#[derive(Debug)] +struct Structure(i32); + +// Put a `Structure` inside of the structure `Deep`. Make it printable +// also. +#[derive(Debug)] +struct Deep(Structure); + +fn main() { + // Printing with `{:?}` is similar to with `{}`. + println!("{:?} months in a year.", 12); + println!("{1:?} {0:?} is the {actor:?} name.", + "Slater", + "Christian", + actor="actor's"); + + // `Structure` is printable! + println!("Now {:?} will print!", Structure(3)); + + // The problem with `derive` is there is no control over how + // the results look. What if I want this to just show a `7`? + println!("Now {:?} will print!", Deep(Structure(7))); +} +``` + +So `fmt::Debug` definitely makes this printable but sacrifices some +elegance. Rust also provides "pretty printing" with `{:#?}`. + +```rust,editable +#[derive(Debug)] +struct Person<'a> { + name: &'a str, + age: u8 +} + +fn main() { + let name = "Peter"; + let age = 27; + let peter = Person { name, age }; + + // Pretty print + println!("{:#?}", peter); +} +``` + +One can manually implement `fmt::Display` to control the display. + +### See also: + +[`attributes`][attributes], [`derive`][derive], [`std::fmt`][fmt], +and [`struct`][structs] + +[attributes]: https://doc.rust-lang.org/reference/attributes.html +[derive]: ../../trait/derive.md +[fmt]: https://doc.rust-lang.org/std/fmt/ +[structs]: ../../custom_types/structs.md + diff --git a/src/hello/print/print_display.md b/src/hello/print/print_display.md new file mode 100644 index 0000000000..fdae9648a9 --- /dev/null +++ b/src/hello/print/print_display.md @@ -0,0 +1,129 @@ +# Display + +`fmt::Debug` hardly looks compact and clean, so it is often advantageous to +customize the output appearance. This is done by manually implementing +[`fmt::Display`][fmt], which uses the `{}` print marker. Implementing it +looks like this: + +```rust +// Import (via `use`) the `fmt` module to make it available. +use std::fmt; + +// Define a structure for which `fmt::Display` will be implemented. This is +// a tuple struct named `Structure` that contains an `i32`. +struct Structure(i32); + +// To use the `{}` marker, the trait `fmt::Display` must be implemented +// manually for the type. +impl fmt::Display for Structure { + // This trait requires `fmt` with this exact signature. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Write strictly the first element into the supplied output + // stream: `f`. Returns `fmt::Result` which indicates whether the + // operation succeeded or failed. Note that `write!` uses syntax which + // is very similar to `println!`. + write!(f, "{}", self.0) + } +} +``` + +`fmt::Display` may be cleaner than `fmt::Debug` but this presents +a problem for the `std` library. How should ambiguous types be displayed? +For example, if the `std` library implemented a single style for all +`Vec`, what style should it be? Would it be either of these two? + +* `Vec`: `/:/etc:/home/username:/bin` (split on `:`) +* `Vec`: `1,2,3` (split on `,`) + +No, because there is no ideal style for all types and the `std` library +doesn't presume to dictate one. `fmt::Display` is not implemented for `Vec` +or for any other generic containers. `fmt::Debug` must then be used for these +generic cases. + +This is not a problem though because for any new *container* type which is +*not* generic,`fmt::Display` can be implemented. + +```rust,editable +use std::fmt; // Import `fmt` + +// A structure holding two numbers. `Debug` will be derived so the results can +// be contrasted with `Display`. +#[derive(Debug)] +struct MinMax(i64, i64); + +// Implement `Display` for `MinMax`. +impl fmt::Display for MinMax { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Use `self.number` to refer to each positional data point. + write!(f, "({}, {})", self.0, self.1) + } +} + +// Define a structure where the fields are nameable for comparison. +#[derive(Debug)] +struct Point2D { + x: f64, + y: f64, +} + +// Similarly, implement `Display` for `Point2D` +impl fmt::Display for Point2D { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Customize so only `x` and `y` are denoted. + write!(f, "x: {}, y: {}", self.x, self.y) + } +} + +fn main() { + let minmax = MinMax(0, 14); + + println!("Compare structures:"); + println!("Display: {}", minmax); + println!("Debug: {:?}", minmax); + + let big_range = MinMax(-300, 300); + let small_range = MinMax(-3, 3); + + println!("The big range is {big} and the small is {small}", + small = small_range, + big = big_range); + + let point = Point2D { x: 3.3, y: 7.2 }; + + println!("Compare points:"); + println!("Display: {}", point); + println!("Debug: {:?}", point); + + // Error. Both `Debug` and `Display` were implemented, but `{:b}` + // requires `fmt::Binary` to be implemented. This will not work. + // println!("What does Point2D look like in binary: {:b}?", point); +} +``` + +So, `fmt::Display` has been implemented but `fmt::Binary` has not, and +therefore cannot be used. `std::fmt` has many such [`traits`][traits] and +each requires its own implementation. This is detailed further in +[`std::fmt`][fmt]. + +### Activity + +After checking the output of the above example, use the `Point2D` struct as a +guide to add a `Complex` struct to the example. When printed in the same +way, the output should be: + +```txt +Display: 3.3 + 7.2i +Debug: Complex { real: 3.3, imag: 7.2 } +``` + +### See also: + +[`derive`][derive], [`std::fmt`][fmt], [`macros`][macros], [`struct`][structs], +[`trait`][traits], and [`use`][use] + +[derive]: ../../trait/derive.md +[fmt]: https://doc.rust-lang.org/std/fmt/ +[macros]: ../../macros.md +[structs]: ../../custom_types/structs.md +[traits]: https://doc.rust-lang.org/std/fmt/#formatting-traits +[use]: ../../mod/use.md diff --git a/src/hello/print/print_display/testcase_list.md b/src/hello/print/print_display/testcase_list.md new file mode 100644 index 0000000000..63e400b6a0 --- /dev/null +++ b/src/hello/print/print_display/testcase_list.md @@ -0,0 +1,71 @@ +# Testcase: List + +Implementing `fmt::Display` for a structure where the elements must each be +handled sequentially is tricky. The problem is that each `write!` generates a +`fmt::Result`. Proper handling of this requires dealing with *all* the +results. Rust provides the `?` operator for exactly this purpose. + +Using `?` on `write!` looks like this: + +```rust,ignore +// Try `write!` to see if it errors. If it errors, return +// the error. Otherwise continue. +write!(f, "{}", value)?; +``` + +With `?` available, implementing `fmt::Display` for a `Vec` is +straightforward: + +```rust,editable +use std::fmt; // Import the `fmt` module. + +// Define a structure named `List` containing a `Vec`. +struct List(Vec); + +impl fmt::Display for List { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Extract the value using tuple indexing, + // and create a reference to `vec`. + let vec = &self.0; + + write!(f, "[")?; + + // Iterate over `v` in `vec` while enumerating the iteration + // count in `count`. + for (count, v) in vec.iter().enumerate() { + // For every element except the first, add a comma. + // Use the ? operator to return on errors. + if count != 0 { write!(f, ", ")?; } + write!(f, "{}", v)?; + } + + // Close the opened bracket and return a fmt::Result value. + write!(f, "]") + } +} + +fn main() { + let v = List(vec![1, 2, 3]); + println!("{}", v); +} +``` + +### Activity + +Try changing the program so that the index of each element in the vector is also printed. The new output should look like this: + +```rust,ignore +[0: 1, 1: 2, 2: 3] +``` + +### See also: + +[`for`][for], [`ref`][ref], [`Result`][result], [`struct`][struct], +[`?`][q_mark], and [`vec!`][vec] + +[for]: ../../../flow_control/for.md +[result]: ../../../std/result.md +[ref]: ../../../scope/borrow/ref.md +[struct]: ../../../custom_types/structs.md +[q_mark]: ../../../std/result/question_mark.md +[vec]: ../../../std/vec.md diff --git a/src/index.md b/src/index.md new file mode 100644 index 0000000000..fecc1906aa --- /dev/null +++ b/src/index.md @@ -0,0 +1,66 @@ +# Rust by Example + +[Rust][rust] is a modern systems programming language focusing on safety, speed, +and concurrency. It accomplishes these goals by being memory safe without using +garbage collection. + +Rust by Example (RBE) is a collection of runnable examples that illustrate various Rust +concepts and standard libraries. To get even more out of these examples, don't forget +to [install Rust locally][install] and check out the [official docs][std]. +Additionally for the curious, you can also [check out the source code for this site][home]. + +Now let's begin! + +- [Hello World](hello.md) - Start with a traditional Hello World program. + +- [Primitives](primitives.md) - Learn about signed integers, unsigned integers and other primitives. + +- [Custom Types](custom_types.md) - `struct` and `enum`. + +- [Variable Bindings](variable_bindings.md) - mutable bindings, scope, shadowing. + +- [Types](types.md) - Learn about changing and defining types. + +- [Conversion](conversion.md) + +- [Expressions](expression.md) + +- [Flow of Control](flow_control.md) - `if`/`else`, `for`, and others. + +- [Functions](fn.md) - Learn about Methods, Closures and High Order Functions. + +- [Modules](mod.md) - Organize code using modules + +- [Crates](crates.md) - A crate is a compilation unit in Rust. Learn to create a library. + +- [Cargo](cargo.md) - Go through some basic features of the official Rust package management tool. + +- [Attributes](attribute.md) - An attribute is metadata applied to some module, crate or item. + +- [Generics](generics.md) - Learn about writing a function or data type which can work for multiple types of arguments. + +- [Scoping rules](scope.md) - Scopes play an important part in ownership, borrowing, and lifetimes. + +- [Traits](trait.md) - A trait is a collection of methods defined for an unknown type: `Self` + +- [Macros](macros.md) + +- [Error handling](error.md) - Learn Rust way of handling failures. + +- [Std library types](std.md) - Learn about some custom types provided by `std` library. + +- [Std misc](std_misc.md) - More custom types for file handling, threads. + +- [Testing](testing.md) - All sorts of testing in Rust. + +- [Unsafe Operations](unsafe.md) + +- [Compatibility](compatibility.md) + +- [Meta](meta.md) - Documentation, Benchmarking. + + +[rust]: https://www.rust-lang.org/ +[install]: https://www.rust-lang.org/tools/install +[std]: https://doc.rust-lang.org/std/ +[home]: https://github.com/rust-lang/rust-by-example diff --git a/src/macros.md b/src/macros.md new file mode 100644 index 0000000000..ffeb923e50 --- /dev/null +++ b/src/macros.md @@ -0,0 +1,40 @@ +# macro_rules! + +Rust provides a powerful macro system that allows metaprogramming. As you've +seen in previous chapters, macros look like functions, except that their name +ends with a bang `!`, but instead of generating a function call, macros are +expanded into source code that gets compiled with the rest of the program. +However, unlike macros in C and other languages, Rust macros are expanded into +abstract syntax trees, rather than string preprocessing, so you don't get +unexpected precedence bugs. + +Macros are created using the `macro_rules!` macro. + +```rust,editable +// This is a simple macro named `say_hello`. +macro_rules! say_hello { + // `()` indicates that the macro takes no argument. + () => { + // The macro will expand into the contents of this block. + println!("Hello!"); + }; +} + +fn main() { + // This call will expand into `println!("Hello");` + say_hello!() +} +``` + +So why are macros useful? + +1. Don't repeat yourself. There are many cases where you may need similar + functionality in multiple places but with different types. Often, writing a + macro is a useful way to avoid repeating code. (More on this later) + +2. Domain-specific languages. Macros allow you to define special syntax for a + specific purpose. (More on this later) + +3. Variadic interfaces. Sometimes you want to define an interface that takes a + variable number of arguments. An example is `println!` which could take any + number of arguments, depending on the format string!. (More on this later) diff --git a/src/macros/designators.md b/src/macros/designators.md new file mode 100644 index 0000000000..78183030a8 --- /dev/null +++ b/src/macros/designators.md @@ -0,0 +1,67 @@ +# Designators + +The arguments of a macro are prefixed by a dollar sign `$` and type annotated +with a *designator*: + +```rust,editable +macro_rules! create_function { + // This macro takes an argument of designator `ident` and + // creates a function named `$func_name`. + // The `ident` designator is used for variable/function names. + ($func_name:ident) => { + fn $func_name() { + // The `stringify!` macro converts an `ident` into a string. + println!("You called {:?}()", + stringify!($func_name)); + } + }; +} + +// Create functions named `foo` and `bar` with the above macro. +create_function!(foo); +create_function!(bar); + +macro_rules! print_result { + // This macro takes an expression of type `expr` and prints + // it as a string along with its result. + // The `expr` designator is used for expressions. + ($expression:expr) => { + // `stringify!` will convert the expression *as it is* into a string. + println!("{:?} = {:?}", + stringify!($expression), + $expression); + }; +} + +fn main() { + foo(); + bar(); + + print_result!(1u32 + 1); + + // Recall that blocks are expressions too! + print_result!({ + let x = 1u32; + + x * x + 2 * x - 1 + }); +} +``` + +These are some of the available designators: + +* `block` +* `expr` is used for expressions +* `ident` is used for variable/function names +* `item` +* `literal` is used for literal constants +* `pat` (*pattern*) +* `path` +* `stmt` (*statement*) +* `tt` (*token tree*) +* `ty` (*type*) +* `vis` (*visibility qualifier*) + +For a complete list, see the [Rust Reference]. + +[Rust Reference]: https://doc.rust-lang.org/reference/macros-by-example.html diff --git a/src/macros/dry.md b/src/macros/dry.md new file mode 100644 index 0000000000..ca015272af --- /dev/null +++ b/src/macros/dry.md @@ -0,0 +1,75 @@ +# DRY (Don't Repeat Yourself) + +Macros allow writing DRY code by factoring out the common parts of functions +and/or test suites. Here is an example that implements and tests the `+=`, `*=` +and `-=` operators on `Vec`: + +```rust,editable +use std::ops::{Add, Mul, Sub}; + +macro_rules! assert_equal_len { + // The `tt` (token tree) designator is used for + // operators and tokens. + ($a:expr, $b:expr, $func:ident, $op:tt) => { + assert!($a.len() == $b.len(), + "{:?}: dimension mismatch: {:?} {:?} {:?}", + stringify!($func), + ($a.len(),), + stringify!($op), + ($b.len(),)); + }; +} + +macro_rules! op { + ($func:ident, $bound:ident, $op:tt, $method:ident) => { + fn $func + Copy>(xs: &mut Vec, ys: &Vec) { + assert_equal_len!(xs, ys, $func, $op); + + for (x, y) in xs.iter_mut().zip(ys.iter()) { + *x = $bound::$method(*x, *y); + // *x = x.$method(*y); + } + } + }; +} + +// Implement `add_assign`, `mul_assign`, and `sub_assign` functions. +op!(add_assign, Add, +=, add); +op!(mul_assign, Mul, *=, mul); +op!(sub_assign, Sub, -=, sub); + +mod test { + use std::iter; + macro_rules! test { + ($func:ident, $x:expr, $y:expr, $z:expr) => { + #[test] + fn $func() { + for size in 0usize..10 { + let mut x: Vec<_> = iter::repeat($x).take(size).collect(); + let y: Vec<_> = iter::repeat($y).take(size).collect(); + let z: Vec<_> = iter::repeat($z).take(size).collect(); + + super::$func(&mut x, &y); + + assert_eq!(x, z); + } + } + }; + } + + // Test `add_assign`, `mul_assign`, and `sub_assign`. + test!(add_assign, 1u32, 2u32, 3u32); + test!(mul_assign, 2u32, 3u32, 6u32); + test!(sub_assign, 3u32, 2u32, 1u32); +} +``` + +```shell +$ rustc --test dry.rs && ./dry +running 3 tests +test test::mul_assign ... ok +test test::add_assign ... ok +test test::sub_assign ... ok + +test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured +``` diff --git a/src/macros/dsl.md b/src/macros/dsl.md new file mode 100644 index 0000000000..fb0c23550d --- /dev/null +++ b/src/macros/dsl.md @@ -0,0 +1,44 @@ +# Domain Specific Languages (DSLs) + +A DSL is a mini "language" embedded in a Rust macro. It is completely valid +Rust because the macro system expands into normal Rust constructs, but it looks +like a small language. This allows you to define concise or intuitive syntax for +some special functionality (within bounds). + +Suppose that I want to define a little calculator API. I would like to supply +an expression and have the output printed to console. + +```rust,editable +macro_rules! calculate { + (eval $e:expr) => {{ + { + let val: usize = $e; // Force types to be integers + println!("{} = {}", stringify!{$e}, val); + } + }}; +} + +fn main() { + calculate! { + eval 1 + 2 // hehehe `eval` is _not_ a Rust keyword! + } + + calculate! { + eval (1 + 2) * (3 / 4) + } +} +``` + +Output: + +```txt +1 + 2 = 3 +(1 + 2) * (3 / 4) = 0 +``` + +This was a very simple example, but much more complex interfaces have been +developed, such as [`lazy_static`](https://crates.io/crates/lazy_static) or +[`clap`](https://crates.io/crates/clap). + +Also, note the two pairs of braces in the macro. The outer ones are +part of the syntax of `macro_rules!`, in addition to `()` or `[]`. diff --git a/src/macros/overload.md b/src/macros/overload.md new file mode 100644 index 0000000000..84d341a56a --- /dev/null +++ b/src/macros/overload.md @@ -0,0 +1,31 @@ +# Overload + +Macros can be overloaded to accept different combinations of arguments. +In that regard, `macro_rules!` can work similarly to a match block: + +```rust,editable +// `test!` will compare `$left` and `$right` +// in different ways depending on how you invoke it: +macro_rules! test { + // Arguments don't need to be separated by a comma. + // Any template can be used! + ($left:expr; and $right:expr) => { + println!("{:?} and {:?} is {:?}", + stringify!($left), + stringify!($right), + $left && $right) + }; + // ^ each arm must end with a semicolon. + ($left:expr; or $right:expr) => { + println!("{:?} or {:?} is {:?}", + stringify!($left), + stringify!($right), + $left || $right) + }; +} + +fn main() { + test!(1i32 + 1 == 2i32; and 2i32 * 2 == 4i32); + test!(true; or false); +} +``` \ No newline at end of file diff --git a/src/macros/repeat.md b/src/macros/repeat.md new file mode 100644 index 0000000000..04c3b7da66 --- /dev/null +++ b/src/macros/repeat.md @@ -0,0 +1,28 @@ +# Repeat + +Macros can use `+` in the argument list to indicate that an argument may +repeat at least once, or `*`, to indicate that the argument may repeat zero or +more times. + +In the following example, surrounding the matcher with `$(...),+` will +match one or more expression, separated by commas. +Also note that the semicolon is optional on the last case. + +```rust,editable +// `find_min!` will calculate the minimum of any number of arguments. +macro_rules! find_min { + // Base case: + ($x:expr) => ($x); + // `$x` followed by at least one `$y,` + ($x:expr, $($y:expr),+) => ( + // Call `find_min!` on the tail `$y` + std::cmp::min($x, find_min!($($y),+)) + ) +} + +fn main() { + println!("{}", find_min!(1u32)); + println!("{}", find_min!(1u32 + 2, 2u32)); + println!("{}", find_min!(5u32, 2u32 * 3, 4u32)); +} +``` diff --git a/src/macros/syntax.md b/src/macros/syntax.md new file mode 100644 index 0000000000..d00e2695c0 --- /dev/null +++ b/src/macros/syntax.md @@ -0,0 +1,12 @@ +# Syntax + +In following subsections, we will show how to define macros in Rust. +There are three basic ideas: + +- [Patterns and Designators][designators] +- [Overloading][overloading] +- [Repetition][repetition] + +[designators]: designators.md +[overloading]: overload.md +[repetition]: repeat.md diff --git a/src/macros/variadics.md b/src/macros/variadics.md new file mode 100644 index 0000000000..e0cb1c1239 --- /dev/null +++ b/src/macros/variadics.md @@ -0,0 +1,41 @@ +# Variadic Interfaces + +A _variadic_ interface takes an arbitrary number of arguments. For example, +`println!` can take an arbitrary number of arguments, as determined by the +format string. + +We can extend our `calculate!` macro from the previous section to be variadic: + +```rust,editable +macro_rules! calculate { + // The pattern for a single `eval` + (eval $e:expr) => {{ + { + let val: usize = $e; // Force types to be integers + println!("{} = {}", stringify!{$e}, val); + } + }}; + + // Decompose multiple `eval`s recursively + (eval $e:expr, $(eval $es:expr),+) => {{ + calculate! { eval $e } + calculate! { $(eval $es),+ } + }}; +} + +fn main() { + calculate! { // Look ma! Variadic `calculate!`! + eval 1 + 2, + eval 3 + 4, + eval (2 * 3) + 1 + } +} +``` + +Output: + +```txt +1 + 2 = 3 +3 + 4 = 7 +(2 * 3) + 1 = 7 +``` diff --git a/src/markdown.rs b/src/markdown.rs deleted file mode 100644 index 811027992f..0000000000 --- a/src/markdown.rs +++ /dev/null @@ -1,162 +0,0 @@ -use file; -use playpen; - -pub struct Markdown<'a, 'b> { - content: String, - id: &'a str, - prefix: &'b str, -} - -impl<'a, 'b> Markdown<'a, 'b> { - pub fn process(number: &[uint], id: &'a str, title: &str, prefix: &'b str) - -> Result<(), String> - { - let mut mkd = try!(Markdown::new(number, id, title, prefix)); - - try!(mkd.insert_sources()); - try!(mkd.insert_outputs()); - try!(mkd.insert_playpen_links()); - try!(mkd.save()); - - Ok(()) - } - - fn new(number: &[uint], id: &'a str, title: &str, prefix: &'b str) - -> Result, String> - { - let path = Path::new(format!("examples/{}/{}/input.md", prefix, id)); - let body = try!(file::read(&path)); - let version = number.iter().map(|x| { - format!("{}", x) - }).collect::>().connect("."); - - let content = format!("{} {} {}\n\n{}", - "#".repeat(number.len()), - version, - title, - body); - - Ok(Markdown { - content: content, - id: id, - prefix: prefix, - }) - } - - fn insert_sources(&mut self) -> Result<(), String> { - let id = self.id; - let prefix = self.prefix; - let re = regex!(r"\{(.*\.rs)\}"); - - let mut table = Vec::new(); - for line in self.content.as_slice().lines() { - match re.captures(line) { - None => {}, - Some(captures) => { - let src = captures.at(1); - let input = format!("{{{}}}", src); - let p = format!("examples/{}/{}/{}", prefix, id, src); - let output = match file::read(&Path::new(p.as_slice())) { - Err(_) => { - return Err(format!("{} not found", p)); - }, - Ok(string) => { - format!("``` rust\n// {}\n{}```", - captures.at(1), string) - } - }; - - table.push((input, output)) - } - } - } - - for (input, output) in table.into_iter() { - self.content = self.content.replace(input.as_slice(), - output.as_slice()); - } - - Ok(()) - } - - fn insert_outputs(&mut self) -> Result<(), String> { - let id = self.id; - let prefix = self.prefix; - let r = regex!(r"\{(.*)\.out\}"); - - let dir = Path::new(format!("bin/{}/{}", prefix, id)); - - file::mkdir(&dir); - - let mut table = Vec::new(); - for line in self.content.as_slice().lines() { - match r.captures(line) { - None => {}, - Some(captures) => { - let src = captures.at(1); - let input = format!("{{{}.out}}", src); - let s = try!(file::run(prefix, id, src)); - let s = format!("```\n$ rustc {0}.rs && ./{0}\n{1}```", - src, s); - - table.push((input, s)); - }, - } - } - - for (input, output) in table.into_iter() { - self.content = self.content.replace(input.as_slice(), - output.as_slice()); - } - - Ok(()) - } - - fn insert_playpen_links(&mut self) -> Result<(), String> { - let id = self.id; - let prefix = self.prefix; - let re = regex!(r"\{(.*)\.play\}"); - - let mut once_ = false; - let mut table = Vec::new(); - for line in self.content.as_slice().lines() { - match re.captures(line) { - None => {}, - Some(captures) => { - if once_ { - return Err(format!("more than one editor!")) - } else { - once_ = true; - } - - let input = format!("{{{}.play}}", captures.at(1)); - let src = format!("{}.rs", captures.at(1)); - let p = format!("examples/{}/{}/{}", prefix, id, src); - let output = match file::read(&Path::new(p.as_slice())) { - Err(_) => { - return Err(format!("{} not found", p)); - }, - Ok(source) => { - playpen::editor(source.as_slice()) - } - }; - - table.push((input, output)) - } - } - } - - for (input, output) in table.into_iter() { - self.content = self.content.replace(input.as_slice(), - output.as_slice()); - } - - Ok(()) - } - - fn save(&self) -> Result<(), String> { - let path = Path::new(format!("stage/{}/{}.md", self.prefix, self.id)); - - file::write(&path, self.content.as_slice()) - } -} diff --git a/src/meta.md b/src/meta.md new file mode 100644 index 0000000000..a7434521c7 --- /dev/null +++ b/src/meta.md @@ -0,0 +1,12 @@ +# Meta + +Some topics aren't exactly relevant to how you program but provide you +tooling or infrastructure support which just makes things better for +everyone. These topics include: + +- [Documentation][doc]: Generate library documentation for users via the included + `rustdoc`. +- [Playpen][playpen]: Integrate the Rust Playpen(also known as the Rust Playground) in your documentation. + +[doc]: meta/doc.md +[playpen]: meta/playpen.md diff --git a/src/meta/doc.md b/src/meta/doc.md new file mode 100644 index 0000000000..63e0b41018 --- /dev/null +++ b/src/meta/doc.md @@ -0,0 +1,124 @@ +# Documentation + +Use `cargo doc` to build documentation in `target/doc`. + +Use `cargo test` to run all tests (including documentation tests), and `cargo test --doc` to only run documentation tests. + +These commands will appropriately invoke `rustdoc` (and `rustc`) as required. + +## Doc comments + +Doc comments are very useful for big projects that require documentation. When +running `rustdoc`, these are the comments that get compiled into +documentation. They are denoted by a `///`, and support [Markdown]. + +````rust,editable,ignore +#![crate_name = "doc"] + +/// A human being is represented here +pub struct Person { + /// A person must have a name, no matter how much Juliet may hate it + name: String, +} + +impl Person { + /// Returns a person with the name given them + /// + /// # Arguments + /// + /// * `name` - A string slice that holds the name of the person + /// + /// # Examples + /// + /// ``` + /// // You can have rust code between fences inside the comments + /// // If you pass --test to `rustdoc`, it will even test it for you! + /// use doc::Person; + /// let person = Person::new("name"); + /// ``` + pub fn new(name: &str) -> Person { + Person { + name: name.to_string(), + } + } + + /// Gives a friendly hello! + /// + /// Says "Hello, [name]" to the `Person` it is called on. + pub fn hello(& self) { + println!("Hello, {}!", self.name); + } +} + +fn main() { + let john = Person::new("John"); + + john.hello(); +} +```` + +To run the tests, first build the code as a library, then tell `rustdoc` where +to find the library so it can link it into each doctest program: + +```shell +$ rustc doc.rs --crate-type lib +$ rustdoc --test --extern doc="libdoc.rlib" doc.rs +``` + +## Doc attributes + +Below are a few examples of the most common `#[doc]` attributes used with `rustdoc`. + +### `inline` + +Used to inline docs, instead of linking out to separate page. + +```rust,ignore +#[doc(inline)] +pub use bar::Bar; + +/// bar docs +mod bar { + /// the docs for Bar + pub struct Bar; +} +``` + +### `no_inline` + +Used to prevent linking out to separate page or anywhere. + +```rust,ignore +// Example from libcore/prelude +#[doc(no_inline)] +pub use crate::mem::drop; +``` + +### `hidden` + +Using this tells `rustdoc` not to include this in documentation: + +```rust,editable,ignore +// Example from the futures-rs library +#[doc(hidden)] +pub use self::async_await::*; +``` + +For documentation, `rustdoc` is widely used by the community. It's what is used to generate the [std library docs](https://doc.rust-lang.org/std/). + +### See also: + +- [The Rust Book: Making Useful Documentation Comments][book] +- [The rustdoc Book][rustdoc-book] +- [The Reference: Doc comments][ref-comments] +- [RFC 1574: API Documentation Conventions][api-conv] +- [RFC 1946: Relative links to other items from doc comments (intra-rustdoc links)][intra-links] +- [Is there any documentation style guide for comments? (reddit)][reddit] + +[markdown]: https://en.wikipedia.org/wiki/Markdown +[book]: https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#making-useful-documentation-comments +[ref-comments]: https://doc.rust-lang.org/stable/reference/comments.html#doc-comments +[rustdoc-book]: https://doc.rust-lang.org/rustdoc/index.html +[api-conv]: https://rust-lang.github.io/rfcs/1574-more-api-documentation-conventions.html#appendix-a-full-conventions-text +[intra-links]: https://rust-lang.github.io/rfcs/1946-intra-rustdoc-links.html +[reddit]: https://www.reddit.com/r/rust/comments/ahb50s/is_there_any_documentation_style_guide_for/ diff --git a/src/meta/playpen.md b/src/meta/playpen.md new file mode 100644 index 0000000000..a125f139d8 --- /dev/null +++ b/src/meta/playpen.md @@ -0,0 +1,46 @@ +# Playpen + +The [Rust Playpen](https://github.com/rust-lang/rust-playpen) is a way to experiment with Rust code through a web interface. This project is now commonly referred to as [Rust Playground](https://play.rust-lang.org/). + +## Using it with `mdbook` + +In [`mdbook`][mdbook], you can make code examples playable and editable. + +```rust,editable +fn main() { + println!("Hello World!"); +} +``` + +This allows the reader to both run your code sample, but also modify and tweak it. The key here is the adding the word `editable` to your codefence block separated by a comma. + +````markdown +```rust,editable +//...place your code here +``` +```` + +Additionally, you can add `ignore` if you want `mdbook` to skip your code when it builds and tests. + +````markdown +```rust,editable,ignore +//...place your code here +``` +```` + +## Using it with docs + +You may have noticed in some of the [official Rust docs][official-rust-docs] a button that says "Run", which opens the code sample up in a new tab in Rust Playground. This feature is enabled if you use the #[doc] attribute called [`html_playground_url`][html-playground-url]. + +### See also: + +- [The Rust Playground][rust-playground] +- [The next-gen playpen][next-gen-playpen] +- [The rustdoc Book][rustdoc-book] + +[rust-playground]: https://play.rust-lang.org/ +[next-gen-playpen]: https://github.com/integer32llc/rust-playground/ +[mdbook]: https://github.com/rust-lang/mdBook +[official-rust-docs]: https://doc.rust-lang.org/core/ +[rustdoc-book]: https://doc.rust-lang.org/rustdoc/what-is-rustdoc.html +[html-playground-url]: https://doc.rust-lang.org/rustdoc/the-doc-attribute.html#html_playground_url diff --git a/examples/mod/input.md b/src/mod.md similarity index 51% rename from examples/mod/input.md rename to src/mod.md index bba4a49771..f9a1183486 100644 --- a/examples/mod/input.md +++ b/src/mod.md @@ -1,8 +1,8 @@ -Rust provides a powerful module system that can be used to hierarchically split -code in logical units (modules), and manage visibility (public/private) -between them. +# Modules -A module is a collection of items like: functions, structs, traits, impl -blocks, and even other modules. +Rust provides a powerful module system that can be used to hierarchically split +code in logical units (modules), and manage visibility (public/private) between +them. -{mod.play} +A module is a collection of items: functions, structs, traits, `impl` blocks, +and even other modules. \ No newline at end of file diff --git a/src/mod/split.md b/src/mod/split.md new file mode 100644 index 0000000000..634e7efae1 --- /dev/null +++ b/src/mod/split.md @@ -0,0 +1,96 @@ +# File hierarchy + +Modules can be mapped to a file/directory hierarchy. Let's break down the +[visibility example][visibility] in files: + +```shell +$ tree . +. +|-- my +| |-- inaccessible.rs +| |-- mod.rs +| `-- nested.rs +`-- split.rs +``` + +In `split.rs`: + +```rust,ignore +// This declaration will look for a file named `my.rs` or `my/mod.rs` and will +// insert its contents inside a module named `my` under this scope +mod my; + +fn function() { + println!("called `function()`"); +} + +fn main() { + my::function(); + + function(); + + my::indirect_access(); + + my::nested::function(); +} + +``` + +In `my/mod.rs`: + +```rust,ignore +// Similarly `mod inaccessible` and `mod nested` will locate the `nested.rs` +// and `inaccessible.rs` files and insert them here under their respective +// modules +mod inaccessible; +pub mod nested; + +pub fn function() { + println!("called `my::function()`"); +} + +fn private_function() { + println!("called `my::private_function()`"); +} + +pub fn indirect_access() { + print!("called `my::indirect_access()`, that\n> "); + + private_function(); +} +``` + +In `my/nested.rs`: + +```rust,ignore +pub fn function() { + println!("called `my::nested::function()`"); +} + +#[allow(dead_code)] +fn private_function() { + println!("called `my::nested::private_function()`"); +} +``` + +In `my/inaccessible.rs`: + +```rust,ignore +#[allow(dead_code)] +pub fn public_function() { + println!("called `my::inaccessible::public_function()`"); +} +``` + +Let's check that things still work as before: + +```shell +$ rustc split.rs && ./split +called `my::function()` +called `function()` +called `my::indirect_access()`, that +> called `my::private_function()` +called `my::nested::function()` +``` + +[visibility]: visibility.md diff --git a/src/mod/struct_visibility.md b/src/mod/struct_visibility.md new file mode 100644 index 0000000000..e7359413c7 --- /dev/null +++ b/src/mod/struct_visibility.md @@ -0,0 +1,59 @@ +# Struct visibility + +Structs have an extra level of visibility with their fields. The visibility +defaults to private, and can be overridden with the `pub` modifier. This +visibility only matters when a struct is accessed from outside the module +where it is defined, and has the goal of hiding information (encapsulation). + +```rust,editable +mod my { + // A public struct with a public field of generic type `T` + pub struct OpenBox { + pub contents: T, + } + + // A public struct with a private field of generic type `T` + #[allow(dead_code)] + pub struct ClosedBox { + contents: T, + } + + impl ClosedBox { + // A public constructor method + pub fn new(contents: T) -> ClosedBox { + ClosedBox { + contents: contents, + } + } + } +} + +fn main() { + // Public structs with public fields can be constructed as usual + let open_box = my::OpenBox { contents: "public information" }; + + // and their fields can be normally accessed. + println!("The open box contains: {}", open_box.contents); + + // Public structs with private fields cannot be constructed using field names. + // Error! `ClosedBox` has private fields + //let closed_box = my::ClosedBox { contents: "classified information" }; + // TODO ^ Try uncommenting this line + + // However, structs with private fields can be created using + // public constructors + let _closed_box = my::ClosedBox::new("classified information"); + + // and the private fields of a public struct cannot be accessed. + // Error! The `contents` field is private + //println!("The closed box contains: {}", _closed_box.contents); + // TODO ^ Try uncommenting this line +} +``` + +### See also: + +[generics][generics] and [methods][methods] + +[generics]: ../generics.md +[methods]: ../fn/methods.md \ No newline at end of file diff --git a/src/mod/super.md b/src/mod/super.md new file mode 100644 index 0000000000..038d4b1271 --- /dev/null +++ b/src/mod/super.md @@ -0,0 +1,56 @@ +# `super` and `self` + +The `super` and `self` keywords can be used in the path to remove ambiguity +when accessing items and to prevent unnecessary hardcoding of paths. + +```rust,editable +fn function() { + println!("called `function()`"); +} + +mod cool { + pub fn function() { + println!("called `cool::function()`"); + } +} + +mod my { + fn function() { + println!("called `my::function()`"); + } + + mod cool { + pub fn function() { + println!("called `my::cool::function()`"); + } + } + + pub fn indirect_call() { + // Let's access all the functions named `function` from this scope! + print!("called `my::indirect_call()`, that\n> "); + + // The `self` keyword refers to the current module scope - in this case `my`. + // Calling `self::function()` and calling `function()` directly both give + // the same result, because they refer to the same function. + self::function(); + function(); + + // We can also use `self` to access another module inside `my`: + self::cool::function(); + + // The `super` keyword refers to the parent scope (outside the `my` module). + super::function(); + + // This will bind to the `cool::function` in the *crate* scope. + // In this case the crate scope is the outermost scope. + { + use crate::cool::function as root_function; + root_function(); + } + } +} + +fn main() { + my::indirect_call(); +} +``` diff --git a/src/mod/use.md b/src/mod/use.md new file mode 100644 index 0000000000..7a57272b15 --- /dev/null +++ b/src/mod/use.md @@ -0,0 +1,55 @@ +# The `use` declaration + +The `use` declaration can be used to bind a full path to a new name, for easier +access. It is often used like this: + +```rust,editable,ignore +use crate::deeply::nested::{ + my_first_function, + my_second_function, + AndATraitType +}; + +fn main() { + my_first_function(); +} +``` + +You can use the `as` keyword to bind imports to a different name: + +```rust,editable +// Bind the `deeply::nested::function` path to `other_function`. +use deeply::nested::function as other_function; + +fn function() { + println!("called `function()`"); +} + +mod deeply { + pub mod nested { + pub fn function() { + println!("called `deeply::nested::function()`"); + } + } +} + +fn main() { + // Easier access to `deeply::nested::function` + other_function(); + + println!("Entering block"); + { + // This is equivalent to `use deeply::nested::function as function`. + // This `function()` will shadow the outer one. + use crate::deeply::nested::function; + + // `use` bindings have a local scope. In this case, the + // shadowing of `function()` is only in this block. + function(); + + println!("Leaving block"); + } + + function(); +} +``` diff --git a/src/mod/visibility.md b/src/mod/visibility.md new file mode 100644 index 0000000000..173122c72a --- /dev/null +++ b/src/mod/visibility.md @@ -0,0 +1,128 @@ +# Visibility + +By default, the items in a module have private visibility, but this can be +overridden with the `pub` modifier. Only the public items of a module can be +accessed from outside the module scope. + +```rust,editable +// A module named `my_mod` +mod my_mod { + // Items in modules default to private visibility. + fn private_function() { + println!("called `my_mod::private_function()`"); + } + + // Use the `pub` modifier to override default visibility. + pub fn function() { + println!("called `my_mod::function()`"); + } + + // Items can access other items in the same module, + // even when private. + pub fn indirect_access() { + print!("called `my_mod::indirect_access()`, that\n> "); + private_function(); + } + + // Modules can also be nested + pub mod nested { + pub fn function() { + println!("called `my_mod::nested::function()`"); + } + + #[allow(dead_code)] + fn private_function() { + println!("called `my_mod::nested::private_function()`"); + } + + // Functions declared using `pub(in path)` syntax are only visible + // within the given path. `path` must be a parent or ancestor module + pub(in crate::my_mod) fn public_function_in_my_mod() { + print!("called `my_mod::nested::public_function_in_my_mod()`, that\n> "); + public_function_in_nested(); + } + + // Functions declared using `pub(self)` syntax are only visible within + // the current module, which is the same as leaving them private + pub(self) fn public_function_in_nested() { + println!("called `my_mod::nested::public_function_in_nested()`"); + } + + // Functions declared using `pub(super)` syntax are only visible within + // the parent module + pub(super) fn public_function_in_super_mod() { + println!("called `my_mod::nested::public_function_in_super_mod()`"); + } + } + + pub fn call_public_function_in_my_mod() { + print!("called `my_mod::call_public_function_in_my_mod()`, that\n> "); + nested::public_function_in_my_mod(); + print!("> "); + nested::public_function_in_super_mod(); + } + + // pub(crate) makes functions visible only within the current crate + pub(crate) fn public_function_in_crate() { + println!("called `my_mod::public_function_in_crate()`"); + } + + // Nested modules follow the same rules for visibility + mod private_nested { + #[allow(dead_code)] + pub fn function() { + println!("called `my_mod::private_nested::function()`"); + } + + // Private parent items will still restrict the visibility of a child item, + // even if it is declared as visible within a bigger scope. + #[allow(dead_code)] + pub(crate) fn restricted_function() { + println!("called `my_mod::private_nested::restricted_function()`"); + } + } +} + +fn function() { + println!("called `function()`"); +} + +fn main() { + // Modules allow disambiguation between items that have the same name. + function(); + my_mod::function(); + + // Public items, including those inside nested modules, can be + // accessed from outside the parent module. + my_mod::indirect_access(); + my_mod::nested::function(); + my_mod::call_public_function_in_my_mod(); + + // pub(crate) items can be called from anywhere in the same crate + my_mod::public_function_in_crate(); + + // pub(in path) items can only be called from within the module specified + // Error! function `public_function_in_my_mod` is private + //my_mod::nested::public_function_in_my_mod(); + // TODO ^ Try uncommenting this line + + // Private items of a module cannot be directly accessed, even if + // nested in a public module: + + // Error! `private_function` is private + //my_mod::private_function(); + // TODO ^ Try uncommenting this line + + // Error! `private_function` is private + //my_mod::nested::private_function(); + // TODO ^ Try uncommenting this line + + // Error! `private_nested` is a private module + //my_mod::private_nested::function(); + // TODO ^ Try uncommenting this line + + // Error! `private_nested` is a private module + //my_mod::private_nested::restricted_function(); + // TODO ^ Try uncommenting this line +} +``` diff --git a/src/playpen.rs b/src/playpen.rs deleted file mode 100644 index 8fd114903d..0000000000 --- a/src/playpen.rs +++ /dev/null @@ -1,26 +0,0 @@ -pub fn editor(source: &str) -> String { - format!("

", escape(source)) -} - -fn escape(source: &str) -> String { - let mut s = String::new(); - - for chr in source.trim().chars() { - match chr { - '*' => s.push_str("*"), - '<' => s.push_str("<"), - '>' => s.push_str(">"), - '\\' => s.push_str("\"), - '_' => s.push_str("_"), - '`' => s.push_str("`"), - chr => s.push(chr), - } - } - - s -} diff --git a/src/primitives.md b/src/primitives.md new file mode 100644 index 0000000000..6b579e5eaf --- /dev/null +++ b/src/primitives.md @@ -0,0 +1,63 @@ +# Primitives + +Rust provides access to a wide variety of `primitives`. A sample includes: + + +### Scalar Types + +* signed integers: `i8`, `i16`, `i32`, `i64`, `i128` and `isize` (pointer size) +* unsigned integers: `u8`, `u16`, `u32`, `u64`, `u128` and `usize` (pointer + size) +* floating point: `f32`, `f64` +* `char` Unicode scalar values like `'a'`, `'α'` and `'∞'` (4 bytes each) +* `bool` either `true` or `false` +* and the unit type `()`, whose only possible value is an empty tuple: `()` + +Despite the value of a unit type being a tuple, it is not considered a +compound type because it does not contain multiple values. + +### Compound Types + +* arrays like `[1, 2, 3]` +* tuples like `(1, true)` + +Variables can always be *type annotated*. Numbers may additionally be +annotated via a *suffix* or *by default*. Integers default to `i32` and +floats to `f64`. Note that Rust can also infer types from context. + +```rust,editable,ignore,mdbook-runnable +fn main() { + // Variables can be type annotated. + let logical: bool = true; + + let a_float: f64 = 1.0; // Regular annotation + let an_integer = 5i32; // Suffix annotation + + // Or a default will be used. + let default_float = 3.0; // `f64` + let default_integer = 7; // `i32` + + // A type can also be inferred from context + let mut inferred_type = 12; // Type i64 is inferred from another line + inferred_type = 4294967296i64; + + // A mutable variable's value can be changed. + let mut mutable = 12; // Mutable `i32` + mutable = 21; + + // Error! The type of a variable can't be changed. + mutable = true; + + // Variables can be overwritten with shadowing. + let mutable = true; +} +``` + +### See also: + +[the `std` library][std], [`mut`][mut], [`inference`][inference], and [`shadowing`][shadowing] + +[std]: https://doc.rust-lang.org/std/ +[mut]: variable_bindings/mut.md +[inference]: types/inference.md +[shadowing]: variable_bindings/scope.md diff --git a/src/primitives/array.md b/src/primitives/array.md new file mode 100644 index 0000000000..50ea52fca4 --- /dev/null +++ b/src/primitives/array.md @@ -0,0 +1,54 @@ +# Arrays and Slices + +An array is a collection of objects of the same type `T`, stored in contiguous +memory. Arrays are created using brackets `[]`, and their length, which is known +at compile time, is part of their type signature `[T; length]`. + +Slices are similar to arrays, but their length is not known at compile time. +Instead, a slice is a two-word object, the first word is a pointer to the data, +and the second word is the length of the slice. The word size is the same as +usize, determined by the processor architecture eg 64 bits on an x86-64. +Slices can be used to borrow a section of an array, and have the type signature +`&[T]`. + +```rust,editable,ignore,mdbook-runnable +use std::mem; + +// This function borrows a slice +fn analyze_slice(slice: &[i32]) { + println!("first element of the slice: {}", slice[0]); + println!("the slice has {} elements", slice.len()); +} + +fn main() { + // Fixed-size array (type signature is superfluous) + let xs: [i32; 5] = [1, 2, 3, 4, 5]; + + // All elements can be initialized to the same value + let ys: [i32; 500] = [0; 500]; + + // Indexing starts at 0 + println!("first element of the array: {}", xs[0]); + println!("second element of the array: {}", xs[1]); + + // `len` returns the count of elements in the array + println!("number of elements in array: {}", xs.len()); + + // Arrays are stack allocated + println!("array occupies {} bytes", mem::size_of_val(&xs)); + + // Arrays can be automatically borrowed as slices + println!("borrow the whole array as a slice"); + analyze_slice(&xs); + + // Slices can point to a section of an array + // They are of the form [starting_index..ending_index] + // starting_index is the first position in the slice + // ending_index is one more than the last position in the slice + println!("borrow a section of the array as a slice"); + analyze_slice(&ys[1 .. 4]); + + // Out of bound indexing causes compile error + println!("{}", xs[5]); +} +``` diff --git a/src/primitives/literals.md b/src/primitives/literals.md new file mode 100644 index 0000000000..4927e6af82 --- /dev/null +++ b/src/primitives/literals.md @@ -0,0 +1,46 @@ +# Literals and operators + +Integers `1`, floats `1.2`, characters `'a'`, strings `"abc"`, booleans `true` +and the unit type `()` can be expressed using literals. + +Integers can, alternatively, be expressed using hexadecimal, octal or binary +notation using these prefixes respectively: `0x`, `0o` or `0b`. + +Underscores can be inserted in numeric literals to improve readability, e.g. +`1_000` is the same as `1000`, and `0.000_001` is the same as `0.000001`. + +We need to tell the compiler the type of the literals we use. For now, +we'll use the `u32` suffix to indicate that the literal is an unsigned 32-bit +integer, and the `i32` suffix to indicate that it's a signed 32-bit integer. + +The operators available and their precedence [in Rust][rust op-prec] are similar to other +[C-like languages][op-prec]. + +```rust,editable +fn main() { + // Integer addition + println!("1 + 2 = {}", 1u32 + 2); + + // Integer subtraction + println!("1 - 2 = {}", 1i32 - 2); + // TODO ^ Try changing `1i32` to `1u32` to see why the type is important + + // Short-circuiting boolean logic + println!("true AND false is {}", true && false); + println!("true OR false is {}", true || false); + println!("NOT true is {}", !true); + + // Bitwise operations + println!("0011 AND 0101 is {:04b}", 0b0011u32 & 0b0101); + println!("0011 OR 0101 is {:04b}", 0b0011u32 | 0b0101); + println!("0011 XOR 0101 is {:04b}", 0b0011u32 ^ 0b0101); + println!("1 << 5 is {}", 1u32 << 5); + println!("0x80 >> 2 is 0x{:x}", 0x80u32 >> 2); + + // Use underscores to improve readability! + println!("One million is written as {}", 1_000_000u32); +} +``` + +[rust op-prec]: https://doc.rust-lang.org/reference/expressions.html#expression-precedence +[op-prec]: https://en.wikipedia.org/wiki/Operator_precedence#Programming_languages diff --git a/src/primitives/tuples.md b/src/primitives/tuples.md new file mode 100644 index 0000000000..82f4083fc9 --- /dev/null +++ b/src/primitives/tuples.md @@ -0,0 +1,97 @@ +# Tuples + +A tuple is a collection of values of different types. Tuples are constructed +using parentheses `()`, and each tuple itself is a value with type signature +`(T1, T2, ...)`, where `T1`, `T2` are the types of its members. Functions can +use tuples to return multiple values, as tuples can hold any number of values. + +```rust,editable +// Tuples can be used as function arguments and as return values +fn reverse(pair: (i32, bool)) -> (bool, i32) { + // `let` can be used to bind the members of a tuple to variables + let (integer, boolean) = pair; + + (boolean, integer) +} + +// The following struct is for the activity. +#[derive(Debug)] +struct Matrix(f32, f32, f32, f32); + +fn main() { + // A tuple with a bunch of different types + let long_tuple = (1u8, 2u16, 3u32, 4u64, + -1i8, -2i16, -3i32, -4i64, + 0.1f32, 0.2f64, + 'a', true); + + // Values can be extracted from the tuple using tuple indexing + println!("long tuple first value: {}", long_tuple.0); + println!("long tuple second value: {}", long_tuple.1); + + // Tuples can be tuple members + let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16); + + // Tuples are printable + println!("tuple of tuples: {:?}", tuple_of_tuples); + + // But long Tuples cannot be printed + // let too_long_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13); + // println!("too long tuple: {:?}", too_long_tuple); + // TODO ^ Uncomment the above 2 lines to see the compiler error + + let pair = (1, true); + println!("pair is {:?}", pair); + + println!("the reversed pair is {:?}", reverse(pair)); + + // To create one element tuples, the comma is required to tell them apart + // from a literal surrounded by parentheses + println!("one element tuple: {:?}", (5u32,)); + println!("just an integer: {:?}", (5u32)); + + //tuples can be destructured to create bindings + let tuple = (1, "hello", 4.5, true); + + let (a, b, c, d) = tuple; + println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d); + + let matrix = Matrix(1.1, 1.2, 2.1, 2.2); + println!("{:?}", matrix); + +} +``` + +### Activity + + 1. *Recap*: Add the `fmt::Display` trait to the `Matrix` struct in the above example, + so that if you switch from printing the debug format `{:?}` to the display + format `{}`, you see the following output: + + ```text + ( 1.1 1.2 ) + ( 2.1 2.2 ) + ``` + + You may want to refer back to the example for [print display][print_display]. + 2. Add a `transpose` function using the `reverse` function as a template, which + accepts a matrix as an argument, and returns a matrix in which two elements + have been swapped. For example: + + ```rust,ignore + println!("Matrix:\n{}", matrix); + println!("Transpose:\n{}", transpose(matrix)); + ``` + + results in the output: + + ```text + Matrix: + ( 1.1 1.2 ) + ( 2.1 2.2 ) + Transpose: + ( 1.1 2.1 ) + ( 1.2 2.2 ) + ``` + +[print_display]: ../hello/print/print_display.md diff --git a/src/scope.md b/src/scope.md new file mode 100644 index 0000000000..ac70132781 --- /dev/null +++ b/src/scope.md @@ -0,0 +1,5 @@ +# Scoping rules + +Scopes play an important part in ownership, borrowing, and lifetimes. +That is, they indicate to the compiler when borrows are valid, when +resources can be freed, and when variables are created or destroyed. \ No newline at end of file diff --git a/src/scope/borrow.md b/src/scope/borrow.md new file mode 100644 index 0000000000..72c70e736a --- /dev/null +++ b/src/scope/borrow.md @@ -0,0 +1,49 @@ +# Borrowing + +Most of the time, we'd like to access data without taking ownership over +it. To accomplish this, Rust uses a *borrowing* mechanism. Instead of +passing objects by value (`T`), objects can be passed by reference (`&T`). + +The compiler statically guarantees (via its borrow checker) that references +*always* point to valid objects. That is, while references to an object +exist, the object cannot be destroyed. + +```rust,editable,ignore,mdbook-runnable +// This function takes ownership of a box and destroys it +fn eat_box_i32(boxed_i32: Box) { + println!("Destroying box that contains {}", boxed_i32); +} + +// This function borrows an i32 +fn borrow_i32(borrowed_i32: &i32) { + println!("This int is: {}", borrowed_i32); +} + +fn main() { + // Create a boxed i32, and a stacked i32 + let boxed_i32 = Box::new(5_i32); + let stacked_i32 = 6_i32; + + // Borrow the contents of the box. Ownership is not taken, + // so the contents can be borrowed again. + borrow_i32(&boxed_i32); + borrow_i32(&stacked_i32); + + { + // Take a reference to the data contained inside the box + let _ref_to_i32: &i32 = &boxed_i32; + + // Error! + // Can't destroy `boxed_i32` while the inner value is borrowed later in scope. + eat_box_i32(boxed_i32); + // FIXME ^ Comment out this line + + // Attempt to borrow `_ref_to_i32` after inner value is destroyed + borrow_i32(_ref_to_i32); + // `_ref_to_i32` goes out of scope and is no longer borrowed. + } + + // `boxed_i32` can now give up ownership to `eat_box` and be destroyed + eat_box_i32(boxed_i32); +} +``` diff --git a/src/scope/borrow/alias.md b/src/scope/borrow/alias.md new file mode 100644 index 0000000000..9cfd5fe5dc --- /dev/null +++ b/src/scope/borrow/alias.md @@ -0,0 +1,58 @@ +# Aliasing + +Data can be immutably borrowed any number of times, but while immutably +borrowed, the original data can't be mutably borrowed. On the other hand, only +*one* mutable borrow is allowed at a time. The original data can be borrowed +again only *after* the mutable reference has been used for the last time. + +```rust,editable +struct Point { x: i32, y: i32, z: i32 } + +fn main() { + let mut point = Point { x: 0, y: 0, z: 0 }; + + let borrowed_point = &point; + let another_borrow = &point; + + // Data can be accessed via the references and the original owner + println!("Point has coordinates: ({}, {}, {})", + borrowed_point.x, another_borrow.y, point.z); + + // Error! Can't borrow `point` as mutable because it's currently + // borrowed as immutable. + // let mutable_borrow = &mut point; + // TODO ^ Try uncommenting this line + + // The borrowed values are used again here + println!("Point has coordinates: ({}, {}, {})", + borrowed_point.x, another_borrow.y, point.z); + + // The immutable references are no longer used for the rest of the code so + // it is possible to reborrow with a mutable reference. + let mutable_borrow = &mut point; + + // Change data via mutable reference + mutable_borrow.x = 5; + mutable_borrow.y = 2; + mutable_borrow.z = 1; + + // Error! Can't borrow `point` as immutable because it's currently + // borrowed as mutable. + // let y = &point.y; + // TODO ^ Try uncommenting this line + + // Error! Can't print because `println!` takes an immutable reference. + // println!("Point Z coordinate is {}", point.z); + // TODO ^ Try uncommenting this line + + // Ok! Mutable references can be passed as immutable to `println!` + println!("Point has coordinates: ({}, {}, {})", + mutable_borrow.x, mutable_borrow.y, mutable_borrow.z); + + // The mutable reference is no longer used for the rest of the code so it + // is possible to reborrow + let new_borrowed_point = &point; + println!("Point now has coordinates: ({}, {}, {})", + new_borrowed_point.x, new_borrowed_point.y, new_borrowed_point.z); +} +``` diff --git a/src/scope/borrow/mut.md b/src/scope/borrow/mut.md new file mode 100644 index 0000000000..62119bb483 --- /dev/null +++ b/src/scope/borrow/mut.md @@ -0,0 +1,59 @@ +# Mutability + +Mutable data can be mutably borrowed using `&mut T`. This is called +a *mutable reference* and gives read/write access to the borrower. +In contrast, `&T` borrows the data via an immutable reference, and +the borrower can read the data but not modify it: + +```rust,editable,ignore,mdbook-runnable +#[allow(dead_code)] +#[derive(Clone, Copy)] +struct Book { + // `&'static str` is a reference to a string allocated in read only memory + author: &'static str, + title: &'static str, + year: u32, +} + +// This function takes a reference to a book +fn borrow_book(book: &Book) { + println!("I immutably borrowed {} - {} edition", book.title, book.year); +} + +// This function takes a reference to a mutable book and changes `year` to 2014 +fn new_edition(book: &mut Book) { + book.year = 2014; + println!("I mutably borrowed {} - {} edition", book.title, book.year); +} + +fn main() { + // Create an immutable Book named `immutabook` + let immutabook = Book { + // string literals have type `&'static str` + author: "Douglas Hofstadter", + title: "Gödel, Escher, Bach", + year: 1979, + }; + + // Create a mutable copy of `immutabook` and call it `mutabook` + let mut mutabook = immutabook; + + // Immutably borrow an immutable object + borrow_book(&immutabook); + + // Immutably borrow a mutable object + borrow_book(&mutabook); + + // Borrow a mutable object as mutable + new_edition(&mut mutabook); + + // Error! Cannot borrow an immutable object as mutable + new_edition(&mut immutabook); + // FIXME ^ Comment out this line +} +``` + +### See also: +[`static`][static] + +[static]: ../lifetime/static_lifetime.md diff --git a/src/scope/borrow/ref.md b/src/scope/borrow/ref.md new file mode 100644 index 0000000000..3c035f64c0 --- /dev/null +++ b/src/scope/borrow/ref.md @@ -0,0 +1,57 @@ +# The ref pattern + +When doing pattern matching or destructuring via the `let` binding, the `ref` +keyword can be used to take references to the fields of a struct/tuple. The +example below shows a few instances where this can be useful: + +```rust,editable +#[derive(Clone, Copy)] +struct Point { x: i32, y: i32 } + +fn main() { + let c = 'Q'; + + // A `ref` borrow on the left side of an assignment is equivalent to + // an `&` borrow on the right side. + let ref ref_c1 = c; + let ref_c2 = &c; + + println!("ref_c1 equals ref_c2: {}", *ref_c1 == *ref_c2); + + let point = Point { x: 0, y: 0 }; + + // `ref` is also valid when destructuring a struct. + let _copy_of_x = { + // `ref_to_x` is a reference to the `x` field of `point`. + let Point { x: ref ref_to_x, y: _ } = point; + + // Return a copy of the `x` field of `point`. + *ref_to_x + }; + + // A mutable copy of `point` + let mut mutable_point = point; + + { + // `ref` can be paired with `mut` to take mutable references. + let Point { x: _, y: ref mut mut_ref_to_y } = mutable_point; + + // Mutate the `y` field of `mutable_point` via a mutable reference. + *mut_ref_to_y = 1; + } + + println!("point is ({}, {})", point.x, point.y); + println!("mutable_point is ({}, {})", mutable_point.x, mutable_point.y); + + // A mutable tuple that includes a pointer + let mut mutable_tuple = (Box::new(5u32), 3u32); + + { + // Destructure `mutable_tuple` to change the value of `last`. + let (_, ref mut last) = mutable_tuple; + *last = 2u32; + } + + println!("tuple is {:?}", mutable_tuple); +} +``` \ No newline at end of file diff --git a/src/scope/lifetime.md b/src/scope/lifetime.md new file mode 100644 index 0000000000..33ffcae71d --- /dev/null +++ b/src/scope/lifetime.md @@ -0,0 +1,42 @@ +# Lifetimes + +A *lifetime* is a construct the compiler (or more specifically, its *borrow +checker*) uses to ensure all borrows are valid. Specifically, a variable's +lifetime begins when it is created and ends when it is destroyed. While +lifetimes and scopes are often referred to together, they are not the same. + +Take, for example, the case where we borrow a variable via `&`. The +borrow has a lifetime that is determined by where it is declared. As a result, +the borrow is valid as long as it ends before the lender is destroyed. However, +the scope of the borrow is determined by where the reference is used. + +In the following example and in the rest of this section, we will see how +lifetimes relate to scopes, as well as how the two differ. + +```rust,editable +// Lifetimes are annotated below with lines denoting the creation +// and destruction of each variable. +// `i` has the longest lifetime because its scope entirely encloses +// both `borrow1` and `borrow2`. The duration of `borrow1` compared +// to `borrow2` is irrelevant since they are disjoint. +fn main() { + let i = 3; // Lifetime for `i` starts. ────────────────┐ + // │ + { // │ + let borrow1 = &i; // `borrow1` lifetime starts. ──┐│ + // ││ + println!("borrow1: {}", borrow1); // ││ + } // `borrow1 ends. ──────────────────────────────────┘│ + // │ + // │ + { // │ + let borrow2 = &i; // `borrow2` lifetime starts. ──┐│ + // ││ + println!("borrow2: {}", borrow2); // ││ + } // `borrow2` ends. ─────────────────────────────────┘│ + // │ +} // Lifetime ends. ─────────────────────────────────────┘ +``` + +Note that no names or types are assigned to label lifetimes. +This restricts how lifetimes will be able to be used as we will see. diff --git a/src/scope/lifetime/elision.md b/src/scope/lifetime/elision.md new file mode 100644 index 0000000000..d1897e7e62 --- /dev/null +++ b/src/scope/lifetime/elision.md @@ -0,0 +1,43 @@ +# Elision + +Some lifetime patterns are overwhelmingly common and so the borrow checker +will allow you to omit them to save typing and to improve readability. +This is known as elision. Elision exists in Rust solely because these patterns +are common. + +The following code shows a few examples of elision. For a more comprehensive +description of elision, see [lifetime elision][elision] in the book. + +```rust,editable +// `elided_input` and `annotated_input` essentially have identical signatures +// because the lifetime of `elided_input` is inferred by the compiler: +fn elided_input(x: &i32) { + println!("`elided_input`: {}", x); +} + +fn annotated_input<'a>(x: &'a i32) { + println!("`annotated_input`: {}", x); +} + +// Similarly, `elided_pass` and `annotated_pass` have identical signatures +// because the lifetime is added implicitly to `elided_pass`: +fn elided_pass(x: &i32) -> &i32 { x } + +fn annotated_pass<'a>(x: &'a i32) -> &'a i32 { x } + +fn main() { + let x = 3; + + elided_input(&x); + annotated_input(&x); + + println!("`elided_pass`: {}", elided_pass(&x)); + println!("`annotated_pass`: {}", annotated_pass(&x)); +} +``` + +### See also: + +[elision][elision] + +[elision]: https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#lifetime-elision diff --git a/src/scope/lifetime/explicit.md b/src/scope/lifetime/explicit.md new file mode 100644 index 0000000000..f0ecdf5fca --- /dev/null +++ b/src/scope/lifetime/explicit.md @@ -0,0 +1,75 @@ +# Explicit annotation + +The borrow checker uses explicit lifetime annotations to determine +how long references should be valid. In cases where lifetimes are not +elided[^1], Rust requires explicit annotations to determine what the +lifetime of a reference should be. The syntax for explicitly annotating +a lifetime uses an apostrophe character as follows: + +```rust,ignore +foo<'a> +// `foo` has a lifetime parameter `'a` +``` + +Similar to [closures][anonymity], using lifetimes requires generics. +Additionally, this lifetime syntax indicates that the lifetime of `foo` +may not exceed that of `'a`. Explicit annotation of a type has the form +`&'a T` where `'a` has already been introduced. + +In cases with multiple lifetimes, the syntax is similar: + +```rust,ignore +foo<'a, 'b> +// `foo` has lifetime parameters `'a` and `'b` +``` + +In this case, the lifetime of `foo` cannot exceed that of either `'a` *or* `'b`. + +See the following example for explicit lifetime annotation in use: + +```rust,editable,ignore,mdbook-runnable +// `print_refs` takes two references to `i32` which have different +// lifetimes `'a` and `'b`. These two lifetimes must both be at +// least as long as the function `print_refs`. +fn print_refs<'a, 'b>(x: &'a i32, y: &'b i32) { + println!("x is {} and y is {}", x, y); +} + +// A function which takes no arguments, but has a lifetime parameter `'a`. +fn failed_borrow<'a>() { + let _x = 12; + + // ERROR: `_x` does not live long enough + let y: &'a i32 = &_x; + // Attempting to use the lifetime `'a` as an explicit type annotation + // inside the function will fail because the lifetime of `&_x` is shorter + // than that of `y`. A short lifetime cannot be coerced into a longer one. +} + +fn main() { + // Create variables to be borrowed below. + let (four, nine) = (4, 9); + + // Borrows (`&`) of both variables are passed into the function. + print_refs(&four, &nine); + // Any input which is borrowed must outlive the borrower. + // In other words, the lifetime of `four` and `nine` must + // be longer than that of `print_refs`. + + failed_borrow(); + // `failed_borrow` contains no references to force `'a` to be + // longer than the lifetime of the function, but `'a` is longer. + // Because the lifetime is never constrained, it defaults to `'static`. +} +``` + +[^1]: [elision] implicitly annotates lifetimes and so is different. + +### See also: + +[generics][generics] and [closures][closures] + +[anonymity]: ../../fn/closures/anonymity.md +[closures]: ../../fn/closures.md +[elision]: elision.md +[generics]: ../../generics.md diff --git a/src/scope/lifetime/fn.md b/src/scope/lifetime/fn.md new file mode 100644 index 0000000000..6c5c8afe60 --- /dev/null +++ b/src/scope/lifetime/fn.md @@ -0,0 +1,63 @@ +# Functions + +Ignoring [elision], function signatures with lifetimes have a few constraints: + +* any reference *must* have an annotated lifetime. +* any reference being returned *must* have the same lifetime as an input or +be `static`. + +Additionally, note that returning references without input is banned if it +would result in returning references to invalid data. The following example shows +off some valid forms of functions with lifetimes: + +```rust,editable +// One input reference with lifetime `'a` which must live +// at least as long as the function. +fn print_one<'a>(x: &'a i32) { + println!("`print_one`: x is {}", x); +} + +// Mutable references are possible with lifetimes as well. +fn add_one<'a>(x: &'a mut i32) { + *x += 1; +} + +// Multiple elements with different lifetimes. In this case, it +// would be fine for both to have the same lifetime `'a`, but +// in more complex cases, different lifetimes may be required. +fn print_multi<'a, 'b>(x: &'a i32, y: &'b i32) { + println!("`print_multi`: x is {}, y is {}", x, y); +} + +// Returning references that have been passed in is acceptable. +// However, the correct lifetime must be returned. +fn pass_x<'a, 'b>(x: &'a i32, _: &'b i32) -> &'a i32 { x } + +//fn invalid_output<'a>() -> &'a String { &String::from("foo") } +// The above is invalid: `'a` must live longer than the function. +// Here, `&String::from("foo")` would create a `String`, followed by a +// reference. Then the data is dropped upon exiting the scope, leaving +// a reference to invalid data to be returned. + +fn main() { + let x = 7; + let y = 9; + + print_one(&x); + print_multi(&x, &y); + + let z = pass_x(&x, &y); + print_one(z); + + let mut t = 3; + add_one(&mut t); + print_one(&t); +} +``` + +### See also: + +[functions][fn] + +[elision]: elision.md +[fn]: fn.md diff --git a/src/scope/lifetime/lifetime_bounds.md b/src/scope/lifetime/lifetime_bounds.md new file mode 100644 index 0000000000..3d635bde1f --- /dev/null +++ b/src/scope/lifetime/lifetime_bounds.md @@ -0,0 +1,53 @@ +# Bounds + +Just like generic types can be bounded, lifetimes (themselves generic) +use bounds as well. The `:` character has a slightly different meaning here, +but `+` is the same. Note how the following read: + +1. `T: 'a`: *All* references in `T` must outlive lifetime `'a`. +2. `T: Trait + 'a`: Type `T` must implement trait `Trait` and *all* references +in `T` must outlive `'a`. + +The example below shows the above syntax in action used after keyword `where`: + +```rust,editable +use std::fmt::Debug; // Trait to bound with. + +#[derive(Debug)] +struct Ref<'a, T: 'a>(&'a T); +// `Ref` contains a reference to a generic type `T` that has +// an unknown lifetime `'a`. `T` is bounded such that any +// *references* in `T` must outlive `'a`. Additionally, the lifetime +// of `Ref` may not exceed `'a`. + +// A generic function which prints using the `Debug` trait. +fn print(t: T) where + T: Debug { + println!("`print`: t is {:?}", t); +} + +// Here a reference to `T` is taken where `T` implements +// `Debug` and all *references* in `T` outlive `'a`. In +// addition, `'a` must outlive the function. +fn print_ref<'a, T>(t: &'a T) where + T: Debug + 'a { + println!("`print_ref`: t is {:?}", t); +} + +fn main() { + let x = 7; + let ref_x = Ref(&x); + + print_ref(&ref_x); + print(ref_x); +} +``` + +### See also: + +[generics][generics], [bounds in generics][bounds], and +[multiple bounds in generics][multibounds] + +[generics]: ../../generics.md +[bounds]: ../../generics/bounds.md +[multibounds]: ../../generics/multi_bounds.md diff --git a/src/scope/lifetime/lifetime_coercion.md b/src/scope/lifetime/lifetime_coercion.md new file mode 100644 index 0000000000..96090f4803 --- /dev/null +++ b/src/scope/lifetime/lifetime_coercion.md @@ -0,0 +1,31 @@ +# Coercion + +A longer lifetime can be coerced into a shorter one +so that it works inside a scope it normally wouldn't work in. +This comes in the form of inferred coercion by the Rust compiler, +and also in the form of declaring a lifetime difference: + +```rust,editable +// Here, Rust infers a lifetime that is as short as possible. +// The two references are then coerced to that lifetime. +fn multiply<'a>(first: &'a i32, second: &'a i32) -> i32 { + first * second +} + +// `<'a: 'b, 'b>` reads as lifetime `'a` is at least as long as `'b`. +// Here, we take in an `&'a i32` and return a `&'b i32` as a result of coercion. +fn choose_first<'a: 'b, 'b>(first: &'a i32, _: &'b i32) -> &'b i32 { + first +} + +fn main() { + let first = 2; // Longer lifetime + + { + let second = 3; // Shorter lifetime + + println!("The product is {}", multiply(&first, &second)); + println!("{} is the first", choose_first(&first, &second)); + }; +} +``` \ No newline at end of file diff --git a/src/scope/lifetime/methods.md b/src/scope/lifetime/methods.md new file mode 100644 index 0000000000..1e1eb96f47 --- /dev/null +++ b/src/scope/lifetime/methods.md @@ -0,0 +1,28 @@ +# Methods + +Methods are annotated similarly to functions: + +```rust,editable +struct Owner(i32); + +impl Owner { + // Annotate lifetimes as in a standalone function. + fn add_one<'a>(&'a mut self) { self.0 += 1; } + fn print<'a>(&'a self) { + println!("`print`: {}", self.0); + } +} + +fn main() { + let mut owner = Owner(18); + + owner.add_one(); + owner.print(); +} +``` + +### See also: + +[methods] + +[methods]: ../../fn/methods.md diff --git a/src/scope/lifetime/static_lifetime.md b/src/scope/lifetime/static_lifetime.md new file mode 100644 index 0000000000..3f31693faa --- /dev/null +++ b/src/scope/lifetime/static_lifetime.md @@ -0,0 +1,110 @@ +# Static + +Rust has a few reserved lifetime names. One of those is `'static`. You +might encounter it in two situations: + +```rust, editable +// A reference with 'static lifetime: +let s: &'static str = "hello world"; + +// 'static as part of a trait bound: +fn generic(x: T) where T: 'static {} +``` + +Both are related but subtly different and this is a common source for +confusion when learning Rust. Here are some examples for each situation: + +## Reference lifetime + +As a reference lifetime `'static` indicates that the data pointed to by +the reference lives for the entire lifetime of the running program. +It can still be coerced to a shorter lifetime. + +There are two ways to make a variable with `'static` lifetime, and both +are stored in the read-only memory of the binary: + +* Make a constant with the `static` declaration. +* Make a `string` literal which has type: `&'static str`. + +See the following example for a display of each method: + +```rust,editable +// Make a constant with `'static` lifetime. +static NUM: i32 = 18; + +// Returns a reference to `NUM` where its `'static` +// lifetime is coerced to that of the input argument. +fn coerce_static<'a>(_: &'a i32) -> &'a i32 { + &NUM +} + +fn main() { + { + // Make a `string` literal and print it: + let static_string = "I'm in read-only memory"; + println!("static_string: {}", static_string); + + // When `static_string` goes out of scope, the reference + // can no longer be used, but the data remains in the binary. + } + + { + // Make an integer to use for `coerce_static`: + let lifetime_num = 9; + + // Coerce `NUM` to lifetime of `lifetime_num`: + let coerced_static = coerce_static(&lifetime_num); + + println!("coerced_static: {}", coerced_static); + } + + println!("NUM: {} stays accessible!", NUM); +} +``` + +## Trait bound + +As a trait bound, it means the type does not contain any non-static +references. Eg. the receiver can hold on to the type for as long as +they want and it will never become invalid until they drop it. + +It's important to understand this means that any owned data always passes +a `'static` lifetime bound, but a reference to that owned data generally +does not: + +```rust,editable,compile_fail +use std::fmt::Debug; + +fn print_it( input: impl Debug + 'static ) { + println!( "'static value passed in is: {:?}", input ); +} + +fn main() { + // i is owned and contains no references, thus it's 'static: + let i = 5; + print_it(i); + + // oops, &i only has the lifetime defined by the scope of + // main(), so it's not 'static: + print_it(&i); +} +``` +The compiler will tell you: +```ignore +error[E0597]: `i` does not live long enough + --> src/lib.rs:15:15 + | +15 | print_it(&i); + | ---------^^-- + | | | + | | borrowed value does not live long enough + | argument requires that `i` is borrowed for `'static` +16 | } + | - `i` dropped here while still borrowed +``` + +### See also: + +[`'static` constants][static_const] + +[static_const]: ../../custom_types/constants.md diff --git a/src/scope/lifetime/struct.md b/src/scope/lifetime/struct.md new file mode 100644 index 0000000000..aca0bfe622 --- /dev/null +++ b/src/scope/lifetime/struct.md @@ -0,0 +1,46 @@ +# Structs + +Annotation of lifetimes in structures are also similar to functions: + +```rust,editable +// A type `Borrowed` which houses a reference to an +// `i32`. The reference to `i32` must outlive `Borrowed`. +#[derive(Debug)] +struct Borrowed<'a>(&'a i32); + +// Similarly, both references here must outlive this structure. +#[derive(Debug)] +struct NamedBorrowed<'a> { + x: &'a i32, + y: &'a i32, +} + +// An enum which is either an `i32` or a reference to one. +#[derive(Debug)] +enum Either<'a> { + Num(i32), + Ref(&'a i32), +} + +fn main() { + let x = 18; + let y = 15; + + let single = Borrowed(&x); + let double = NamedBorrowed { x: &x, y: &y }; + let reference = Either::Ref(&x); + let number = Either::Num(y); + + println!("x is borrowed in {:?}", single); + println!("x and y are borrowed in {:?}", double); + println!("x is borrowed in {:?}", reference); + println!("y is *not* borrowed in {:?}", number); +} +``` + +### See also: + +[`struct`s][structs] + + +[structs]: ../../custom_types/structs.md diff --git a/src/scope/lifetime/trait.md b/src/scope/lifetime/trait.md new file mode 100644 index 0000000000..3c26df1194 --- /dev/null +++ b/src/scope/lifetime/trait.md @@ -0,0 +1,33 @@ +# Traits + +Annotation of lifetimes in trait methods basically are similar to functions. +Note that `impl` may have annotation of lifetimes too. + +```rust,editable +// A struct with annotation of lifetimes. +#[derive(Debug)] +struct Borrowed<'a> { + x: &'a i32, +} + +// Annotate lifetimes to impl. +impl<'a> Default for Borrowed<'a> { + fn default() -> Self { + Self { + x: &10, + } + } +} + +fn main() { + let b: Borrowed = Default::default(); + println!("b is {:?}", b); +} +``` + +### See also: + +[`trait`s][trait] + + +[trait]: ../../trait.md diff --git a/src/scope/move.md b/src/scope/move.md new file mode 100644 index 0000000000..0433e8ac1a --- /dev/null +++ b/src/scope/move.md @@ -0,0 +1,60 @@ +# Ownership and moves + +Because variables are in charge of freeing their own resources, +**resources can only have one owner**. This also prevents resources +from being freed more than once. Note that not all variables own +resources (e.g. [references]). + +When doing assignments (`let x = y`) or passing function arguments by value +(`foo(x)`), the *ownership* of the resources is transferred. In Rust-speak, +this is known as a *move*. + +After moving resources, the previous owner can no longer be used. This avoids +creating dangling pointers. + +```rust,editable +// This function takes ownership of the heap allocated memory +fn destroy_box(c: Box) { + println!("Destroying a box that contains {}", c); + + // `c` is destroyed and the memory freed +} + +fn main() { + // _Stack_ allocated integer + let x = 5u32; + + // *Copy* `x` into `y` - no resources are moved + let y = x; + + // Both values can be independently used + println!("x is {}, and y is {}", x, y); + + // `a` is a pointer to a _heap_ allocated integer + let a = Box::new(5i32); + + println!("a contains: {}", a); + + // *Move* `a` into `b` + let b = a; + // The pointer address of `a` is copied (not the data) into `b`. + // Both are now pointers to the same heap allocated data, but + // `b` now owns it. + + // Error! `a` can no longer access the data, because it no longer owns the + // heap memory + //println!("a contains: {}", a); + // TODO ^ Try uncommenting this line + + // This function takes ownership of the heap allocated memory from `b` + destroy_box(b); + + // Since the heap memory has been freed at this point, this action would + // result in dereferencing freed memory, but it's forbidden by the compiler + // Error! Same reason as the previous Error + //println!("b contains: {}", b); + // TODO ^ Try uncommenting this line +} +``` + +[references]: ../flow_control/match/destructuring/destructure_pointers.md diff --git a/examples/move/mut/mut.rs b/src/scope/move/mut.md similarity index 52% rename from examples/move/mut/mut.rs rename to src/scope/move/mut.md index 4f6de6711b..3dddc4a17e 100644 --- a/examples/move/mut/mut.rs +++ b/src/scope/move/mut.md @@ -1,18 +1,24 @@ +# Mutability + +Mutability of data can be changed when ownership is transferred. + +```rust,editable fn main() { - let immutable_box = box 5u; + let immutable_box = Box::new(5u32); println!("immutable_box contains {}", immutable_box); // Mutability error //*immutable_box = 4; - // Hand over the box, changing the mutability + // *Move* the box, changing the ownership (and mutability) let mut mutable_box = immutable_box; - println!("mutable_box contained {}", mutable_box); + println!("mutable_box contains {}", mutable_box); // Modify the contents of the box *mutable_box = 4; println!("mutable_box now contains {}", mutable_box); } +``` \ No newline at end of file diff --git a/src/scope/move/partial_move.md b/src/scope/move/partial_move.md new file mode 100644 index 0000000000..98c6c8dc81 --- /dev/null +++ b/src/scope/move/partial_move.md @@ -0,0 +1,41 @@ +# Partial moves + +Within the [destructuring] of a single variable, both `by-move` and +`by-reference` pattern bindings can be used at the same time. Doing +this will result in a _partial move_ of the variable, which means +that parts of the variable will be moved while other parts stay. In +such a case, the parent variable cannot be used afterwards as a +whole, however the parts that are only referenced (and not moved) +can still be used. + +```rust,editable +fn main() { + #[derive(Debug)] + struct Person { + name: String, + age: u8, + } + + let person = Person { + name: String::from("Alice"), + age: 20, + }; + + // `name` is moved out of person, but `age` is referenced + let Person { name, ref age } = person; + + println!("The person's age is {}", age); + + println!("The person's name is {}", name); + + // Error! borrow of partially moved value: `person` partial move occurs + //println!("The person struct is {:?}", person); + + // `person` cannot be used but `person.age` can be used as it is not moved + println!("The person's age from person struct is {}", person.age); +} +``` +### See also: +[destructuring][destructuring] + +[destructuring]: ../../flow_control/match/destructuring.md diff --git a/src/scope/raii.md b/src/scope/raii.md new file mode 100644 index 0000000000..7b6bca6184 --- /dev/null +++ b/src/scope/raii.md @@ -0,0 +1,96 @@ +# RAII + +Variables in Rust do more than just hold data in the stack: they also *own* +resources, e.g. `Box` owns memory in the heap. Rust enforces [RAII][raii] +(Resource Acquisition Is Initialization), so whenever an object goes out of +scope, its destructor is called and its owned resources are freed. + +This behavior shields against *resource leak* bugs, so you'll never have to +manually free memory or worry about memory leaks again! Here's a quick showcase: + +```rust,editable +// raii.rs +fn create_box() { + // Allocate an integer on the heap + let _box1 = Box::new(3i32); + + // `_box1` is destroyed here, and memory gets freed +} + +fn main() { + // Allocate an integer on the heap + let _box2 = Box::new(5i32); + + // A nested scope: + { + // Allocate an integer on the heap + let _box3 = Box::new(4i32); + + // `_box3` is destroyed here, and memory gets freed + } + + // Creating lots of boxes just for fun + // There's no need to manually free memory! + for _ in 0u32..1_000 { + create_box(); + } + + // `_box2` is destroyed here, and memory gets freed +} +``` + +Of course, we can double check for memory errors using [`valgrind`][valgrind]: + +```shell +$ rustc raii.rs && valgrind ./raii +==26873== Memcheck, a memory error detector +==26873== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al. +==26873== Using Valgrind-3.9.0 and LibVEX; rerun with -h for copyright info +==26873== Command: ./raii +==26873== +==26873== +==26873== HEAP SUMMARY: +==26873== in use at exit: 0 bytes in 0 blocks +==26873== total heap usage: 1,013 allocs, 1,013 frees, 8,696 bytes allocated +==26873== +==26873== All heap blocks were freed -- no leaks are possible +==26873== +==26873== For counts of detected and suppressed errors, rerun with: -v +==26873== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2) +``` + +No leaks here! + +## Destructor + +The notion of a destructor in Rust is provided through the [`Drop`] trait. The +destructor is called when the resource goes out of scope. This trait is not +required to be implemented for every type, only implement it for your type if +you require its own destructor logic. + +Run the below example to see how the [`Drop`] trait works. When the variable in +the `main` function goes out of scope the custom destructor will be invoked. + +```rust,editable +struct ToDrop; + +impl Drop for ToDrop { + fn drop(&mut self) { + println!("ToDrop is being dropped"); + } +} + +fn main() { + let x = ToDrop; + println!("Made a ToDrop!"); +} +``` + +### See also: + +[Box][box] + +[raii]: https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization +[box]: ../std/box.md +[valgrind]: http://valgrind.org/info/ +[`Drop`]: https://doc.rust-lang.org/std/ops/trait.Drop.html diff --git a/src/std.md b/src/std.md new file mode 100644 index 0000000000..8863c788ae --- /dev/null +++ b/src/std.md @@ -0,0 +1,17 @@ +# Std library types + +The `std` library provides many custom types which expands drastically on +the `primitives`. Some of these include: + +* growable `String`s like: `"hello world"` +* growable vectors: `[1, 2, 3]` +* optional types: `Option` +* error handling types: `Result` +* heap allocated pointers: `Box` + +### See also: + +[primitives] and [the std library][std] + +[primitives]: primitives.md +[std]: https://doc.rust-lang.org/std/ diff --git a/src/std/arc.md b/src/std/arc.md new file mode 100644 index 0000000000..d36ca0802a --- /dev/null +++ b/src/std/arc.md @@ -0,0 +1,27 @@ +# Arc + +When shared ownership between threads is needed, `Arc`(Atomic Reference Counted) can be used. This struct, via the `Clone` implementation can create a reference pointer for the location of a value in the memory heap while increasing the reference counter. As it shares ownership between threads, when the last reference pointer to a value is out of scope, the variable is dropped. + +```rust,editable + +fn main() { +use std::sync::Arc; +use std::thread; + +// This variable declaration is where its value is specified. +let apple = Arc::new("the same apple"); + +for _ in 0..10 { + // Here there is no value specification as it is a pointer to a reference + // in the memory heap. + let apple = Arc::clone(&apple); + + thread::spawn(move || { + // As Arc was used, threads can be spawned using the value allocated + // in the Arc variable pointer's location. + println!("{:?}", apple); + }); +} +} + +``` diff --git a/src/std/box.md b/src/std/box.md new file mode 100644 index 0000000000..ebc8ff430a --- /dev/null +++ b/src/std/box.md @@ -0,0 +1,77 @@ +# Box, stack and heap + +All values in Rust are stack allocated by default. Values can be *boxed* +(allocated on the heap) by creating a `Box`. A box is a smart pointer to a +heap allocated value of type `T`. When a box goes out of scope, its destructor +is called, the inner object is destroyed, and the memory on the heap is freed. + +Boxed values can be dereferenced using the `*` operator; this removes one layer +of indirection. + +```rust,editable +use std::mem; + +#[allow(dead_code)] +#[derive(Debug, Clone, Copy)] +struct Point { + x: f64, + y: f64, +} + +// A Rectangle can be specified by where its top left and bottom right +// corners are in space +#[allow(dead_code)] +struct Rectangle { + top_left: Point, + bottom_right: Point, +} + +fn origin() -> Point { + Point { x: 0.0, y: 0.0 } +} + +fn boxed_origin() -> Box { + // Allocate this point on the heap, and return a pointer to it + Box::new(Point { x: 0.0, y: 0.0 }) +} + +fn main() { + // (all the type annotations are superfluous) + // Stack allocated variables + let point: Point = origin(); + let rectangle: Rectangle = Rectangle { + top_left: origin(), + bottom_right: Point { x: 3.0, y: -4.0 } + }; + + // Heap allocated rectangle + let boxed_rectangle: Box = Box::new(Rectangle { + top_left: origin(), + bottom_right: Point { x: 3.0, y: -4.0 }, + }); + + // The output of functions can be boxed + let boxed_point: Box = Box::new(origin()); + + // Double indirection + let box_in_a_box: Box> = Box::new(boxed_origin()); + + println!("Point occupies {} bytes on the stack", + mem::size_of_val(&point)); + println!("Rectangle occupies {} bytes on the stack", + mem::size_of_val(&rectangle)); + + // box size == pointer size + println!("Boxed point occupies {} bytes on the stack", + mem::size_of_val(&boxed_point)); + println!("Boxed rectangle occupies {} bytes on the stack", + mem::size_of_val(&boxed_rectangle)); + println!("Boxed box occupies {} bytes on the stack", + mem::size_of_val(&box_in_a_box)); + + // Copy the data contained in `boxed_point` into `unboxed_point` + let unboxed_point: Point = *boxed_point; + println!("Unboxed point occupies {} bytes on the stack", + mem::size_of_val(&unboxed_point)); +} +``` \ No newline at end of file diff --git a/examples/staging/hash/hash.rs b/src/std/hash.md similarity index 58% rename from examples/staging/hash/hash.rs rename to src/std/hash.md index 4cebfa8ffa..94faacbf25 100644 --- a/examples/staging/hash/hash.rs +++ b/src/std/hash.md @@ -1,3 +1,17 @@ +# HashMap + +Where vectors store values by an integer index, `HashMap`s store values by key. +`HashMap` keys can be booleans, integers, strings, +or any other type that implements the `Eq` and `Hash` traits. +More on this in the next section. + +Like vectors, `HashMap`s are growable, but HashMaps can also shrink themselves +when they have excess space. +You can create a HashMap with a certain starting capacity using +`HashMap::with_capacity(uint)`, or use `HashMap::new()` to get a HashMap +with a default initial capacity (recommended). + +```rust,editable use std::collections::HashMap; fn call(number: &str) -> &str { @@ -24,8 +38,8 @@ fn main() { _ => println!("Don't have Daniel's number."), } - // `HashMap::insert()` returns true - // if the inserted value is new, false otherwise + // `HashMap::insert()` returns `None` + // if the inserted value is new, `Some(value)` otherwise contacts.insert("Daniel", "164-6743"); match contacts.get(&"Ashley") { @@ -33,7 +47,7 @@ fn main() { _ => println!("Don't have Ashley's number."), } - contacts.remove(&("Ashley")); + contacts.remove(&"Ashley"); // `HashMap::iter()` returns an iterator that yields // (&'a key, &'a value) pairs in arbitrary order. @@ -41,3 +55,10 @@ fn main() { println!("Calling {}: {}", contact, call(number)); } } +``` + +For more information on how hashing and hash maps +(sometimes called hash tables) work, have a look at +[Hash Table Wikipedia][wiki-hash] + +[wiki-hash]: https://en.wikipedia.org/wiki/Hash_table diff --git a/src/std/hash/alt_key_types.md b/src/std/hash/alt_key_types.md new file mode 100644 index 0000000000..ab94819b25 --- /dev/null +++ b/src/std/hash/alt_key_types.md @@ -0,0 +1,89 @@ +# Alternate/custom key types + +Any type that implements the `Eq` and `Hash` traits can be a key in `HashMap`. +This includes: + +* `bool` (though not very useful since there is only two possible keys) +* `int`, `uint`, and all variations thereof +* `String` and `&str` (protip: you can have a `HashMap` keyed by `String` +and call `.get()` with an `&str`) + +Note that `f32` and `f64` do *not* implement `Hash`, +likely because [floating-point precision errors][floating] +would make using them as hashmap keys horribly error-prone. + +All collection classes implement `Eq` and `Hash` +if their contained type also respectively implements `Eq` and `Hash`. +For example, `Vec` will implement `Hash` if `T` implements `Hash`. + +You can easily implement `Eq` and `Hash` for a custom type with just one line: +`#[derive(PartialEq, Eq, Hash)]` + +The compiler will do the rest. If you want more control over the details, +you can implement `Eq` and/or `Hash` yourself. +This guide will not cover the specifics of implementing `Hash`. + +To play around with using a `struct` in `HashMap`, +let's try making a very simple user logon system: + +```rust,editable +use std::collections::HashMap; + +// Eq requires that you derive PartialEq on the type. +#[derive(PartialEq, Eq, Hash)] +struct Account<'a>{ + username: &'a str, + password: &'a str, +} + +struct AccountInfo<'a>{ + name: &'a str, + email: &'a str, +} + +type Accounts<'a> = HashMap, AccountInfo<'a>>; + +fn try_logon<'a>(accounts: &Accounts<'a>, + username: &'a str, password: &'a str){ + println!("Username: {}", username); + println!("Password: {}", password); + println!("Attempting logon..."); + + let logon = Account { + username, + password, + }; + + match accounts.get(&logon) { + Some(account_info) => { + println!("Successful logon!"); + println!("Name: {}", account_info.name); + println!("Email: {}", account_info.email); + }, + _ => println!("Login failed!"), + } +} + +fn main(){ + let mut accounts: Accounts = HashMap::new(); + + let account = Account { + username: "j.everyman", + password: "password123", + }; + + let account_info = AccountInfo { + name: "John Everyman", + email: "j.everyman@email.com", + }; + + accounts.insert(account, account_info); + + try_logon(&accounts, "j.everyman", "psasword123"); + + try_logon(&accounts, "j.everyman", "password123"); +} +``` + +[hash]: https://en.wikipedia.org/wiki/Hash_function +[floating]: https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems diff --git a/src/std/hash/hashset.md b/src/std/hash/hashset.md new file mode 100644 index 0000000000..63d5af8782 --- /dev/null +++ b/src/std/hash/hashset.md @@ -0,0 +1,76 @@ +# HashSet + +Consider a `HashSet` as a `HashMap` where we just care about the keys ( +`HashSet` is, in actuality, just a wrapper around `HashMap`). + +"What's the point of that?" you ask. "I could just store the keys in a `Vec`." + +A `HashSet`'s unique feature is that +it is guaranteed to not have duplicate elements. +That's the contract that any set collection fulfills. +`HashSet` is just one implementation. (see also: [`BTreeSet`][treeset]) + +If you insert a value that is already present in the `HashSet`, +(i.e. the new value is equal to the existing and they both have the same hash), +then the new value will replace the old. + +This is great for when you never want more than one of something, +or when you want to know if you've already got something. + +But sets can do more than that. + +Sets have 4 primary operations (all of the following calls return an iterator): + +* `union`: get all the unique elements in both sets. + +* `difference`: get all the elements that are in the first set but not the second. + +* `intersection`: get all the elements that are only in *both* sets. + +* `symmetric_difference`: +get all the elements that are in one set or the other, but *not* both. + +Try all of these in the following example: + +```rust,editable,ignore,mdbook-runnable +use std::collections::HashSet; + +fn main() { + let mut a: HashSet = vec![1i32, 2, 3].into_iter().collect(); + let mut b: HashSet = vec![2i32, 3, 4].into_iter().collect(); + + assert!(a.insert(4)); + assert!(a.contains(&4)); + + // `HashSet::insert()` returns false if + // there was a value already present. + assert!(b.insert(4), "Value 4 is already in set B!"); + // FIXME ^ Comment out this line + + b.insert(5); + + // If a collection's element type implements `Debug`, + // then the collection implements `Debug`. + // It usually prints its elements in the format `[elem1, elem2, ...]` + println!("A: {:?}", a); + println!("B: {:?}", b); + + // Print [1, 2, 3, 4, 5] in arbitrary order + println!("Union: {:?}", a.union(&b).collect::>()); + + // This should print [1] + println!("Difference: {:?}", a.difference(&b).collect::>()); + + // Print [2, 3, 4] in arbitrary order. + println!("Intersection: {:?}", a.intersection(&b).collect::>()); + + // Print [1, 5] + println!("Symmetric Difference: {:?}", + a.symmetric_difference(&b).collect::>()); +} +``` + +(Examples are adapted from the [documentation.][hash-set]) + +[treeset]: https://doc.rust-lang.org/std/collections/struct.BTreeSet.html +[hash-set]: https://doc.rust-lang.org/std/collections/struct.HashSet.html#method.difference diff --git a/src/std/option.md b/src/std/option.md new file mode 100644 index 0000000000..30927e87ea --- /dev/null +++ b/src/std/option.md @@ -0,0 +1,50 @@ +# `Option` + +Sometimes it's desirable to catch the failure of some parts of a program +instead of calling `panic!`; this can be accomplished using the `Option` enum. + +The `Option` enum has two variants: + +* `None`, to indicate failure or lack of value, and +* `Some(value)`, a tuple struct that wraps a `value` with type `T`. + +```rust,editable,ignore,mdbook-runnable +// An integer division that doesn't `panic!` +fn checked_division(dividend: i32, divisor: i32) -> Option { + if divisor == 0 { + // Failure is represented as the `None` variant + None + } else { + // Result is wrapped in a `Some` variant + Some(dividend / divisor) + } +} + +// This function handles a division that may not succeed +fn try_division(dividend: i32, divisor: i32) { + // `Option` values can be pattern matched, just like other enums + match checked_division(dividend, divisor) { + None => println!("{} / {} failed!", dividend, divisor), + Some(quotient) => { + println!("{} / {} = {}", dividend, divisor, quotient) + }, + } +} + +fn main() { + try_division(4, 2); + try_division(1, 0); + + // Binding `None` to a variable needs to be type annotated + let none: Option = None; + let _equivalent_none = None::; + + let optional_float = Some(0f32); + + // Unwrapping a `Some` variant will extract the value wrapped. + println!("{:?} unwraps to {:?}", optional_float, optional_float.unwrap()); + + // Unwrapping a `None` variant will `panic!` + println!("{:?} unwraps to {:?}", none, none.unwrap()); +} +``` diff --git a/src/std/panic.md b/src/std/panic.md new file mode 100644 index 0000000000..b22000494c --- /dev/null +++ b/src/std/panic.md @@ -0,0 +1,54 @@ +# `panic!` + +The `panic!` macro can be used to generate a panic and start unwinding +its stack. While unwinding, the runtime will take care of freeing all the +resources *owned* by the thread by calling the destructor of all its objects. + +Since we are dealing with programs with only one thread, `panic!` will cause the +program to report the panic message and exit. + +```rust,editable,ignore,mdbook-runnable +// Re-implementation of integer division (/) +fn division(dividend: i32, divisor: i32) -> i32 { + if divisor == 0 { + // Division by zero triggers a panic + panic!("division by zero"); + } else { + dividend / divisor + } +} + +// The `main` task +fn main() { + // Heap allocated integer + let _x = Box::new(0i32); + + // This operation will trigger a task failure + division(3, 0); + + println!("This point won't be reached!"); + + // `_x` should get destroyed at this point +} +``` + +Let's check that `panic!` doesn't leak memory. + +```shell +$ rustc panic.rs && valgrind ./panic +==4401== Memcheck, a memory error detector +==4401== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al. +==4401== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info +==4401== Command: ./panic +==4401== +thread '
' panicked at 'division by zero', panic.rs:5 +==4401== +==4401== HEAP SUMMARY: +==4401== in use at exit: 0 bytes in 0 blocks +==4401== total heap usage: 18 allocs, 18 frees, 1,648 bytes allocated +==4401== +==4401== All heap blocks were freed -- no leaks are possible +==4401== +==4401== For counts of detected and suppressed errors, rerun with: -v +==4401== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) +``` diff --git a/src/std/rc.md b/src/std/rc.md new file mode 100644 index 0000000000..a9691b2448 --- /dev/null +++ b/src/std/rc.md @@ -0,0 +1,54 @@ +# `Rc` + +When multiple ownership is needed, `Rc`(Reference Counting) can be used. `Rc` keeps track of the number of the references which means the number of owners of the value wrapped inside an `Rc`. + +Reference count of an `Rc` increases by 1 whenever an `Rc` is cloned, and decreases by 1 whenever one cloned `Rc` is dropped out of the scope. When an `Rc`'s reference count becomes zero, which means there are no owners remained, both the `Rc` and the value are all dropped. + +Cloning an `Rc` never performs a deep copy. Cloning creates just another pointer to the wrapped value, and increments the count. + +```rust,editable +use std::rc::Rc; + +fn main() { + let rc_examples = "Rc examples".to_string(); + { + println!("--- rc_a is created ---"); + + let rc_a: Rc = Rc::new(rc_examples); + println!("Reference Count of rc_a: {}", Rc::strong_count(&rc_a)); + + { + println!("--- rc_a is cloned to rc_b ---"); + + let rc_b: Rc = Rc::clone(&rc_a); + println!("Reference Count of rc_b: {}", Rc::strong_count(&rc_b)); + println!("Reference Count of rc_a: {}", Rc::strong_count(&rc_a)); + + // Two `Rc`s are equal if their inner values are equal + println!("rc_a and rc_b are equal: {}", rc_a.eq(&rc_b)); + + // We can use methods of a value directly + println!("Length of the value inside rc_a: {}", rc_a.len()); + println!("Value of rc_b: {}", rc_b); + + println!("--- rc_b is dropped out of scope ---"); + } + + println!("Reference Count of rc_a: {}", Rc::strong_count(&rc_a)); + + println!("--- rc_a is dropped out of scope ---"); + } + + // Error! `rc_examples` already moved into `rc_a` + // And when `rc_a` is dropped, `rc_examples` is dropped together + // println!("rc_examples: {}", rc_examples); + // TODO ^ Try uncommenting this line +} +``` + +### See also: + +[std::rc][1] and [std::sync::arc][2]. + +[1]: https://doc.rust-lang.org/std/rc/index.html +[2]: https://doc.rust-lang.org/std/sync/struct.Arc.html diff --git a/examples/result/result.rs b/src/std/result.md similarity index 57% rename from examples/result/result.rs rename to src/std/result.md index 53ccd532e4..b812b9de99 100644 --- a/examples/result/result.rs +++ b/src/std/result.md @@ -1,11 +1,24 @@ +# `Result` + +We've seen that the `Option` enum can be used as a return value from functions +that may fail, where `None` can be returned to indicate failure. However, +sometimes it is important to express *why* an operation failed. To do this we +have the `Result` enum. + +The `Result` enum has two variants: + +* `Ok(value)` which indicates that the operation succeeded, and wraps the + `value` returned by the operation. (`value` has type `T`) +* `Err(why)`, which indicates that the operation failed, and wraps `why`, + which (hopefully) explains the cause of the failure. (`why` has type `E`) + +```rust,editable,ignore,mdbook-runnable mod checked { - // For .ln() and .sqrt() - use std::num::Float; // Mathematical "errors" we want to catch - #[deriving(Show)] + #[derive(Debug)] pub enum MathError { DivisionByZero, - NegativeLogarithm, + NonPositiveLogarithm, NegativeSquareRoot, } @@ -31,8 +44,8 @@ mod checked { } pub fn ln(x: f64) -> MathResult { - if x < 0.0 { - Err(MathError::NegativeLogarithm) + if x <= 0.0 { + Err(MathError::NonPositiveLogarithm) } else { Ok(x.ln()) } @@ -43,11 +56,11 @@ mod checked { fn op(x: f64, y: f64) -> f64 { // This is a three level match pyramid! match checked::div(x, y) { - Err(why) => panic!("{}", why), + Err(why) => panic!("{:?}", why), Ok(ratio) => match checked::ln(ratio) { - Err(why) => panic!("{}", why), + Err(why) => panic!("{:?}", why), Ok(ln) => match checked::sqrt(ln) { - Err(why) => panic!("{}", why), + Err(why) => panic!("{:?}", why), Ok(sqrt) => sqrt, }, }, @@ -58,3 +71,4 @@ fn main() { // Will this fail? println!("{}", op(1.0, 10.0)); } +``` diff --git a/examples/result/try/try.rs b/src/std/result/question_mark.md similarity index 53% rename from examples/result/try/try.rs rename to src/std/result/question_mark.md index d2259f0dd1..a1f7706840 100644 --- a/examples/result/try/try.rs +++ b/src/std/result/question_mark.md @@ -1,11 +1,17 @@ -mod checked { - // For .sqrt() and .ln() - use std::num::Float; +# `?` + +Chaining results using match can get pretty untidy; luckily, the `?` operator +can be used to make things pretty again. `?` is used at the end of an expression +returning a `Result`, and is equivalent to a match expression, where the +`Err(err)` branch expands to an early `Err(From::from(err))`, and the `Ok(ok)` +branch expands to an `ok` expression. - #[deriving(Show)] +```rust,editable,ignore,mdbook-runnable +mod checked { + #[derive(Debug)] enum MathError { DivisionByZero, - NegativeLogarithm, + NonPositiveLogarithm, NegativeSquareRoot, } @@ -28,8 +34,8 @@ mod checked { } fn ln(x: f64) -> MathResult { - if x < 0.0 { - Err(MathError::NegativeLogarithm) + if x <= 0.0 { + Err(MathError::NonPositiveLogarithm) } else { Ok(x.ln()) } @@ -38,19 +44,19 @@ mod checked { // Intermediate function fn op_(x: f64, y: f64) -> MathResult { // if `div` "fails", then `DivisionByZero` will be `return`ed - let ratio = try!(div(x, y)); + let ratio = div(x, y)?; - // if `ln` "fails", then `NegativeLogarithm` will be `return`ed - let ln = try!(ln(ratio)); + // if `ln` "fails", then `NonPositiveLogarithm` will be `return`ed + let ln = ln(ratio)?; sqrt(ln) } pub fn op(x: f64, y: f64) { match op_(x, y) { - Err(why) => panic!(match why { - MathError::NegativeLogarithm - => "logarithm of negative number", + Err(why) => panic!("{}", match why { + MathError::NonPositiveLogarithm + => "logarithm of non-positive number", MathError::DivisionByZero => "division by zero", MathError::NegativeSquareRoot @@ -64,3 +70,9 @@ mod checked { fn main() { checked::op(1.0, 10.0); } +``` + +Be sure to check the [documentation][docs], +as there are many methods to map/compose `Result`. + +[docs]: https://doc.rust-lang.org/std/result/index.html diff --git a/src/std/str.md b/src/std/str.md new file mode 100644 index 0000000000..ba14b59db1 --- /dev/null +++ b/src/std/str.md @@ -0,0 +1,166 @@ +# Strings + +There are two types of strings in Rust: `String` and `&str`. + +A `String` is stored as a vector of bytes (`Vec`), but guaranteed to +always be a valid UTF-8 sequence. `String` is heap allocated, growable and not +null terminated. + +`&str` is a slice (`&[u8]`) that always points to a valid UTF-8 sequence, and +can be used to view into a `String`, just like `&[T]` is a view into `Vec`. + +```rust,editable +fn main() { + // (all the type annotations are superfluous) + // A reference to a string allocated in read only memory + let pangram: &'static str = "the quick brown fox jumps over the lazy dog"; + println!("Pangram: {}", pangram); + + // Iterate over words in reverse, no new string is allocated + println!("Words in reverse"); + for word in pangram.split_whitespace().rev() { + println!("> {}", word); + } + + // Copy chars into a vector, sort and remove duplicates + let mut chars: Vec = pangram.chars().collect(); + chars.sort(); + chars.dedup(); + + // Create an empty and growable `String` + let mut string = String::new(); + for c in chars { + // Insert a char at the end of string + string.push(c); + // Insert a string at the end of string + string.push_str(", "); + } + + // The trimmed string is a slice to the original string, hence no new + // allocation is performed + let chars_to_trim: &[char] = &[' ', ',']; + let trimmed_str: &str = string.trim_matches(chars_to_trim); + println!("Used characters: {}", trimmed_str); + + // Heap allocate a string + let alice = String::from("I like dogs"); + // Allocate new memory and store the modified string there + let bob: String = alice.replace("dog", "cat"); + + println!("Alice says: {}", alice); + println!("Bob says: {}", bob); +} +``` + +More `str`/`String` methods can be found under the +[std::str][str] and +[std::string][string] +modules + +## Literals and escapes + +There are multiple ways to write string literals with special characters in them. +All result in a similar `&str` so it's best to use the form that is the most +convenient to write. Similarly there are multiple ways to write byte string literals, +which all result in `&[u8; N]`. + +Generally special characters are escaped with a backslash character: `\`. +This way you can add any character to your string, even unprintable ones +and ones that you don't know how to type. If you want a literal backslash, +escape it with another one: `\\` + +String or character literal delimiters occuring within a literal must be escaped: `"\""`, `'\''`. + +```rust,editable +fn main() { + // You can use escapes to write bytes by their hexadecimal values... + let byte_escape = "I'm writing \x52\x75\x73\x74!"; + println!("What are you doing\x3F (\\x3F means ?) {}", byte_escape); + + // ...or Unicode code points. + let unicode_codepoint = "\u{211D}"; + let character_name = "\"DOUBLE-STRUCK CAPITAL R\""; + + println!("Unicode character {} (U+211D) is called {}", + unicode_codepoint, character_name ); + + + let long_string = "String literals + can span multiple lines. + The linebreak and indentation here ->\ + <- can be escaped too!"; + println!("{}", long_string); +} +``` + +Sometimes there are just too many characters that need to be escaped or it's just +much more convenient to write a string out as-is. This is where raw string literals come into play. + +```rust, editable +fn main() { + let raw_str = r"Escapes don't work here: \x3F \u{211D}"; + println!("{}", raw_str); + + // If you need quotes in a raw string, add a pair of #s + let quotes = r#"And then I said: "There is no escape!""#; + println!("{}", quotes); + + // If you need "# in your string, just use more #s in the delimiter. + // There is no limit for the number of #s you can use. + let longer_delimiter = r###"A string with "# in it. And even "##!"###; + println!("{}", longer_delimiter); +} +``` + +Want a string that's not UTF-8? (Remember, `str` and `String` must be valid UTF-8). +Or maybe you want an array of bytes that's mostly text? Byte strings to the rescue! + +```rust, editable +use std::str; + +fn main() { + // Note that this is not actually a `&str` + let bytestring: &[u8; 21] = b"this is a byte string"; + + // Byte arrays don't have the `Display` trait, so printing them is a bit limited + println!("A byte string: {:?}", bytestring); + + // Byte strings can have byte escapes... + let escaped = b"\x52\x75\x73\x74 as bytes"; + // ...but no unicode escapes + // let escaped = b"\u{211D} is not allowed"; + println!("Some escaped bytes: {:?}", escaped); + + + // Raw byte strings work just like raw strings + let raw_bytestring = br"\u{211D} is not escaped here"; + println!("{:?}", raw_bytestring); + + // Converting a byte array to `str` can fail + if let Ok(my_str) = str::from_utf8(raw_bytestring) { + println!("And the same as text: '{}'", my_str); + } + + let _quotes = br#"You can also use "fancier" formatting, \ + like with normal raw strings"#; + + // Byte strings don't have to be UTF-8 + let shift_jis = b"\x82\xe6\x82\xa8\x82\xb1\x82\xbb"; // "ようこそ" in SHIFT-JIS + + // But then they can't always be converted to `str` + match str::from_utf8(shift_jis) { + Ok(my_str) => println!("Conversion successful: '{}'", my_str), + Err(e) => println!("Conversion failed: {:?}", e), + }; +} +``` + +For conversions between character encodings check out the [encoding][encoding-crate] crate. + +A more detailed listing of the ways to write string literals and escape characters +is given in the ['Tokens' chapter][tokens] of the Rust Reference. + +[str]: https://doc.rust-lang.org/std/str/ +[string]: https://doc.rust-lang.org/std/string/ +[tokens]: https://doc.rust-lang.org/reference/tokens.html +[encoding-crate]: https://crates.io/crates/encoding diff --git a/src/std/vec.md b/src/std/vec.md new file mode 100644 index 0000000000..f5cb1cae0c --- /dev/null +++ b/src/std/vec.md @@ -0,0 +1,70 @@ +# Vectors + +Vectors are re-sizable arrays. Like slices, their size is not known at compile +time, but they can grow or shrink at any time. A vector is represented using +3 parameters: +- pointer to the data +- length +- capacity + +The capacity indicates how much memory is reserved for the vector. The vector +can grow as long as the length is smaller than the capacity. When this threshold +needs to be surpassed, the vector is reallocated with a larger capacity. + +```rust,editable,ignore,mdbook-runnable +fn main() { + // Iterators can be collected into vectors + let collected_iterator: Vec = (0..10).collect(); + println!("Collected (0..10) into: {:?}", collected_iterator); + + // The `vec!` macro can be used to initialize a vector + let mut xs = vec![1i32, 2, 3]; + println!("Initial vector: {:?}", xs); + + // Insert new element at the end of the vector + println!("Push 4 into the vector"); + xs.push(4); + println!("Vector: {:?}", xs); + + // Error! Immutable vectors can't grow + collected_iterator.push(0); + // FIXME ^ Comment out this line + + // The `len` method yields the number of elements currently stored in a vector + println!("Vector length: {}", xs.len()); + + // Indexing is done using the square brackets (indexing starts at 0) + println!("Second element: {}", xs[1]); + + // `pop` removes the last element from the vector and returns it + println!("Pop last element: {:?}", xs.pop()); + + // Out of bounds indexing yields a panic + println!("Fourth element: {}", xs[3]); + // FIXME ^ Comment out this line + + // `Vector`s can be easily iterated over + println!("Contents of xs:"); + for x in xs.iter() { + println!("> {}", x); + } + + // A `Vector` can also be iterated over while the iteration + // count is enumerated in a separate variable (`i`) + for (i, x) in xs.iter().enumerate() { + println!("In position {} we have value {}", i, x); + } + + // Thanks to `iter_mut`, mutable `Vector`s can also be iterated + // over in a way that allows modifying each value + for x in xs.iter_mut() { + *x *= 3; + } + println!("Updated vector: {:?}", xs); +} +``` + +More `Vec` methods can be found under the +[std::vec][vec] module + +[vec]: https://doc.rust-lang.org/std/vec/ diff --git a/src/std_misc.md b/src/std_misc.md new file mode 100644 index 0000000000..ac9c57864f --- /dev/null +++ b/src/std_misc.md @@ -0,0 +1,17 @@ +# Std misc + +Many other types are provided by the std library to support +things such as: + +* Threads +* Channels +* File I/O + +These expand beyond what the [primitives] provide. + +### See also: + +[primitives] and [the std library][std] + +[primitives]: primitives.md +[std]: https://doc.rust-lang.org/std/ diff --git a/src/std_misc/arg.md b/src/std_misc/arg.md new file mode 100644 index 0000000000..b5dd89ce60 --- /dev/null +++ b/src/std_misc/arg.md @@ -0,0 +1,37 @@ +# Program arguments + +## Standard Library + +The command line arguments can be accessed using `std::env::args`, which +returns an iterator that yields a `String` for each argument: + +```rust,editable +use std::env; + +fn main() { + let args: Vec = env::args().collect(); + + // The first argument is the path that was used to call the program. + println!("My path is {}.", args[0]); + + // The rest of the arguments are the passed command line parameters. + // Call the program like this: + // $ ./args arg1 arg2 + println!("I got {:?} arguments: {:?}.", args.len() - 1, &args[1..]); +} +``` + +```shell +$ ./args 1 2 3 +My path is ./args. +I got 3 arguments: ["1", "2", "3"]. +``` + +## Crates + +Alternatively, there are numerous crates that can provide extra functionality +when creating command-line applications. The [Rust Cookbook] exhibits best +practices on how to use one of the more popular command line argument crates, +`clap`. + +[Rust Cookbook]: https://rust-lang-nursery.github.io/rust-cookbook/cli/arguments.html diff --git a/src/std_misc/arg/matching.md b/src/std_misc/arg/matching.md new file mode 100644 index 0000000000..4cb68eabf0 --- /dev/null +++ b/src/std_misc/arg/matching.md @@ -0,0 +1,94 @@ +# Argument parsing + +Matching can be used to parse simple arguments: + +```rust,editable +use std::env; + +fn increase(number: i32) { + println!("{}", number + 1); +} + +fn decrease(number: i32) { + println!("{}", number - 1); +} + +fn help() { + println!("usage: +match_args + Check whether given string is the answer. +match_args {{increase|decrease}} + Increase or decrease given integer by one."); +} + +fn main() { + let args: Vec = env::args().collect(); + + match args.len() { + // no arguments passed + 1 => { + println!("My name is 'match_args'. Try passing some arguments!"); + }, + // one argument passed + 2 => { + match args[1].parse() { + Ok(42) => println!("This is the answer!"), + _ => println!("This is not the answer."), + } + }, + // one command and one argument passed + 3 => { + let cmd = &args[1]; + let num = &args[2]; + // parse the number + let number: i32 = match num.parse() { + Ok(n) => { + n + }, + Err(_) => { + eprintln!("error: second argument not an integer"); + help(); + return; + }, + }; + // parse the command + match &cmd[..] { + "increase" => increase(number), + "decrease" => decrease(number), + _ => { + eprintln!("error: invalid command"); + help(); + }, + } + }, + // all the other cases + _ => { + // show a help message + help(); + } + } +} +``` + +```shell +$ ./match_args Rust +This is not the answer. +$ ./match_args 42 +This is the answer! +$ ./match_args do something +error: second argument not an integer +usage: +match_args + Check whether given string is the answer. +match_args {increase|decrease} + Increase or decrease given integer by one. +$ ./match_args do 42 +error: invalid command +usage: +match_args + Check whether given string is the answer. +match_args {increase|decrease} + Increase or decrease given integer by one. +$ ./match_args increase 42 +43 +``` diff --git a/src/std_misc/channels.md b/src/std_misc/channels.md new file mode 100644 index 0000000000..8c4d45165f --- /dev/null +++ b/src/std_misc/channels.md @@ -0,0 +1,55 @@ +# Channels + +Rust provides asynchronous `channels` for communication between threads. Channels +allow a unidirectional flow of information between two end-points: the +`Sender` and the `Receiver`. + +```rust,editable +use std::sync::mpsc::{Sender, Receiver}; +use std::sync::mpsc; +use std::thread; + +static NTHREADS: i32 = 3; + +fn main() { + // Channels have two endpoints: the `Sender` and the `Receiver`, + // where `T` is the type of the message to be transferred + // (type annotation is superfluous) + let (tx, rx): (Sender, Receiver) = mpsc::channel(); + let mut children = Vec::new(); + + for id in 0..NTHREADS { + // The sender endpoint can be copied + let thread_tx = tx.clone(); + + // Each thread will send its id via the channel + let child = thread::spawn(move || { + // The thread takes ownership over `thread_tx` + // Each thread queues a message in the channel + thread_tx.send(id).unwrap(); + + // Sending is a non-blocking operation, the thread will continue + // immediately after sending its message + println!("thread {} finished", id); + }); + + children.push(child); + } + + // Here, all the messages are collected + let mut ids = Vec::with_capacity(NTHREADS as usize); + for _ in 0..NTHREADS { + // The `recv` method picks a message from the channel + // `recv` will block the current thread if there are no messages available + ids.push(rx.recv()); + } + + // Wait for the threads to complete any remaining work + for child in children { + child.join().expect("oops! the child thread panicked"); + } + + // Show the order in which the messages were sent + println!("{:?}", ids); +} +``` diff --git a/src/std_misc/ffi.md b/src/std_misc/ffi.md new file mode 100644 index 0000000000..71977e66fa --- /dev/null +++ b/src/std_misc/ffi.md @@ -0,0 +1,56 @@ +# Foreign Function Interface + +Rust provides a Foreign Function Interface (FFI) to C libraries. Foreign +functions must be declared inside an `extern` block annotated with a `#[link]` +attribute containing the name of the foreign library. + +```rust,ignore +use std::fmt; + +// this extern block links to the libm library +#[link(name = "m")] +extern { + // this is a foreign function + // that computes the square root of a single precision complex number + fn csqrtf(z: Complex) -> Complex; + + fn ccosf(z: Complex) -> Complex; +} + +// Since calling foreign functions is considered unsafe, +// it's common to write safe wrappers around them. +fn cos(z: Complex) -> Complex { + unsafe { ccosf(z) } +} + +fn main() { + // z = -1 + 0i + let z = Complex { re: -1., im: 0. }; + + // calling a foreign function is an unsafe operation + let z_sqrt = unsafe { csqrtf(z) }; + + println!("the square root of {:?} is {:?}", z, z_sqrt); + + // calling safe API wrapped around unsafe operation + println!("cos({:?}) = {:?}", z, cos(z)); +} + +// Minimal implementation of single precision complex numbers +#[repr(C)] +#[derive(Clone, Copy)] +struct Complex { + re: f32, + im: f32, +} + +impl fmt::Debug for Complex { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if self.im < 0. { + write!(f, "{}-{}i", self.re, -self.im) + } else { + write!(f, "{}+{}i", self.re, self.im) + } + } +} +``` diff --git a/src/std_misc/file.md b/src/std_misc/file.md new file mode 100644 index 0000000000..60e28cfb3d --- /dev/null +++ b/src/std_misc/file.md @@ -0,0 +1,11 @@ +# File I/O + +The `File` struct represents a file that has been opened (it wraps a file +descriptor), and gives read and/or write access to the underlying file. + +Since many things can go wrong when doing file I/O, all the `File` methods +return the `io::Result` type, which is an alias for `Result`. + +This makes the failure of all I/O operations *explicit*. Thanks to this, the +programmer can see all the failure paths, and is encouraged to handle them in +a proactive manner. \ No newline at end of file diff --git a/src/std_misc/file/create.md b/src/std_misc/file/create.md new file mode 100644 index 0000000000..16eba89747 --- /dev/null +++ b/src/std_misc/file/create.md @@ -0,0 +1,58 @@ +# `create` + +The `create` static method opens a file in write-only mode. If the file +already existed, the old content is destroyed. Otherwise, a new file is +created. + +```rust,ignore +static LOREM_IPSUM: &str = + "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod +tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, +quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo +consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse +cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non +proident, sunt in culpa qui officia deserunt mollit anim id est laborum. +"; + +use std::fs::File; +use std::io::prelude::*; +use std::path::Path; + +fn main() { + let path = Path::new("lorem_ipsum.txt"); + let display = path.display(); + + // Open a file in write-only mode, returns `io::Result` + let mut file = match File::create(&path) { + Err(why) => panic!("couldn't create {}: {}", display, why), + Ok(file) => file, + }; + + // Write the `LOREM_IPSUM` string to `file`, returns `io::Result<()>` + match file.write_all(LOREM_IPSUM.as_bytes()) { + Err(why) => panic!("couldn't write to {}: {}", display, why), + Ok(_) => println!("successfully wrote to {}", display), + } +} +``` + +Here's the expected successful output: + +```shell +$ rustc create.rs && ./create +successfully wrote to lorem_ipsum.txt +$ cat lorem_ipsum.txt +Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod +tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, +quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo +consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse +cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non +proident, sunt in culpa qui officia deserunt mollit anim id est laborum. +``` + +(As in the previous example, you are encouraged to test this example under +failure conditions.) + +There is [`OpenOptions`] struct that can be used to configure how a file is opened. + +[`OpenOptions`]: https://doc.rust-lang.org/std/fs/struct.OpenOptions.html diff --git a/src/std_misc/file/open.md b/src/std_misc/file/open.md new file mode 100644 index 0000000000..16fdb2c91c --- /dev/null +++ b/src/std_misc/file/open.md @@ -0,0 +1,46 @@ +# `open` + +The `open` static method can be used to open a file in read-only mode. + +A `File` owns a resource, the file descriptor and takes care of closing the +file when it is `drop`ed. + +```rust,editable,ignore +use std::fs::File; +use std::io::prelude::*; +use std::path::Path; + +fn main() { + // Create a path to the desired file + let path = Path::new("hello.txt"); + let display = path.display(); + + // Open the path in read-only mode, returns `io::Result` + let mut file = match File::open(&path) { + Err(why) => panic!("couldn't open {}: {}", display, why), + Ok(file) => file, + }; + + // Read the file contents into a string, returns `io::Result` + let mut s = String::new(); + match file.read_to_string(&mut s) { + Err(why) => panic!("couldn't read {}: {}", display, why), + Ok(_) => print!("{} contains:\n{}", display, s), + } + + // `file` goes out of scope, and the "hello.txt" file gets closed +} +``` + +Here's the expected successful output: + +```shell +$ echo "Hello World!" > hello.txt +$ rustc open.rs && ./open +hello.txt contains: +Hello World! +``` + +(You are encouraged to test the previous example under different failure +conditions: `hello.txt` doesn't exist, or `hello.txt` is not readable, +etc.) diff --git a/src/std_misc/file/read_lines.md b/src/std_misc/file/read_lines.md new file mode 100644 index 0000000000..6792b1706e --- /dev/null +++ b/src/std_misc/file/read_lines.md @@ -0,0 +1,44 @@ +# `read_lines` + +The method `lines()` returns an iterator over the lines +of a file. + +`File::open` expects a generic, `AsRef`. That's what +`read_lines()` expects as input. + +```rust,no_run +use std::fs::File; +use std::io::{self, BufRead}; +use std::path::Path; + +fn main() { + // File hosts must exist in current path before this produces output + if let Ok(lines) = read_lines("./hosts") { + // Consumes the iterator, returns an (Optional) String + for line in lines { + if let Ok(ip) = line { + println!("{}", ip); + } + } + } +} + +// The output is wrapped in a Result to allow matching on errors +// Returns an Iterator to the Reader of the lines of the file. +fn read_lines

(filename: P) -> io::Result>> +where P: AsRef, { + let file = File::open(filename)?; + Ok(io::BufReader::new(file).lines()) +} +``` + +Running this program simply prints the lines individually. +```shell +$ echo -e "127.0.0.1\n192.168.0.1\n" > hosts +$ rustc read_lines.rs && ./read_lines +127.0.0.1 +192.168.0.1 +``` + +This process is more efficient than creating a `String` in memory +especially working with larger files. \ No newline at end of file diff --git a/src/std_misc/fs.md b/src/std_misc/fs.md new file mode 100644 index 0000000000..33612d7b3d --- /dev/null +++ b/src/std_misc/fs.md @@ -0,0 +1,146 @@ +# Filesystem Operations + +The `std::fs` module contains several functions that deal with the filesystem. + +```rust,ignore +use std::fs; +use std::fs::{File, OpenOptions}; +use std::io; +use std::io::prelude::*; +use std::os::unix; +use std::path::Path; + +// A simple implementation of `% cat path` +fn cat(path: &Path) -> io::Result { + let mut f = File::open(path)?; + let mut s = String::new(); + match f.read_to_string(&mut s) { + Ok(_) => Ok(s), + Err(e) => Err(e), + } +} + +// A simple implementation of `% echo s > path` +fn echo(s: &str, path: &Path) -> io::Result<()> { + let mut f = File::create(path)?; + + f.write_all(s.as_bytes()) +} + +// A simple implementation of `% touch path` (ignores existing files) +fn touch(path: &Path) -> io::Result<()> { + match OpenOptions::new().create(true).write(true).open(path) { + Ok(_) => Ok(()), + Err(e) => Err(e), + } +} + +fn main() { + println!("`mkdir a`"); + // Create a directory, returns `io::Result<()>` + match fs::create_dir("a") { + Err(why) => println!("! {:?}", why.kind()), + Ok(_) => {}, + } + + println!("`echo hello > a/b.txt`"); + // The previous match can be simplified using the `unwrap_or_else` method + echo("hello", &Path::new("a/b.txt")).unwrap_or_else(|why| { + println!("! {:?}", why.kind()); + }); + + println!("`mkdir -p a/c/d`"); + // Recursively create a directory, returns `io::Result<()>` + fs::create_dir_all("a/c/d").unwrap_or_else(|why| { + println!("! {:?}", why.kind()); + }); + + println!("`touch a/c/e.txt`"); + touch(&Path::new("a/c/e.txt")).unwrap_or_else(|why| { + println!("! {:?}", why.kind()); + }); + + println!("`ln -s ../b.txt a/c/b.txt`"); + // Create a symbolic link, returns `io::Result<()>` + if cfg!(target_family = "unix") { + unix::fs::symlink("../b.txt", "a/c/b.txt").unwrap_or_else(|why| { + println!("! {:?}", why.kind()); + }); + } + + println!("`cat a/c/b.txt`"); + match cat(&Path::new("a/c/b.txt")) { + Err(why) => println!("! {:?}", why.kind()), + Ok(s) => println!("> {}", s), + } + + println!("`ls a`"); + // Read the contents of a directory, returns `io::Result>` + match fs::read_dir("a") { + Err(why) => println!("! {:?}", why.kind()), + Ok(paths) => for path in paths { + println!("> {:?}", path.unwrap().path()); + }, + } + + println!("`rm a/c/e.txt`"); + // Remove a file, returns `io::Result<()>` + fs::remove_file("a/c/e.txt").unwrap_or_else(|why| { + println!("! {:?}", why.kind()); + }); + + println!("`rmdir a/c/d`"); + // Remove an empty directory, returns `io::Result<()>` + fs::remove_dir("a/c/d").unwrap_or_else(|why| { + println!("! {:?}", why.kind()); + }); +} + +``` + +Here's the expected successful output: + +```shell +$ rustc fs.rs && ./fs +`mkdir a` +`echo hello > a/b.txt` +`mkdir -p a/c/d` +`touch a/c/e.txt` +`ln -s ../b.txt a/c/b.txt` +`cat a/c/b.txt` +> hello +`ls a` +> "a/b.txt" +> "a/c" +`rm a/c/e.txt` +`rmdir a/c/d` +``` + +And the final state of the `a` directory is: + +```shell +$ tree a +a +|-- b.txt +`-- c + `-- b.txt -> ../b.txt + +1 directory, 2 files +``` + +An alternative way to define the function `cat` is with `?` notation: + +```rust,ignore +fn cat(path: &Path) -> io::Result { + let mut f = File::open(path)?; + let mut s = String::new(); + f.read_to_string(&mut s)?; + Ok(s) +} +``` + +### See also: + +[`cfg!`][cfg] + +[cfg]: ../attribute/cfg.md diff --git a/src/std_misc/path.md b/src/std_misc/path.md new file mode 100644 index 0000000000..eb83df8e10 --- /dev/null +++ b/src/std_misc/path.md @@ -0,0 +1,46 @@ +# Path + +The `Path` struct represents file paths in the underlying filesystem. There are +two flavors of `Path`: `posix::Path`, for UNIX-like systems, and +`windows::Path`, for Windows. The prelude exports the appropriate +platform-specific `Path` variant. + +A `Path` can be created from an `OsStr`, and provides several methods to get +information from the file/directory the path points to. + +Note that a `Path` is *not* internally represented as an UTF-8 string, but +instead is stored as a vector of bytes (`Vec`). Therefore, converting a +`Path` to a `&str` is *not* free and may fail (an `Option` is returned). + +```rust,editable +use std::path::Path; + +fn main() { + // Create a `Path` from an `&'static str` + let path = Path::new("."); + + // The `display` method returns a `Show`able structure + let _display = path.display(); + + // `join` merges a path with a byte container using the OS specific + // separator, and returns the new path + let new_path = path.join("a").join("b"); + + // Convert the path into a string slice + match new_path.to_str() { + None => panic!("new path is not a valid UTF-8 sequence"), + Some(s) => println!("new path is {}", s), + } +} + +``` + +Be sure to check at other `Path` methods (`posix::Path` or `windows::Path`) and +the `Metadata` struct. + +### See also: + +[OsStr][1] and [Metadata][2]. + +[1]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html +[2]: https://doc.rust-lang.org/std/fs/struct.Metadata.html diff --git a/src/std_misc/process.md b/src/std_misc/process.md new file mode 100644 index 0000000000..9c9423090b --- /dev/null +++ b/src/std_misc/process.md @@ -0,0 +1,29 @@ +# Child processes + +The `process::Output` struct represents the output of a finished child process, +and the `process::Command` struct is a process builder. + +```rust,editable,ignore +use std::process::Command; + +fn main() { + let output = Command::new("rustc") + .arg("--version") + .output().unwrap_or_else(|e| { + panic!("failed to execute process: {}", e) + }); + + if output.status.success() { + let s = String::from_utf8_lossy(&output.stdout); + + print!("rustc succeeded and stdout was:\n{}", s); + } else { + let s = String::from_utf8_lossy(&output.stderr); + + print!("rustc failed and stderr was:\n{}", s); + } +} +``` + +(You are encouraged to try the previous example with an incorrect flag passed +to `rustc`) diff --git a/src/std_misc/process/pipe.md b/src/std_misc/process/pipe.md new file mode 100644 index 0000000000..fb0be0ea11 --- /dev/null +++ b/src/std_misc/process/pipe.md @@ -0,0 +1,46 @@ +# Pipes + +The `std::Child` struct represents a running child process, and exposes the +`stdin`, `stdout` and `stderr` handles for interaction with the underlying +process via pipes. + +```rust,ignore +use std::io::prelude::*; +use std::process::{Command, Stdio}; + +static PANGRAM: &'static str = +"the quick brown fox jumped over the lazy dog\n"; + +fn main() { + // Spawn the `wc` command + let process = match Command::new("wc") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() { + Err(why) => panic!("couldn't spawn wc: {}", why), + Ok(process) => process, + }; + + // Write a string to the `stdin` of `wc`. + // + // `stdin` has type `Option`, but since we know this instance + // must have one, we can directly `unwrap` it. + match process.stdin.unwrap().write_all(PANGRAM.as_bytes()) { + Err(why) => panic!("couldn't write to wc stdin: {}", why), + Ok(_) => println!("sent pangram to wc"), + } + + // Because `stdin` does not live after the above calls, it is `drop`ed, + // and the pipe is closed. + // + // This is very important, otherwise `wc` wouldn't start processing the + // input we just sent. + + // The `stdout` field also has type `Option` so must be unwrapped. + let mut s = String::new(); + match process.stdout.unwrap().read_to_string(&mut s) { + Err(why) => panic!("couldn't read wc stdout: {}", why), + Ok(_) => print!("wc responded with:\n{}", s), + } +} +``` diff --git a/src/std_misc/process/wait.md b/src/std_misc/process/wait.md new file mode 100644 index 0000000000..ea7dd54a86 --- /dev/null +++ b/src/std_misc/process/wait.md @@ -0,0 +1,21 @@ +# Wait + +If you'd like to wait for a `process::Child` to finish, you must call +`Child::wait`, which will return a `process::ExitStatus`. + +```rust,ignore +use std::process::Command; + +fn main() { + let mut child = Command::new("sleep").arg("5").spawn().unwrap(); + let _result = child.wait().unwrap(); + + println!("reached end of main"); +} +``` + +```bash +$ rustc wait.rs && ./wait +# `wait` keeps running for 5 seconds until the `sleep 5` command finishes +reached end of main +``` diff --git a/src/std_misc/threads.md b/src/std_misc/threads.md new file mode 100644 index 0000000000..2f37d1c4a3 --- /dev/null +++ b/src/std_misc/threads.md @@ -0,0 +1,30 @@ +# Threads + +Rust provides a mechanism for spawning native OS threads via the `spawn` +function, the argument of this function is a moving closure. + +```rust,editable +use std::thread; + +const NTHREADS: u32 = 10; + +// This is the `main` thread +fn main() { + // Make a vector to hold the children which are spawned. + let mut children = vec![]; + + for i in 0..NTHREADS { + // Spin up another thread + children.push(thread::spawn(move || { + println!("this is thread number {}", i); + })); + } + + for child in children { + // Wait for the thread to finish. Returns a result. + let _ = child.join(); + } +} +``` + +These threads will be scheduled by the OS. diff --git a/src/std_misc/threads/testcase_mapreduce.md b/src/std_misc/threads/testcase_mapreduce.md new file mode 100644 index 0000000000..641dc227cd --- /dev/null +++ b/src/std_misc/threads/testcase_mapreduce.md @@ -0,0 +1,144 @@ +# Testcase: map-reduce + +Rust makes it very easy to parallelise data processing, without many of the headaches traditionally associated with such an attempt. + +The standard library provides great threading primitives out of the box. +These, combined with Rust's concept of Ownership and aliasing rules, automatically prevent +data races. + +The aliasing rules (one writable reference XOR many readable references) automatically prevent +you from manipulating state that is visible to other threads. (Where synchronisation is needed, +there are synchronisation +primitives like `Mutex`es or `Channel`s.) + +In this example, we will calculate the sum of all digits in a block of numbers. +We will do this by parcelling out chunks of the block into different threads. Each thread will sum +its tiny block of digits, and subsequently we will sum the intermediate sums produced by each +thread. + +Note that, although we're passing references across thread boundaries, Rust understands that we're +only passing read-only references, and that thus no unsafety or data races can occur. Because +we're `move`-ing the data segments into the thread, Rust will also ensure the data is kept alive +until the threads exit, so no dangling pointers occur. + +```rust,editable +use std::thread; + +// This is the `main` thread +fn main() { + + // This is our data to process. + // We will calculate the sum of all digits via a threaded map-reduce algorithm. + // Each whitespace separated chunk will be handled in a different thread. + // + // TODO: see what happens to the output if you insert spaces! + let data = "86967897737416471853297327050364959 +11861322575564723963297542624962850 +70856234701860851907960690014725639 +38397966707106094172783238747669219 +52380795257888236525459303330302837 +58495327135744041048897885734297812 +69920216438980873548808413720956532 +16278424637452589860345374828574668"; + + // Make a vector to hold the child-threads which we will spawn. + let mut children = vec![]; + + /************************************************************************* + * "Map" phase + * + * Divide our data into segments, and apply initial processing + ************************************************************************/ + + // split our data into segments for individual calculation + // each chunk will be a reference (&str) into the actual data + let chunked_data = data.split_whitespace(); + + // Iterate over the data segments. + // .enumerate() adds the current loop index to whatever is iterated + // the resulting tuple "(index, element)" is then immediately + // "destructured" into two variables, "i" and "data_segment" with a + // "destructuring assignment" + for (i, data_segment) in chunked_data.enumerate() { + println!("data segment {} is \"{}\"", i, data_segment); + + // Process each data segment in a separate thread + // + // spawn() returns a handle to the new thread, + // which we MUST keep to access the returned value + // + // 'move || -> u32' is syntax for a closure that: + // * takes no arguments ('||') + // * takes ownership of its captured variables ('move') and + // * returns an unsigned 32-bit integer ('-> u32') + // + // Rust is smart enough to infer the '-> u32' from + // the closure itself so we could have left that out. + // + // TODO: try removing the 'move' and see what happens + children.push(thread::spawn(move || -> u32 { + // Calculate the intermediate sum of this segment: + let result = data_segment + // iterate over the characters of our segment.. + .chars() + // .. convert text-characters to their number value.. + .map(|c| c.to_digit(10).expect("should be a digit")) + // .. and sum the resulting iterator of numbers + .sum(); + + // println! locks stdout, so no text-interleaving occurs + println!("processed segment {}, result={}", i, result); + + // "return" not needed, because Rust is an "expression language", the + // last evaluated expression in each block is automatically its value. + result + + })); + } + + + /************************************************************************* + * "Reduce" phase + * + * Collect our intermediate results, and combine them into a final result + ************************************************************************/ + + // combine each thread's intermediate results into a single final sum. + // + // we use the "turbofish" ::<> to provide sum() with a type hint. + // + // TODO: try without the turbofish, by instead explicitly + // specifying the type of final_result + let final_result = children.into_iter().map(|c| c.join().unwrap()).sum::(); + + println!("Final sum result: {}", final_result); +} + + +``` + +### Assignments +It is not wise to let our number of threads depend on user inputted data. +What if the user decides to insert a lot of spaces? Do we _really_ want to spawn 2,000 threads? +Modify the program so that the data is always chunked into a limited number of chunks, +defined by a static constant at the beginning of the program. + +### See also: +* [Threads][thread] +* [vectors][vectors] and [iterators][iterators] +* [closures][closures], [move][move] semantics and [`move` closures][move_closure] +* [destructuring][destructuring] assignments +* [turbofish notation][turbofish] to help type inference +* [unwrap vs. expect][unwrap] +* [enumerate][enumerate] + +[thread]: ../threads.md +[vectors]: ../../std/vec.md +[iterators]: ../../trait/iter.md +[destructuring]: https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html#destructuring-to-break-apart-values +[closures]: ../../fn/closures.md +[move]: ../../scope/move.md +[move_closure]: https://doc.rust-lang.org/book/ch13-01-closures.html#closures-can-capture-their-environment +[turbofish]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect +[unwrap]: ../../error/option_unwrap.md +[enumerate]: https://doc.rust-lang.org/book/loops.html#enumerate diff --git a/src/testing.md b/src/testing.md new file mode 100644 index 0000000000..6de0ca63fd --- /dev/null +++ b/src/testing.md @@ -0,0 +1,26 @@ +# Testing + +Rust is a programming language that cares a lot about correctness and it +includes support for writing software tests within the language itself. + +Testing comes in three styles: + +* [Unit][unit] testing. +* [Doc][doc] testing. +* [Integration][integration] testing. + +Also Rust has support for specifying additional dependencies for tests: + +* [Dev-dependencies][dev-dependencies] + +## See Also + +* [The Book][doc-testing] chapter on testing +* [API Guidelines][doc-nursery] on doc-testing + +[unit]: testing/unit_testing.md +[doc]: testing/doc_testing.md +[integration]: testing/integration_testing.md +[dev-dependencies]: testing/dev_dependencies.md +[doc-testing]: https://doc.rust-lang.org/book/ch11-00-testing.html +[doc-nursery]: https://rust-lang-nursery.github.io/api-guidelines/documentation.html diff --git a/src/testing/dev_dependencies.md b/src/testing/dev_dependencies.md new file mode 100644 index 0000000000..3d4ccde556 --- /dev/null +++ b/src/testing/dev_dependencies.md @@ -0,0 +1,43 @@ +# Development dependencies + +Sometimes there is a need to have dependencies for tests (or examples, +or benchmarks) only. Such dependencies are added to `Cargo.toml` in the +`[dev-dependencies]` section. These dependencies are not propagated to other +packages which depend on this package. + +One such example is using a crate that extends standard `assert!` macros. +File `Cargo.toml`: + +```toml +# standard crate data is left out +[dev-dependencies] +pretty_assertions = "0.4.0" +``` + +File `src/lib.rs`: + +```rust,ignore +// externing crate for test-only use +#[cfg(test)] +#[macro_use] +extern crate pretty_assertions; + +pub fn add(a: i32, b: i32) -> i32 { + a + b +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_add() { + assert_eq!(add(2, 3), 5); + } +} +``` + +## See Also +[Cargo][cargo] docs on specifying dependencies. + +[cargo]: http://doc.crates.io/specifying-dependencies.html diff --git a/src/testing/doc_testing.md b/src/testing/doc_testing.md new file mode 100644 index 0000000000..642cbe8a58 --- /dev/null +++ b/src/testing/doc_testing.md @@ -0,0 +1,110 @@ +# Documentation testing + +The primary way of documenting a Rust project is through annotating the source +code. Documentation comments are written in [markdown] and support code +blocks in them. Rust takes care about correctness, so these code blocks are +compiled and used as tests. + +```rust,ignore +/// First line is a short summary describing function. +/// +/// The next lines present detailed documentation. Code blocks start with +/// triple backquotes and have implicit `fn main()` inside +/// and `extern crate `. Assume we're testing `doccomments` crate: +/// +/// ``` +/// let result = doccomments::add(2, 3); +/// assert_eq!(result, 5); +/// ``` +pub fn add(a: i32, b: i32) -> i32 { + a + b +} + +/// Usually doc comments may include sections "Examples", "Panics" and "Failures". +/// +/// The next function divides two numbers. +/// +/// # Examples +/// +/// ``` +/// let result = doccomments::div(10, 2); +/// assert_eq!(result, 5); +/// ``` +/// +/// # Panics +/// +/// The function panics if the second argument is zero. +/// +/// ```rust,should_panic +/// // panics on division by zero +/// doccomments::div(10, 0); +/// ``` +pub fn div(a: i32, b: i32) -> i32 { + if b == 0 { + panic!("Divide-by-zero error"); + } + + a / b +} +``` + +Tests can be run with `cargo test`: + +```shell +$ cargo test +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests doccomments + +running 3 tests +test src/lib.rs - add (line 7) ... ok +test src/lib.rs - div (line 21) ... ok +test src/lib.rs - div (line 31) ... ok + +test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out +``` + +## Motivation behind documentation tests + +The main purpose of documentation tests is to serve as examples that exercise +the functionality, which is one of the most important +[guidelines][question-instead-of-unwrap]. It allows using examples from docs as +complete code snippets. But using `?` makes compilation fail since `main` +returns `unit`. The ability to hide some source lines from documentation comes +to the rescue: one may write `fn try_main() -> Result<(), ErrorType>`, hide it and +`unwrap` it in hidden `main`. Sounds complicated? Here's an example: + +```rust,ignore +/// Using hidden `try_main` in doc tests. +/// +/// ``` +/// # // hidden lines start with `#` symbol, but they're still compileable! +/// # fn try_main() -> Result<(), String> { // line that wraps the body shown in doc +/// let res = try::try_div(10, 2)?; +/// # Ok(()) // returning from try_main +/// # } +/// # fn main() { // starting main that'll unwrap() +/// # try_main().unwrap(); // calling try_main and unwrapping +/// # // so that test will panic in case of error +/// # } +/// ``` +pub fn try_div(a: i32, b: i32) -> Result { + if b == 0 { + Err(String::from("Divide-by-zero")) + } else { + Ok(a / b) + } +} +``` + +## See Also + +* [RFC505][RFC505] on documentation style +* [API Guidelines][doc-nursery] on documentation guidelines + +[doc-nursery]: https://rust-lang-nursery.github.io/api-guidelines/documentation.html +[markdown]: https://daringfireball.net/projects/markdown/ +[RFC505]: https://github.com/rust-lang/rfcs/blob/master/text/0505-api-comment-conventions.md +[question-instead-of-unwrap]: https://rust-lang-nursery.github.io/api-guidelines/documentation.html#examples-use--not-try-not-unwrap-c-question-mark diff --git a/src/testing/integration_testing.md b/src/testing/integration_testing.md new file mode 100644 index 0000000000..0ac77588c3 --- /dev/null +++ b/src/testing/integration_testing.md @@ -0,0 +1,81 @@ +# Integration testing + +[Unit tests][unit] are testing one module in isolation at a time: they're small +and can test private code. Integration tests are external to your crate and use +only its public interface in the same way any other code would. Their purpose is +to test that many parts of your library work correctly together. + +Cargo looks for integration tests in `tests` directory next to `src`. + +File `src/lib.rs`: + +```rust,ignore +// Define this in a crate called `adder`. +pub fn add(a: i32, b: i32) -> i32 { + a + b +} +``` + +File with test: `tests/integration_test.rs`: + +```rust,ignore +#[test] +fn test_add() { + assert_eq!(adder::add(3, 2), 5); +} +``` + +Running tests with `cargo test` command: + +```shell +$ cargo test +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Running target/debug/deps/integration_test-bcd60824f5fbfe19 + +running 1 test +test test_add ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests adder + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out +``` + +Each Rust source file in the `tests` directory is compiled as a separate crate. One +way of sharing some code between integration tests is making a module with public +functions, importing and using it within tests. + +File `tests/common.rs`: + +```rust,ignore +pub fn setup() { + // some setup code, like creating required files/directories, starting + // servers, etc. +} +``` + +File with test: `tests/integration_test.rs` + +```rust,ignore +// importing common module. +mod common; + +#[test] +fn test_add() { + // using common code. + common::setup(); + assert_eq!(adder::add(3, 2), 5); +} +``` + +Modules with common code follow the ordinary [modules][mod] rules, so it's ok to +create common module as `tests/common/mod.rs`. + +[unit]: unit_testing.md +[mod]: ../mod.md diff --git a/src/testing/unit_testing.md b/src/testing/unit_testing.md new file mode 100644 index 0000000000..cd87706640 --- /dev/null +++ b/src/testing/unit_testing.md @@ -0,0 +1,262 @@ +# Unit testing + +Tests are Rust functions that verify that the non-test code is functioning in +the expected manner. The bodies of test functions typically perform some setup, +run the code we want to test, then assert whether the results are what we +expect. + +Most unit tests go into a `tests` [mod][mod] with the `#[cfg(test)]` [attribute][attribute]. +Test functions are marked with the `#[test]` attribute. + +Tests fail when something in the test function [panics][panic]. There are some +helper [macros][macros]: + +* `assert!(expression)` - panics if expression evaluates to `false`. +* `assert_eq!(left, right)` and `assert_ne!(left, right)` - testing left and + right expressions for equality and inequality respectively. + +```rust,ignore +pub fn add(a: i32, b: i32) -> i32 { + a + b +} + +// This is a really bad adding function, its purpose is to fail in this +// example. +#[allow(dead_code)] +fn bad_add(a: i32, b: i32) -> i32 { + a - b +} + +#[cfg(test)] +mod tests { + // Note this useful idiom: importing names from outer (for mod tests) scope. + use super::*; + + #[test] + fn test_add() { + assert_eq!(add(1, 2), 3); + } + + #[test] + fn test_bad_add() { + // This assert would fire and test will fail. + // Please note, that private functions can be tested too! + assert_eq!(bad_add(1, 2), 3); + } +} +``` + +Tests can be run with `cargo test`. + +```shell +$ cargo test + +running 2 tests +test tests::test_bad_add ... FAILED +test tests::test_add ... ok + +failures: + +---- tests::test_bad_add stdout ---- + thread 'tests::test_bad_add' panicked at 'assertion failed: `(left == right)` + left: `-1`, + right: `3`', src/lib.rs:21:8 +note: Run with `RUST_BACKTRACE=1` for a backtrace. + + +failures: + tests::test_bad_add + +test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out +``` + +## Tests and `?` +None of the previous unit test examples had a return type. But in Rust 2018, +your unit tests can return `Result<()>`, which lets you use `?` in them! This +can make them much more concise. + +```rust,editable +fn sqrt(number: f64) -> Result { + if number >= 0.0 { + Ok(number.powf(0.5)) + } else { + Err("negative floats don't have square roots".to_owned()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_sqrt() -> Result<(), String> { + let x = 4.0; + assert_eq!(sqrt(x)?.powf(2.0), x); + Ok(()) + } +} +``` + +See ["The Edition Guide"][editionguide] for more details. + +## Testing panics + +To check functions that should panic under certain circumstances, use attribute +`#[should_panic]`. This attribute accepts optional parameter `expected = ` with +the text of the panic message. If your function can panic in multiple ways, it helps +make sure your test is testing the correct panic. + +```rust,ignore +pub fn divide_non_zero_result(a: u32, b: u32) -> u32 { + if b == 0 { + panic!("Divide-by-zero error"); + } else if a < b { + panic!("Divide result is zero"); + } + a / b +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_divide() { + assert_eq!(divide_non_zero_result(10, 2), 5); + } + + #[test] + #[should_panic] + fn test_any_panic() { + divide_non_zero_result(1, 0); + } + + #[test] + #[should_panic(expected = "Divide result is zero")] + fn test_specific_panic() { + divide_non_zero_result(1, 10); + } +} +``` + +Running these tests gives us: + +```shell +$ cargo test + +running 3 tests +test tests::test_any_panic ... ok +test tests::test_divide ... ok +test tests::test_specific_panic ... ok + +test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests tmp-test-should-panic + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out +``` + +## Running specific tests + +To run specific tests one may specify the test name to `cargo test` command. + +```shell +$ cargo test test_any_panic +running 1 test +test tests::test_any_panic ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out + + Doc-tests tmp-test-should-panic + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out +``` + +To run multiple tests one may specify part of a test name that matches all the +tests that should be run. + +```shell +$ cargo test panic +running 2 tests +test tests::test_any_panic ... ok +test tests::test_specific_panic ... ok + +test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out + + Doc-tests tmp-test-should-panic + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out +``` + +## Ignoring tests + +Tests can be marked with the `#[ignore]` attribute to exclude some tests. Or to run +them with command `cargo test -- --ignored` + +```rust +pub fn add(a: i32, b: i32) -> i32 { + a + b +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_add() { + assert_eq!(add(2, 2), 4); + } + + #[test] + fn test_add_hundred() { + assert_eq!(add(100, 2), 102); + assert_eq!(add(2, 100), 102); + } + + #[test] + #[ignore] + fn ignored_test() { + assert_eq!(add(0, 0), 0); + } +} +``` + +```shell +$ cargo test +running 3 tests +test tests::ignored_test ... ignored +test tests::test_add ... ok +test tests::test_add_hundred ... ok + +test result: ok. 2 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out + + Doc-tests tmp-ignore + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + +$ cargo test -- --ignored +running 1 test +test tests::ignored_test ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests tmp-ignore + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out +``` + +[attribute]: ../attribute.md +[panic]: ../std/panic.md +[macros]: ../macros.md +[mod]: ../mod.md +[editionguide]: https://doc.rust-lang.org/edition-guide/rust-2018/error-handling-and-panics/question-mark-in-main-and-tests.html diff --git a/src/trait.md b/src/trait.md new file mode 100644 index 0000000000..7878d4742b --- /dev/null +++ b/src/trait.md @@ -0,0 +1,80 @@ +# Traits + +A `trait` is a collection of methods defined for an unknown type: +`Self`. They can access other methods declared in the same trait. + +Traits can be implemented for any data type. In the example below, +we define `Animal`, a group of methods. The `Animal` `trait` is +then implemented for the `Sheep` data type, allowing the use of +methods from `Animal` with a `Sheep`. + +```rust,editable +struct Sheep { naked: bool, name: &'static str } + +trait Animal { + // Static method signature; `Self` refers to the implementor type. + fn new(name: &'static str) -> Self; + + // Instance method signatures; these will return a string. + fn name(&self) -> &'static str; + fn noise(&self) -> &'static str; + + // Traits can provide default method definitions. + fn talk(&self) { + println!("{} says {}", self.name(), self.noise()); + } +} + +impl Sheep { + fn is_naked(&self) -> bool { + self.naked + } + + fn shear(&mut self) { + if self.is_naked() { + // Implementor methods can use the implementor's trait methods. + println!("{} is already naked...", self.name()); + } else { + println!("{} gets a haircut!", self.name); + + self.naked = true; + } + } +} + +// Implement the `Animal` trait for `Sheep`. +impl Animal for Sheep { + // `Self` is the implementor type: `Sheep`. + fn new(name: &'static str) -> Sheep { + Sheep { name: name, naked: false } + } + + fn name(&self) -> &'static str { + self.name + } + + fn noise(&self) -> &'static str { + if self.is_naked() { + "baaaaah?" + } else { + "baaaaah!" + } + } + + // Default trait methods can be overridden. + fn talk(&self) { + // For example, we can add some quiet contemplation. + println!("{} pauses briefly... {}", self.name, self.noise()); + } +} + +fn main() { + // Type annotation is necessary in this case. + let mut dolly: Sheep = Animal::new("Dolly"); + // TODO ^ Try removing the type annotations. + + dolly.talk(); + dolly.shear(); + dolly.talk(); +} +``` \ No newline at end of file diff --git a/src/trait/clone.md b/src/trait/clone.md new file mode 100644 index 0000000000..5d6747a47b --- /dev/null +++ b/src/trait/clone.md @@ -0,0 +1,55 @@ +# Clone + +When dealing with resources, the default behavior is to transfer them during +assignments or function calls. However, sometimes we need to make a +copy of the resource as well. + +The [`Clone`][clone] trait helps us do exactly this. Most commonly, we can +use the `.clone()` method defined by the `Clone` trait. + +```rust,editable +// A unit struct without resources +#[derive(Debug, Clone, Copy)] +struct Unit; + +// A tuple struct with resources that implements the `Clone` trait +#[derive(Clone, Debug)] +struct Pair(Box, Box); + +fn main() { + // Instantiate `Unit` + let unit = Unit; + // Copy `Unit`, there are no resources to move + let copied_unit = unit; + + // Both `Unit`s can be used independently + println!("original: {:?}", unit); + println!("copy: {:?}", copied_unit); + + // Instantiate `Pair` + let pair = Pair(Box::new(1), Box::new(2)); + println!("original: {:?}", pair); + + // Move `pair` into `moved_pair`, moves resources + let moved_pair = pair; + println!("moved: {:?}", moved_pair); + + // Error! `pair` has lost its resources + //println!("original: {:?}", pair); + // TODO ^ Try uncommenting this line + + // Clone `moved_pair` into `cloned_pair` (resources are included) + let cloned_pair = moved_pair.clone(); + // Drop the original pair using std::mem::drop + drop(moved_pair); + + // Error! `moved_pair` has been dropped + //println!("copy: {:?}", moved_pair); + // TODO ^ Try uncommenting this line + + // The result from .clone() can still be used! + println!("clone: {:?}", cloned_pair); +} +``` + +[clone]: https://doc.rust-lang.org/std/clone/trait.Clone.html diff --git a/src/trait/derive.md b/src/trait/derive.md new file mode 100644 index 0000000000..4769efe627 --- /dev/null +++ b/src/trait/derive.md @@ -0,0 +1,77 @@ +# Derive + +The compiler is capable of providing basic implementations for some traits via +the `#[derive]` [attribute][attribute]. These traits can still be +manually implemented if a more complex behavior is required. + +The following is a list of derivable traits: +* Comparison traits: + [`Eq`][eq], [`PartialEq`][partial-eq], [`Ord`][ord], [`PartialOrd`][partial-ord]. +* [`Clone`][clone], to create `T` from `&T` via a copy. +* [`Copy`][copy], to give a type 'copy semantics' instead of 'move semantics'. +* [`Hash`][hash], to compute a hash from `&T`. +* [`Default`][default], to create an empty instance of a data type. +* [`Debug`][debug], to format a value using the `{:?}` formatter. + +```rust,editable +// `Centimeters`, a tuple struct that can be compared +#[derive(PartialEq, PartialOrd)] +struct Centimeters(f64); + +// `Inches`, a tuple struct that can be printed +#[derive(Debug)] +struct Inches(i32); + +impl Inches { + fn to_centimeters(&self) -> Centimeters { + let &Inches(inches) = self; + + Centimeters(inches as f64 * 2.54) + } +} + +// `Seconds`, a tuple struct with no additional attributes +struct Seconds(i32); + +fn main() { + let _one_second = Seconds(1); + + // Error: `Seconds` can't be printed; it doesn't implement the `Debug` trait + //println!("One second looks like: {:?}", _one_second); + // TODO ^ Try uncommenting this line + + // Error: `Seconds` can't be compared; it doesn't implement the `PartialEq` trait + //let _this_is_true = (_one_second == _one_second); + // TODO ^ Try uncommenting this line + + let foot = Inches(12); + + println!("One foot equals {:?}", foot); + + let meter = Centimeters(100.0); + + let cmp = + if foot.to_centimeters() < meter { + "smaller" + } else { + "bigger" + }; + + println!("One foot is {} than one meter.", cmp); +} +``` + +### See also: +[`derive`][derive] + +[attribute]: ../attribute.md +[eq]: https://doc.rust-lang.org/std/cmp/trait.Eq.html +[partial-eq]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html +[ord]: https://doc.rust-lang.org/std/cmp/trait.Ord.html +[partial-ord]: https://doc.rust-lang.org/std/cmp/trait.PartialOrd.html +[clone]: https://doc.rust-lang.org/std/clone/trait.Clone.html +[copy]: https://doc.rust-lang.org/core/marker/trait.Copy.html +[hash]: https://doc.rust-lang.org/std/hash/trait.Hash.html +[default]: https://doc.rust-lang.org/std/default/trait.Default.html +[debug]: https://doc.rust-lang.org/std/fmt/trait.Debug.html +[derive]: https://doc.rust-lang.org/reference/attributes.html#derive diff --git a/src/trait/disambiguating.md b/src/trait/disambiguating.md new file mode 100644 index 0000000000..c893e9dc8d --- /dev/null +++ b/src/trait/disambiguating.md @@ -0,0 +1,62 @@ +# Disambiguating overlapping traits + +A type can implement many different traits. What if two traits both require the same name? For example, many traits might have a method named `get()`. They might even have different return types! + +Good news: because each trait implementation gets its own `impl` block, it's +clear which trait's `get` method you're implementing. + +What about when it comes time to _call_ those methods? To disambiguate between +them, we have to use Fully Qualified Syntax. + +```rust,editable +trait UsernameWidget { + // Get the selected username out of this widget + fn get(&self) -> String; +} + +trait AgeWidget { + // Get the selected age out of this widget + fn get(&self) -> u8; +} + +// A form with both a UsernameWidget and an AgeWidget +struct Form { + username: String, + age: u8, +} + +impl UsernameWidget for Form { + fn get(&self) -> String { + self.username.clone() + } +} + +impl AgeWidget for Form { + fn get(&self) -> u8 { + self.age + } +} + +fn main() { + let form = Form{ + username: "rustacean".to_owned(), + age: 28, + }; + + // If you uncomment this line, you'll get an error saying + // "multiple `get` found". Because, after all, there are multiple methods + // named `get`. + // println!("{}", form.get()); + + let username =

::get(&form); + assert_eq!("rustacean".to_owned(), username); + let age = ::get(&form); + assert_eq!(28, age); +} +``` + +### See also: + +[The Rust Programming Language chapter on Fully Qualified syntax][trpl_fqsyntax] + +[trpl_fqsyntax]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#fully-qualified-syntax-for-disambiguation-calling-methods-with-the-same-name diff --git a/examples/drop/drop.rs b/src/trait/drop.md similarity index 55% rename from examples/drop/drop.rs rename to src/trait/drop.md index 5cae6bd099..7aeaca7173 100644 --- a/examples/drop/drop.rs +++ b/src/trait/drop.md @@ -1,9 +1,22 @@ +# Drop + +The [`Drop`][Drop] trait only has one method: `drop`, which is called automatically +when an object goes out of scope. The main use of the `Drop` trait is to free the +resources that the implementor instance owns. + +`Box`, `Vec`, `String`, `File`, and `Process` are some examples of types that +implement the `Drop` trait to free resources. The `Drop` trait can also be +manually implemented for any custom data type. + +The following example adds a print to console to the `drop` function to announce +when it is called. + +```rust,editable struct Droppable { name: &'static str, } -// This `drop` implementation doesn't free resources; but instead reports its -// usage via a print to the console +// This trivial implementation of `drop` adds a print to console. impl Drop for Droppable { fn drop(&mut self) { println!("> Dropping {}", self.name); @@ -39,3 +52,6 @@ fn main() { // `_a` *won't* be `drop`ed again here, because it already has been // (manually) `drop`ed } +``` + +[Drop]: https://doc.rust-lang.org/std/ops/trait.Drop.html \ No newline at end of file diff --git a/src/trait/dyn.md b/src/trait/dyn.md new file mode 100644 index 0000000000..5b2f8c2f3e --- /dev/null +++ b/src/trait/dyn.md @@ -0,0 +1,47 @@ +# Returning Traits with `dyn` + +The Rust compiler needs to know how much space every function's return type requires. This means all your functions have to return a concrete type. Unlike other languages, if you have a trait like `Animal`, you can't write a function that returns `Animal`, because its different implementations will need different amounts of memory. + +However, there's an easy workaround. Instead of returning a trait object directly, our functions return a `Box` which _contains_ some `Animal`. A `box` is just a reference to some memory in the heap. Because a reference has a statically-known size, and the compiler can guarantee it points to a heap-allocated `Animal`, we can return a trait from our function! + +Rust tries to be as explicit as possible whenever it allocates memory on the heap. So if your function returns a pointer-to-trait-on-heap in this way, you need to write the return type with the `dyn` keyword, e.g. `Box`. + +```rust,editable +struct Sheep {} +struct Cow {} + +trait Animal { + // Instance method signature + fn noise(&self) -> &'static str; +} + +// Implement the `Animal` trait for `Sheep`. +impl Animal for Sheep { + fn noise(&self) -> &'static str { + "baaaaah!" + } +} + +// Implement the `Animal` trait for `Cow`. +impl Animal for Cow { + fn noise(&self) -> &'static str { + "moooooo!" + } +} + +// Returns some struct that implements Animal, but we don't know which one at compile time. +fn random_animal(random_number: f64) -> Box { + if random_number < 0.5 { + Box::new(Sheep {}) + } else { + Box::new(Cow {}) + } +} + +fn main() { + let random_number = 0.234; + let animal = random_animal(random_number); + println!("You've randomly chosen an animal, and it says {}", animal.noise()); +} + +``` \ No newline at end of file diff --git a/src/trait/impl_trait.md b/src/trait/impl_trait.md new file mode 100644 index 0000000000..7b87bd2e9c --- /dev/null +++ b/src/trait/impl_trait.md @@ -0,0 +1,71 @@ +# `impl Trait` + +If your function returns a type that implements `MyTrait`, you can write its +return type as `-> impl MyTrait`. This can help simplify your type signatures quite a lot! + +```rust,editable +use std::iter; +use std::vec::IntoIter; + +// This function combines two `Vec` and returns an iterator over it. +// Look how complicated its return type is! +fn combine_vecs_explicit_return_type( + v: Vec, + u: Vec, +) -> iter::Cycle, IntoIter>> { + v.into_iter().chain(u.into_iter()).cycle() +} + +// This is the exact same function, but its return type uses `impl Trait`. +// Look how much simpler it is! +fn combine_vecs( + v: Vec, + u: Vec, +) -> impl Iterator { + v.into_iter().chain(u.into_iter()).cycle() +} + +fn main() { + let v1 = vec![1, 2, 3]; + let v2 = vec![4, 5]; + let mut v3 = combine_vecs(v1, v2); + assert_eq!(Some(1), v3.next()); + assert_eq!(Some(2), v3.next()); + assert_eq!(Some(3), v3.next()); + assert_eq!(Some(4), v3.next()); + assert_eq!(Some(5), v3.next()); + println!("all done"); +} +``` + +More importantly, some Rust types can't be written out. For example, every +closure has its own unnamed concrete type. Before `impl Trait` syntax, you had +to allocate on the heap in order to return a closure. But now you can do it all +statically, like this: + +```rust,editable +// Returns a function that adds `y` to its input +fn make_adder_function(y: i32) -> impl Fn(i32) -> i32 { + let closure = move |x: i32| { x + y }; + closure +} + +fn main() { + let plus_one = make_adder_function(1); + assert_eq!(plus_one(2), 3); +} +``` + +You can also use `impl Trait` to return an iterator that uses `map` or `filter` +closures! This makes using `map` and `filter` easier. Because closure types don't +have names, you can't write out an explicit return type if your function returns +iterators with closures. But with `impl Trait` you can do this easily: + +```rust,editable +fn double_positives<'a>(numbers: &'a Vec) -> impl Iterator + 'a { + numbers + .iter() + .filter(|x| x > &&0) + .map(|x| x * 2) +} +``` diff --git a/src/trait/iter.md b/src/trait/iter.md new file mode 100644 index 0000000000..2af4fcb784 --- /dev/null +++ b/src/trait/iter.md @@ -0,0 +1,87 @@ +# Iterators + +The [`Iterator`][iter] trait is used to implement iterators over collections such as arrays. + +The trait requires only a method to be defined for the `next` element, +which may be manually defined in an `impl` block or automatically +defined (as in arrays and ranges). + +As a point of convenience for common situations, the `for` construct +turns some collections into iterators using the [`.into_iter()`][intoiter] method. + +```rust,editable +struct Fibonacci { + curr: u32, + next: u32, +} + +// Implement `Iterator` for `Fibonacci`. +// The `Iterator` trait only requires a method to be defined for the `next` element. +impl Iterator for Fibonacci { + // We can refer to this type using Self::Item + type Item = u32; + + // Here, we define the sequence using `.curr` and `.next`. + // The return type is `Option`: + // * When the `Iterator` is finished, `None` is returned. + // * Otherwise, the next value is wrapped in `Some` and returned. + // We use Self::Item in the return type, so we can change + // the type without having to update the function signatures. + fn next(&mut self) -> Option { + let new_next = self.curr + self.next; + + self.curr = self.next; + self.next = new_next; + + // Since there's no endpoint to a Fibonacci sequence, the `Iterator` + // will never return `None`, and `Some` is always returned. + Some(self.curr) + } +} + +// Returns a Fibonacci sequence generator +fn fibonacci() -> Fibonacci { + Fibonacci { curr: 0, next: 1 } +} + +fn main() { + // `0..3` is an `Iterator` that generates: 0, 1, and 2. + let mut sequence = 0..3; + + println!("Four consecutive `next` calls on 0..3"); + println!("> {:?}", sequence.next()); + println!("> {:?}", sequence.next()); + println!("> {:?}", sequence.next()); + println!("> {:?}", sequence.next()); + + // `for` works through an `Iterator` until it returns `None`. + // Each `Some` value is unwrapped and bound to a variable (here, `i`). + println!("Iterate through 0..3 using `for`"); + for i in 0..3 { + println!("> {}", i); + } + + // The `take(n)` method reduces an `Iterator` to its first `n` terms. + println!("The first four terms of the Fibonacci sequence are: "); + for i in fibonacci().take(4) { + println!("> {}", i); + } + + // The `skip(n)` method shortens an `Iterator` by dropping its first `n` terms. + println!("The next four terms of the Fibonacci sequence are: "); + for i in fibonacci().skip(4).take(4) { + println!("> {}", i); + } + + let array = [1u32, 3, 3, 7]; + + // The `iter` method produces an `Iterator` over an array/slice. + println!("Iterate the following array {:?}", &array); + for i in array.iter() { + println!("> {}", i); + } +} +``` + +[intoiter]: https://doc.rust-lang.org/std/iter/trait.IntoIterator.html +[iter]: https://doc.rust-lang.org/core/iter/trait.Iterator.html diff --git a/src/trait/ops.md b/src/trait/ops.md new file mode 100644 index 0000000000..3d4aa3bc8e --- /dev/null +++ b/src/trait/ops.md @@ -0,0 +1,61 @@ +# Operator Overloading + +In Rust, many of the operators can be overloaded via traits. That is, some operators can +be used to accomplish different tasks based on their input arguments. This is possible +because operators are syntactic sugar for method calls. For example, the `+` operator in +`a + b` calls the `add` method (as in `a.add(b)`). This `add` method is part of the `Add` +trait. Hence, the `+` operator can be used by any implementor of the `Add` trait. + +A list of the traits, such as `Add`, that overload operators can be found in [`core::ops`][ops]. + +```rust,editable +use std::ops; + +struct Foo; +struct Bar; + +#[derive(Debug)] +struct FooBar; + +#[derive(Debug)] +struct BarFoo; + +// The `std::ops::Add` trait is used to specify the functionality of `+`. +// Here, we make `Add` - the trait for addition with a RHS of type `Bar`. +// The following block implements the operation: Foo + Bar = FooBar +impl ops::Add for Foo { + type Output = FooBar; + + fn add(self, _rhs: Bar) -> FooBar { + println!("> Foo.add(Bar) was called"); + + FooBar + } +} + +// By reversing the types, we end up implementing non-commutative addition. +// Here, we make `Add` - the trait for addition with a RHS of type `Foo`. +// This block implements the operation: Bar + Foo = BarFoo +impl ops::Add for Bar { + type Output = BarFoo; + + fn add(self, _rhs: Foo) -> BarFoo { + println!("> Bar.add(Foo) was called"); + + BarFoo + } +} + +fn main() { + println!("Foo + Bar = {:?}", Foo + Bar); + println!("Bar + Foo = {:?}", Bar + Foo); +} +``` + +### See Also + +[Add][add], [Syntax Index][syntax] + +[add]: https://doc.rust-lang.org/core/ops/trait.Add.html +[ops]: https://doc.rust-lang.org/core/ops/ +[syntax]:https://doc.rust-lang.org/book/appendix-02-operators.html diff --git a/src/trait/supertraits.md b/src/trait/supertraits.md new file mode 100644 index 0000000000..5a735af1ae --- /dev/null +++ b/src/trait/supertraits.md @@ -0,0 +1,44 @@ +# Supertraits + +Rust doesn't have "inheritance", but you can define a trait as being a superset +of another trait. For example: + +```rust,editable +trait Person { + fn name(&self) -> String; +} + +// Person is a supertrait of Student. +// Implementing Student requires you to also impl Person. +trait Student: Person { + fn university(&self) -> String; +} + +trait Programmer { + fn fav_language(&self) -> String; +} + +// CompSciStudent (computer science student) is a subtrait of both Programmer +// and Student. Implementing CompSciStudent requires you to impl both supertraits. +trait CompSciStudent: Programmer + Student { + fn git_username(&self) -> String; +} + +fn comp_sci_student_greeting(student: &dyn CompSciStudent) -> String { + format!( + "My name is {} and I attend {}. My favorite language is {}. My Git username is {}", + student.name(), + student.university(), + student.fav_language(), + student.git_username() + ) +} + +fn main() {} +``` + +### See also: + +[The Rust Programming Language chapter on supertraits][trpl_supertraits] + +[trpl_supertraits]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#using-supertraits-to-require-one-traits-functionality-within-another-trait diff --git a/src/types.md b/src/types.md new file mode 100644 index 0000000000..1d3b50aaba --- /dev/null +++ b/src/types.md @@ -0,0 +1,13 @@ +# Types + +Rust provides several mechanisms to change or define the type of primitive and +user defined types. The following sections cover: +* [Casting] between primitive types +* Specifying the desired type of [literals] +* Using [type inference] +* [Aliasing] types + +[Casting]: types/cast.md +[literals]: types/literals.md +[type inference]: types/inference.md +[Aliasing]: types/alias.md diff --git a/src/types/alias.md b/src/types/alias.md new file mode 100644 index 0000000000..5fda9477e8 --- /dev/null +++ b/src/types/alias.md @@ -0,0 +1,36 @@ +# Aliasing + +The `type` statement can be used to give a new name to an existing type. Types +must have `UpperCamelCase` names, or the compiler will raise a warning. The +exception to this rule are the primitive types: `usize`, `f32`, etc. + +```rust,editable +// `NanoSecond` is a new name for `u64`. +type NanoSecond = u64; +type Inch = u64; + +// Use an attribute to silence warning. +#[allow(non_camel_case_types)] +type u64_t = u64; +// TODO ^ Try removing the attribute + +fn main() { + // `NanoSecond` = `Inch` = `u64_t` = `u64`. + let nanoseconds: NanoSecond = 5 as u64_t; + let inches: Inch = 2 as u64_t; + + // Note that type aliases *don't* provide any extra type safety, because + // aliases are *not* new types + println!("{} nanoseconds + {} inches = {} unit?", + nanoseconds, + inches, + nanoseconds + inches); +} +``` + +The main use of aliases is to reduce boilerplate; for example the `IoResult` type +is an alias for the `Result` type. + +### See also: + +[Attributes](../attribute.md) diff --git a/src/types/cast.md b/src/types/cast.md new file mode 100644 index 0000000000..79e070d375 --- /dev/null +++ b/src/types/cast.md @@ -0,0 +1,88 @@ +# Casting + +Rust provides no implicit type conversion (coercion) between primitive types. +But, explicit type conversion (casting) can be performed using the `as` keyword. + +Rules for converting between integral types follow C conventions generally, +except in cases where C has undefined behavior. The behavior of all casts +between integral types is well defined in Rust. + +```rust,editable,ignore,mdbook-runnable +// Suppress all warnings from casts which overflow. +#![allow(overflowing_literals)] + +fn main() { + let decimal = 65.4321_f32; + + // Error! No implicit conversion + let integer: u8 = decimal; + // FIXME ^ Comment out this line + + // Explicit conversion + let integer = decimal as u8; + let character = integer as char; + + // Error! There are limitations in conversion rules. + // A float cannot be directly converted to a char. + let character = decimal as char; + // FIXME ^ Comment out this line + + println!("Casting: {} -> {} -> {}", decimal, integer, character); + + // when casting any value to an unsigned type, T, + // T::MAX + 1 is added or subtracted until the value + // fits into the new type + + // 1000 already fits in a u16 + println!("1000 as a u16 is: {}", 1000 as u16); + + // 1000 - 256 - 256 - 256 = 232 + // Under the hood, the first 8 least significant bits (LSB) are kept, + // while the rest towards the most significant bit (MSB) get truncated. + println!("1000 as a u8 is : {}", 1000 as u8); + // -1 + 256 = 255 + println!(" -1 as a u8 is : {}", (-1i8) as u8); + + // For positive numbers, this is the same as the modulus + println!("1000 mod 256 is : {}", 1000 % 256); + + // When casting to a signed type, the (bitwise) result is the same as + // first casting to the corresponding unsigned type. If the most significant + // bit of that value is 1, then the value is negative. + + // Unless it already fits, of course. + println!(" 128 as a i16 is: {}", 128 as i16); + // 128 as u8 -> 128, whose two's complement in eight bits is: + println!(" 128 as a i8 is : {}", 128 as i8); + + // repeating the example above + // 1000 as u8 -> 232 + println!("1000 as a u8 is : {}", 1000 as u8); + // and the two's complement of 232 is -24 + println!(" 232 as a i8 is : {}", 232 as i8); + + // Since Rust 1.45, the `as` keyword performs a *saturating cast* + // when casting from float to int. If the floating point value exceeds + // the upper bound or is less than the lower bound, the returned value + // will be equal to the bound crossed. + + // 300.0 is 255 + println!("300.0 is {}", 300.0_f32 as u8); + // -100.0 as u8 is 0 + println!("-100.0 as u8 is {}", -100.0_f32 as u8); + // nan as u8 is 0 + println!("nan as u8 is {}", f32::NAN as u8); + + // This behavior incurs a small runtime cost and can be avoided + // with unsafe methods, however the results might overflow and + // return **unsound values**. Use these methods wisely: + unsafe { + // 300.0 is 44 + println!("300.0 is {}", 300.0_f32.to_int_unchecked::()); + // -100.0 as u8 is 156 + println!("-100.0 as u8 is {}", (-100.0_f32).to_int_unchecked::()); + // nan as u8 is 0 + println!("nan as u8 is {}", f32::NAN.to_int_unchecked::()); + } +} +``` diff --git a/src/types/inference.md b/src/types/inference.md new file mode 100644 index 0000000000..5d10301f42 --- /dev/null +++ b/src/types/inference.md @@ -0,0 +1,28 @@ +# Inference + +The type inference engine is pretty smart. It does more than looking at the +type of the value expression +during an initialization. It also looks at how the variable is used afterwards +to infer its type. Here's an advanced example of type inference: + +```rust,editable +fn main() { + // Because of the annotation, the compiler knows that `elem` has type u8. + let elem = 5u8; + + // Create an empty vector (a growable array). + let mut vec = Vec::new(); + // At this point the compiler doesn't know the exact type of `vec`, it + // just knows that it's a vector of something (`Vec<_>`). + + // Insert `elem` in the vector. + vec.push(elem); + // Aha! Now the compiler knows that `vec` is a vector of `u8`s (`Vec`) + // TODO ^ Try commenting out the `vec.push(elem)` line + + println!("{:?}", vec); +} +``` + +No type annotation of variables was needed, the compiler is happy and so is the +programmer! diff --git a/src/types/literals.md b/src/types/literals.md new file mode 100644 index 0000000000..fd26b9dcaf --- /dev/null +++ b/src/types/literals.md @@ -0,0 +1,40 @@ +# Literals + +Numeric literals can be type annotated by adding the type as a suffix. As an example, +to specify that the literal `42` should have the type `i32`, write `42i32`. + +The type of unsuffixed numeric literals will depend on how they are used. If no +constraint exists, the compiler will use `i32` for integers, and `f64` for +floating-point numbers. + +```rust,editable +fn main() { + // Suffixed literals, their types are known at initialization + let x = 1u8; + let y = 2u32; + let z = 3f32; + + // Unsuffixed literals, their types depend on how they are used + let i = 1; + let f = 1.0; + + // `size_of_val` returns the size of a variable in bytes + println!("size of `x` in bytes: {}", std::mem::size_of_val(&x)); + println!("size of `y` in bytes: {}", std::mem::size_of_val(&y)); + println!("size of `z` in bytes: {}", std::mem::size_of_val(&z)); + println!("size of `i` in bytes: {}", std::mem::size_of_val(&i)); + println!("size of `f` in bytes: {}", std::mem::size_of_val(&f)); +} +``` + +There are some concepts used in the previous code that haven't been explained +yet, here's a brief explanation for the impatient readers: + +* `std::mem::size_of_val` is a function, but called with its *full path*. Code + can be split in logical units called *modules*. In this case, the + `size_of_val` function is defined in the `mem` module, and the `mem` module + is defined in the `std` *crate*. For more details, see + [modules][mod] and [crates][crate]. + +[mod]: ../mod.md +[crate]: ../crates.md diff --git a/src/unsafe.md b/src/unsafe.md new file mode 100644 index 0000000000..1eeec6ba35 --- /dev/null +++ b/src/unsafe.md @@ -0,0 +1,61 @@ +# Unsafe Operations + +As an introduction to this section, to borrow from [the official docs][unsafe], +"one should try to minimize the amount of unsafe code in a code base." With that +in mind, let's get started! Unsafe annotations in Rust are used to bypass +protections put in place by the compiler; specifically, there are four primary +things that unsafe is used for: + +* dereferencing raw pointers +* calling functions or methods which are `unsafe` (including calling a function + over FFI, see [a previous chapter](std_misc/ffi.md) of the book) +* accessing or modifying static mutable variables +* implementing unsafe traits + +### Raw Pointers +Raw pointers `*` and references `&T` function similarly, but references are +always safe because they are guaranteed to point to valid data due to the +borrow checker. Dereferencing a raw pointer can only be done through an unsafe +block. + +```rust,editable +fn main() { + let raw_p: *const u32 = &10; + + unsafe { + assert!(*raw_p == 10); + } +} +``` + +### Calling Unsafe Functions +Some functions can be declared as `unsafe`, meaning it is the programmer's +responsibility to ensure correctness instead of the compiler's. One example +of this is [`std::slice::from_raw_parts`] which will create a slice given a +pointer to the first element and a length. + +```rust,editable +use std::slice; + +fn main() { + let some_vector = vec![1, 2, 3, 4]; + + let pointer = some_vector.as_ptr(); + let length = some_vector.len(); + + unsafe { + let my_slice: &[u32] = slice::from_raw_parts(pointer, length); + + assert_eq!(some_vector.as_slice(), my_slice); + } +} +``` + +For `slice::from_raw_parts`, one of the assumptions which *must* be upheld is +that the pointer passed in points to valid memory and that the memory pointed to +is of the correct type. If these invariants aren't upheld then the program's +behaviour is undefined and there is no knowing what will happen. + + +[unsafe]: https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html +[`std::slice::from_raw_parts`]: https://doc.rust-lang.org/std/slice/fn.from_raw_parts.html diff --git a/src/update.rs b/src/update.rs deleted file mode 100644 index 181e3919e8..0000000000 --- a/src/update.rs +++ /dev/null @@ -1,47 +0,0 @@ -#![deny(warnings)] -#![feature(phase)] - -extern crate regex; -#[phase(plugin)] -extern crate regex_macros; -extern crate serialize; - -use example::Example; - -mod example; -mod file; -mod markdown; -mod playpen; - -fn main() { - let examples = Example::get_list(); - let (tx, rx) = channel(); - - let mut nexamples = 0; - for (i, example) in examples.into_iter().enumerate() { - let tx = tx.clone(); - let count = example.count(); - - spawn(proc() { - example.process(vec!(i + 1), tx, 0, String::new()); - }); - - nexamples += count; - } - - let mut entries = range(0, nexamples).map(|_| { - rx.recv() - }).collect::, String)>>(); - - entries.sort_by(|&(ref i, _), &(ref j, _)| i.cmp(j)); - - let summary = entries.into_iter() - .map(|(_, s)| s) - .collect::>() - .connect("\n"); - - match file::write(&Path::new("stage/SUMMARY.md"), summary.as_slice()) { - Err(why) => panic!("{}", why), - Ok(_) => {}, - } -} diff --git a/src/variable_bindings.md b/src/variable_bindings.md new file mode 100644 index 0000000000..b280ed5486 --- /dev/null +++ b/src/variable_bindings.md @@ -0,0 +1,30 @@ +# Variable Bindings + +Rust provides type safety via static typing. Variable bindings can be type +annotated when declared. However, in most cases, the compiler will be able +to infer the type of the variable from the context, heavily reducing the +annotation burden. + +Values (like literals) can be bound to variables, using the `let` binding. + +```rust,editable +fn main() { + let an_integer = 1u32; + let a_boolean = true; + let unit = (); + + // copy `an_integer` into `copied_integer` + let copied_integer = an_integer; + + println!("An integer: {:?}", copied_integer); + println!("A boolean: {:?}", a_boolean); + println!("Meet the unit value: {:?}", unit); + + // The compiler warns about unused variable bindings; these warnings can + // be silenced by prefixing the variable name with an underscore + let _unused_variable = 3u32; + + let noisy_unused_variable = 2u32; + // FIXME ^ Prefix with an underscore to suppress the warning +} +``` \ No newline at end of file diff --git a/src/variable_bindings/declare.md b/src/variable_bindings/declare.md new file mode 100644 index 0000000000..e9dee6a132 --- /dev/null +++ b/src/variable_bindings/declare.md @@ -0,0 +1,34 @@ +# Declare first + +It's possible to declare variable bindings first, and initialize them later. +However, this form is seldom used, as it may lead to the use of uninitialized +variables. + +```rust,editable,ignore,mdbook-runnable +fn main() { + // Declare a variable binding + let a_binding; + + { + let x = 2; + + // Initialize the binding + a_binding = x * x; + } + + println!("a binding: {}", a_binding); + + let another_binding; + + // Error! Use of uninitialized binding + println!("another binding: {}", another_binding); + // FIXME ^ Comment out this line + + another_binding = 1; + + println!("another binding: {}", another_binding); +} +``` + +The compiler forbids use of uninitialized variables, as this would lead to +undefined behavior. diff --git a/src/variable_bindings/freeze.md b/src/variable_bindings/freeze.md new file mode 100644 index 0000000000..b399570ff8 --- /dev/null +++ b/src/variable_bindings/freeze.md @@ -0,0 +1,24 @@ +# Freezing + +When data is bound by the same name immutably, it also *freezes*. *Frozen* data can't be +modified until the immutable binding goes out of scope: + +```rust,editable,ignore,mdbook-runnable +fn main() { + let mut _mutable_integer = 7i32; + + { + // Shadowing by immutable `_mutable_integer` + let _mutable_integer = _mutable_integer; + + // Error! `_mutable_integer` is frozen in this scope + _mutable_integer = 50; + // FIXME ^ Comment out this line + + // `_mutable_integer` goes out of scope + } + + // Ok! `_mutable_integer` is not frozen in this scope + _mutable_integer = 3; +} +``` diff --git a/src/variable_bindings/mut.md b/src/variable_bindings/mut.md new file mode 100644 index 0000000000..0925132f20 --- /dev/null +++ b/src/variable_bindings/mut.md @@ -0,0 +1,24 @@ +# Mutability + +Variable bindings are immutable by default, but this can be overridden using +the `mut` modifier. + +```rust,editable,ignore,mdbook-runnable +fn main() { + let _immutable_binding = 1; + let mut mutable_binding = 1; + + println!("Before mutation: {}", mutable_binding); + + // Ok + mutable_binding += 1; + + println!("After mutation: {}", mutable_binding); + + // Error! + _immutable_binding += 1; + // FIXME ^ Comment out this line +} +``` + +The compiler will throw a detailed diagnostic about mutability errors. diff --git a/src/variable_bindings/scope.md b/src/variable_bindings/scope.md new file mode 100644 index 0000000000..9e3c79e3ee --- /dev/null +++ b/src/variable_bindings/scope.md @@ -0,0 +1,46 @@ +# Scope and Shadowing + +Variable bindings have a scope, and are constrained to live in a *block*. A +block is a collection of statements enclosed by braces `{}`. +```rust,editable,ignore,mdbook-runnable +fn main() { + // This binding lives in the main function + let long_lived_binding = 1; + + // This is a block, and has a smaller scope than the main function + { + // This binding only exists in this block + let short_lived_binding = 2; + + println!("inner short: {}", short_lived_binding); + } + // End of the block + + // Error! `short_lived_binding` doesn't exist in this scope + println!("outer short: {}", short_lived_binding); + // FIXME ^ Comment out this line + + println!("outer long: {}", long_lived_binding); +} +``` +Also, [variable shadowing][variable-shadow] is allowed. +```rust,editable,ignore,mdbook-runnable +fn main() { + let shadowed_binding = 1; + + { + println!("before being shadowed: {}", shadowed_binding); + + // This binding *shadows* the outer one + let shadowed_binding = "abc"; + + println!("shadowed in inner block: {}", shadowed_binding); + } + println!("outside inner block: {}", shadowed_binding); + + // This binding *shadows* the previous binding + let shadowed_binding = 2; + println!("shadowed in outer block: {}", shadowed_binding); +} +``` +[variable-shadow]: https://en.wikipedia.org/wiki/Variable_shadowing diff --git a/triagebot.toml b/triagebot.toml new file mode 100644 index 0000000000..fa0824ac53 --- /dev/null +++ b/triagebot.toml @@ -0,0 +1 @@ +[assign] diff --git a/vendor/gitbook/jsrepl/engines/javascript-default.js b/vendor/gitbook/jsrepl/engines/javascript-default.js deleted file mode 100755 index b26c5c033f..0000000000 --- a/vendor/gitbook/jsrepl/engines/javascript-default.js +++ /dev/null @@ -1,32 +0,0 @@ -/* - - Copyright Joyent, Inc. and other Node contributors. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to permit - persons to whom the Software is furnished to do so, subject to the - following conditions: - - The above copyright notice and this permission notice shall be included - in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - USE OR OTHER DEALINGS IN THE SOFTWARE. - - Original at: https://github.com/joyent/node/blob/master/lib/util.js -*/ -(function(){function o(c){return c instanceof Array||Array.isArray(c)||c&&c!==Object.prototype&&o(c.__proto__)}function p(c){return c instanceof RegExp||typeof c==="function"&&c.constructor.name==="RegExp"&&c.compile&&c.test&&c.exec&&(""+c).match(/^\/.*\/[gim]{0,3}$/)}var q=80,l=function(c,h,b,f){function m(a,c){switch(typeof a){case "undefined":return d("undefined","undefined");case "string":var b="'"+JSON.stringify(a).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return d(b,"string"); -case "number":return d(""+a,"number");case "boolean":return d(""+a,"boolean")}if(a===null)return d("null","null");var f=Object.keys(a),i=h?Object.getOwnPropertyNames(a):f;if(typeof a==="function"&&i.length===0)return p(a)?d(""+a,"regexp"):d("[Function"+(a.name?": "+a.name:"")+"]","special");if(a instanceof Date&&i.length===0)return d(a.toUTCString(),"date");var j,l;o(a)?(l="Array",b=["[","]"]):(l="Object",b=["{","}"]);typeof a==="function"?(j=a.name?": "+a.name:"",j=p(a)?" "+a:" [Function"+j+"]"): -j="";a instanceof Date&&(j=" "+a.toUTCString());if(i.length===0)return b[0]+j+b[1];if(c<0)return p(a)?d(""+a,"regexp"):d("[Object]","special");k.push(a);i=i.map(function(b){var e,g;a.__lookupGetter__&&(a.__lookupGetter__(b)?g=a.__lookupSetter__(b)?d("[Getter/Setter]","special"):d("[Getter]","special"):a.__lookupSetter__(b)&&(g=d("[Setter]","special")));f.indexOf(b)<0&&(e="["+b+"]");g||(k.indexOf(a[b])<0?(g=c===null?m(a[b]):m(a[b],c-1),g.indexOf("\n")>-1&&(g=o(a)?g.split("\n").map(function(a){return" "+ -a}).join("\n").substr(2):"\n"+g.split("\n").map(function(a){return" "+a}).join("\n"))):g=d("[Circular]","special"));if(typeof e==="undefined"){if(l==="Array"&&b.match(/^\d+$/))return g;e=JSON.stringify(""+b);e.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(e=e.substr(1,e.length-2),e=d(e,"name")):(e=e.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),e=d(e,"string"))}return e+": "+g});k.pop();var n=0;return i=i.reduce(function(a,b){n++;b.indexOf("\n")>=0&&n++;return a+b.length+1},0)>q?b[0]+ -(j===""?"":j+"\n ")+" "+i.join(",\n ")+" "+b[1]:b[0]+j+" "+i.join(", ")+" "+b[1]}var k=[],d=function(a,b){var c={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},d={special:"cyan",number:"blue","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"}[b];return d?"\u001b["+c[d][0]+"m"+a+"\u001b["+c[d][1]+"m":a};f||(d=function(a){return a}); -return m(c,typeof b==="undefined"?2:b)},r=/%[sdj%]/g,s=function(c){if(typeof c!=="string"){for(var h=[],b=0;b=m)return c;switch(c){case "%s":return String(f[b++]);case "%d":return Number(f[b++]);case "%j":return JSON.stringify(f[b++]);case "%%":return"%";default:return c}}),k=f[b];b-1?g.push(f.splice(b,1)):g.push(void 0)):g.push(this.listeners[b]=[]));return g};h.prototype.fire=function(a,c){var b,f,d,e,c=this.makeArray(c); -f=this.listeners[a];if(f!=null){c.push(a);var g;g=[];for(d=0,e=f.length;d - - - jsREPL Sandbox - - - - - diff --git a/vendor/gitbook/jsrepl/sandbox.js b/vendor/gitbook/jsrepl/sandbox.js deleted file mode 100755 index 48f7c74f74..0000000000 --- a/vendor/gitbook/jsrepl/sandbox.js +++ /dev/null @@ -1,52 +0,0 @@ -/* - - Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - 3. The names of its contributors may not be used to endorse or promote - products derived from this software without specific prior written - permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - Any feedback is very welcome. - http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html - email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) -*/ -(function(c){try{c.window=c.window||c}catch(b){}try{c.self=c.self||c}catch(e){}var a;c.addEventListener("message",function(d){for(var d=JSON.parse(d.data),b=a,c=d.type.split("."),e=0;ethis.OUT_EVERY_MS&&(clearTimeout(this.outTimeout),this.flush())},flush:function(){if(this.output_buffer.length)this.post({type:"output",data:this.output_buffer.join("")}),this.outTimeout=0,this.output_buffer=[]},err:function(a){a={type:"error", -data:a.toString()};this.flush();this.post(a)},input:function(a){this.input.write=a;this.flush();this.post({type:"input"})},result:function(a){a={type:"result",data:a};this.flush();this.post(a)},ready:function(){this.post({type:"ready"})},getNextLineIndent:function(a){this.post({type:"indent",data:this.engine.GetNextLineIndent(a)})},progress:function(a){this.post({type:"progress",data:a})},dbInput:function(){this.flush();this.post({type:"db_input"})},serverInput:function(){this.flush();this.post({type:"server_input"})}, -bindAll:function(a){for(var b in a)(function(b){var c=a[b];typeof c=="function"&&(a[b]=function(){var b=[].slice.call(arguments);return c.apply(a,b)})})(b)},hide:function(a){try{Object.defineProperty(c,a,{writable:false,enumerable:false,configurable:false,value:c[a]})}catch(b){}},set_input_server:function(a){this.input_server={url:(a.url||"/emscripten/input/")+a.input_id,cors:a.cors||false}}};a.bindAll(a);c.Sandboss=a;a.hide("Sandboss");if(self.openDatabaseSync){var f=self.openDatabaseSync("replit_input", -"1.0","Emscripted input",1024);self.prompt=function(){a.dbInput();var b=null;f.transaction(function(a){b=a});for(var c;!(c=b.executeSql("SELECT * FROM input").rows).length;)for(c=0;c<1E8;c++);b.executeSql("DELETE FROM input");return c.item(0).text};a.hide("prompt")}else if(!a.isFrame)self.prompt=function(){a.serverInput();var b;b=a.input_server.url;var c=new XMLHttpRequest;if(a.input_server.cors)if("withCredentials"in c)c.open("GET",b,false);else if(typeof XDomainRequest!="undefined")c=new XDomainRequest, -c.open("GET",b);else throw Error("Your browser doesn' support CORS");else c.open("GET",b,false);b=c;b.send(null);return b.status===200?b.responseText:"ERROR: ON NON-WEBKIT BROWSERS CONNECTION TO THE SERVER IS NEEDED FOR INPUT"}})(this); -(function(){var c=function(b){b==void 0&&(b=Date.now());this.N=624;this.M=397;this.MATRIX_A=2567483615;this.UPPER_MASK=2147483648;this.LOWER_MASK=2147483647;this.mt=Array(this.N);this.mti=this.N+1;this.init_genrand(b)};c.prototype.init_genrand=function(b){this.mt[0]=b>>>0;for(this.mti=1;this.mti>>30,this.mt[this.mti]=(((b&4294901760)>>>16)*1812433253<<16)+(b&65535)*1812433253+this.mti,this.mt[this.mti]>>>=0};c.prototype.init_by_array=function(b, -c){var a,f,d;this.init_genrand(19650218);a=1;f=0;for(d=this.N>c?this.N:c;d;d--){var h=this.mt[a-1]^this.mt[a-1]>>>30;this.mt[a]=(this.mt[a]^(((h&4294901760)>>>16)*1664525<<16)+(h&65535)*1664525)+b[f]+f;this.mt[a]>>>=0;a++;f++;a>=this.N&&(this.mt[0]=this.mt[this.N-1],a=1);f>=c&&(f=0)}for(d=this.N-1;d;d--)h=this.mt[a-1]^this.mt[a-1]>>>30,this.mt[a]=(this.mt[a]^(((h&4294901760)>>>16)*1566083941<<16)+(h&65535)*1566083941)-a,this.mt[a]>>>=0,a++,a>=this.N&&(this.mt[0]=this.mt[this.N-1],a=1);this.mt[0]= -2147483648};c.prototype.genrand_int32=function(){var b,c=[0,this.MATRIX_A];if(this.mti>=this.N){var a;this.mti==this.N+1&&this.init_genrand(5489);for(a=0;a>>1^c[b&1];for(;a>>1^c[b&1];b=this.mt[this.N-1]&this.UPPER_MASK|this.mt[0]&this.LOWER_MASK;this.mt[this.N-1]=this.mt[this.M-1]^ -b>>>1^c[b&1];this.mti=0}b=this.mt[this.mti++];b^=b>>>11;b^=b<<7&2636928640;b^=b<<15&4022730752;b^=b>>>18;return b>>>0};c.prototype.genrand_int31=function(){return this.genrand_int32()>>>1};c.prototype.genrand_real1=function(){return this.genrand_int32()*(1/4294967295)};c.prototype.random=function(){return this.genrand_int32()*(1/4294967296)};c.prototype.genrand_real3=function(){return(this.genrand_int32()+0.5)*(1/4294967296)};c.prototype.genrand_res53=function(){var b=this.genrand_int32()>>>5,c=this.genrand_int32()>>> -6;return(b*67108864+c)*1.1102230246251565E-16};(function(){Math._random=Math.random;var b=new c(42);Math.random=function(){return b.random()};Math.seed=function(e){b=new c(e)}})()})();if(!Date.now)Date.now=function(){return+new Date};if(!Object.keys)Object.keys=function(c){if(c!==Object(c))throw new TypeError("Object.keys called on non-object");var b=[],e;for(e in c)Object.prototype.hasOwnProperty.call(c,e)&&b.push(e);return b};if(!Object.getOwnPropertyNames)Object.getOwnPropertyNames=Object.keys; -if(!Object.create)Object.create=function(c){function b(){}b.prototype=c;return new b};if(!Array.isArray)Array.isArray=function(c){return{}.toString.call(c)=="[object Array]"}; -if(!Function.prototype.bind)Function.prototype.bind=function(c){if(typeof this!=="function")throw new TypeError("Function.prototype.bind - what is trying to be fBound is not callable");var b=Array.prototype.slice.call(arguments,1),e=this,a=function(){},f=function(){try{return e.apply(this instanceof a?this:c||window,b.concat(Array.prototype.slice.call(arguments)))}catch(d){return e.apply(c||window,b.concat(Array.prototype.slice.call(arguments)))}};a.prototype=this.prototype;f.prototype=new a;return f}; -if(!Object.freeze)Object.freeze=function(c){return c.___frozen___=true};if(!Object.isFrozen)Object.isFrozen=function(c){return Boolean(c.___frozen___)}; diff --git a/vendor/gitbook/plugins/gitbook-plugin-livereload/plugin.js b/vendor/gitbook/plugins/gitbook-plugin-livereload/plugin.js deleted file mode 100644 index 923b3aed5c..0000000000 --- a/vendor/gitbook/plugins/gitbook-plugin-livereload/plugin.js +++ /dev/null @@ -1,11 +0,0 @@ -(function() { - var newEl = document.createElement('script'), - firstScriptTag = document.getElementsByTagName('script')[0]; - - if (firstScriptTag) { - newEl.async = 1; - newEl.src = '//' + window.location.hostname + ':35729/livereload.js'; - firstScriptTag.parentNode.insertBefore(newEl, firstScriptTag); - } - -})();