[
  {
    "path": ".github/workflows/github-pages.yml",
    "content": "name: github pages\n\non:\n  push:\n    branches:\n      - master\n\njobs:\n  deploy:\n    runs-on: ubuntu-20.04\n    steps:\n      - uses: actions/checkout@v2\n      - run: sudo apt install linuxbrew-wrapper\n      - run: brew install coreutils\n      #- run: cargo install mdbook\n      - run: chmod 777 -R ./\n      - run: make github_pages\n\n      - name: Setup mdBook\n        uses: peaceiris/actions-mdbook@v1\n        with:\n          mdbook-version: 'latest'\n\n      - run: mdbook build\n\n      - name: Deploy\n        uses: peaceiris/actions-gh-pages@v3\n        with:\n          github_token: ${{ secrets.GITHUB_TOKEN }}\n          publish_dir: ./book"
  },
  {
    "path": ".gitignore",
    "content": "# macOS garbage\n.DS_Store\n\nsnippets\nbook\nlatex\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2020 Dhghomon\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "Makefile",
    "content": "###############################################################################\n# Make file for the Easy Rust project.\n#\n# Author: Alexander Willner\n# License : MIT\n###############################################################################\n\n# Config\nSNIPPETS = snippets\n.PHONY: help snippets snippets-test book\n\nhelp: ## Print help for each target\n\t$(info Rust Makefile)\n\t$(info =============)\n\t$(info )\n\t$(info Consider to use 'cargo' for other targets.)\n\t$(info )\n\t$(info Available commands:)\n\t$(info )\n\t@grep '^[[:alnum:]_-]*:.* ##' $(MAKEFILE_LIST) \\\n        | sort | awk 'BEGIN {FS=\":.* ## \"}; {printf \"%-25s %s\\n\", $$1, $$2};'\n\nbook: ## Generate an mdBook version on your local and start serving in browser\n\t@./createBookFromReadme.sh\n\ngithub_pages: ## Generate an mdBook version for the Github Pages\n\t@./createGithubPagesFromReadme.sh\n\nsnippets: clean ## Create snippets\n\t@type md2src >/dev/null 2>&1 || (echo \"Run 'cargo install md2src' first.\" >&2 ; exit 1)\n\t@mkdir -p $(SNIPPETS)\n\t@md2src \"README.md\" \"$(SNIPPETS)\" -i \"// ⚠️\" -i \"// 🚧\" ## ignore snippets that contain these strings\n\nsnippets-test: snippets ## Test snippets\n\t@for snippet in $$(ls $(SNIPPETS)/*.rs); do \\\n\t    echo \"File $$snippet:\" ; \\\n\t\trustc --out-dir \"$(SNIPPETS)\" $$snippet; \\\n\tdone\n\nfeedback: ## Give feedback\n\t@open https://github.com/Dhghomon/easy_rust/issues\n\nclean: ## Cleanup\n\t@rm -rf \"$(SNIPPETS)\"\n"
  },
  {
    "path": "README.md",
    "content": "## Updates\n![example workflow name](https://github.com/Dhghomon/easy_rust/workflows/github%20pages/badge.svg)\n\n19 January 2023: [Learn Rust in a Month of Lunches](https://www.manning.com/books/learn-rust-in-a-month-of-lunches) is now available for purchase on Manning. Rust in a Month of Lunches is based on the content in the original Easy Rust but updated, improved with reader feedback and expanded (about twice the size).\n\n![](Learn_Rust_in_a_Month_of_Lunches.png)\n\n31 October 2022: [Now available in Spanish](https://www.jmgaguilera.com/rust_facil/)\n\n23 May 2021: [Now available in Indonesian](https://github.com/ariandy/easy-rust-indonesia) thanks to [Ariandy](https://github.com/ariandy)/[1kb](https://1kilobyte.github.io/).\n\n2 April 2021: [Added BuyMeACoffee link](https://www.buymeacoffee.com/mithridates) for those who would like to buy me a coffee.\n\n1 February 2021: [Now available on YouTube!](https://www.youtube.com/playlist?list=PLfllocyHVgsRwLkTAhG0E-2QxCf-ozBkk) Two months later: all done as of 1 April 2021 for 186 videos in total (slightly over 23 hours).\n\n22 December 2020: mdBook can be found [here](https://dhghomon.github.io/easy_rust).\n\n28 November 2020: [Now also available in simplified Chinese](https://github.com/kumakichi/easy_rust_chs) thanks to [kumakichi](https://github.com/kumakichi)!\n\n27 November 2021: [Videos for Easy Rust are now being recorded in Korean!](https://www.youtube.com/watch?v=W9DO6m8JSSs&list=PLfllocyHVgsSJf1zO6k6o3SX2mbZjAqYE) 한국어판 비디오도 녹화 시작!\n\n![](Easy_Rust_sample_image.png)\n\n## Introduction\n\nRust is a new language that already has good textbooks. But sometimes its textbooks are difficult because they are for native English speakers. Many companies and people now learn Rust, and they could learn faster with a book that has easy English. This textbook is for these companies and people to learn Rust with simple English.\n\nRust is a language that is quite new, but already very popular. It's popular because it gives you the speed and control of C or C++ but also the memory safety of other newer languages like Python. It does this with some new ideas that are sometimes different from other languages. That means that there are some new things to learn, and you can't just \"figure it out as you go along\". Rust is a language that you have to think about for a while to understand. But it still looks pretty familiar if you know another language and it is made to help you write good code.\n\n## Who am I?\n\nI am a Canadian who lives in Korea, and I wrote Easy Rust while thinking of how to make it easy for companies here to start using it. I hope that other countries that don't use English as a first language can use it too.\n\n## Writing Rust in Easy English\n\n*Rust in Easy English* was written from July to August 2020, and is over 400 pages long. You can contact me here or [on LinkedIn](https://www.linkedin.com/in/davemacleod) or [on Twitter](https://twitter.com/mithridates) if you have any questions. If you see anything wrong or have a pull request to make, go ahead. Over 20 people have already helped out by fixing typos and problems in the code, so you can too. I'm not the world's best Rust expert so I always like to hear new ideas or see where I can make the book better.\n\n\n\n- [Part 1 - Rust in your browser](#part-1---rust-in-your-browser)\n  - [Rust Playground](#rust-playground)\n  - [🚧 and ⚠️](#-and-️)\n  - [Comments](#comments)\n  - [Types](#types)\n    - [Primitive types](#primitive-types)\n  - [Type inference](#type-inference)\n    - [Floats](#floats)\n  - [Printing 'hello, world!'](#printing-hello-world)\n    - [Declaring variables and code blocks](#declaring-variables-and-code-blocks)\n  - [Display and debug](#display-and-debug)\n    - [Smallest and largest numbers](#smallest-and-largest-numbers)\n  - [Mutability (changing)](#mutability-changing)\n    - [Shadowing](#shadowing)\n  - [The stack, the heap, and pointers](#the-stack-the-heap-and-pointers)\n  - [More about printing](#more-about-printing)\n  - [Strings](#strings)\n  - [const and static](#const-and-static)\n  - [More on references](#more-on-references)\n  - [Mutable references](#mutable-references)\n    - [Shadowing again](#shadowing-again)\n  - [Giving references to functions](#giving-references-to-functions)\n  - [Copy types](#copy-types)\n    - [Variables without values](#variables-without-values)\n  - [Collection types](#collection-types)\n    - [Arrays](#arrays)\n  - [Vectors](#vectors)\n  - [Tuples](#tuples)\n  - [Control flow](#control-flow)\n  - [Structs](#structs)\n  - [Enums](#enums)\n    - [Enums to use multiple types](#enums-to-use-multiple-types)\n  - [Loops](#loops)\n  - [Implementing structs and enums](#implementing-structs-and-enums)\n  - [Destructuring](#destructuring)\n  - [References and the dot operator](#references-and-the-dot-operator)\n  - [Generics](#generics)\n  - [Option and Result](#option-and-result)\n    - [Option](#option)\n    - [Result](#result)\n  - [Other collections](#other-collections)\n    - [HashMap (and BTreeMap)](#hashmap-and-btreemap)\n    - [HashSet and BTreeSet](#hashset-and-btreeset)\n    - [BinaryHeap](#binaryheap)\n    - [VecDeque](#vecdeque)\n  - [The ? operator](#the--operator)\n    - [When panic and unwrap are good](#when-panic-and-unwrap-are-good)\n  - [Traits](#traits)\n    - [The From trait](#the-from-trait)\n    - [Taking a String and a &str in a function](#taking-a-string-and-a-str-in-a-function)\n  - [Chaining methods](#chaining-methods)\n  - [Iterators](#iterators)\n    - [How an iterator works](#how-an-iterator-works)\n  - [Closures](#closures)\n    - [|_| in a closure](#_-in-a-closure)\n    - [Helpful methods for closures and iterators](#helpful-methods-for-closures-and-iterators)\n  - [The dbg! macro and .inspect](#the-dbg-macro-and-inspect)\n  - [Types of &str](#types-of-str)\n  - [Lifetimes](#lifetimes)\n  - [Interior mutability](#interior-mutability)\n    - [Cell](#cell)\n    - [RefCell](#refcell)\n    - [Mutex](#mutex)\n    - [RwLock](#rwlock)\n  - [Cow](#cow)\n  - [Type aliases](#type-aliases)\n    - [Importing and renaming inside a function](#importing-and-renaming-inside-a-function)\n  - [The todo! macro](#the-todo-macro)\n  - [Rc](#rc)\n  - [Multiple threads](#multiple-threads)\n  - [Closures in functions](#closures-in-functions)\n  - [impl Trait](#impl-trait)\n  - [Arc](#arc)\n  - [Channels](#channels)\n  - [Reading Rust documentation](#reading-rust-documentation)\n    - [assert_eq!](#assert_eq)\n    - [Searching](#searching)\n    - [[src] button](#src-button)\n    - [Information on traits](#information-on-traits)\n  - [Attributes](#attributes)\n  - [Box](#box)\n  - [Box around traits](#box-around-traits)\n  - [Default and the builder pattern](#default-and-the-builder-pattern)\n  - [Deref and DerefMut](#deref-and-derefmut)\n  - [Crates and modules](#crates-and-modules)\n  - [Testing](#testing)\n    - [Test-driven development](#test-driven-development)\n  - [External crates](#external-crates)\n    - [rand](#rand)\n    - [rayon](#rayon)\n    - [serde](#serde)\n    - [regex](#regex)\n    - [chrono](#chrono)\n  - [A tour of the standard library](#a-tour-of-the-standard-library)\n    - [Arrays](#arrays-1)\n    - [char](#char)\n    - [Integers](#integers)\n    - [Floats](#floats)\n    - [Bool](#bool)\n    - [Vec](#vec)\n    - [String](#string)\n    - [OsString and CString](#osstring-and-cstring)\n    - [Mem](#mem)\n    - [Prelude](#prelude)\n    - [Time](#time)\n    - [Other-macros](#other-macros)\n  - [Writing macros](#writing-macros)\n- [Part 2 - Rust on your computer](#part-2---rust-on-your-computer)\n  - [Cargo](#cargo)\n  - [Taking_user_input](#taking-user-input)\n  - [Using files](#using-files)\n  - [Cargo doc](#cargo-doc)\n  - [The end?](#the-end)\n\n# Part 1 - Rust in your browser\n\nThis book has two parts. In Part 1, you will learn as much Rust as you can just in your browser. You can actually learn almost everything you need to know without installing Rust, so Part 1 is very long. Then at the end is Part 2. It is much shorter, and is about Rust on your computer. That's where you will learn everything else you need to know that you can only do outside of a browser. Some examples are: working with files, taking user input, graphics, and personal settings. Hopefully, by the end of Part 1 you will like Rust enough that you will install it. And if you don't, no problem - Part 1 teaches you so much that you won't mind.\n\n## Rust Playground\n**[See this chapter on YouTube](https://youtu.be/-lYeJeQ11OI)**\n\nMaybe you don't want to install Rust yet, and that's okay. You can go to [https://play.rust-lang.org/](https://play.rust-lang.org/) and start writing Rust without leaving your browser. You can write your code there and click Run to see the results. You can run most of the samples in this book inside the Playground in your browser. Only near the end you will see samples that go beyond what you can do in the Playground (like opening files).\n\nHere are some tips when using the Rust Playground:\n\n- Run your code with Run\n- Change Debug to Release if you want your code to be faster. Debug: compiles faster, runs slower, contains debug information. Release: compiles slower, runs much faster, removes debug information.\n- Click on Share to get a url link. You can use that to share your code if you want help. After you click share, you can click on `Open a new thread in the Rust user forum` to ask people there for help right away.\n- Tools: Rustfmt will format your code nicely.\n- Tools: Clippy will give you extra information about how to make your code better.\n- Config: here you can change your theme to dark mode so you can work at night, and many other configurations.\n\nIf you want to install Rust, go here [https://www.rust-lang.org/tools/install](https://www.rust-lang.org/tools/install) and follow the instructions. Usually you will use `rustup` to install and update Rust.\n\n## 🚧 and ⚠️\n\nSometimes the code examples in the book don't work. If an example doesn't work, it will have a 🚧 or a ⚠️ in it. 🚧 is like \"under construction\": it means that the code is not complete. Rust needs a `fn main()` (a main function) to run, but sometimes we just want to look at small pieces of code so it won't have a `fn main()`. Those examples are correct, but need a `fn main()` for you to run them. And some code examples show you a problem that we will fix. Those ones might have a `fn main()` but generate an error, and so they will have a ⚠️.\n\n## Comments\n**[See this chapter on YouTube](https://youtu.be/fJ7jBZG_Rpo)**\n\nComments are made for programmers to read, not the computer. It's good to write comments to help other people understand your code.  It's also good to help you understand your code later.  (Many people write good code but then forget why they wrote it.) To write comments in Rust you usually use `//`:\n\n```rust\nfn main() {\n    // Rust programs start with fn main()\n    // You put the code inside a block. It starts with { and ends with }\n    let some_number = 100; // We can write as much as we want here and the compiler won't look at it\n}\n```\n\nWhen you do this, the compiler won't look at anything to the right of the `//`.\n\nThere is another kind of comment that you write with `/*` to start and `*/` to end. This one is useful to write in the middle of your code.\n\n```rust\nfn main() {\n    let some_number/*: i16*/ = 100;\n}\n```\n\nTo the compiler, `let some_number/*: i16*/ = 100;` looks like `let some_number = 100;`.\n\nThe `/* */` form is also useful for very long comments over more than one line. In this example you can see that you need to write `//` for every line. But if you type `/*`, it won't stop until you finish it with `*/`.\n\n```rust\nfn main() {\n    let some_number = 100; /* Let me tell you\n    a little about this number.\n    It's 100, which is my favourite number.\n    It's called some_number but actually I think that... */\n\n    let some_number = 100; // Let me tell you\n    // a little about this number.\n    // It's 100, which is my favourite number.\n    // It's called some_number but actually I think that...\n}\n```\n\n## Types\n\nRust has many types that let you work with numbers, characters, and so on. Some are simple, others are more complicated, and you can even create your own.\n\n### Primitive types\n**[See this chapter on YouTube](https://youtu.be/OxTPU5UGMhs)**\n\nRust has simple types that are called **primitive types** (primitive = very basic). We will start with integers and `char` (characters). Integers are whole numbers with no decimal point. There are two types of integers:\n\n- Signed integers,\n- Unsigned integers.\n\nSigned means `+` (plus sign) and `-` (minus sign), so signed integers can be positive (e.g. +8), negative (e.g. -8), or zero. But unsigned integers can only be positive or zero, because they do not have a sign.\n\nThe signed integers are: `i8`, `i16`, `i32`, `i64`, `i128`, and `isize`.\nThe unsigned integers are: `u8`, `u16`, `u32`, `u64`, `u128`, and `usize`.\n\nThe number after the i or the u means the number of bits for the number, so numbers with more bits can be larger. 8 bits = one byte, so `i8` is one byte, `i64` is 8 bytes, and so on. Number types with larger sizes can hold larger numbers. For example, a `u8` can hold up to 255, but a `u16` can hold up to 65535. And a `u128` can hold up to 340282366920938463463374607431768211455.\n\nSo what is `isize` and `usize`? This means the number of bits on your type of computer. (The number of bits on your computer is called the **architecture** of your computer.) So `isize` and `usize` on a 32-bit computer is like `i32` and `u32`, and `isize` and `usize` on a 64-bit computer is like `i64` and `u64`.\n\nThere are many reasons for the different types of integers. One reason is computer performance: a smaller number of bytes is faster to process. For example, the number -10 as an `i8` is `11110110`, but as an `i128` it is `11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111110110`. But here are some other uses:\n\nCharacters in Rust are called `char`. Every `char` has a number: the letter `A` is number 65, while the character `友` (\"friend\" in Chinese) is number 21451. The list of numbers is called \"Unicode\". Unicode uses smaller numbers for characters that are used more, like A through Z, or digits 0 through 9, or space.\n\n```rust\nfn main() {\n    let first_letter = 'A';\n    let space = ' '; // A space inside ' ' is also a char\n    let other_language_char = 'Ꮔ'; // Thanks to Unicode, other languages like Cherokee display just fine too\n    let cat_face = '😺'; // Emojis are chars too\n}\n```\n\nThe characters that are used most have numbers less than 256, and they can fit into a `u8`. Remember, a `u8` is 0 plus all the numbers up to 255, for 256 in total. This means that Rust can safely **cast** a `u8` into a `char`, using `as`. (\"Cast `u8` as `char`\" means \"pretend `u8` is a `char`\")\n\nCasting with `as` is useful because Rust is very strict. It always needs to know the type, and won't let you use two different types together even if they are both integers. For example, this will not work:\n\n```rust\nfn main() { // main() is where Rust programs start to run. Code goes inside {} (curly brackets)\n\n    let my_number = 100; // We didn't write a type of integer,\n                         // so Rust chooses i32. Rust always\n                         // chooses i32 for integers if you don't\n                         // tell it to use a different type\n\n    println!(\"{}\", my_number as char); // ⚠️\n}\n```\n\nHere is the reason:\n\n```text\nerror[E0604]: only `u8` can be cast as `char`, not `i32`\n --> src\\main.rs:3:20\n  |\n3 |     println!(\"{}\", my_number as char);\n  |                    ^^^^^^^^^^^^^^^^^\n```\n\nFortunately we can easily fix this with `as`. We can't cast `i32` as a `char`, but we can cast an `i32` as a `u8`. And then we can do the same from `u8` to `char`. So in one line we use `as` to make my_number a `u8`, and again to make it a `char`. Now it will compile:\n\n```rust\nfn main() {\n    let my_number = 100;\n    println!(\"{}\", my_number as u8 as char);\n}\n```\n\nIt prints `d` because that is the `char` in place 100.\n\nThe easier way, however, is just to tell Rust that `my_number` is a `u8`. Here's how you do it:\n\n```rust\nfn main() {\n    let my_number: u8 = 100; //  change my_number to my_number: u8\n    println!(\"{}\", my_number as char);\n}\n```\n\nSo those are two reasons for all the different number types in Rust. Here is another reason: `usize` is the size that Rust uses for *indexing*. (Indexing means \"which item is first\", \"which item is second\", etc.) `usize` is the best size for indexing because:\n\n- An index can't be negative, so it needs to be a number with a u\n- It should be big, because sometimes you need to index many things, but\n- It can't be a u64 because 32-bit computers can't use u64.\n\nSo Rust uses `usize` so that your computer can get the biggest number for indexing that it can read.\n\n\n\nLet's learn some more about `char`. You saw that a `char` is always one character, and uses `''` instead of `\"\"`.\n\nAll `chars` use 4 bytes of memory, since 4 bytes are enough to hold any kind of character:\n- Basic letters and symbols usually need 1 out of 4 bytes: `a b 1 2 + - = $ @`\n- Other letters like German Umlauts or accents need 2 out of 4 bytes: `ä ö ü ß è é à ñ`\n- Korean, Japanese or Chinese characters need 3 or 4 bytes: `国 안 녕`\n\nWhen using characters as part of a string, the string is encoded to use the least amount of memory needed for each character.\n\nWe can use `.len()` to see this for ourselves:\n\n```rust\nfn main() {\n    println!(\"Size of a char: {}\", std::mem::size_of::<char>()); // 4 bytes\n    println!(\"Size of string containing 'a': {}\", \"a\".len()); // .len() gives the size of the string in bytes\n    println!(\"Size of string containing 'ß': {}\", \"ß\".len());\n    println!(\"Size of string containing '国': {}\", \"国\".len());\n    println!(\"Size of string containing '𓅱': {}\", \"𓅱\".len());\n}\n```\n\nThis prints:\n\n```text\nSize of a char: 4\nSize of string containing 'a': 1\nSize of string containing 'ß': 2\nSize of string containing '国': 3\nSize of string containing '𓅱': 4\n```\n\nYou can see that `a` is one byte, the German `ß` is two, the Japanese `国` is three, and the ancient Egyptian `𓅱` is 4 bytes.\n\n```rust\nfn main() {\n    let slice = \"Hello!\";\n    println!(\"Slice is {} bytes.\", slice.len());\n    let slice2 = \"안녕!\"; // Korean for \"hi\"\n    println!(\"Slice2 is {} bytes.\", slice2.len());\n}\n```\n\nThis prints:\n\n```text\nSlice is 6 bytes.\nSlice2 is 7 bytes.\n```\n\n`slice` is 6 characters in length and 6 bytes, but `slice2` is 3 characters in length and 7 bytes.\n\nIf `.len()` gives the size in bytes, what about the size in characters? We will learn about these methods later, but you can just remember that `.chars().count()` will do it. `.chars().count()` turns what you wrote into characters and then counts how many there are.\n\n\n```rust\nfn main() {\n    let slice = \"Hello!\";\n    println!(\"Slice is {} bytes and also {} characters.\", slice.len(), slice.chars().count());\n    let slice2 = \"안녕!\";\n    println!(\"Slice2 is {} bytes but only {} characters.\", slice2.len(), slice2.chars().count());\n}\n```\n\nThis prints:\n\n```text\nSlice is 6 bytes and also 6 characters.\nSlice2 is 7 bytes but only 3 characters.\n```\n\n## Type inference\n**[See this chapter on YouTube](https://youtu.be/q1D2vpy3kEI)**\n\nType inference means that if you don't tell the compiler the type, but it can decide by itself, it will decide. The compiler always needs to know the type of the variables, but you don’t always need to tell it. Actually, usually you don't need to tell it. For example, for `let my_number = 8`, `my_number` will be an `i32`. That is because the compiler chooses i32 for integers if you don't tell it. But if you say `let my_number: u8 = 8`, it will make `my_number` a `u8`, because you told it `u8`.\n\nSo usually the compiler can guess. But sometimes you need to tell it, for two reasons:\n\n1) You are doing something very complex and the compiler doesn't know the type you want.\n2) You want a different type (for example, you want an `i128`, not an `i32`).\n\nTo specify a type, add a colon after the variable name.\n\n```rust\nfn main() {\n    let small_number: u8 = 10;\n}\n```\n\nFor numbers, you can say the type after the number. You don't need a space - just type it right after the number.\n\n```rust\nfn main() {\n    let small_number = 10u8; // 10u8 = 10 of type u8\n}\n```\n\nYou can also add `_` if you want to make the number easy to read.\n\n```rust\nfn main() {\n    let small_number = 10_u8; // This is easier to read\n    let big_number = 100_000_000_i32; // 100 million is easy to read with _\n}\n```\n\nThe `_` does not change the number. It is only to make it easy for you to read. And it doesn't matter how many `_` you use:\n\n```rust\nfn main() {\n    let number = 0________u8;\n    let number2 = 1___6______2____4______i32;\n    println!(\"{}, {}\", number, number2);\n}\n```\n\nThis prints `0, 1624`.\n\n### Floats\n\nFloats are numbers with decimal points. 5.5 is a float, and 6 is an integer. 5.0 is also a float, and even 5. is a float.\n\n```rust\nfn main() {\n    let my_float = 5.; // Rust sees . and knows that it is a float\n}\n```\n\nBut the types are not called `float`, they are called `f32` and `f64`. It is the same as integers: the number after `f` shows the number of bits. If you don't write the type, Rust will choose `f64`.\n\nOf course, only floats of the same type can be used together. So you can't add an `f32` to an `f64`.\n\n```rust\nfn main() {\n    let my_float: f64 = 5.0; // This is an f64\n    let my_other_float: f32 = 8.5; // This is an f32\n\n    let third_float = my_float + my_other_float; // ⚠️\n}\n```\n\nWhen you try to run this, Rust will say:\n\n```text\nerror[E0308]: mismatched types\n --> src\\main.rs:5:34\n  |\n5 |     let third_float = my_float + my_other_float;\n  |                                  ^^^^^^^^^^^^^^ expected `f64`, found `f32`\n```\n\nThe compiler writes \"expected (type), found (type)\" when you use the wrong type. It reads your code like this:\n\n```rust\nfn main() {\n    let my_float: f64 = 5.0; // The compiler sees an f64\n    let my_other_float: f32 = 8.5; // The compiler sees an f32. It is a different type.\n    let third_float = my_float + // You want to add my_float to something, so it must be an f64 plus another f64. Now it expects an f64...\n    let third_float = my_float + my_other_float;  // ⚠️ but it found an f32. It can't add them.\n}\n```\n\nSo when you see \"expected (type), found (type)\", you must find why the compiler expected a different type.\n\nOf course, with simple numbers it is easy to fix. You can cast the `f32` to an `f64` with `as`:\n\n```rust\nfn main() {\n    let my_float: f64 = 5.0;\n    let my_other_float: f32 = 8.5;\n\n    let third_float = my_float + my_other_float as f64; // my_other_float as f64 = use my_other_float like an f64\n}\n```\n\nOr even more simply, remove the type declarations. (\"to declare a type\" = \"to tell Rust to use the type\") Rust will choose types that can add together.\n\n```rust\nfn main() {\n    let my_float = 5.0; // Rust will choose f64\n    let my_other_float = 8.5; // Here again it will choose f64\n\n    let third_float = my_float + my_other_float;\n}\n```\n\nThe Rust compiler is smart and will not choose f64 if you need f32:\n\n```rust\nfn main() {\n    let my_float: f32 = 5.0;\n    let my_other_float = 8.5; // Usually Rust would choose f64,\n\n    let third_float = my_float + my_other_float; // but now it knows that you need to add it to an f32. So it chooses f32 for my_other_float too\n}\n```\n\n## Printing 'hello, world!'\n**See this chapter on YouTube: [Video 1](https://youtu.be/yYlPHRl2geQ), [Video 2](https://youtu.be/DTCSfBJJZb8)**\n\nWhen you start a new Rust program, it always has this code:\n\n```rust\nfn main() {\n    println!(\"Hello, world!\");\n}\n```\n\n- `fn` means function,\n- `main` is the function that starts the program,\n- `()` means that we didn't give the function any variables to start.\n\n`{}` is called a **code block**. This is the space where code lives.\n\n`println!` is a **macro** that prints to the console. A **macro** is like a function that writes code for you. Macros have a `!` after them. We will learn about making macros later. For now, remember that `!` means that it is a macro.\n\nTo learn about the `;`, we will create another function. First, in `main` we will print a number 8:\n\n```rust\nfn main() {\n    println!(\"Hello, world number {}!\", 8);\n}\n```\n\nThe `{}` in `println!` means \"put the variable inside here\". This prints `Hello, world number 8!`.\n\n\nWe can put more in, just like we did before:\n\n```rust\nfn main() {\n    println!(\"Hello, worlds number {} and {}!\", 8, 9);\n}\n```\n\nThis prints `Hello, worlds number 8 and 9!`.\n\nNow let's create the function.\n\n```rust\nfn number() -> i32 {\n    8\n}\n\nfn main() {\n    println!(\"Hello, world number {}!\", number());\n}\n```\n\nThis also prints `Hello, world number 8!`. When Rust looks at `number()` it sees a function. This function:\n\n- Does not take anything (because it has `()`)\n- Returns an `i32`. The `->` (called a \"skinny arrow\") shows what the function returns.\n\nInside the function is just `8`. Because there is no `;`, this is the value it returns. If it had a `;`, it would not return anything (it would return a `()`). Rust will not compile this if it has a `;`, because the return is `i32` and `;` returns `()`, not `i32`:\n\n```rust\nfn main() {\n    println!(\"Hello, world number {}\", number());\n}\n\nfn number() -> i32 {\n    8;  // ⚠️\n}\n```\n\n```text\n5 | fn number() -> i32 {\n  |    ------      ^^^ expected `i32`, found `()`\n  |    |\n  |    implicitly returns `()` as its body has no tail or `return` expression\n6 |     8;\n  |      - help: consider removing this semicolon\n```\n\nThis means \"you told me that `number()` returns an `i32`, but you added a `;` so it doesn't return anything\". So the compiler suggests removing the semicolon.\n\nYou can also write `return 8;` but in Rust it is normal to just remove the `;` to `return`.\n\nWhen you want to give variables to a function, put them inside the `()`. You have to give them a name and write the type.\n\n```rust\nfn multiply(number_one: i32, number_two: i32) { // Two i32s will enter the function. We will call them number_one and number_two.\n    let result = number_one * number_two;\n    println!(\"{} times {} is {}\", number_one, number_two, result);\n}\n\nfn main() {\n    multiply(8, 9); // We can give the numbers directly\n    let some_number = 10; // Or we can declare two variables\n    let some_other_number = 2;\n    multiply(some_number, some_other_number); // and put them in the function\n}\n```\n\nWe can also return an `i32`. Just take out the semicolon at the end:\n\n```rust\nfn multiply(number_one: i32, number_two: i32) -> i32 {\n    let result = number_one * number_two;\n    println!(\"{} times {} is {}\", number_one, number_two, result);\n    result // this is the i32 that we return\n}\n\nfn main() {\n    let multiply_result = multiply(8, 9); // We used multiply() to print and to give the result to multiply_result\n}\n```\n\n### Declaring variables and code blocks\n\nUse `let` to declare a variable (declare a variable = tell Rust to make a variable).\n\n```rust\nfn main() {\n    let my_number = 8;\n    println!(\"Hello, number {}\", my_number);\n}\n```\n\nVariables start and end inside a code block `{}`. In this example, `my_number` ends before we call `println!`, because it is inside its own code block.\n\n```rust\nfn main() {\n    {\n        let my_number = 8; // my_number starts here\n                           // my_number ends here!\n    }\n\n    println!(\"Hello, number {}\", my_number); // ⚠️ there is no my_number and\n                                             // println!() can't find it\n}\n```\n\nYou can use a code block to return a value:\n\n```rust\nfn main() {\n    let my_number = {\n        let second_number = 8;\n        second_number + 9 // No semicolon, so the code block returns 8 + 9.\n                          // It works just like a function\n    };\n\n    println!(\"My number is: {}\", my_number);\n}\n```\n\nIf you add a semicolon inside the block, it will return `()` (nothing):\n\n```rust\nfn main() {\n    let my_number = {\n        let second_number = 8; // declare second_number,\n        second_number + 9; // add 9 to second_number\n                           // but we didn't return it!\n                           // second_number dies now\n    };\n\n    println!(\"My number is: {:?}\", my_number); // my_number is ()\n}\n```\n\nSo why did we write `{:?}` and not `{}`? We will talk about that now.\n\n## Display and debug\n**[See this chapter on YouTube](https://youtu.be/jd3pC248c0o)**\n\nSimple variables in Rust can be printed with `{}` inside `println!`. But some variables can't, and you need to **debug print**. Debug print is printing for the programmer, because it usually shows more information. Debug sometimes doesn't look pretty, because it has extra information to help you.\n\nHow do you know if you need `{:?}` and not `{}`? The compiler will tell you. For example:\n\n```rust\nfn main() {\n    let doesnt_print = ();\n    println!(\"This will not print: {}\", doesnt_print); // ⚠️\n}\n```\n\nWhen we run this, the compiler says:\n\n```text\nerror[E0277]: `()` doesn't implement `std::fmt::Display`\n --> src\\main.rs:3:41\n  |\n3 |     println!(\"This will not print: {}\", doesnt_print);\n  |                                         ^^^^^^^^^^^^ `()` cannot be formatted with the default formatter\n  |\n  = help: the trait `std::fmt::Display` is not implemented for `()`\n  = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead\n  = note: required by `std::fmt::Display::fmt`\n  = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)\n```\n\nThis is a lot of information. But the important part is: `you may be able to use {:?} (or {:#?} for pretty-print) instead`. This means that you can try `{:?}`, and also `{:#?}` `{:#?}` is called \"pretty printing\". It is like `{:?}` but prints with different formatting over more lines.\n\nSo Display means printing with `{}`, and Debug means printing with `{:?}`.\n\nOne more thing: you can also use `print!` without `ln` if you don't want a new line.\n\n```rust\nfn main() {\n    print!(\"This will not print a new line\");\n    println!(\" so this will be on the same line\");\n}\n```\n\nThis prints `This will not print a new line so this will be on the same line`.\n\n### Smallest and largest numbers\n\nIf you want to see the smallest and biggest numbers, you can use MIN and MAX after the name of the type:\n\n```rust\nfn main() {\n    println!(\"The smallest i8 is {} and the biggest i8 is {}.\", i8::MIN, i8::MAX); // hint: printing std::i8::MIN means \"print MIN inside of the i8 section in the standard library\"\n    println!(\"The smallest u8 is {} and the biggest u8 is {}.\", u8::MIN, u8::MAX);\n    println!(\"The smallest i16 is {} and the biggest i16 is {}.\", i16::MIN, i16::MAX);\n    println!(\"The smallest u16 is {} and the biggest u16 is {}.\", u16::MIN, u16::MAX);\n    println!(\"The smallest i32 is {} and the biggest i32 is {}.\", i32::MIN, i32::MAX);\n    println!(\"The smallest u32 is {} and the biggest u32 is {}.\", u32::MIN, u32::MAX);\n    println!(\"The smallest i64 is {} and the biggest i64 is {}.\", i64::MIN, i64::MAX);\n    println!(\"The smallest u64 is {} and the biggest u64 is {}.\", u64::MIN, u64::MAX);\n    println!(\"The smallest i128 is {} and the biggest i128 is {}.\", i128::MIN, i128::MAX);\n    println!(\"The smallest u128 is {} and the biggest u128 is {}.\", u128::MIN, u128::MAX);\n\n}\n```\n\nThis will print:\n\n```text\nThe smallest i8 is -128 and the biggest i8 is 127.\nThe smallest u8 is 0 and the biggest u8 is 255.\nThe smallest i16 is -32768 and the biggest i16 is 32767.\nThe smallest u16 is 0 and the biggest u16 is 65535.\nThe smallest i32 is -2147483648 and the biggest i32 is 2147483647.\nThe smallest u32 is 0 and the biggest u32 is 4294967295.\nThe smallest i64 is -9223372036854775808 and the biggest i64 is 9223372036854775807.\nThe smallest u64 is 0 and the biggest u64 is 18446744073709551615.\nThe smallest i128 is -170141183460469231731687303715884105728 and the biggest i128 is 170141183460469231731687303715884105727.\nThe smallest u128 is 0 and the biggest u128 is 340282366920938463463374607431768211455.\n```\n\n## Mutability (changing)\n**[See this chapter on YouTube](https://youtu.be/Nyyd6qn7dZY)**\n\nWhen you declare a variable with `let`, it is immutable (cannot be changed).\n\nThis will not work:\n\n```rust\nfn main() {\n    let my_number = 8;\n    my_number = 10; // ⚠️\n}\n```\n\nThe compiler says: `error[E0384]: cannot assign twice to immutable variable my_number`. This is because variables are immutable if you only write `let`.\n\nBut sometimes you want to change your variable. To make a variable that you can change, add `mut` after `let`:\n\n```rust\nfn main() {\n    let mut my_number = 8;\n    my_number = 10;\n}\n```\n\nNow there is no problem.\n\nHowever, you cannot change the type: even `mut` doesn't let you do that. This will not work:\n\n```rust\nfn main() {\n    let mut my_variable = 8; // it is now an i32. That can't be changed\n    my_variable = \"Hello, world!\"; // ⚠️\n}\n```\n\nYou will see the same \"expected\" message from the compiler: `expected integer, found &str`. `&str` is a string type that we will learn soon.\n\n### Shadowing\n**[See this chapter on YouTube](https://youtu.be/InULHyRGw7g)**\n\nShadowing means using `let` to declare a new variable with the same name as another variable. It looks like mutability, but it is completely different. Shadowing looks like this:\n\n```rust\nfn main() {\n    let my_number = 8; // This is an i32\n    println!(\"{}\", my_number); // prints 8\n    let my_number = 9.2; // This is an f64 with the same name. But it's not the first my_number - it is completely different!\n    println!(\"{}\", my_number) // Prints 9.2\n}\n```\n\nHere we say that we \"shadowed\" `my_number` with a new \"let binding\".\n\nSo is the first `my_number` destroyed? No, but when we call `my_number` we now get `my_number` the `f64`. And because they are in the same scope block (the same `{}`), we can't see the first `my_number` anymore.\n\nBut if they are in different blocks, we can see both. For example:\n\n```rust\nfn main() {\n    let my_number = 8; // This is an i32\n    println!(\"{}\", my_number); // prints 8\n    {\n        let my_number = 9.2; // This is an f64. It is not my_number - it is completely different!\n        println!(\"{}\", my_number) // Prints 9.2\n                                  // But the shadowed my_number only lives until here.\n                                  // The first my_number is still alive!\n    }\n    println!(\"{}\", my_number); // prints 8\n}\n```\n\nSo when you shadow a variable, you don't destroy it. You **block** it.\n\nSo what is the advantage of shadowing? Shadowing is good when you need to change a variable a lot. Imagine that you want to do a lot of simple math with a variable:\n\n```rust\nfn times_two(number: i32) -> i32 {\n    number * 2\n}\n\nfn main() {\n    let final_number = {\n        let y = 10;\n        let x = 9; // x starts at 9\n        let x = times_two(x); // shadow with new x: 18\n        let x = x + y; // shadow with new x: 28\n        x // return x: final_number is now the value of x\n    };\n    println!(\"The number is now: {}\", final_number)\n}\n```\n\nWithout shadowing you would have to think of different names, even though you don't care about x:\n\n```rust\nfn times_two(number: i32) -> i32 {\n    number * 2\n}\n\nfn main() {\n    // Pretending we are using Rust without shadowing\n    let final_number = {\n        let y = 10;\n        let x = 9; // x starts at 9\n        let x_twice = times_two(x); // second name for x\n        let x_twice_and_y = x_twice + y; // third name for x!\n        x_twice_and_y // too bad we didn't have shadowing - we could have just used x\n    };\n    println!(\"The number is now: {}\", final_number)\n}\n```\n\nIn general, you see shadowing in Rust in this case. It happens where you want to quickly take variable, do something to it, and do something else again. And you usually use it for quick variables that you don't care too much about.\n\n## The stack, the heap, and pointers\n\nThe stack, the heap, and pointers are very important in Rust.\n\nThe stack and the heap are two places to keep memory in computers. The important differences are:\n\n- The stack is very fast, but the heap is not so fast. It's not super slow either, but the stack is always faster. But you can't just use the stack all the time, because:\n- Rust needs to know the size of a variable at compile time. So simple variables like `i32` go on the stack, because we know their exact size. You always know that an `i32` is going to be 4 bytes, because 32 bits = 4 bytes. So `i32` can always go on the stack.\n- But some types don't know the size at compile time. But the stack needs to know the exact size. So what do you do? First you put the data in the heap, because the heap can have any size of data. And then to find it a pointer goes on the stack. This is fine because we always know the size of a pointer. So then the computer first goes to the stack, reads the pointer, and follows it to the heap where the data is.\n\nPointers sound complicated, but they are easy. Pointers are like a table of contents in a book. Imagine this book:\n\n```text\nMY BOOK\n\nTABLE OF CONTENTS\n\nChapter                        Page\nChapter 1: My life              1\nChapter 2: My cat               15\nChapter 3: My job               23\nChapter 4: My family            30\nChapter 5: Future plans         43\n```\n\nSo this is like five pointers. You can read them and find the information they are talking about. Where is the chapter \"My life\"? It's on page 1 (it *points* to page 1). Where is the chapter \"My job?\" It's on page 23.\n\nThe pointer you usually see in Rust is called a **reference**. This is the important part to know: a reference points to the memory of another value. A reference means you *borrow* the value, but you don't own it. It's the same as our book: the table of contents doesn't own the information. It's the chapters that own the information. In Rust, references have a `&` in front of them. So:\n\n- `let my_variable = 8` makes a regular variable, but\n- `let my_reference = &my_variable` makes a reference.\n\nYou read `my_reference = &my_variable` like this: \"my_reference is a reference to my_variable\". Or: \"my_reference refers to my_variable\".\n\nThis means that `my_reference` is only looking at the data of `my_variable`. `my_variable` still owns its data.\n\nYou can also have a reference to a reference, or any number of references.\n\n```rust\nfn main() {\n    let my_number = 15; // This is an i32\n    let single_reference = &my_number; //  This is a &i32\n    let double_reference = &single_reference; // This is a &&i32\n    let five_references = &&&&&my_number; // This is a &&&&&i32\n}\n```\n\nThese are all different types, just in the same way that \"a friend of a friend\" is different from \"a friend\".\n\n## More about printing\n\nIn Rust you can print things in almost any way you want. Here are some more things to know about printing.\n\nAdding `\\n` will make a new line, and `\\t` will make a tab:\n\n```rust\nfn main() {\n    // Note: this is print!, not println!\n    print!(\"\\t Start with a tab\\nand move to a new line\");\n}\n```\n\nThis prints:\n\n```text\n         Start with a tab\nand move to a new line\n```\n\nInside `\"\"` you can write over many lines with no problem, but be careful with the spacing:\n\n```rust\nfn main() {\n    // Note: After the first line you have to start on the far left.\n    // If you write directly under println!, it will add the spaces\n    println!(\"Inside quotes\nyou can write over\nmany lines\nand it will print just fine.\");\n\n    println!(\"If you forget to write\n    on the left side, the spaces\n    will be added when you print.\");\n}\n```\n\nThis prints:\n\n```text\nInside quotes\nyou can write over\nmany lines\nand it will print just fine.\nIf you forget to write\n    on the left side, the spaces\n    will be added when you print.\n```\n\nIf you want to print characters like `\\n` (called \"escape characters\"), you can add an extra `\\`:\n\n```rust\nfn main() {\n    println!(\"Here are two escape characters: \\\\n and \\\\t\");\n}\n```\n\nThis prints:\n\n```text\nHere are two escape characters: \\n and \\t\n```\n\nSometimes you have too many `\"` and escape characters, and want Rust to ignore everything. To do this, you can add `r#` to the beginning and `#` to the end.\n\n```rust\nfn main() {\n    println!(\"He said, \\\"You can find the file at c:\\\\files\\\\my_documents\\\\file.txt.\\\" Then I found the file.\"); // We used \\ five times here\n    println!(r#\"He said, \"You can find the file at c:\\files\\my_documents\\file.txt.\" Then I found the file.\"#)\n}\n```\n\nThis prints the same thing, but using `r#` makes it easier for humans to read.\n\n```text\nHe said, \"You can find the file at c:\\files\\my_documents\\file.txt.\" Then I found the file.\nHe said, \"You can find the file at c:\\files\\my_documents\\file.txt.\" Then I found the file.\n```\n\nIf you need to print with a `#` inside, then you can start with `r##` and end with `##`. And if you need more than one, you can add one more # on each side.\n\nHere are four examples:\n\n```rust\nfn main() {\n\n    let my_string = \"'Ice to see you,' he said.\"; // single quotes\n    let quote_string = r#\"\"Ice to see you,\" he said.\"#; // double quotes\n    let hashtag_string = r##\"The hashtag #IceToSeeYou had become very popular.\"##; // Has one # so we need at least ##\n    let many_hashtags = r####\"\"You don't have to type ### to use a hashtag. You can just use #.\"\"####; // Has three ### so we need at least ####\n\n    println!(\"{}\\n{}\\n{}\\n{}\\n\", my_string, quote_string, hashtag_string, many_hashtags);\n\n}\n```\n\nThis will print:\n\n```text\n'Ice to see you,' he said.\n\"Ice to see you,\" he said.\nThe hashtag #IceToSeeYou had become very popular.\n\"You don't have to type ### to use a hashtag. You can just use #.\"\n```\n\n`r#` has another use: with it you can use a keyword (words like `let`, `fn`, etc.) as a variable name.\n\n```rust\nfn main() {\n    let r#let = 6; // The variable's name is let\n    let mut r#mut = 10; // This variable's name is mut\n}\n```\n\n`r#` has this function because older versions of Rust had fewer keywords than Rust now. So with `r#` you can avoid mistakes with variable names that were not keywords before.\n\nOr maybe for some reason you *really* need a function to have a name like `return`. Then you can write this:\n\n```rust\nfn r#return() -> u8 {\n    println!(\"Here is your number.\");\n    8\n}\n\nfn main() {\n    let my_number = r#return();\n    println!(\"{}\", my_number);\n}\n```\n\nThis prints:\n\n```text\nHere is your number.\n8\n```\n\nSo you probably won't need it, but if you really need to use a keyword for a variable then you can use `r#`.\n\n\n\nIf you want to print the bytes of a `&str` or a `char`, you can just write `b` before the string. This works for all ASCII characters. These are all the ASCII characters:\n\n```text\n☺☻♥♦♣♠♫☼►◄↕‼¶§▬↨↑↓→∟↔▲▼123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\n```\n\nSo when you print this:\n\n```rust\nfn main() {\n    println!(\"{:?}\", b\"This will look like numbers\");\n}\n```\n\nHere is the result:\n\n```text\n[84, 104, 105, 115, 32, 119, 105, 108, 108, 32, 108, 111, 111, 107, 32, 108, 105, 107, 101, 32, 110, 117, 109, 98, 101, 114, 115]\n```\n\nFor a `char` this is called a *byte*, and for a `&str` it's called a *byte string*.\n\n\nYou can also put `b` and `r` together if you need to:\n\n```rust\nfn main() {\n    println!(\"{:?}\", br##\"I like to write \"#\".\"##);\n}\n```\n\nThat will print `[73, 32, 108, 105, 107, 101, 32, 116, 111, 32, 119, 114, 105, 116, 101, 32, 34, 35, 34, 46]`.\n\n\n\nThere is also a Unicode escape that lets you print any Unicode character inside a string: `\\u{}`. A hexadecimal number goes inside the `{}` to print it. Here is a short example of how to get the Unicode number, and how to print it again.\n\n```rust\nfn main() {\n    println!(\"{:X}\", '행' as u32); // Cast char as u32 to get the hexadecimal value\n    println!(\"{:X}\", 'H' as u32);\n    println!(\"{:X}\", '居' as u32);\n    println!(\"{:X}\", 'い' as u32);\n\n    println!(\"\\u{D589}, \\u{48}, \\u{5C45}, \\u{3044}\"); // Try printing them with unicode escape \\u\n}\n```\n\n\n\nWe know that `println!` can print with `{}` (for Display) and `{:?}` (for Debug), plus `{:#?}` for pretty printing. But there are many other ways to print.\n\nFor example, if you have a reference, you can use `{:p}` to print the *pointer address*. Pointer address means the location in your computer's memory.\n\n```rust\nfn main() {\n    let number = 9;\n    let number_ref = &number;\n    println!(\"{:p}\", number_ref);\n}\n```\n\nThis prints `0xe2bc0ffcfc` or some other address. It might be different every time, depending on where your computer stores it.\n\nOr you can print binary, hexadecimal and octal:\n\n```rust\nfn main() {\n    let number = 555;\n    println!(\"Binary: {:b}, hexadecimal: {:x}, octal: {:o}\", number, number, number);\n}\n```\n\nThis prints `Binary: 1000101011, hexadecimal: 22b, octal: 1053`.\n\nOr you can add numbers to change the order. The first variable will be in index 0, the next in index 1, and so on.\n\n```rust\nfn main() {\n    let father_name = \"Vlad\";\n    let son_name = \"Adrian Fahrenheit\";\n    let family_name = \"Țepeș\";\n    println!(\"This is {1} {2}, son of {0} {2}.\", father_name, son_name, family_name);\n}\n```\n\n`father_name` is in position 0, `son_name` is in position 1, and `family_name` is in position 2. So it prints `This is Adrian Fahrenheit Țepeș, son of Vlad Țepeș`.\n\n\nMaybe you have a very complex string to print with too many variables inside the `{}` curly brackets. Or maybe you need to print a variable more than one time. Then it can help to add names to the `{}`:\n\n```rust\nfn main() {\n    println!(\n        \"{city1} is in {country} and {city2} is also in {country},\nbut {city3} is not in {country}.\",\n        city1 = \"Seoul\",\n        city2 = \"Busan\",\n        city3 = \"Tokyo\",\n        country = \"Korea\"\n    );\n}\n```\n\nThat will print:\n\n```text\nSeoul is in Korea and Busan is also in Korea,\nbut Tokyo is not in Korea.\n```\n\n\nVery complex printing is also possible in Rust if you want to use it. Here is how to do it:\n\n{variable:padding alignment minimum.maximum}\n\nTo understand this, look at the\n\n1) Do you want a variable name? Write that first, like when we wrote {country} above.\n(Then add a `:` after it if you want to do more things)\n2) Do you want a padding character? For example, 55 with three \"padding zeros\" looks like 00055.\n3) What alignment (left / middle / right) for the padding?\n4) Do you want a minimum length? (just write a number)\n5) Do you want a maximum length? (write a number with a `.` in front)\n\nFor example, if I want to write \"a\" with five ㅎ characters on the left and five ㅎ characters on the right:\n\n```rust\nfn main() {\n    let letter = \"a\";\n    println!(\"{:ㅎ^11}\", letter);\n}\n```\n\nThis prints `ㅎㅎㅎㅎㅎaㅎㅎㅎㅎㅎ`. Let's look at 1) to 5) for this to understand how the compiler reads it.\n\n- Do you want a variable name? `{:ㅎ^11}` There is no variable name. There is nothing before `:`.\n- Do you want a padding character? `{:ㅎ^11}` Yes. ㅎ comes after the `:` and has a `^`. `<` means padding with the character on the left, `>` means on the right, and `^` means in the middle.\n- Do you want a minimum length? `{:ㅎ^11}` Yes: there is an 11 after.\n- Do you want a maximum length? `{:ㅎ^11}` No: there is no number with a `.` before.\n\nHere is an example of many types of formatting.\n\n```rust\nfn main() {\n    let title = \"TODAY'S NEWS\";\n    println!(\"{:-^30}\", title); // no variable name, pad with -, put in centre, 30 characters long\n    let bar = \"|\";\n    println!(\"{: <15}{: >15}\", bar, bar); // no variable name, pad with space, 15 characters each, one to the left, one to the right\n    let a = \"SEOUL\";\n    let b = \"TOKYO\";\n    println!(\"{city1:-<15}{city2:->15}\", city1 = a, city2 = b); // variable names city1 and city2, pad with -, one to the left, one to the right\n}\n```\n\nIt prints:\n\n```text\n---------TODAY'S NEWS---------\n|                            |\nSEOUL--------------------TOKYO\n```\n\n## Strings\n**[See this chapter on YouTube](https://youtu.be/pSyaGzGg26o)**\n\nRust has two main types of strings: `String` and `&str`. What is the difference?\n\n- `&str` is a simple string. When you write `let my_variable = \"Hello, world!\"`, you create a `&str`. A `&str` is very fast.\n- `String` is a more complicated string. It is a bit slower, but it has more functions. A `String` is a pointer, with data on the heap.\n\nAlso note that `&str` has the `&` in front of it because you need a reference to use a `str`. That's because of the reason we saw above: the stack needs to know the size. So we give it a `&` that it knows the size of, and then it is happy. Also, because you use a `&` to interact with a `str`, you don't own it. But a `String` is an *owned* type. We will soon learn why that is important to know.\n\nBoth `&str` and `String` are UTF-8. For example, you can write:\n\n```rust\nfn main() {\n    let name = \"서태지\"; // This is a Korean name. No problem, because a &str is UTF-8.\n    let other_name = String::from(\"Adrian Fahrenheit Țepeș\"); // Ț and ș are no problem in UTF-8.\n}\n```\n\nYou can see in `String::from(\"Adrian Fahrenheit Țepeș\")` that it is easy to make a `String` from a `&str`. The two types are very closely linked together, even though they are different.\n\nYou can even write emojis, thanks to UTF-8.\n\n```rust\nfn main() {\n    let name = \"😂\";\n    println!(\"My name is actually {}\", name);\n}\n```\n\nOn your computer that will print `My name is actually 😂` unless your command line can't print it. Then it will show `My name is actually �`. But Rust has no problem with emojis or any other Unicode.\n\nLet's look at the reason for using a `&` for `str`s again to make sure we understand.\n\n- `str` is a dynamically sized type (dynamically sized = the size can be different). For example, the names \"서태지\" and \"Adrian Fahrenheit Țepeș\" are not the same size:\n\n```rust\nfn main() {\n\n    println!(\"A String is always {:?} bytes. It is Sized.\", std::mem::size_of::<String>()); // std::mem::size_of::<Type>() gives you the size in bytes of a type\n    println!(\"And an i8 is always {:?} bytes. It is Sized.\", std::mem::size_of::<i8>());\n    println!(\"And an f64 is always {:?} bytes. It is Sized.\", std::mem::size_of::<f64>());\n    println!(\"But a &str? It can be anything. '서태지' is {:?} bytes. It is not Sized.\", std::mem::size_of_val(\"서태지\")); // std::mem::size_of_val() gives you the size in bytes of a variable\n    println!(\"And 'Adrian Fahrenheit Țepeș' is {:?} bytes. It is not Sized.\", std::mem::size_of_val(\"Adrian Fahrenheit Țepeș\"));\n}\n```\n\nThis prints:\n\n```text\nA String is always 24 bytes. It is Sized.\nAnd an i8 is always 1 bytes. It is Sized.\nAnd an f64 is always 8 bytes. It is Sized.\nBut a &str? It can be anything. '서태지' is 9 bytes. It is not Sized.\nAnd 'Adrian Fahrenheit Țepeș' is 25 bytes. It is not Sized.\n```\n\nThat is why we need a &, because `&` makes a pointer, and Rust knows the size of the pointer. So the pointer goes on the stack. If we wrote `str`, Rust wouldn't know what to do because it doesn't know the size.\n\n\n\nThere are many ways to make a `String`. Here are some:\n\n- `String::from(\"This is the string text\");` This is a method for String that takes text and creates a String.\n- `\"This is the string text\".to_string()`. This is a method for &str that makes it a String.\n- The `format!` macro. This is like `println!` except it creates a String instead of printing. So you can do this:\n\n```rust\nfn main() {\n    let my_name = \"Billybrobby\";\n    let my_country = \"USA\";\n    let my_home = \"Korea\";\n\n    let together = format!(\n        \"I am {} and I come from {} but I live in {}.\",\n        my_name, my_country, my_home\n    );\n}\n```\n\nNow we have a String named *together*, but did not print it yet.\n\nOne other way to make a String is called `.into()` but it is a bit different because `.into()` isn't just for making a `String`. Some types can easily convert to and from another type using `From` and `.into()`. And if you have `From`, then you also have `.into()`. `From` is clearer because you already know the types: you know that `String::from(\"Some str\")` is a `String` from a `&str`. But with `.into()`, sometimes the compiler doesn't know:\n\n```rust\nfn main() {\n    let my_string = \"Try to make this a String\".into(); // ⚠️\n}\n```\n\nRust doesn't know what type you want, because many types can be made from a `&str`. It says, \"I can make a &str into a lot of things. Which one do you want?\"\n\n```text\nerror[E0282]: type annotations needed\n --> src\\main.rs:2:9\n  |\n2 |     let my_string = \"Try to make this a String\".into();\n  |         ^^^^^^^^^ consider giving `my_string` a type\n```\n\nSo you can do this:\n\n```rust\nfn main() {\n    let my_string: String = \"Try to make this a String\".into();\n}\n```\n\nAnd now you get a String.\n\n## const and static\n**[See this chapter on YouTube](https://youtu.be/Ky3HqkWUcI0)**\n\nThere are two other ways to declare values, not just with `let`. These are `const` and `static`. Also, Rust won't use type inference: you need to write the type for them. These are for values that don't change (`const` means constant). The difference is that:\n\n- `const` is for values that don't change, the name is replaced with the value when it's used,\n- `static` is similar to `const`, but has a fixed memory location and can act as a global variable.\n\nSo they are almost the same. Rust programmers almost always use `const`.\n\nYou write them with ALL CAPITAL LETTERS, and usually outside of `main` so that they can live for the whole program.\n\nTwo examples are: `const NUMBER_OF_MONTHS: u32 = 12;` and `static SEASONS: [&str; 4] = [\"Spring\", \"Summer\", \"Fall\", \"Winter\"];`\n\n## More on references\n**[See this chapter on YouTube](https://youtu.be/R13sQ8SNoEQ)**\n\nReferences are very important in Rust. Rust uses references to make sure that all memory access is safe. We know that we use `&` to create a reference:\n\n```rust\nfn main() {\n    let country = String::from(\"Austria\");\n    let ref_one = &country;\n    let ref_two = &country;\n\n    println!(\"{}\", ref_one);\n}\n```\n\nThis prints `Austria`.\n\nIn the code, `country` is a `String`. We then created two references to `country`. They have the type `&String`, which you say is a \"reference to a String\". We could create three references or one hundred references to `country` and it would be no problem.\n\nBut this is a problem:\n\n```rust\nfn return_str() -> &str {\n    let country = String::from(\"Austria\");\n    let country_ref = &country;\n    country_ref // ⚠️\n}\n\nfn main() {\n    let country = return_str();\n}\n```\n\nThe function `return_str()` creates a String, then it creates a reference to the String. Then it tries to return the reference. But the String `country` only lives inside the function, and then it dies. Once a variable is gone, the computer will clean up the memory and use it for something else. So after the function is over, `country_ref` is referring to memory that is already gone, and that's not okay. Rust prevents us from making a mistake with memory here.\n\nThis is the important part about the \"owned\" type that we talked about above. Because you own a `String`, you can pass it around. But a `&String` will die if its `String` dies, so you don't pass around \"ownership\" with it.\n\n## Mutable references\n**[See this chapter on YouTube](https://youtu.be/G48z6Rv76vc)**\n\nIf you want to use a reference to change data, you can use a mutable reference. For a mutable reference, you write `&mut` instead of `&`.\n\n```rust\nfn main() {\n    let mut my_number = 8; // don't forget to write mut here!\n    let num_ref = &mut my_number;\n}\n```\n\nSo what are the two types? `my_number` is an `i32`, and `num_ref` is `&mut i32` (we say a \"mutable reference to an `i32`\").\n\nSo let's use it to add 10 to my_number. But you can't write `num_ref += 10`, because `num_ref` is not the `i32` value, it is a `&i32`. The value is actually inside the `i32`. To reach the place where the value is, we use `*`. `*` means \"I don't want the reference, I want the value behind the reference\". In other words, one `*` is the opposite of `&`. Also, one `*` erases one `&`.\n\n```rust\nfn main() {\n    let mut my_number = 8;\n    let num_ref = &mut my_number;\n    *num_ref += 10; // Use * to change the i32 value.\n    println!(\"{}\", my_number);\n\n    let second_number = 800;\n    let triple_reference = &&&second_number;\n    println!(\"Second_number = triple_reference? {}\", second_number == ***triple_reference);\n}\n```\n\nThis prints:\n\n```text\n18\nSecond_number = triple_reference? true\n```\n\nBecause using `&` is called \"referencing\", using `*` is called \"**de**referencing\".\n\nRust has two rules for mutable and immutable references. They are very important, but also easy to remember because they make sense.\n\n- **Rule 1**: If you have only immutable references, you can have as many as you want. 1 is fine, 3 is fine, 1000 is fine. No problem.\n- **Rule 2**: If you have a mutable reference, you can only have one. Also, you can't have an immutable reference **and** a mutable reference together.\n\nThis is because mutable references can change the data. You could get problems if you change the data when other references are reading it.\n\n\nA good way to understand is to think of a Powerpoint presentation.\n\nSituation one is about **only one mutable reference**.\n\nSituation one: An employee is writing a Powerpoint presentation. He wants his manager to help him. The employee gives his login information to his manager, and asks him to help by making edits. Now the manager has a \"mutable reference\" to the employee's presentation. The manager can make any changes he wants, and give the computer back later. This is fine, because nobody else is looking at the presentation.\n\nSituation two is about **only immutable references**.\n\nSituation two: The employee is giving the presentation to 100 people. All 100 people can now see the employee's data. They all have an \"immutable reference\" to the employee's presentation. This is fine, because they can see it but nobody can change the data.\n\nSituation three is **the problem situation**.\n\nSituation three: The Employee gives his manager his login information. His manager now has a \"mutable reference\". Then the employee went to give the presentation to 100 people, but the manager can still login. This is not fine, because the manager can log in and do anything. Maybe his manager will log into the computer and start typing an email to his mother! Now the 100 people have to watch the manager write an email to his mother instead of the presentation. That's not what they expected to see.\n\nHere is an example of a mutable borrow with an immutable borrow:\n\n```rust\nfn main() {\n    let mut number = 10;\n    let number_ref = &number;\n    let number_change = &mut number;\n    *number_change += 10;\n    println!(\"{}\", number_ref); // ⚠️\n}\n```\n\nThe compiler prints a helpful message to show us the problem.\n\n```text\nerror[E0502]: cannot borrow `number` as mutable because it is also borrowed as immutable\n --> src\\main.rs:4:25\n  |\n3 |     let number_ref = &number;\n  |                      ------- immutable borrow occurs here\n4 |     let number_change = &mut number;\n  |                         ^^^^^^^^^^^ mutable borrow occurs here\n5 |     *number_change += 10;\n6 |     println!(\"{}\", number_ref);\n  |                    ---------- immutable borrow later used here\n```\n\nHowever, this code will work. Why?\n\n```rust\nfn main() {\n    let mut number = 10;\n    let number_change = &mut number; // create a mutable reference\n    *number_change += 10; // use mutable reference to add 10\n    let number_ref = &number; // create an immutable reference\n    println!(\"{}\", number_ref); // print the immutable reference\n}\n```\n\nIt prints `20` with no problem. It works because the compiler is smart enough to understand our code. It knows that we used `number_change` to change `number`, but didn't use it again. So here there is no problem. We are not using immutable and mutable references together.\n\nEarlier in Rust this kind of code actually generated an error, but the compiler is smarter now. It can understand not just what we type, but how we use everything.\n\n### Shadowing again\n\nRemember when we said that shadowing doesn't **destroy** a value but **blocks** it? Now we can use references to see this.\n\n```rust\nfn main() {\n    let country = String::from(\"Austria\");\n    let country_ref = &country;\n    let country = 8;\n    println!(\"{}, {}\", country_ref, country);\n}\n```\n\nDoes this print `Austria, 8` or `8, 8`? It prints `Austria, 8`. First we declare a `String` called `country`. Then we create a reference `country_ref` to this string. Then we shadow country with 8, which is an `i32`. But the first `country` was not destroyed, so `country_ref` still says \"Austria\", not \"8\". Here is the same code with some comments to show how it works:\n\n```rust\nfn main() {\n    let country = String::from(\"Austria\"); // Now we have a String called country\n    let country_ref = &country; // country_ref is a reference to this data. It's not going to change\n    let country = 8; // Now we have a variable called country that is an i8. But it has no relation to the other one, or to country_ref\n    println!(\"{}, {}\", country_ref, country); // country_ref still refers to the data of String::from(\"Austria\") that we gave it.\n}\n```\n\n## Giving references to functions\n**See this chapter on YouTube: [immutable references](https://youtu.be/mKWXt9YTavc) and [mutable references](https://youtu.be/kJV1wIvAbyk)**\n\nReferences are very useful for functions. The rule in Rust on values is: a value can only have one owner.\n\nThis code will not work:\n\n```rust\nfn print_country(country_name: String) {\n    println!(\"{}\", country_name);\n}\n\nfn main() {\n    let country = String::from(\"Austria\");\n    print_country(country); // We print \"Austria\"\n    print_country(country); // ⚠️ That was fun, let's do it again!\n}\n```\n\nIt does not work because `country` is destroyed. Here's how:\n\n- Step 1: We create the `String` called `country`. `country` is the owner.\n- Step 2: We give `country` to `print_country`. `print_country` doesn't have an `->`, so it doesn't return anything. After `print_country` finishes, our `String` is now dead.\n- Step 3: We try to give `country` to `print_country`, but we already did that. We don't have `country` to give anymore.\n\nWe can make `print_country` give the `String` back, but it is a bit awkward.\n\n```rust\nfn print_country(country_name: String) -> String {\n    println!(\"{}\", country_name);\n    country_name // return it here\n}\n\nfn main() {\n    let country = String::from(\"Austria\");\n    let country = print_country(country); // we have to use let here now to get the String back\n    print_country(country);\n}\n```\n\nNow it prints:\n\n```text\nAustria\nAustria\n```\n\nThe much better way to fix this is by adding `&`.\n\n```rust\nfn print_country(country_name: &String) {\n    println!(\"{}\", country_name);\n}\n\nfn main() {\n    let country = String::from(\"Austria\");\n    print_country(&country); // We print \"Austria\"\n    print_country(&country); // That was fun, let's do it again!\n}\n```\n\nNow `print_country()` is a function that takes a reference to a `String`: a `&String`. Also, we give it a reference to country by writing `&country`. This says \"you can look at it, but I will keep it\".\n\nNow let's do something similar with a mutable reference. Here is an example of a function that uses a mutable variable.\n\n```rust\nfn add_hungary(country_name: &mut String) { // first we say that the function takes a mutable reference\n    country_name.push_str(\"-Hungary\"); // push_str() adds a &str to a String\n    println!(\"Now it says: {}\", country_name);\n}\n\nfn main() {\n    let mut country = String::from(\"Austria\");\n    add_hungary(&mut country); // we also need to give it a mutable reference.\n}\n```\n\nThis prints `Now it says: Austria-Hungary`.\n\nSo to conclude:\n\n- `fn function_name(variable: String)` takes a `String` and owns it. If it doesn't return anything, then the variable dies inside the function.\n- `fn function_name(variable: &String)` borrows a `String` and can look at it\n- `fn function_name(variable: &mut String)` borrows a `String` and can change it\n\nHere is an example that looks like a mutable reference, but it is different.\n\n```rust\nfn main() {\n    let country = String::from(\"Austria\"); // country is not mutable, but we are going to print Austria-Hungary. How?\n    adds_hungary(country);\n}\n\nfn adds_hungary(mut country: String) { // Here's how: adds_hungary takes the String and declares it mutable!\n    country.push_str(\"-Hungary\");\n    println!(\"{}\", country);\n}\n```\n\nHow is this possible? It is because `mut country` is not a reference: `adds_hungary` owns `country` now. (Remember, it takes `String` and not `&String`). The moment you call `adds_hungary`, it becomes the full owner. `country` has nothing to do with `String::from(\"Austria\")` anymore. So `adds_hungary` can take `country` as mutable, and it is perfectly safe to do so.\n\nRemember our employee Powerpoint and manager situation above? In this situation it is like the employee just giving his whole computer to the manager. The employee won't ever touch it again, so the manager can do anything he wants to it.\n\n## Copy types\n\nSome types in Rust are very simple. They are called **copy types**. These simple types are all on the stack, and the compiler knows their size. That means that they are very easy to copy, so the compiler always copies when you send it to a function. It always copies because they are so small and easy that there is no reason not to copy. So you don't need to worry about ownership for these types.\n\nThese simple types include: integers, floats, booleans (`true` and `false`), and `char`.\n\nHow do you know if a type **implements** copy? (implements = can use) You can check the documentation. For example, here is the documentation for char:\n\n[https://doc.rust-lang.org/std/primitive.char.html](https://doc.rust-lang.org/std/primitive.char.html)\n\nOn the left you can see **Trait Implementations**. You can see for example **Copy**, **Debug**, and **Display**. So you know that a `char`:\n\n- is copied when you send it to a function (**Copy**)\n- can use `{}` to print (**Display**)\n- can use `{:?}` to print (**Debug**)\n\n```rust\nfn prints_number(number: i32) { // There is no -> so it's not returning anything\n                             // If number was not copy type, it would take it\n                             // and we couldn't use it again\n    println!(\"{}\", number);\n}\n\nfn main() {\n    let my_number = 8;\n    prints_number(my_number); // Prints 8. prints_number gets a copy of my_number\n    prints_number(my_number); // Prints 8 again.\n                              // No problem, because my_number is copy type!\n}\n```\n\nBut if you look at the documentation for String, it is not copy type.\n\n[https://doc.rust-lang.org/std/string/struct.String.html](https://doc.rust-lang.org/std/string/struct.String.html)\n\nOn the left in **Trait Implementations** you can look in alphabetical order. A, B, C... there is no **Copy** in C. But there is **Clone**. **Clone** is similar to **Copy**, but usually needs more memory. Also, you have to call it with `.clone()` - it won't clone just by itself.\n\nIn this example, `prints_country()` prints the country name, a `String`. We want to print it two times, but we can't:\n\n```rust\nfn prints_country(country_name: String) {\n    println!(\"{}\", country_name);\n}\n\nfn main() {\n    let country = String::from(\"Kiribati\");\n    prints_country(country);\n    prints_country(country); // ⚠️\n}\n```\n\nBut now we understand the message.\n\n```text\nerror[E0382]: use of moved value: `country`\n --> src\\main.rs:4:20\n  |\n2 |     let country = String::from(\"Kiribati\");\n  |         ------- move occurs because `country` has type `std::string::String`, which does not implement the `Copy` trait\n3 |     prints_country(country);\n  |                    ------- value moved here\n4 |     prints_country(country);\n  |                    ^^^^^^^ value used here after move\n```\n\nThe important part is `which does not implement the Copy trait`. But in the documentation we saw that String implements the `Clone` trait. So we can add `.clone()` to our code. This creates a clone, and we send the clone to the function. Now `country` is still alive, so we can use it.\n\n```rust\nfn prints_country(country_name: String) {\n    println!(\"{}\", country_name);\n}\n\nfn main() {\n    let country = String::from(\"Kiribati\");\n    prints_country(country.clone()); // make a clone and give it to the function. Only the clone goes in, and country is still alive\n    prints_country(country);\n}\n```\n\nOf course, if the `String` is very large, `.clone()` can use a lot of memory. One `String` can be a whole book in length, and every time we call `.clone()` it will copy the book. So using `&` for a reference is faster, if you can. For example, this code pushes a `&str` onto a `String` and then makes a clone every time it gets used in a function:\n\n```rust\nfn get_length(input: String) { // Takes ownership of a String\n    println!(\"It's {} words long.\", input.split_whitespace().count()); // splits to count the number of words\n}\n\nfn main() {\n    let mut my_string = String::new();\n    for _ in 0..50 {\n        my_string.push_str(\"Here are some more words \"); // push the words on\n        get_length(my_string.clone()); // gives it a clone every time\n    }\n}\n```\n\nIt prints:\n\n```text\nIt's 5 words long.\nIt's 10 words long.\n...\nIt's 250 words long.\n```\n\nThat's 50 clones. Here it is using a reference instead, which is better:\n\n```rust\nfn get_length(input: &String) {\n    println!(\"It's {} words long.\", input.split_whitespace().count());\n}\n\nfn main() {\n    let mut my_string = String::new();\n    for _ in 0..50 {\n        my_string.push_str(\"Here are some more words \");\n        get_length(&my_string);\n    }\n}\n```\n\nInstead of 50 clones, it's zero.\n\n\n\n### Variables without values\n\nA variable without a value is called an \"uninitialized\" variable. Uninitialized means \"hasn't started yet\". They are simple: just write `let` and the variable name:\n\n```rust\nfn main() {\n    let my_variable; // ⚠️\n}\n```\n\nBut you can't use it yet, and Rust won't compile if anything is uninitialized.\n\nBut sometimes they can be useful. A good example is when:\n\n- You have a code block and the value for your variable is inside it, and\n- The variable needs to live outside of the code block.\n\n```rust\nfn loop_then_return(mut counter: i32) -> i32 {\n    loop {\n        counter += 1;\n        if counter % 50 == 0 {\n            break;\n        }\n    }\n    counter\n}\n\nfn main() {\n    let my_number;\n\n    {\n        // Pretend we need to have this code block\n        let number = {\n            // Pretend there is code here to make a number\n            // Lots of code, and finally:\n            57\n        };\n\n        my_number = loop_then_return(number);\n    }\n\n    println!(\"{}\", my_number);\n}\n```\n\nThis prints `100`.\n\nYou can see that `my_number` was declared in the `main()` function, so it lives until the end. But it gets its value from inside a loop. However, that value lives as long as `my_number`, because `my_number` has the value. And if you wrote `let my_number = loop_then_return(number)` inside the block, it would just die right away.\n\nIt helps to imagine if you simplify the code. `loop_then_return(number)` gives the result 100, so let's delete it and write `100` instead. Also, now we don't need `number` so we will delete it too. Now it looks like this:\n\n```rust\nfn main() {\n    let my_number;\n    {\n        my_number = 100;\n    }\n\n    println!(\"{}\", my_number);\n}\n```\n\nSo it's almost like saying `let my_number = { 100 };`.\n\nAlso note that `my_number` is not `mut`. It didn't get a value until it got 100, so it never changed its value. In the end, the real code for `my_number` is just `let my_number = 100;`.\n\n## Collection types\n\nRust has a lot of types for making a collection. Collections are for when you need more than one value in one spot. For example, you could have information on all the cities in your country inside one variable. We will start with arrays, which are fastest but also have the least functionality. They are kind of like `&str` in that way.\n\n### Arrays\n\nAn array is data inside square brackets: `[]`. Arrays:\n\n- must not change their size,\n- must only contain the same type.\n\nThey are very fast, however.\n\nThe type of an array is: `[type; number]`. For example, the type of `[\"One\", \"Two\"]` is `[&str; 2]`. This means that even these two arrays have different types:\n\n```rust\nfn main() {\n    let array1 = [\"One\", \"Two\"]; // This one is type [&str; 2]\n    let array2 = [\"One\", \"Two\", \"Five\"]; // But this one is type [&str; 3]. Different type!\n}\n```\n\nHere is a good tip: to know the type of a variable, you can \"ask\" the compiler by giving it bad instructions. For example:\n\n```rust\nfn main() {\n    let seasons = [\"Spring\", \"Summer\", \"Autumn\", \"Winter\"];\n    let seasons2 = [\"Spring\", \"Summer\", \"Fall\", \"Autumn\", \"Winter\"];\n    seasons.ddd(); // ⚠️\n    seasons2.thd(); // ⚠️ as well\n}\n```\n\nThe compiler says, \"What? There's no `.ddd()` method for seasons and no `.thd()` method for seasons 2 either!!\" as you can see:\n\n```text\nerror[E0599]: no method named `ddd` found for array `[&str; 4]` in the current scope\n --> src\\main.rs:4:13\n  |\n4 |     seasons.ddd(); // \n  |             ^^^ method not found in `[&str; 4]`\n\nerror[E0599]: no method named `thd` found for array `[&str; 5]` in the current scope\n --> src\\main.rs:5:14\n  |\n5 |     seasons2.thd(); // \n  |              ^^^ method not found in `[&str; 5]`\n```\n\nSo it tells you `` method not found in `[&str; 4]` ``, which is the type.\n\nIf you want an array with all the same value, you can declare it like this:\n\n```rust\nfn main() {\n    let my_array = [\"a\"; 10];\n    println!(\"{:?}\", my_array);\n}\n```\n\nThis prints `[\"a\", \"a\", \"a\", \"a\", \"a\", \"a\", \"a\", \"a\", \"a\", \"a\"]`.\n\nThis method is used a lot to create buffers. For example, `let mut buffer = [0; 640]` creates an array of 640 zeroes. Then we can change zero to other numbers in order to add data.\n\nYou can index (get) entries in an array with []. The first entry is [0], the second is [1], and so on.\n\n```rust\nfn main() {\n    let my_numbers = [0, 10, -20];\n    println!(\"{}\", my_numbers[1]); // prints 10\n}\n```\n\nYou can get a slice (a piece) of an array. First you need a &, because the compiler doesn't know the size. Then you can use `..` to show the range.\n\nFor example, let's use this array: `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`.\n\n```rust\nfn main() {\n    let array_of_ten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n\n    let three_to_five = &array_of_ten[2..5];\n    let start_at_two = &array_of_ten[1..];\n    let end_at_five = &array_of_ten[..5];\n    let everything = &array_of_ten[..];\n\n    println!(\"Three to five: {:?}, start at two: {:?}, end at five: {:?}, everything: {:?}\", three_to_five, start_at_two, end_at_five, everything);\n}\n```\n\nRemember that:\n\n- Index numbers start at 0 (not 1)\n- Index ranges are **exclusive** (they do not include the last number)\n\nSo `[0..2]` means the first index and the second index (0 and 1). Or you can call it the \"zeroth and first\" index. It doesn't have the third item, which is index 2.\n\nYou can also have an **inclusive** range, which means it includes the last number too. To do this, add `=` to write `..=` instead of `..`. So instead of `[0..2]` you can write `[0..=2]` if you want the first, second, and third item.\n\n## Vectors\n**[See this chapter on YouTube](https://youtu.be/Eh-DsRnDKmw)**\n\nIn the same way that we have `&str` and `String`, we have arrays and vectors. Arrays are faster with less functionality, and vectors are slower with more functionality. (Of course, Rust is always very fast so vectors are not slow, just slow*er* than arrays.) The type is written `Vec`, and you can also just call it a \"vec\".\n\nThere are two main ways to declare a vector. One is like with `String` using `new`:\n\n```rust\nfn main() {\n    let name1 = String::from(\"Windy\");\n    let name2 = String::from(\"Gomesy\");\n\n    let mut my_vec = Vec::new();\n    // If we run the program now, the compiler will give an error.\n    // It doesn't know the type of vec.\n\n    my_vec.push(name1); // Now it knows: it's Vec<String>\n    my_vec.push(name2);\n}\n```\n\nYou can see that a `Vec` always has something else inside it, and that's what the `<>` (angle brackets) are for. A `Vec<String>` is a vector with one or more `String`s. You can also have more types inside. For example:\n\n- `Vec<(i32, i32)>` this is a `Vec` where each item is a tuple: `(i32, i32)`.\n- `Vec<Vec<String>>` this is a `Vec` that has `Vec`s of `Strings`. Say for example you wanted to save your favourite book as a `Vec<String>`. Then you do it again with another book, and get another `Vec<String>`. To hold both books, you would put them into another `Vec` and that would be a `Vec<Vec<String>>`.\n\nInstead of using `.push()` to make Rust decide the type, you can just declare the type.\n\n```rust\nfn main() {\n    let mut my_vec: Vec<String> = Vec::new(); // The compiler knows the type\n                                              // so there is no error.\n}\n```\n\nYou can see that items in vectors must have the same type.\n\nAnother easy way to create a vector is with the `vec!` macro. It looks like an array declaration, but has `vec!` in front of it.\n\n```rust\nfn main() {\n    let mut my_vec = vec![8, 10, 10];\n}\n```\n\nThe type is `Vec<i32>`. You call it a \"Vec of i32s\". And a `Vec<String>` is a \"Vec of strings\". And a `Vec<Vec<String>>` is a \"Vec of a vec of strings\".\n\nYou can slice a vector too, just like in an array.\n\n```rust\nfn main() {\n    let vec_of_ten = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n    // Everything is the same as above except we added vec!.\n    let three_to_five = &vec_of_ten[2..5];\n    let start_at_two = &vec_of_ten[1..];\n    let end_at_five = &vec_of_ten[..5];\n    let everything = &vec_of_ten[..];\n\n    println!(\"Three to five: {:?},\nstart at two: {:?}\nend at five: {:?}\neverything: {:?}\", three_to_five, start_at_two, end_at_five, everything);\n}\n```\n\nBecause a vec is slower than an array, we can use some methods to make it faster. A vec has a **capacity**, which means the space given to the vector. When you push a new item on the vector, it gets closer and closer to the capacity. Then if you go past the capacity, it will make its capacity double and copy the items into the new space. This is called reallocation. We'll use a method called `.capacity()` to look at the capacity of a vector as we add items to it.\n\nFor example:\n\n```rust\nfn main() {\n    let mut num_vec = Vec::new();\n    println!(\"{}\", num_vec.capacity()); // 0 elements: prints 0\n    num_vec.push('a'); // add one character\n    println!(\"{}\", num_vec.capacity()); // 1 element: prints 4. Vecs with 1 item always start with capacity 4\n    num_vec.push('a'); // add one more\n    num_vec.push('a'); // add one more\n    num_vec.push('a'); // add one more\n    println!(\"{}\", num_vec.capacity()); // 4 elements: still prints 4.\n    num_vec.push('a'); // add one more\n    println!(\"{}\", num_vec.capacity()); // prints 8. We have 5 elements, but it doubled 4 to 8 to make space\n}\n```\n\nThis prints:\n\n```text\n0\n4\n4\n8\n```\n\nSo this vector has two reallocations: 0 to 4, and 4 to 8. We can make it faster:\n\n```rust\nfn main() {\n    let mut num_vec = Vec::with_capacity(8); // Give it capacity 8\n    num_vec.push('a'); // add one character\n    println!(\"{}\", num_vec.capacity()); // prints 8\n    num_vec.push('a'); // add one more\n    println!(\"{}\", num_vec.capacity()); // prints 8\n    num_vec.push('a'); // add one more\n    println!(\"{}\", num_vec.capacity()); // prints 8.\n    num_vec.push('a'); // add one more\n    num_vec.push('a'); // add one more // Now we have 5 elements\n    println!(\"{}\", num_vec.capacity()); // Still 8\n}\n```\n\nThis vector has 0 reallocations, which is better. So if you think you know how many elements you need, you can use `Vec::with_capacity()` to make it faster.\n\nYou remember that you can use `.into()` to make a `&str` into a `String`. You can also use it to make an array into a `Vec`. You have to tell `.into()` that you want a `Vec`, but you don't have to choose the type of `Vec`. If you don't want to choose, you can write `Vec<_>`.\n\n```rust\nfn main() {\n    let my_vec: Vec<u8> = [1, 2, 3].into();\n    let my_vec2: Vec<_> = [9, 0, 10].into(); // Vec<_> means \"choose the Vec type for me\"\n                                             // Rust will choose Vec<i32>\n}\n```\n\n## Tuples\n**[See this chapter on YouTube](https://youtu.be/U67Diy6SlTg)**\n\nTuples in Rust use `()`. We have seen many empty tuples already, because *nothing* in a function actually means an empty tuple:\n\n```text\nfn do_something() {}\n```\n\nis actually short for:\n\n```text\nfn do_something() -> () {}\n```\n\nThat function gets nothing (an empty tuple), and returns nothing (an empty tuple). So we have been using tuples a lot already. When you don't return anything in a function, you actually return an empty tuple.\n\n```rust\nfn just_prints() {\n    println!(\"I am printing\"); // Adding ; means we return an empty tuple\n}\n\nfn main() {}\n```\n\nBut tuples can hold many things, and can hold different types too. Items inside a tuple are also indexed with numbers 0, 1, 2, and so on. But to access them, you use a `.` instead of a `[]`. Let's put a whole bunch of types into a single tuple.\n\n```rust\nfn main() {\n    let random_tuple = (\"Here is a name\", 8, vec!['a'], 'b', [8, 9, 10], 7.7);\n    println!(\n        \"Inside the tuple is: First item: {:?}\nSecond item: {:?}\nThird item: {:?}\nFourth item: {:?}\nFifth item: {:?}\nSixth item: {:?}\",\n        random_tuple.0,\n        random_tuple.1,\n        random_tuple.2,\n        random_tuple.3,\n        random_tuple.4,\n        random_tuple.5,\n    )\n}\n```\n\nThis prints:\n\n```text\nInside the tuple is: First item: \"Here is a name\"\nSecond item: 8\nThird item: ['a']\nFourth item: 'b'\nFifth item: [8, 9, 10]\nSixth item: 7.7\n```\n\nThat tuple is of type `(&str, i32, Vec<char>, char, [i32; 3], f64)`.\n\n\nYou can use a tuple to create multiple variables. Take a look at this code:\n\n```rust\nfn main() {\n    let str_vec = vec![\"one\", \"two\", \"three\"];\n}\n```\n\n`str_vec` has three items in it. What if we want to pull them out? That's where we can use a tuple.\n\n```rust\nfn main() {\n    let str_vec = vec![\"one\", \"two\", \"three\"];\n\n    let (a, b, c) = (str_vec[0], str_vec[1], str_vec[2]); // call them a, b, and c\n    println!(\"{:?}\", b);\n}\n```\n\nThat prints `\"two\"`, which is what `b` is. This is called *destructuring*. That is because first the variables are inside a structure, but then we made `a`, `b`, and `c` that are not inside a structure.\n\nIf you need to destructure but don't want all the variables, you can use `_`.\n\n```rust\nfn main() {\n    let str_vec = vec![\"one\", \"two\", \"three\"];\n\n    let (_, _, variable) = (str_vec[0], str_vec[1], str_vec[2]);\n}\n```\n\nNow it only creates a variable called `variable` but doesn't make a variable for the others.\n\nThere are many more collection types, and many more ways to use arrays, vecs, and tuples. We will learn more about them too, but first we will learn control flow.\n\n## Control flow\n**See this chapter on YouTube: [Part 1](https://youtu.be/UAymDOpv_us) and [Part 2](https://youtu.be/eqysTfiiQZs)**\n\nControl flow means telling your code what to do in different situations. The simplest control flow is `if`.\n\n```rust\nfn main() {\n    let my_number = 5;\n    if my_number == 7 {\n        println!(\"It's seven\");\n    }\n}\n```\n\nAlso note that you use `==` and not `=`. `==` is to compare, `=` is to *assign* (to give a value). Also note that we wrote `if my_number == 7` and not `if (my_number == 7)`. You don't need brackets with `if` in Rust.\n\n`else if` and `else` give you more control:\n\n```rust\nfn main() {\n    let my_number = 5;\n    if my_number == 7 {\n        println!(\"It's seven\");\n    } else if my_number == 6 {\n        println!(\"It's six\")\n    } else {\n        println!(\"It's a different number\")\n    }\n}\n```\n\nThis prints `It's a different number` because it's not equal to 7 or 6.\n\nYou can add more conditions with `&&` (and) and `||` (or).\n\n```rust\nfn main() {\n    let my_number = 5;\n    if my_number % 2 == 1 && my_number > 0 { // % 2 means the number that remains after diving by two\n        println!(\"It's a positive odd number\");\n    } else if my_number == 6 {\n        println!(\"It's six\")\n    } else {\n        println!(\"It's a different number\")\n    }\n}\n```\n\nThis prints `It's a positive odd number` because when you divide it by 2 you have a remainder of 1, and it's greater than 0.\n\n\nYou can see that too much `if`, `else`, and `else if` can be difficult to read. In this case you can use `match` instead, which looks much cleaner. But you must match for every possible result. For example, this will not work:\n\n```rust\nfn main() {\n    let my_number: u8 = 5;\n    match my_number {\n        0 => println!(\"it's zero\"),\n        1 => println!(\"it's one\"),\n        2 => println!(\"it's two\"),\n        // ⚠️\n    }\n}\n```\n\nThe compiler says:\n\n```text\nerror[E0004]: non-exhaustive patterns: `3u8..=std::u8::MAX` not covered\n --> src\\main.rs:3:11\n  |\n3 |     match my_number {\n  |           ^^^^^^^^^ pattern `3u8..=std::u8::MAX` not covered\n```\n\nThis means \"you told me about 0 to 2, but `u8`s can go up to 255. What about 3? What about 4? What about 5?\" And so on. So you can add `_` which means \"anything else\".\n\n```rust\nfn main() {\n    let my_number: u8 = 5;\n    match my_number {\n        0 => println!(\"it's zero\"),\n        1 => println!(\"it's one\"),\n        2 => println!(\"it's two\"),\n        _ => println!(\"It's some other number\"),\n    }\n}\n```\n\nThat prints `It's some other number`.\n\nRemember this for match:\n\n- You write `match` and then make a `{}` code block.\n- Write the *pattern* on the left and use a `=>` fat arrow to say what to do when it matches.\n- Each line is called an \"arm\".\n- Put a comma between the arms (not a semicolon).\n\nYou can declare a value with a match:\n\n```rust\nfn main() {\n    let my_number = 5;\n    let second_number = match my_number {\n        0 => 0,\n        5 => 10,\n        _ => 2,\n    };\n}\n```\n\n`second_number` will be 10. Do you see the semicolon at the end? That is because, after the match is over, we actually told the compiler this: `let second_number = 10;`\n\n\nYou can match on more complicated things too. You use a tuple to do it.\n\n```rust\nfn main() {\n    let sky = \"cloudy\";\n    let temperature = \"warm\";\n\n    match (sky, temperature) {\n        (\"cloudy\", \"cold\") => println!(\"It's dark and unpleasant today\"),\n        (\"clear\", \"warm\") => println!(\"It's a nice day\"),\n        (\"cloudy\", \"warm\") => println!(\"It's dark but not bad\"),\n        _ => println!(\"Not sure what the weather is.\"),\n    }\n}\n```\n\nThis prints `It's dark but not bad` because it matches \"cloudy\" and \"warm\" for `sky` and `temperature`.\n\nYou can even put `if` inside of `match`. This is called a \"match guard\":\n\n```rust\nfn main() {\n    let children = 5;\n    let married = true;\n\n    match (children, married) {\n        (children, married) if married == false => println!(\"Not married with {} children\", children),\n        (children, married) if children == 0 && married == true => println!(\"Married but no children\"),\n        _ => println!(\"Married? {}. Number of children: {}.\", married, children),\n    }\n}\n```\n\nThis will print `Married? true. Number of children: 5.`\n\nYou can use _ as many times as you want in a match. In this match on colours, we have three but only check one at a time.\n\n```rust\nfn match_colours(rbg: (i32, i32, i32)) {\n    match rbg {\n        (r, _, _) if r < 10 => println!(\"Not much red\"),\n        (_, b, _) if b < 10 => println!(\"Not much blue\"),\n        (_, _, g) if g < 10 => println!(\"Not much green\"),\n        _ => println!(\"Each colour has at least 10\"),\n    }\n}\n\nfn main() {\n    let first = (200, 0, 0);\n    let second = (50, 50, 50);\n    let third = (200, 50, 0);\n\n    match_colours(first);\n    match_colours(second);\n    match_colours(third);\n\n}\n```\n\nThis prints:\n\n```text\nNot much blue\nEach colour has at least 10\nNot much green\n```\n\nThis also shows how `match` statements work, because in the first example it only printed `Not much blue`. But `first` also has not much green. A `match` statement always stops when it finds a match, and doesn't check the rest. This is a good example of code that compiles well but is not the code you want.\n\nYou can make a really big `match` statement to fix it, but it is probably better to use a `for` loop. We will talk about loops soon.\n\nA match has to return the same type. So you can't do this:\n\n```rust\nfn main() {\n    let my_number = 10;\n    let some_variable = match my_number {\n        10 => 8,\n        _ => \"Not ten\", // ⚠️\n    };\n}\n```\n\nThe compiler tells you that:\n\n```text\nerror[E0308]: `match` arms have incompatible types\n  --> src\\main.rs:17:14\n   |\n15 |       let some_variable = match my_number {\n   |  _________________________-\n16 | |         10 => 8,\n   | |               - this is found to be of type `{integer}`\n17 | |         _ => \"Not ten\",\n   | |              ^^^^^^^^^ expected integer, found `&str`\n18 | |     };\n   | |_____- `match` arms have incompatible types\n```\n\nThis will also not work, for the same reason:\n\n```rust\nfn main() {\n    let some_variable = if my_number == 10 { 8 } else { \"something else \"}; // ⚠️\n}\n```\n\nBut this works, because it's not a `match` so you have a different `let` statement each time:\n\n```rust\nfn main() {\n    let my_number = 10;\n\n    if my_number == 10 {\n        let some_variable = 8;\n    } else {\n        let some_variable = \"Something else\";\n    }\n}\n```\n\nYou can also use `@` to give a name to the value of a `match` expression, and then you can use it. In this example we match an `i32` input in a function. If it's 4 or 13 we want to use that number in a `println!` statement. Otherwise, we don't need to use it.\n\n```rust\nfn match_number(input: i32) {\n    match input {\n    number @ 4 => println!(\"{} is an unlucky number in China (sounds close to 死)!\", number),\n    number @ 13 => println!(\"{} is unlucky in North America, lucky in Italy! In bocca al lupo!\", number),\n    _ => println!(\"Looks like a normal number\"),\n    }\n}\n\nfn main() {\n    match_number(50);\n    match_number(13);\n    match_number(4);\n}\n```\n\nThis prints:\n\n```text\nLooks like a normal number\n13 is unlucky in North America, lucky in Italy! In bocca al lupo!\n4 is an unlucky number in China (sounds close to 死)!\n```\n\n## Structs\n**See this chapter on YouTube: [Part 1](https://youtu.be/W23uQghBOFk) and [Part 2](https://youtu.be/GSVhrjLCuNA)**\n\nWith structs, you can create your own type. You will use structs all the time in Rust because they are so convenient. Structs are created with the keyword `struct`. The name of a struct should be in UpperCamelCase (capital letter for each word, no spaces). If you write a struct in all lowercase, the compiler will tell you.\n\nThere are three types of structs. One is a \"unit struct\". Unit means \"doesn't have anything\". For a unit struct, you just write the name and a semicolon.\n\n```rust\nstruct FileDirectory;\nfn main() {}\n```\n\nThe next is a tuple struct, or an unnamed struct. It is \"unnamed\" because you only need to write the types, not the field names. Tuple structs are good when you need a simple struct and don't need to remember names.\n\n```rust\nstruct Colour(u8, u8, u8);\n\nfn main() {\n    let my_colour = Colour(50, 0, 50); // Make a colour out of RGB (red, green, blue)\n    println!(\"The second part of the colour is: {}\", my_colour.1);\n}\n```\n\nThis prints `The second part of the colour is: 0`.\n\nThe third type is the named struct. This is probably the most common struct. In this struct you declare field names and types inside a `{}` code block. Note that you don't write a semicolon after a named struct, because there is a whole code block after it.\n\n```rust\nstruct Colour(u8, u8, u8); // Declare the same Colour tuple struct\n\nstruct SizeAndColour {\n    size: u32,\n    colour: Colour, // And we put it in our new named struct\n}\n\nfn main() {\n    let my_colour = Colour(50, 0, 50);\n\n    let size_and_colour = SizeAndColour {\n        size: 150,\n        colour: my_colour\n    };\n}\n```\n\nYou separate fields by commas in a named struct too. For the last field you can add a comma or not - it's up to you. `SizeAndColour` had a comma after `colour`:\n\n```rust\nstruct Colour(u8, u8, u8); // Declare the same Colour tuple struct\n\nstruct SizeAndColour {\n    size: u32,\n    colour: Colour, // And we put it in our new named struct\n}\n\nfn main() {}\n```\n\nbut you don't need it. But it can be a good idea to always put a comma, because sometimes you will change the order of the fields:\n\n```rust\nstruct Colour(u8, u8, u8); // Declare the same Colour tuple struct\n\nstruct SizeAndColour {\n    size: u32,\n    colour: Colour // No comma here\n}\n\nfn main() {}\n```\n\nThen we decide to change the order...\n\n```rust\nstruct SizeAndColour {\n    colour: Colour // ⚠️ Whoops! Now this doesn't have a comma.\n    size: u32,\n}\n\nfn main() {}\n```\n\nBut it is not very important either way so you can choose whether to use a comma or not.\n\n\nLet's create a `Country` struct to give an example. The `Country` struct has the fields `population`, `capital`, and `leader_name`.\n\n```rust\nstruct Country {\n    population: u32,\n    capital: String,\n    leader_name: String\n}\n\nfn main() {\n    let population = 500_000;\n    let capital = String::from(\"Elista\");\n    let leader_name = String::from(\"Batu Khasikov\");\n\n    let kalmykia = Country {\n        population: population,\n        capital: capital,\n        leader_name: leader_name,\n    };\n}\n```\n\nDid you notice that we wrote the same thing twice? We wrote `population: population`, `capital: capital`, and `leader_name: leader_name`. Actually, you don't need to do that. If the field name and variable name are the same, you don't have to write it twice.\n\n```rust\nstruct Country {\n    population: u32,\n    capital: String,\n    leader_name: String\n}\n\nfn main() {\n    let population = 500_000;\n    let capital = String::from(\"Elista\");\n    let leader_name = String::from(\"Batu Khasikov\");\n\n    let kalmykia = Country {\n        population,\n        capital,\n        leader_name,\n    };\n}\n```\n\n## Enums\n**See this chapter on YouTube: [Part 1](https://youtu.be/SRnqNTJUgjs), [Part 2](https://youtu.be/F_EcbWM63lk), [Part 3](https://youtu.be/2uh64U9JesA) and [Part 4](https://youtu.be/LOHVUYTc5Us)**\n\nAn `enum` is short for enumerations. They look very similar to a struct, but are different. Here is the difference:\n\n- Use a `struct` when you want one thing **AND** another thing.\n- Use an `enum` when you want one thing **OR** another thing.\n\nSo structs are for **many things** together, while enums are for **many choices** together.\n\nTo declare an enum, write `enum` and use a code block with the options, separated by commas. Just like a `struct`, the last part can have a comma or not. We will create an enum called `ThingsInTheSky`:\n\n```rust\nenum ThingsInTheSky {\n    Sun,\n    Stars,\n}\n\nfn main() {}\n```\n\nThis is an enum because you can either see the sun, **or** the stars: you have to choose one. These are called **variants**.\n\n```rust\n// create the enum with two choices\nenum ThingsInTheSky {\n    Sun,\n    Stars,\n}\n\n// With this function we can use an i32 to create ThingsInTheSky.\nfn create_skystate(time: i32) -> ThingsInTheSky {\n    match time {\n        6..=18 => ThingsInTheSky::Sun, // Between 6 and 18 hours we can see the sun\n        _ => ThingsInTheSky::Stars, // Otherwise, we can see stars\n    }\n}\n\n// With this function we can match against the two choices in ThingsInTheSky.\nfn check_skystate(state: &ThingsInTheSky) {\n    match state {\n        ThingsInTheSky::Sun => println!(\"I can see the sun!\"),\n        ThingsInTheSky::Stars => println!(\"I can see the stars!\")\n    }\n}\n\nfn main() {\n    let time = 8; // it's 8 o'clock\n    let skystate = create_skystate(time); // create_skystate returns a ThingsInTheSky\n    check_skystate(&skystate); // Give it a reference so it can read the variable skystate\n}\n```\n\nThis prints `I can see the sun!`.\n\nYou can add data to an enum too.\n\n```rust\nenum ThingsInTheSky {\n    Sun(String), // Now each variant has a string\n    Stars(String),\n}\n\nfn create_skystate(time: i32) -> ThingsInTheSky {\n    match time {\n        6..=18 => ThingsInTheSky::Sun(String::from(\"I can see the sun!\")), // Write the strings here\n        _ => ThingsInTheSky::Stars(String::from(\"I can see the stars!\")),\n    }\n}\n\nfn check_skystate(state: &ThingsInTheSky) {\n    match state {\n        ThingsInTheSky::Sun(description) => println!(\"{}\", description), // Give the string the name description so we can use it\n        ThingsInTheSky::Stars(n) => println!(\"{}\", n), // Or you can name it n. Or anything else - it doesn't matter\n    }\n}\n\nfn main() {\n    let time = 8; // it's 8 o'clock\n    let skystate = create_skystate(time); // create_skystate returns a ThingsInTheSky\n    check_skystate(&skystate); // Give it a reference so it can read the variable skystate\n}\n```\n\nThis prints the same thing: `I can see the sun!`\n\nYou can also \"import\" an enum so you don't have to type so much. Here's an example where we have to type `Mood::` every time we match on our mood:\n\n```rust\nenum Mood {\n    Happy,\n    Sleepy,\n    NotBad,\n    Angry,\n}\n\nfn match_mood(mood: &Mood) -> i32 {\n    let happiness_level = match mood {\n        Mood::Happy => 10, // Here we type Mood:: every time\n        Mood::Sleepy => 6,\n        Mood::NotBad => 7,\n        Mood::Angry => 2,\n    };\n    happiness_level\n}\n\nfn main() {\n    let my_mood = Mood::NotBad;\n    let happiness_level = match_mood(&my_mood);\n    println!(\"Out of 1 to 10, my happiness is {}\", happiness_level);\n}\n```\n\nIt prints `Out of 1 to 10, my happiness is 7`. Let's import so we can type less. To import everything, write `*`. Note: it's the same key as `*` for dereferencing but is completely different.\n\n```rust\nenum Mood {\n    Happy,\n    Sleepy,\n    NotBad,\n    Angry,\n}\n\nfn match_mood(mood: &Mood) -> i32 {\n    use Mood::*; // We imported everything in Mood. Now we can just write Happy, Sleepy, etc.\n    let happiness_level = match mood {\n        Happy => 10, // We don't have to write Mood:: anymore\n        Sleepy => 6,\n        NotBad => 7,\n        Angry => 2,\n    };\n    happiness_level\n}\n\nfn main() {\n    let my_mood = Mood::Happy;\n    let happiness_level = match_mood(&my_mood);\n    println!(\"Out of 1 to 10, my happiness is {}\", happiness_level);\n}\n```\n\n\nParts of an `enum` can also be turned into an integer. That's because Rust gives each arm of an `enum` a number that starts with 0 for its own use. You can do things with it if your enum doesn't have any other data in it.\n\n```rust\nenum Season {\n    Spring, // If this was Spring(String) or something it wouldn't work\n    Summer,\n    Autumn,\n    Winter,\n}\n\nfn main() {\n    use Season::*;\n    let four_seasons = vec![Spring, Summer, Autumn, Winter];\n    for season in four_seasons {\n        println!(\"{}\", season as u32);\n    }\n}\n```\n\nThis prints:\n\n```text\n0\n1\n2\n3\n```\n\nThough you can give it a different number, if you want - Rust doesn't care and can use it in the same way. Just add an `=` and your number to the variant that you want to have a number. You don't have to give all of them a number. But if you don't, Rust will just add 1 from the arm before to give it a number.\n\n```rust\nenum Star {\n    BrownDwarf = 10,\n    RedDwarf = 50,\n    YellowStar = 100,\n    RedGiant = 1000,\n    DeadStar, // Think about this one. What number will it have?\n}\n\nfn main() {\n    use Star::*;\n    let starvec = vec![BrownDwarf, RedDwarf, YellowStar, RedGiant];\n    for star in starvec {\n        match star as u32 {\n            size if size <= 80 => println!(\"Not the biggest star.\"), // Remember: size doesn't mean anything. It's just a name we chose so we can print it\n            size if size >= 80 => println!(\"This is a good-sized star.\"),\n            _ => println!(\"That star is pretty big!\"),\n        }\n    }\n    println!(\"What about DeadStar? It's the number {}.\", DeadStar as u32);\n}\n```\n\nThis prints:\n\n\n```text\nNot the biggest star.\nNot the biggest star.\nThis is a good-sized star.\nThis is a good-sized star.\nWhat about DeadStar? It's the number 1001.\n```\n\n`DeadStar` would have been number 4, but now it's 1001.\n\n### Enums to use multiple types\n\nYou know that items in a `Vec`, array, etc. all need the same type (only tuples are different). But you can actually use an enum to put different types in. Imagine we want to have a `Vec` with `u32`s or `i32`s. Of course, you can make a `Vec<(u32, i32)>` (a vec with `(u32, i32)` tuples) but we only want one each time. So here you can use an enum. Here is a simple example:\n\n```rust\nenum Number {\n    U32(u32),\n    I32(i32),\n}\n\nfn main() {}\n```\n\nSo there are two variants: the `U32` variant with a `u32` inside, and the `I32` variant with `i32` inside. `U32` and `I32` are just names we made. They could have been `UThirtyTwo` or `IThirtyTwo` or anything else.\n\nNow, if we put them into a `Vec` we just have a `Vec<Number>`, and the compiler is happy because it's all the same type. The compiler doesn't care that we have either `u32` or `i32` because they are all inside a single type called `Number`. And because it's an enum, you have to pick one, which is what we want. We will use the `.is_positive()` method to pick. If it's `true` then we will choose `U32`, and if it's `false` then we will choose `I32`.\n\nNow the code looks like this:\n\n```rust\nenum Number {\n    U32(u32),\n    I32(i32),\n}\n\nfn get_number(input: i32) -> Number {\n    let number = match input.is_positive() {\n        true => Number::U32(input as u32), // change it to u32 if it's positive\n        false => Number::I32(input), // otherwise just give the number because it's already i32\n    };\n    number\n}\n\n\nfn main() {\n    let my_vec = vec![get_number(-800), get_number(8)];\n\n    for item in my_vec {\n        match item {\n            Number::U32(number) => println!(\"It's a u32 with the value {}\", number),\n            Number::I32(number) => println!(\"It's an i32 with the value {}\", number),\n        }\n    }\n}\n```\n\nThis prints what we wanted to see:\n\n```text\nIt's an i32 with the value -800\nIt's a u32 with the value 8\n```\n\n\n## Loops\n\nWith loops you can tell Rust to continue something until you want it to stop. You use `loop` to start a loop that does not stop, unless you tell it when to `break`.\n\n```rust\nfn main() { // This program will never stop\n    loop {\n\n    }\n}\n```\n\nSo let's tell the compiler when it can break.\n\n```rust\nfn main() {\n    let mut counter = 0; // set a counter to 0\n    loop {\n        counter +=1; // increase the counter by 1\n        println!(\"The counter is now: {}\", counter);\n        if counter == 5 { // stop when counter == 5\n            break;\n        }\n    }\n}\n```\n\nThis will print:\n\n```text\nThe counter is now: 1\nThe counter is now: 2\nThe counter is now: 3\nThe counter is now: 4\nThe counter is now: 5\n```\n\nIf you have a loop inside of a loop, you can give them names. With names, you can tell Rust which loop to `break` out of. Use `'` (called a \"tick\") and a `:` to give it a name:\n\n```rust\nfn main() {\n    let mut counter = 0;\n    let mut counter2 = 0;\n    println!(\"Now entering the first loop.\");\n\n    'first_loop: loop {\n        // Give the first loop a name\n        counter += 1;\n        println!(\"The counter is now: {}\", counter);\n        if counter > 9 {\n            // Starts a second loop inside this loop\n            println!(\"Now entering the second loop.\");\n\n            'second_loop: loop {\n                // now we are inside 'second_loop\n                println!(\"The second counter is now: {}\", counter2);\n                counter2 += 1;\n                if counter2 == 3 {\n                    break 'first_loop; // Break out of 'first_loop so we can exit the program\n                }\n            }\n        }\n    }\n}\n```\n\nThis will print:\n\n```text\nNow entering the first loop.\nThe counter is now: 1\nThe counter is now: 2\nThe counter is now: 3\nThe counter is now: 4\nThe counter is now: 5\nThe counter is now: 6\nThe counter is now: 7\nThe counter is now: 8\nThe counter is now: 9\nThe counter is now: 10\nNow entering the second loop.\nThe second counter is now: 0\nThe second counter is now: 1\nThe second counter is now: 2\n```\n\nA `while` loop is a loop that continues while something is still `true`. Each loop, Rust will check if it is still `true`. If it becomes `false`, Rust will stop the loop.\n\n```rust\nfn main() {\n    let mut counter = 0;\n\n    while counter < 5 {\n        counter +=1;\n        println!(\"The counter is now: {}\", counter);\n    }\n}\n```\n\nA `for` loop lets you tell Rust what to do each time. But in a `for` loop, the loop stops after a certain number of times. `for` loops use **ranges** very often. You use `..` and `..=` to create a range.\n\n- `..` creates an **exclusive** range: `0..3` creates `0, 1, 2`.\n- `..=` creates an **inclusive** range: `0..=3` = `0, 1, 2, 3`.\n\n```rust\nfn main() {\n    for number in 0..3 {\n        println!(\"The number is: {}\", number);\n    }\n\n    for number in 0..=3 {\n        println!(\"The next number is: {}\", number);\n    }\n}\n```\n\nThis prints:\n\n```text\nThe number is: 0\nThe number is: 1\nThe number is: 2\nThe next number is: 0\nThe next number is: 1\nThe next number is: 2\nThe next number is: 3\n```\n\nAlso notice that `number` becomes the variable name for 0..3. We could have called it `n`, or `ntod_het___hno_f`, or anything. We can then use that name in `println!`.\n\nIf you don't need a variable name, use `_`.\n\n```rust\nfn main() {\n    for _ in 0..3 {\n        println!(\"Printing the same thing three times\");\n    }\n}\n```\n\nThis prints:\n\n```text\nPrinting the same thing three times\nPrinting the same thing three times\nPrinting the same thing three times\n```\n\nbecause we didn't give it any number to print each time.\n\nAnd actually, if you give a variable name and don't use it, Rust will tell you:\n\n```rust\nfn main() {\n    for number in 0..3 {\n        println!(\"Printing the same thing three times\");\n    }\n}\n```\n\nThis prints the same thing as above. The program compiles fine, but Rust will remind you that you didn't use `number`:\n\n```text\nwarning: unused variable: `number`\n --> src\\main.rs:2:9\n  |\n2 |     for number in 0..3 {\n  |         ^^^^^^ help: if this is intentional, prefix it with an underscore: `_number`\n```\n\nRust suggests writing `_number` instead of `_`. Putting `_` in front of a variable name means \"maybe I will use it later\". But using just `_` means \"I don't care about this variable at all\". So you can put `_` in front of variable names if you will use them later and don't want the compiler to tell you about them.\n\nYou can also use `break` to return a value. You write the value right after `break` and use a `;`. Here is an example with a `loop` and a break that gives `my_number` its value.\n\n```rust\nfn main() {\n    let mut counter = 5;\n    let my_number = loop {\n        counter +=1;\n        if counter % 53 == 3 {\n            break counter;\n        }\n    };\n    println!(\"{}\", my_number);\n}\n```\n\nThis prints `56`. `break counter;` means \"break and return the value of counter\". And because the whole block starts with `let`, `my_number` gets the value.\n\nNow that we know how to use loops, here is a better solution to our `match` problem with colours from before. It is a better solution because we want to compare everything, and a `for` loop looks at every item.\n\n```rust\nfn match_colours(rbg: (i32, i32, i32)) {\n    println!(\"Comparing a colour with {} red, {} blue, and {} green:\", rbg.0, rbg.1, rbg.2);\n    let new_vec = vec![(rbg.0, \"red\"), (rbg.1, \"blue\"), (rbg.2, \"green\")]; // Put the colours in a vec. Inside are tuples with the colour names\n    let mut all_have_at_least_10 = true; // Start with true. We will set it to false if one colour is less than 10\n    for item in new_vec {\n        if item.0 < 10 {\n            all_have_at_least_10 = false; // Now it's false\n            println!(\"Not much {}.\", item.1) // And we print the colour name.\n        }\n    }\n    if all_have_at_least_10 { // Check if it's still true, and print if true\n        println!(\"Each colour has at least 10.\")\n    }\n    println!(); // Add one more line\n}\n\nfn main() {\n    let first = (200, 0, 0);\n    let second = (50, 50, 50);\n    let third = (200, 50, 0);\n\n    match_colours(first);\n    match_colours(second);\n    match_colours(third);\n}\n```\n\nThis prints:\n\n```text\nComparing a colour with 200 red, 0 blue, and 0 green:\nNot much blue.\nNot much green.\n\nComparing a colour with 50 red, 50 blue, and 50 green:\nEach colour has at least 10.\n\nComparing a colour with 200 red, 50 blue, and 0 green:\nNot much green.\n```\n\n## Implementing structs and enums\n\nThis is where you can start to give your structs and enums some real power. To call functions on a `struct` or an `enum`, use an `impl` block. These functions are called **methods**. There are two kinds of methods in an `impl` block.\n\n- Methods: these take **self** (or **&self** or **&mut self**). Regular methods use a `.` (a period). `.clone()` is an example of a regular method.\n- Associated functions (known as \"static\" methods in some languages): these do not take self. Associated means \"related to\". They are written differently, using `::`. `String::from()` is an associated function, and so is `Vec::new()`. You see associated functions most often used to create new variables.\n\nIn our example we are going to create animals and print them.\n\nFor a new `struct` or `enum`, you need to give it **Debug** if you want to use `{:?}` to print, so we will do that. If you write `#[derive(Debug)]` above the struct or enum then you can print it with `{:?}`. These messages with `#[]` are called **attributes**. You can sometimes use them to tell the compiler to give your struct an ability like `Debug`. There are many attributes and we will learn about them later. But `derive` is probably the most common and you see it a lot above structs and enums.\n\n```rust\n#[derive(Debug)]\nstruct Animal {\n    age: u8,\n    animal_type: AnimalType,\n}\n\n#[derive(Debug)]\nenum AnimalType {\n    Cat,\n    Dog,\n}\n\nimpl Animal {\n    fn new() -> Self {\n        // Self means Animal.\n        // You can also write Animal instead of Self\n\n        Self {\n            // When we write Animal::new(), we always get a cat that is 10 years old\n            age: 10,\n            animal_type: AnimalType::Cat,\n        }\n    }\n\n    fn change_to_dog(&mut self) { // because we are inside Animal, &mut self means &mut Animal\n                                  // use .change_to_dog() to change the cat to a dog\n                                  // with &mut self we can change it\n        println!(\"Changing animal to dog!\");\n        self.animal_type = AnimalType::Dog;\n    }\n\n    fn change_to_cat(&mut self) {\n        // use .change_to_cat() to change the dog to a cat\n        // with &mut self we can change it\n        println!(\"Changing animal to cat!\");\n        self.animal_type = AnimalType::Cat;\n    }\n\n    fn check_type(&self) {\n        // we want to read self\n        match self.animal_type {\n            AnimalType::Dog => println!(\"The animal is a dog\"),\n            AnimalType::Cat => println!(\"The animal is a cat\"),\n        }\n    }\n}\n\n\n\nfn main() {\n    let mut new_animal = Animal::new(); // Associated function to create a new animal\n                                        // It is a cat, 10 years old\n    new_animal.check_type();\n    new_animal.change_to_dog();\n    new_animal.check_type();\n    new_animal.change_to_cat();\n    new_animal.check_type();\n}\n```\n\nThis prints:\n\n```text\nThe animal is a cat\nChanging animal to dog!\nThe animal is a dog\nChanging animal to cat!\nThe animal is a cat\n```\n\n\nRemember that Self (the type Self) and self (the variable self) are abbreviations. (abbreviation = short way to write)\n\nSo in our code, Self = Animal. Also, `fn change_to_dog(&mut self)` means `fn change_to_dog(&mut Animal)`.\n\nHere is one more small example. This time we will use `impl` on an `enum`:\n\n```rust\nenum Mood {\n    Good,\n    Bad,\n    Sleepy,\n}\n\nimpl Mood {\n    fn check(&self) {\n        match self {\n            Mood::Good => println!(\"Feeling good!\"),\n            Mood::Bad => println!(\"Eh, not feeling so good\"),\n            Mood::Sleepy => println!(\"Need sleep NOW\"),\n        }\n    }\n}\n\nfn main() {\n    let my_mood = Mood::Sleepy;\n    my_mood.check();\n}\n```\n\nThis prints `Need sleep NOW`.\n\n## Destructuring\n\nLet's look at some more destructuring. You can get the values from a struct or enum by using `let` backwards. We learned that this is  `destructuring`, because you get variables that are not part of a structure. Now you have the values separately. First a simple example:\n\n```rust\nstruct Person { // make a simple struct for a person\n    name: String,\n    real_name: String,\n    height: u8,\n    happiness: bool\n}\n\nfn main() {\n    let papa_doc = Person { // create variable papa_doc\n        name: \"Papa Doc\".to_string(),\n        real_name: \"Clarence\".to_string(),\n        height: 170,\n        happiness: false\n    };\n\n    let Person { // destructure papa_doc\n        name: a,\n        real_name: b,\n        height: c,\n        happiness: d\n    } = papa_doc;\n\n    println!(\"They call him {} but his real name is {}. He is {} cm tall and is he happy? {}\", a, b, c, d);\n}\n```\n\nThis prints: `They call him Papa Doc but his real name is Clarence. He is 170 cm tall and is he happy? false`\n\nYou can see that it's backwards. First we say `let papa_doc = Person { fields }` to create the struct. Then we say `let Person { fields } = papa_doc` to destructure it.\n\nYou don't have to write `name: a` - you can just write `name`. But here we write `name: a` because we want to use a variable with the name `a`.\n\nNow a bigger example. In this example we have a `City` struct. We give it a `new` function to make it. Then we have a `process_city_values` function to do things with the values. In the function we just create a `Vec`, but you can imagine that we can do much more after we destructure it.\n\n```rust\nstruct City {\n    name: String,\n    name_before: String,\n    population: u32,\n    date_founded: u32,\n}\n\nimpl City {\n    fn new(name: String, name_before: String, population: u32, date_founded: u32) -> Self {\n        Self {\n            name,\n            name_before,\n            population,\n            date_founded,\n        }\n    }\n}\n\nfn process_city_values(city: &City) {\n    let City {\n        name,\n        name_before,\n        population,\n        date_founded,\n    } = city;\n        // now we have the values to use separately\n    let two_names = vec![name, name_before];\n    println!(\"The city's two names are {:?}\", two_names);\n}\n\nfn main() {\n    let tallinn = City::new(\"Tallinn\".to_string(), \"Reval\".to_string(), 426_538, 1219);\n    process_city_values(&tallinn);\n}\n```\n\nThis prints `The city's two names are [\"Tallinn\", \"Reval\"]`.\n\n\n## References and the dot operator\n\nWe learned that when you have a reference, you need to use `*` to get to the value. A reference is a different type, so this won't work:\n\n```rust\nfn main() {\n    let my_number = 9;\n    let reference = &my_number;\n\n    println!(\"{}\", my_number == reference); // ⚠️\n}\n```\n\nThe compiler prints:\n\n```text\nerror[E0277]: can't compare `{integer}` with `&{integer}`\n --> src\\main.rs:5:30\n  |\n5 |     println!(\"{}\", my_number == reference);\n  |                              ^^ no implementation for `{integer} == &{integer}`\n```\n\nSo we change line 5 to `println!(\"{}\", my_number == *reference);` and now it prints `true` because it's now `i32` == `i32`, not `i32` == `&i32`. This is called dereferencing.\n\nBut when you use a method, Rust will dereference for you. The `.` in a method is called the dot operator, and it does dereferencing for free.\n\nFirst, let's make a struct with one `u8` field. Then we will make a reference to it and try to compare. It will not work:\n\n```rust\nstruct Item {\n    number: u8,\n}\n\nfn main() {\n    let item = Item {\n        number: 8,\n    };\n\n    let reference_number = &item.number; // reference number type is &u8\n\n    println!(\"{}\", reference_number == 8); // ⚠️ &u8 and u8 cannot be compared\n}\n```\n\nTo make it work, we need to dereference: `println!(\"{}\", *reference_number == 8);`.\n\nBut with the dot operator, we don't need `*`. For example:\n\n```rust\nstruct Item {\n    number: u8,\n}\n\nfn main() {\n    let item = Item {\n        number: 8,\n    };\n\n    let reference_item = &item;\n\n    println!(\"{}\", reference_item.number == 8); // we don't need to write *reference_item.number\n}\n```\n\nNow let's create a method for `Item` that compares `number` to another number. We don't need to use `*` anywhere:\n\n```rust\nstruct Item {\n    number: u8,\n}\n\nimpl Item {\n    fn compare_number(&self, other_number: u8) { // takes a reference to self\n        println!(\"Are {} and {} equal? {}\", self.number, other_number, self.number == other_number);\n            // We don't need to write *self.number\n    }\n}\n\nfn main() {\n    let item = Item {\n        number: 8,\n    };\n\n    let reference_item = &item; // This is type &Item\n    let reference_item_two = &reference_item; // This is type &&Item\n\n    item.compare_number(8); // the method works\n    reference_item.compare_number(8); // it works here too\n    reference_item_two.compare_number(8); // and here\n\n}\n```\n\nSo just remember: when you use the `.` operator, you don't need to worry about `*`.\n\n\n\n\n## Generics\n\nIn functions, you write what type to take as input:\n\n```rust\nfn return_number(number: i32) -> i32 {\n    println!(\"Here is your number.\");\n    number\n}\n\nfn main() {\n    let number = return_number(5);\n}\n```\n\nBut what if you want to take more than just `i32`? You can use generics for this. Generics means \"maybe one type, maybe another type\".\n\nFor generics, you use angle brackets with the type inside, like this: `<T>` This means \"any type you put into the function\". Usually, generics uses types with one capital letter (T, U, V, etc.), though you don't have to just use one letter.\n\nThis is how you change the function to make it generic:\n\n```rust\nfn return_number<T>(number: T) -> T {\n    println!(\"Here is your number.\");\n    number\n}\n\nfn main() {\n    let number = return_number(5);\n}\n```\n\nThe important part is the `<T>` after the function name. Without this, Rust will think that T is a concrete (concrete = not generic) type, like `String` or `i8`.\n\nThis is easier to understand if we write out a type name. See what happens when we change `T` to `MyType`:\n\n```rust\nfn return_number(number: MyType) -> MyType { // ⚠️\n    println!(\"Here is your number.\");\n    number\n}\n```\n\nAs you can see, `MyType` is concrete, not generic. So we need to write this and so now it works:\n\n```rust\nfn return_number<MyType>(number: MyType) -> MyType {\n    println!(\"Here is your number.\");\n    number\n}\n\nfn main() {\n    let number = return_number(5);\n}\n```\n\nSo the single letter `T` is for human eyes, but the part after the function name is for the compiler's \"eyes\". Without it, it's not generic.\n\nNow we will go back to type `T`, because Rust code usually uses `T`.\n\nYou will remember that some types in Rust are **Copy**, some are **Clone**, some are **Display**, some are **Debug**, and so on. With **Debug**, we can print with `{:?}`. So now you can see that we have a problem if we want to print `T`:\n\n```rust\nfn print_number<T>(number: T) {\n    println!(\"Here is your number: {:?}\", number); // ⚠️\n}\n\nfn main() {\n    print_number(5);\n}\n```\n\n`print_number` needs **Debug** to print `number`, but is `T` a type with `Debug`? Maybe not. Maybe it doesn't have `#[derive(Debug)]`, who knows. The compiler doesn't know either, so it gives an error:\n\n```text\nerror[E0277]: `T` doesn't implement `std::fmt::Debug`\n  --> src\\main.rs:29:43\n   |\n29 |     println!(\"Here is your number: {:?}\", number);\n   |                                           ^^^^^^ `T` cannot be formatted using `{:?}` because it doesn't implement `std::fmt::Debug`\n```\n\nT doesn't implement **Debug**. So do we implement Debug for T? No, because we don't know what T is. But we can tell the function: \"Don't worry, because any type T for this function will have Debug\".\n\n```rust\nuse std::fmt::Debug; // Debug is located at std::fmt::Debug. So now we can just write 'Debug'.\n\nfn print_number<T: Debug>(number: T) { // <T: Debug> is the important part\n    println!(\"Here is your number: {:?}\", number);\n}\n\nfn main() {\n    print_number(5);\n}\n```\n\nSo now the compiler knows: \"Okay, this type T is going to have Debug\". Now the code works, because `i32` has Debug. Now we can give it many types: `String`, `&str`, and so on, because they all have Debug.\n\nNow we can create a struct and give it Debug with #[derive(Debug)], so now we can print it too. Our function can take `i32`, the struct Animal, and more:\n\n```rust\nuse std::fmt::Debug;\n\n#[derive(Debug)]\nstruct Animal {\n    name: String,\n    age: u8,\n}\n\nfn print_item<T: Debug>(item: T) {\n    println!(\"Here is your item: {:?}\", item);\n}\n\nfn main() {\n    let charlie = Animal {\n        name: \"Charlie\".to_string(),\n        age: 1,\n    };\n\n    let number = 55;\n\n    print_item(charlie);\n    print_item(number);\n}\n```\n\nThis prints:\n\n```text\nHere is your item: Animal { name: \"Charlie\", age: 1 }\nHere is your item: 55\n```\n\nSometimes we need more than one type in a generic function. We have to write out each type name, and think about how we want to use it. In this example, we want two types. First we want to print a statement for type T. Printing with `{}` is nicer, so we will require `Display` for `T`.\n\nNext is type U, and the two variables `num_1` and `num_2` have type U (U is some sort of number). We want to compare them, so we need `PartialOrd`. That trait lets us use things like `<`, `>`, `==`, and so on. We want to print them too, so we require `Display` for `U` as well.\n\n```rust\nuse std::fmt::Display;\nuse std::cmp::PartialOrd;\n\nfn compare_and_display<T: Display, U: Display + PartialOrd>(statement: T, num_1: U, num_2: U) {\n    println!(\"{}! Is {} greater than {}? {}\", statement, num_1, num_2, num_1 > num_2);\n}\n\nfn main() {\n    compare_and_display(\"Listen up!\", 9, 8);\n}\n```\n\nThis prints `Listen up!! Is 9 greater than 8? true`.\n\nSo `fn compare_and_display<T: Display, U: Display + PartialOrd>(statement: T, num_1: U, num_2: U)` says:\n\n- The function name is `compare_and_display`,\n- The first type is T, and it is generic. It must be a type that can print with {}.\n- The next type is U, and it is generic. It must be a type that can print with {}. Also, it must be a type that can compare (use `>`, `<`, and `==`).\n\nNow we can give `compare_and_display` different types. `statement` can be a `String`, a `&str`, anything with Display.\n\nTo make generic functions easier to read, we can also write it like this with `where` right before the code block:\n\n```rust\nuse std::cmp::PartialOrd;\nuse std::fmt::Display;\n\nfn compare_and_display<T, U>(statement: T, num_1: U, num_2: U)\nwhere\n    T: Display,\n    U: Display + PartialOrd,\n{\n    println!(\"{}! Is {} greater than {}? {}\", statement, num_1, num_2, num_1 > num_2);\n}\n\nfn main() {\n    compare_and_display(\"Listen up!\", 9, 8);\n}\n```\n\nUsing `where` is a good idea when you have many generic types.\n\nAlso note:\n\n- If you have one type T and another type T, they must be the same.\n- If you have one type T and another type U, they can be different. But they can also be the same.\n\nFor example:\n\n```rust\nuse std::fmt::Display;\n\nfn say_two<T: Display, U: Display>(statement_1: T, statement_2: U) { // Type T needs Display, type U needs Display\n    println!(\"I have two things to say: {} and {}\", statement_1, statement_2);\n}\n\nfn main() {\n\n    say_two(\"Hello there!\", String::from(\"I hate sand.\")); // Type T is a &str, but type U is a String.\n    say_two(String::from(\"Where is Padme?\"), String::from(\"Is she all right?\")); // Both types are String.\n}\n```\n\nThis prints:\n\n```text\nI have two things to say: Hello there! and I hate sand.\nI have two things to say: Where is Padme? and Is she all right?\n```\n\n## Option and Result\n\nWe understand enums and generics now, so we can understand `Option` and `Result`. Rust uses these two enums to make code safer.\n\nWe will start with `Option`.\n\n### Option\n\nYou use `Option` when you have a value that might exist, or might not exist. When a value exists it is `Some(value)` and when it doesn't it's just `None`, Here is an example of bad code that can be improved with `Option`.\n\n```rust\n    // ⚠️\nfn take_fifth(value: Vec<i32>) -> i32 {\n    value[4]\n}\n\nfn main() {\n    let new_vec = vec![1, 2];\n    let index = take_fifth(new_vec);\n}\n```\n\nWhen we run the code, it panics. Here is the message:\n\n```text\nthread 'main' panicked at 'index out of bounds: the len is 2 but the index is 4', src\\main.rs:34:5\n```\n\nPanic means that the program stops before the problem happens. Rust sees that the function wants something impossible, and stops. It \"unwinds the stack\" (takes the values off the stack) and tells you \"sorry, I can't do that\".\n\nSo now we will change the return type from `i32` to `Option<i32>`. This means \"give me a `Some(i32)` if it's there, and give me `None` if it's not\". We say that the `i32` is \"wrapped\" in an `Option`, which means that it's inside an `Option`. You have to do something to get the value out.\n\n```rust\nfn take_fifth(value: Vec<i32>) -> Option<i32> {\n    if value.len() < 5 { // .len() gives the length of the vec.\n                         // It must be at least 5.\n        None\n    } else {\n        Some(value[4])\n    }\n}\n\nfn main() {\n    let new_vec = vec![1, 2];\n    let bigger_vec = vec![1, 2, 3, 4, 5];\n    println!(\"{:?}, {:?}\", take_fifth(new_vec), take_fifth(bigger_vec));\n}\n```\n\nThis prints `None, Some(5)`. This is good, because now we don't panic anymore. But how do we get the value 5?\n\nWe can get the value inside an option with `.unwrap()`, but be careful with `.unwrap()`. It's just like unwrapping a present: maybe there's something good inside, or maybe there's an angry snake inside. You only want to `.unwrap()` if you are sure. If you unwrap a value that is `None`, the program will panic.\n\n```rust\n// ⚠️\nfn take_fifth(value: Vec<i32>) -> Option<i32> {\n    if value.len() < 5 {\n        None\n    } else {\n        Some(value[4])\n    }\n}\n\nfn main() {\n    let new_vec = vec![1, 2];\n    let bigger_vec = vec![1, 2, 3, 4, 5];\n    println!(\"{:?}, {:?}\",\n        take_fifth(new_vec).unwrap(), // this one is None. .unwrap() will panic!\n        take_fifth(bigger_vec).unwrap()\n    );\n}\n```\n\nThe message is:\n\n```text\nthread 'main' panicked at 'called `Option::unwrap()` on a `None` value', src\\main.rs:14:9\n```\n\nBut we don't have to use `.unwrap()`. We can use a `match`. Then we can print the value we have `Some`, and not touch it if we have `None`. For example:\n\n```rust\nfn take_fifth(value: Vec<i32>) -> Option<i32> {\n    if value.len() < 5 {\n        None\n    } else {\n        Some(value[4])\n    }\n}\n\nfn handle_option(my_option: Vec<Option<i32>>) {\n  for item in my_option {\n    match item {\n      Some(number) => println!(\"Found a {}!\", number),\n      None => println!(\"Found a None!\"),\n    }\n  }\n}\n\nfn main() {\n    let new_vec = vec![1, 2];\n    let bigger_vec = vec![1, 2, 3, 4, 5];\n    let mut option_vec = Vec::new(); // Make a new vec to hold our options\n                                     // The vec is type: Vec<Option<i32>>. That means a vec of Option<i32>.\n\n    option_vec.push(take_fifth(new_vec)); // This pushes \"None\" into the vec\n    option_vec.push(take_fifth(bigger_vec)); // This pushes \"Some(5)\" into the vec\n\n    handle_option(option_vec); // handle_option looks at every option in the vec.\n                               // It prints the value if it is Some. It doesn't touch it if it is None.\n}\n```\n\nThis prints:\n\n```text\nFound a None!\nFound a 5!\n```\n\nBecause we know generics, we are able to read the code for `Option`. It looks like this:\n\n```rust\nenum Option<T> {\n    None,\n    Some(T),\n}\n\nfn main() {}\n```\n\nThe important point to remember: with `Some`, you have a value of type `T` (any type). Also note that the angle brackets after the `enum` name around `T` is what tells the compiler that it's generic. It has no trait like `Display` or anything to limit it, so it can be anything. But with `None`, you don't have anything.\n\nSo in a `match` statement for Option you can't say:\n\n```rust\n// 🚧\nSome(value) => println!(\"The value is {}\", value),\nNone(value) => println!(\"The value is {}\", value),\n```\n\nbecause `None` is just `None`.\n\nOf course, there are easier ways to use Option. In this code, we will use a method called `.is_some()` to tell us if it is `Some`. (Yes, there is also a method called `.is_none()`.) In this easier way, we don't need `handle_option()` anymore. We also don't need a vec for the Options.\n\n```rust\nfn take_fifth(value: Vec<i32>) -> Option<i32> {\n    if value.len() < 5 {\n        None\n    } else {\n        Some(value[4])\n    }\n}\n\nfn main() {\n    let new_vec = vec![1, 2];\n    let bigger_vec = vec![1, 2, 3, 4, 5];\n    let vec_of_vecs = vec![new_vec, bigger_vec];\n    for vec in vec_of_vecs {\n        let inside_number = take_fifth(vec);\n        if inside_number.is_some() {\n            // .is_some() returns true if we get Some, false if we get None\n            println!(\"We got: {}\", inside_number.unwrap()); // now it is safe to use .unwrap() because we already checked\n        } else {\n            println!(\"We got nothing.\");\n        }\n    }\n}\n```\n\nThis prints:\n\n```text\nWe got nothing.\nWe got: 5\n```\n\n### Result\n\nResult is similar to Option, but here is the difference:\n\n- Option is about `Some` or `None` (value or no value),\n- Result is about `Ok` or `Err` (okay result, or error result).\n\nSo `Option` is if you are thinking: \"Maybe there will be something, and maybe there won't.\" But `Result` is if you are thinking: \"Maybe it will fail.\"\n\nTo compare, here are the signatures for Option and Result.\n\n```rust\nenum Option<T> {\n    None,\n    Some(T),\n}\n\nenum Result<T, E> {\n    Ok(T),\n    Err(E),\n}\n\nfn main() {}\n```\n\nSo Result has a value inside of `Ok`, and a value inside of `Err`. That is because errors usually contain information that describes the error.\n\n`Result<T, E>` means you need to think of what you want to return for `Ok`, and what you want to return for `Err`. Actually, you can decide anything. Even this is okay:\n\n```rust\nfn check_error() -> Result<(), ()> {\n    Ok(())\n}\n\nfn main() {\n    check_error();\n}\n```\n\n`check_error` says \"return `()` if we get `Ok`, and return `()` if we get `Err`\". Then we return `Ok` with a `()`.\n\nThe compiler gives us an interesting warning:\n\n```text\nwarning: unused `std::result::Result` that must be used\n --> src\\main.rs:6:5\n  |\n6 |     check_error();\n  |     ^^^^^^^^^^^^^^\n  |\n  = note: `#[warn(unused_must_use)]` on by default\n  = note: this `Result` may be an `Err` variant, which should be handled\n```\n\nThis is true: we only returned the `Result` but it could have been an `Err`. So let's handle the error a bit, even though we're still not really doing anything.\n\n```rust\nfn give_result(input: i32) -> Result<(), ()> {\n    if input % 2 == 0 {\n        return Ok(())\n    } else {\n        return Err(())\n    }\n}\n\nfn main() {\n    if give_result(5).is_ok() {\n        println!(\"It's okay, guys\")\n    } else {\n        println!(\"It's an error, guys\")\n    }\n}\n```\n\nThis prints `It's an error, guys`. So we just handled our first error.\n\nRemember, the four methods to easily check are `.is_some()`, `is_none()`, `is_ok()`, and `is_err()`.\n\n\nSometimes a function with Result will use a `String` for the `Err` value. This is not the best method to use, but it is a little better than what we've done so far.\n\n```rust\nfn check_if_five(number: i32) -> Result<i32, String> {\n    match number {\n        5 => Ok(number),\n        _ => Err(\"Sorry, the number wasn't five.\".to_string()), // This is our error message\n    }\n}\n\nfn main() {\n    let mut result_vec = Vec::new(); // Create a new vec for the results\n\n    for number in 2..7 {\n        result_vec.push(check_if_five(number)); // push each result into the vec\n    }\n\n    println!(\"{:?}\", result_vec);\n}\n```\n\nOur vec prints:\n\n```text\n[Err(\"Sorry, the number wasn\\'t five.\"), Err(\"Sorry, the number wasn\\'t five.\"), Err(\"Sorry, the number wasn\\'t five.\"), Ok(5),\nErr(\"Sorry, the number wasn\\'t five.\")]\n```\n\nJust like Option, `.unwrap()` on `Err` will panic.\n\n```rust\n    // ⚠️\nfn main() {\n    let error_value: Result<i32, &str> = Err(\"There was an error\"); // Create a Result that is already an Err\n    println!(\"{}\", error_value.unwrap()); // Unwrap it\n}\n```\n\nThe program panics, and prints:\n\n```text\nthread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: \"There was an error\"', src\\main.rs:30:20\n```\n\nThis information helps you fix your code. `src\\main.rs:30:20` means \"inside main.rs in directory src, on line 30 and column 20\". So you can go there to look at your code and fix the problem.\n\nYou can also create your own error types. Result functions in the standard library and other people's code usually do this. For example, this function from the standard library:\n\n```rust\n// 🚧\npub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error>\n```\n\nThis function takes a vector of bytes (`u8`) and tries to make a `String`. So the success case for the Result is a `String` and the error case is `FromUtf8Error`. You can give your error type any name you want.\n\nUsing a `match` with `Option` and `Result` sometimes requires a lot of code. For example, the `.get()` method returns an `Option` on a `Vec`.\n\n```rust\nfn main() {\n    let my_vec = vec![2, 3, 4];\n    let get_one = my_vec.get(0); // 0 to get the first number\n    let get_two = my_vec.get(10); // Returns None\n    println!(\"{:?}\", get_one);\n    println!(\"{:?}\", get_two);\n}\n```\n\nThis prints\n\n```text\nSome(2)\nNone\n```\n\nSo now we can match to get the values. Let's use a range from 0 to 10 to see if it matches the numbers in `my_vec`.\n\n```rust\nfn main() {\n    let my_vec = vec![2, 3, 4];\n\n    for index in 0..10 {\n      match my_vec.get(index) {\n        Some(number) => println!(\"The number is: {}\", number),\n        None => {}\n      }\n    }\n}\n```\n\nThis is good, but we don't do anything for `None` because we don't care. Here we can make the code smaller by using `if let`. `if let` means \"do something if it matches, and don't do anything if it doesn't\". `if let` is when you don't care about matching for everything.\n\n```rust\nfn main() {\n    let my_vec = vec![2, 3, 4];\n\n    for index in 0..10 {\n      if let Some(number) = my_vec.get(index) {\n        println!(\"The number is: {}\", number);\n      }\n    }\n}\n```\n\n**Important to remember**: `if let Some(number) = my_vec.get(index)` means \"if you get `Some(number)` from `my_vec.get(index)`\".\n\nAlso note: it uses one `=`. It is not a boolean.\n\n`while let` is like a while loop for `if let`. Imagine that we have weather station data like this:\n\n```text\n[\"Berlin\", \"cloudy\", \"5\", \"-7\", \"78\"]\n[\"Athens\", \"sunny\", \"not humid\", \"20\", \"10\", \"50\"]\n```\n\nWe want to get the numbers, but not the words. For the numbers, we can use a method called `parse::<i32>()`. `parse()` is the method, and `::<i32>` is the type. It will try to turn the `&str` into an `i32`, and give it to us if it can. It returns a `Result`, because it might not work (like if you wanted it to parse \"Billybrobby\" - that's not a number).\n\nWe will also use `.pop()`. This takes the last item off of the vector.\n\n```rust\nfn main() {\n    let weather_vec = vec![\n        vec![\"Berlin\", \"cloudy\", \"5\", \"-7\", \"78\"],\n        vec![\"Athens\", \"sunny\", \"not humid\", \"20\", \"10\", \"50\"],\n    ];\n    for mut city in weather_vec {\n        println!(\"For the city of {}:\", city[0]); // In our data, every first item is the city name\n        while let Some(information) = city.pop() {\n            // This means: keep going until you can't pop anymore\n            // When the vector reaches 0 items, it will return None\n            // and it will stop.\n            if let Ok(number) = information.parse::<i32>() {\n                // Try to parse the variable we called information\n                // This returns a result. If it's Ok(number), it will print it\n                println!(\"The number is: {}\", number);\n            }  // We don't write anything here because we do nothing if we get an error. Throw them all away\n        }\n    }\n}\n```\n\nThis will print:\n\n```text\nFor the city of Berlin:\nThe number is: 78\nThe number is: -7\nThe number is: 5\nFor the city of Athens:\nThe number is: 50\nThe number is: 10\nThe number is: 20\n```\n\n## Other collections\n\nRust has many more types of collections. You can see them at https://doc.rust-lang.org/beta/std/collections/ in the standard library. That page has good explanations for why to use one type, so go there if you don't know what type you want. These collections are all inside `std::collections` in the standard library. The best way to use them is with a `use` statement, like we did with our `enums`. We will start with `HashMap`, which is very common.\n\n### HashMap (and BTreeMap)\n\nA HashMap is a collection made out of *keys* and *values*. You use the key to look up the value that matches the key. You can create a new `HashMap` with just `HashMap::new()` and use `.insert(key, value)` to insert items.\n\nA `HashMap` is not in order, so if you print every key in a `HashMap` together it will probably print differently. We can see this in an example:\n\n```rust\nuse std::collections::HashMap; // This is so we can just write HashMap instead of std::collections::HashMap every time\n\nstruct City {\n    name: String,\n    population: HashMap<u32, u32>, // This will have the year and the population for the year\n}\n\nfn main() {\n\n    let mut tallinn = City {\n        name: \"Tallinn\".to_string(),\n        population: HashMap::new(), // So far the HashMap is empty\n    };\n\n    tallinn.population.insert(1372, 3_250); // insert three dates\n    tallinn.population.insert(1851, 24_000);\n    tallinn.population.insert(2020, 437_619);\n\n\n    for (year, population) in tallinn.population { // The HashMap is HashMap<u32, u32> so it returns a two items each time\n        println!(\"In the year {} the city of {} had a population of {}.\", year, tallinn.name, population);\n    }\n}\n```\n\nThis prints:\n\n```text\nIn the year 1372 the city of Tallinn had a population of 3250.\nIn the year 2020 the city of Tallinn had a population of 437619.\nIn the year 1851 the city of Tallinn had a population of 24000.\n```\n\nor it might print:\n\n```text\nIn the year 1851 the city of Tallinn had a population of 24000.\nIn the year 2020 the city of Tallinn had a population of 437619.\nIn the year 1372 the city of Tallinn had a population of 3250.\n```\n\nYou can see that it's not in order.\n\nIf you want a `HashMap` that you can sort, you can use a `BTreeMap`. Actually they are very similar to each other, so we can quickly change our `HashMap` to a `BTreeMap` to see. You can see that it is almost the same code.\n\n```rust\nuse std::collections::BTreeMap; // Just change HashMap to BTreeMap\n\nstruct City {\n    name: String,\n    population: BTreeMap<u32, u32>, // Just change HashMap to BTreeMap\n}\n\nfn main() {\n\n    let mut tallinn = City {\n        name: \"Tallinn\".to_string(),\n        population: BTreeMap::new(), // Just change HashMap to BTreeMap\n    };\n\n    tallinn.population.insert(1372, 3_250);\n    tallinn.population.insert(1851, 24_000);\n    tallinn.population.insert(2020, 437_619);\n\n    for (year, population) in tallinn.population {\n        println!(\"In the year {} the city of {} had a population of {}.\", year, tallinn.name, population);\n    }\n}\n```\n\nNow it will always print:\n\n```text\nIn the year 1372 the city of Tallinn had a population of 3250.\nIn the year 1851 the city of Tallinn had a population of 24000.\nIn the year 2020 the city of Tallinn had a population of 437619.\n```\n\nNow we will go back to `HashMap`.\n\nYou can get a value in a `HashMap` by just putting the key in `[]` square brackets. In this next example we will bring up the value for the key `Bielefeld`, which is `Germany`. But be careful, because the program will crash if there is no key. If you write `println!(\"{:?}\", city_hashmap[\"Bielefeldd\"]);` for example then it will crash, because `Bielefeldd` doesn't exist.\n\nIf you are not sure that there will be a key, you can use `.get()` which returns an `Option`. If it exists it will be `Some(value)`, and if not you will get `None` instead of crashing the program. That's why `.get()` is the safer way to get a value from a `HashMap`.\n\n```rust\nuse std::collections::HashMap;\n\nfn main() {\n    let canadian_cities = vec![\"Calgary\", \"Vancouver\", \"Gimli\"];\n    let german_cities = vec![\"Karlsruhe\", \"Bad Doberan\", \"Bielefeld\"];\n\n    let mut city_hashmap = HashMap::new();\n\n    for city in canadian_cities {\n        city_hashmap.insert(city, \"Canada\");\n    }\n    for city in german_cities {\n        city_hashmap.insert(city, \"Germany\");\n    }\n\n    println!(\"{:?}\", city_hashmap[\"Bielefeld\"]);\n    println!(\"{:?}\", city_hashmap.get(\"Bielefeld\"));\n    println!(\"{:?}\", city_hashmap.get(\"Bielefeldd\"));\n}\n```\n\nThis prints:\n\n```text\n\"Germany\"\nSome(\"Germany\")\nNone\n```\n\nThis is because *Bielefeld* exists, but *Bielefeldd* does not exist.\n\nIf a `HashMap` already has a key when you try to put it in, it will overwrite its value:\n\n```rust\nuse std::collections::HashMap;\n\nfn main() {\n    let mut book_hashmap = HashMap::new();\n\n    book_hashmap.insert(1, \"L'Allemagne Moderne\");\n    book_hashmap.insert(1, \"Le Petit Prince\");\n    book_hashmap.insert(1, \"섀도우 오브 유어 스마일\");\n    book_hashmap.insert(1, \"Eye of the World\");\n\n    println!(\"{:?}\", book_hashmap.get(&1));\n}\n```\n\nThis prints `Some(\"Eye of the World\")`, because it was the last one you used `.insert()` for.\n\nIt is easy to check if an entry exists, because you can check with `.get()` which gives an `Option`:\n\n```rust\nuse std::collections::HashMap;\n\nfn main() {\n    let mut book_hashmap = HashMap::new();\n\n    book_hashmap.insert(1, \"L'Allemagne Moderne\");\n\n    if book_hashmap.get(&1).is_none() { // is_none() returns a bool: true if it's None, false if it's Some\n        book_hashmap.insert(1, \"Le Petit Prince\");\n    }\n\n    println!(\"{:?}\", book_hashmap.get(&1));\n}\n```\n\nThis prints `Some(\"L\\'Allemagne Moderne\")` because there was already a key for `1`, so we didn't insert `Le Petit Prince`.\n\n`HashMap` has a very interesting method called `.entry()` that you definitely want to try out. With it you can try to make an entry and use another method like `.or_insert()` to insert the value if there is no key. The interesting part is that it also gives a mutable reference so you can change it if you want. First is an example where we just insert `true` every time we insert a book title into the `HashMap`.\n\nLet's pretend that we have a library and want to keep track of our books.\n\n```rust\nuse std::collections::HashMap;\n\nfn main() {\n    let book_collection = vec![\"L'Allemagne Moderne\", \"Le Petit Prince\", \"Eye of the World\", \"Eye of the World\"]; // Eye of the World appears twice\n\n    let mut book_hashmap = HashMap::new();\n\n    for book in book_collection {\n        book_hashmap.entry(book).or_insert(true);\n    }\n    for (book, true_or_false) in book_hashmap {\n        println!(\"Do we have {}? {}\", book, true_or_false);\n    }\n}\n```\n\nThis prints:\n\n```text\nDo we have Eye of the World? true\nDo we have Le Petit Prince? true\nDo we have L'Allemagne Moderne? true\n```\n\nBut that's not exactly what we want. Maybe it would be better to count the number of books so that we know that there are two copies of *Eye of the World*. First let's look at what `.entry()` does, and what `.or_insert()` does. `.entry()` actually returns an `enum` called `Entry`:\n\n```rust\npub fn entry(&mut self, key: K) -> Entry<K, V> // 🚧\n```\n\n\n[Here is the page for Entry](https://doc.rust-lang.org/std/collections/hash_map/enum.Entry.html). Here is a simple version of its code. `K` means key and `V` means value.\n\n```rust\n// 🚧\nuse std::collections::hash_map::*;\n\nenum Entry<K, V> {\n    Occupied(OccupiedEntry<K, V>),\n    Vacant(VacantEntry<K, V>),\n}\n```\n\nThen when we call `.or_insert()`, it looks at the enum and decides what to do.\n\n```rust\nfn or_insert(self, default: V) -> &mut V { // 🚧\n    match self {\n        Occupied(entry) => entry.into_mut(),\n        Vacant(entry) => entry.insert(default),\n    }\n}\n```\n\nThe interesting part is that it returns a `mut` reference: `&mut V`. That means you can use `let` to attach it to a variable, and change the variable to change the value in the `HashMap`. So for every book we will insert a 0 if there is no entry. And if there is one, we will use `+= 1` on the reference to increase the number. Now it looks like this:\n\n```rust\nuse std::collections::HashMap;\n\nfn main() {\n    let book_collection = vec![\"L'Allemagne Moderne\", \"Le Petit Prince\", \"Eye of the World\", \"Eye of the World\"];\n\n    let mut book_hashmap = HashMap::new();\n\n    for book in book_collection {\n        let return_value = book_hashmap.entry(book).or_insert(0); // return_value is a mutable reference. If nothing is there, it will be 0\n        *return_value +=1; // Now return_value is at least 1. And if there was another book, it will go up by 1\n    }\n\n    for (book, number) in book_hashmap {\n        println!(\"{}, {}\", book, number);\n    }\n}\n```\n\n\nThe important part is `let return_value = book_hashmap.entry(book).or_insert(0);`. If you take out the `let`, you get `book_hashmap.entry(book).or_insert(0)`. Without `let` it does nothing: it inserts 0, and nobody takes the mutable reference to 0. So we bind it to `return_value` so we can keep the 0. Then we increase the value by 1, which gives at least 1 for every book in the `HashMap`. Then when `.entry()` looks at *Eye of the World* again it doesn't insert anything, but it gives us a mutable 1. Then we increase it to 2, and that's why it prints this:\n\n```text\nL'Allemagne Moderne, 1\nLe Petit Prince, 1\nEye of the World, 2\n```\n\n\nYou can also do things with `.or_insert()` like insert a vec and then push into the vec. Let's pretend that we asked men and women on the street what they think of a politician. They give a rating from 0 to 10. Then we want to put the numbers together to see if the politician is more popular with men or women. It can look like this:\n\n\n```rust\nuse std::collections::HashMap;\n\nfn main() {\n    let data = vec![ // This is the raw data\n        (\"male\", 9),\n        (\"female\", 5),\n        (\"male\", 0),\n        (\"female\", 6),\n        (\"female\", 5),\n        (\"male\", 10),\n    ];\n\n    let mut survey_hash = HashMap::new();\n\n    for item in data { // This gives a tuple of (&str, i32)\n        survey_hash.entry(item.0).or_insert(Vec::new()).push(item.1); // This pushes the number into the Vec inside\n    }\n\n    for (male_or_female, numbers) in survey_hash {\n        println!(\"{:?}: {:?}\", male_or_female, numbers);\n    }\n}\n```\n\nThis prints:\n\n```text\n\"female\", [5, 6, 5]\n\"male\", [9, 0, 10]\n```\n\nThe important line is: `survey_hash.entry(item.0).or_insert(Vec::new()).push(item.1);` So if it sees \"female\" it will check to see if there is \"female\" already in the `HashMap`. If not, it will insert a `Vec::new()`, then push the number in. If it sees \"female\" already in the `HashMap`, it will not insert a new Vec, and will just push the number into it.\n\n### HashSet and BTreeSet\n\nA `HashSet` is actually a `HashMap` that only has keys. On [the page for HashSet](https://doc.rust-lang.org/std/collections/struct.HashSet.html) it explains this on the top:\n\n`A hash set implemented as a HashMap where the value is ().` So it's a `HashMap` with keys, no values.\n\nYou often use a `HashSet` if you just want to know if a key exists, or doesn't exist.\n\nImagine that you have 100 random numbers, and each number between 1 and 100. If you do this, some numbers will appear more than once, while some won't appear at all. If you put them into a `HashSet` then you will have a list of all the numbers that appeared.\n\n```rust\nuse std::collections::HashSet;\n\nfn main() {\n    let many_numbers = vec![\n        94, 42, 59, 64, 32, 22, 38, 5, 59, 49, 15, 89, 74, 29, 14, 68, 82, 80, 56, 41, 36, 81, 66,\n        51, 58, 34, 59, 44, 19, 93, 28, 33, 18, 46, 61, 76, 14, 87, 84, 73, 71, 29, 94, 10, 35, 20,\n        35, 80, 8, 43, 79, 25, 60, 26, 11, 37, 94, 32, 90, 51, 11, 28, 76, 16, 63, 95, 13, 60, 59,\n        96, 95, 55, 92, 28, 3, 17, 91, 36, 20, 24, 0, 86, 82, 58, 93, 68, 54, 80, 56, 22, 67, 82,\n        58, 64, 80, 16, 61, 57, 14, 11];\n\n    let mut number_hashset = HashSet::new();\n\n    for number in many_numbers {\n        number_hashset.insert(number);\n    }\n\n    let hashset_length = number_hashset.len(); // The length tells us how many numbers are in it\n    println!(\"There are {} unique numbers, so we are missing {}.\", hashset_length, 100 - hashset_length);\n\n    // Let's see what numbers we are missing\n    let mut missing_vec = vec![];\n    for number in 0..100 {\n        if number_hashset.get(&number).is_none() { // If .get() returns None,\n            missing_vec.push(number);\n        }\n    }\n\n    print!(\"It does not contain: \");\n    for number in missing_vec {\n        print!(\"{} \", number);\n    }\n}\n```\n\nThis prints:\n\n```text\nThere are 66 unique numbers, so we are missing 34.\nIt does not contain: 1 2 4 6 7 9 12 21 23 27 30 31 39 40 45 47 48 50 52 53 62 65 69 70 72 75 77 78 83 85 88 97 98 99\n```\n\nA `BTreeSet` is similar to a `HashSet` in the same way that a `BTreeMap` is similar to a `HashMap`. If we print each item in the `HashSet`, we don't know what the order will be:\n\n```rust\nfor entry in number_hashset { // 🚧\n    print!(\"{} \", entry);\n}\n```\n\nMaybe it will print this: `67 28 42 25 95 59 87 11 5 81 64 34 8 15 13 86 10 89 63 93 49 41 46 57 60 29 17 22 74 43 32 38 36 76 71 18 14 84 61 16 35 90 56 54 91 19 94 44 3 0 68 80 51 92 24 20 82 26 58 33 55 96 37 66 79 73`. But it will almost never print it in the same way again.\n\nHere as well, it is easy to change your `HashSet` to a `BTreeSet` if you decide you need ordering. In our code, we only need to make two changes to switch from a `HashSet` to a `BTreeSet`.\n\n```rust\nuse std::collections::BTreeSet; // Change HashSet to BTreeSet\n\nfn main() {\n    let many_numbers = vec![\n        94, 42, 59, 64, 32, 22, 38, 5, 59, 49, 15, 89, 74, 29, 14, 68, 82, 80, 56, 41, 36, 81, 66,\n        51, 58, 34, 59, 44, 19, 93, 28, 33, 18, 46, 61, 76, 14, 87, 84, 73, 71, 29, 94, 10, 35, 20,\n        35, 80, 8, 43, 79, 25, 60, 26, 11, 37, 94, 32, 90, 51, 11, 28, 76, 16, 63, 95, 13, 60, 59,\n        96, 95, 55, 92, 28, 3, 17, 91, 36, 20, 24, 0, 86, 82, 58, 93, 68, 54, 80, 56, 22, 67, 82,\n        58, 64, 80, 16, 61, 57, 14, 11];\n\n    let mut number_btreeset = BTreeSet::new(); // Change HashSet to BTreeSet\n\n    for number in many_numbers {\n        number_btreeset.insert(number);\n    }\n    for entry in number_btreeset {\n        print!(\"{} \", entry);\n    }\n}\n```\n\nNow it will print in order: `0 3 5 8 10 11 13 14 15 16 17 18 19 20 22 24 25 26 28 29 32 33 34 35 36 37 38 41 42 43 44 46 49 51 54 55 56 57 58 59 60 61 63 64 66 67 68 71 73 74 76 79 80 81 82 84 86 87 89 90 91 92 93 94 95 96`.\n\n### BinaryHeap\n\nA `BinaryHeap` is an interesting collection type, because it is mostly unordered but has a bit of order. It keeps the largest item in the front, but the other items are in any order.\n\nWe will use another list of items for an example, but this time smaller.\n\n```rust\nuse std::collections::BinaryHeap;\n\nfn show_remainder(input: &BinaryHeap<i32>) -> Vec<i32> { // This function shows the remainder in the BinaryHeap. Actually an iterator would be\n                                                         // faster than a function - we will learn them later.\n    let mut remainder_vec = vec![];\n    for number in input {\n        remainder_vec.push(*number)\n    }\n    remainder_vec\n}\n\nfn main() {\n    let many_numbers = vec![0, 5, 10, 15, 20, 25, 30]; // These numbers are in order\n\n    let mut my_heap = BinaryHeap::new();\n\n    for number in many_numbers {\n        my_heap.push(number);\n    }\n\n    while let Some(number) = my_heap.pop() { // .pop() returns Some(number) if a number is there, None if not. It pops from the front\n        println!(\"Popped off {}. Remaining numbers are: {:?}\", number, show_remainder(&my_heap));\n    }\n}\n```\n\nThis prints:\n\n```text\nPopped off 30. Remaining numbers are: [25, 15, 20, 0, 10, 5]\nPopped off 25. Remaining numbers are: [20, 15, 5, 0, 10]\nPopped off 20. Remaining numbers are: [15, 10, 5, 0]\nPopped off 15. Remaining numbers are: [10, 0, 5]\nPopped off 10. Remaining numbers are: [5, 0]\nPopped off 5. Remaining numbers are: [0]\nPopped off 0. Remaining numbers are: []\n```\n\nYou can see that the number in the 0 index is always largest: 25, 20, 15, 10, 5, then 0. But the other ones are all different.\n\nA good way to use a `BinaryHeap` is for a collection of things to do. Here we create a `BinaryHeap<(u8, &str)>` where the `u8` is a number for the importance of the task. The `&str` is a description of what to do.\n\n```rust\nuse std::collections::BinaryHeap;\n\nfn main() {\n    let mut jobs = BinaryHeap::new();\n\n    // Add jobs to do throughout the day\n    jobs.push((100, \"Write back to email from the CEO\"));\n    jobs.push((80, \"Finish the report today\"));\n    jobs.push((5, \"Watch some YouTube\"));\n    jobs.push((70, \"Tell your team members thanks for always working hard\"));\n    jobs.push((30, \"Plan who to hire next for the team\"));\n\n    while let Some(job) = jobs.pop() {\n        println!(\"You need to: {}\", job.1);\n    }\n}\n```\n\nThis will always print:\n\n```text\nYou need to: Write back to email from the CEO\nYou need to: Finish the report today\nYou need to: Tell your team members thanks for always working hard\nYou need to: Plan who to hire next for the team\nYou need to: Watch some YouTube\n```\n\n### VecDeque\n\nA `VecDeque` is a `Vec` that is good at popping items both off the front and the back. Rust has `VecDeque` because a `Vec` is great for popping off the back (the last item), but not so great off the front. When you use `.pop()` on a `Vec`, it just takes off the last item on the right and nothing else is moved. But if you take it off another part, all the items to the right are moved over one position to the left. You can see this in the description for `.remove()`:\n\n\n```text\nRemoves and returns the element at position index within the vector, shifting all elements after it to the left.\n```\n\nSo if you do this:\n\n```rust\nfn main() {\n    let mut my_vec = vec![9, 8, 7, 6, 5];\n    my_vec.remove(0);\n}\n```\n\nit will remove `9`. `8` in index 1 will move to index 0, `7` in index 2 will move to index 1, and so on. Imagine a big parking lot where every time one car leaves all the cars on the right side have to move over.\n\nThis, for example, is a *lot* of work for the computer. In fact, if you run it on the Playground it will probably just give up because it's too much work.\n\n```rust\nfn main() {\n    let mut my_vec = vec![0; 600_000];\n    for i in 0..600000 {\n        my_vec.remove(0);\n    }\n}\n```\n\nThis is a `Vec` of 600,000 zeros. Every time you use `remove(0)` on it, it moves each zero left one space to the left. And then it does it 600,000 times.\n\nYou don't have to worry about that with a `VecDeque`. It is usually a bit slower than a `Vec`, but if you have to do things on both ends then it is much faster. You can just use `VecDeque::from` with a `Vec` to make one. Our code above then looks like this:\n\n```rust\nuse std::collections::VecDeque;\n\nfn main() {\n    let mut my_vec = VecDeque::from(vec![0; 600000]);\n    for i in 0..600000 {\n        my_vec.pop_front(); // pop_front is like .pop but for the front\n    }\n}\n```\n\nIt is now much faster, and on the Playground it finishes in under a second instead of giving up.\n\nIn this next example we have a `Vec` of things to do. Then we make a `VecDeque` and use `.push_front()` to put them at the front, so the first item we added will be on the right. But each item we push is a `(&str, bool)`: `&str` is the description and `false` means it's not done yet. We use our `done()` function to pop an item off the back, but we don't want to delete it. Instead, we change `false` to `true` and push it at the front so that we can keep it.\n\nIt looks like this:\n\n```rust\nuse std::collections::VecDeque;\n\nfn check_remaining(input: &VecDeque<(&str, bool)>) { // Each item is a (&str, bool)\n    for item in input {\n        if item.1 == false {\n            println!(\"You must: {}\", item.0);\n        }\n    }\n}\n\nfn done(input: &mut VecDeque<(&str, bool)>) {\n    let mut task_done = input.pop_back().unwrap(); // pop off the back\n    task_done.1 = true;                            // now it's done - mark as true\n    input.push_front(task_done);                   // put it at the front now\n}\n\nfn main() {\n    let mut my_vecdeque = VecDeque::new();\n    let things_to_do = vec![\"send email to customer\", \"add new product to list\", \"phone Loki back\"];\n\n    for thing in things_to_do {\n        my_vecdeque.push_front((thing, false));\n    }\n\n    done(&mut my_vecdeque);\n    done(&mut my_vecdeque);\n\n    check_remaining(&my_vecdeque);\n\n    for task in my_vecdeque {\n        print!(\"{:?} \", task);\n    }\n}\n```\n\nThis prints:\n\n```text\nYou must: phone Loki back\n(\"add new product to list\", true) (\"send email to customer\", true) (\"phone Loki back\", false)\n```\n\n## The ? operator\n\nThere is an even shorter way to deal with `Result` (and `Option`), shorter than `match` and even shorter than `if let`. It is called the \"question mark operator\", and is just `?`. After a function that returns a result, you can add `?`. This will:\n\n- return what is inside the `Result` if it is `Ok`\n- pass the error back if it is `Err`\n\nIn other words, it does almost everything for you.\n\nWe can try this with `.parse()` again. We will write a function called `parse_str` that tries to turn a `&str` into a `i32`. It looks like this:\n\n```rust\nuse std::num::ParseIntError;\n\nfn parse_str(input: &str) -> Result<i32, ParseIntError> {\n    let parsed_number = input.parse::<i32>()?; // Here is the question mark\n    Ok(parsed_number)\n}\n\nfn main() {}\n```\n\nThis function takes a `&str`. If it is `Ok`, it gives an `i32` wrapped in `Ok`. If it is an `Err`, it returns a `ParseIntError`. Then we try to parse the number, and add `?`. That means \"check if it is an error, and give what is inside the Result if it is okay\". If it is not okay, it will return the error and end. But if it is okay, it will go to the next line. On the next line is the number inside of `Ok()`. We need to wrap it in `Ok` because the return is `Result<i32, ParseIntError>`, not `i32`.\n\nNow, we can try out our function. Let's see what it does with a vec of `&str`s.\n\n```rust\nfn parse_str(input: &str) -> Result<i32, std::num::ParseIntError> {\n    let parsed_number = input.parse::<i32>()?;\n    Ok(parsed_number)\n}\n\nfn main() {\n    let str_vec = vec![\"Seven\", \"8\", \"9.0\", \"nice\", \"6060\"];\n    for item in str_vec {\n        let parsed = parse_str(item);\n        println!(\"{:?}\", parsed);\n    }\n}\n```\n\nThis prints:\n\n```text\nErr(ParseIntError { kind: InvalidDigit })\nOk(8)\nErr(ParseIntError { kind: InvalidDigit })\nErr(ParseIntError { kind: InvalidDigit })\nOk(6060)\n```\n\nHow did we find `std::num::ParseIntError`? One easy way is to \"ask\" the compiler again.\n\n```rust\nfn main() {\n    let failure = \"Not a number\".parse::<i32>();\n    failure.rbrbrb(); // ⚠️ Compiler: \"What is rbrbrb()???\"\n}\n```\n\nThe compiler doesn't understand, and says:\n\n```text\nerror[E0599]: no method named `rbrbrb` found for enum `std::result::Result<i32, std::num::ParseIntError>` in the current scope\n --> src\\main.rs:3:13\n  |\n3 |     failure.rbrbrb();\n  |             ^^^^^^ method not found in `std::result::Result<i32, std::num::ParseIntError>`\n```\n\nSo `std::result::Result<i32, std::num::ParseIntError>` is the signature we need.\n\nWe don't need to write `std::result::Result` because `Result` is always \"in scope\" (in scope = ready to use). Rust does this for all the types we use a lot so we don't have to write `std::result::Result`, `std::collections::Vec`, etc.\n\nWe aren't working with things like files yet, so the ? operator doesn't look too useful yet. But here is a useless but quick example that shows how you can use it on a single line. Instead of making an `i32` with `.parse()`, we'll do a lot more. We'll make an `u16`, then turn it to a `String`, then a `u32`, then to a `String` again, and finally to a `i32`.\n\n```rust\nuse std::num::ParseIntError;\n\nfn parse_str(input: &str) -> Result<i32, ParseIntError> {\n    let parsed_number = input.parse::<u16>()?.to_string().parse::<u32>()?.to_string().parse::<i32>()?; // Add a ? each time to check and pass it on\n    Ok(parsed_number)\n}\n\nfn main() {\n    let str_vec = vec![\"Seven\", \"8\", \"9.0\", \"nice\", \"6060\"];\n    for item in str_vec {\n        let parsed = parse_str(item);\n        println!(\"{:?}\", parsed);\n    }\n}\n```\n\nThis prints the same thing, but this time we handled three `Result`s in a single line. Later on we will do this with files, because they always return `Result`s because many things can go wrong.\n\nImagine the following: you want to open a file, write to it, and close it. First you need to successfully find the file (that's a `Result`). Then you need to successfully write to it (that's a `Result`). With `?` you can do that on one line.\n\n### When panic and unwrap are good\n\nRust has a `panic!` macro that you can use to make it panic. It is easy to use:\n\n```rust\nfn main() {\n    panic!(\"Time to panic!\");\n}\n```\n\nThe message `\"Time to panic!\"` displays when you run the program: `thread 'main' panicked at 'Time to panic!', src\\main.rs:2:3`\n\nYou will remember that `src\\main.rs` is the directory and file name, and `2:3` are the line and column numbers. With this information, you can find the code and fix it.\n\n`panic!` is a good macro to use to make sure that you know when something changes. For example, this function called `prints_three_things` always prints index [0], [1], and [2] from a vector. It is okay because we always give it a vector with three items:\n\n```rust\nfn prints_three_things(vector: Vec<i32>) {\n    println!(\"{}, {}, {}\", vector[0], vector[1], vector[2]);\n}\n\nfn main() {\n    let my_vec = vec![8, 9, 10];\n    prints_three_things(my_vec);\n}\n```\n\nIt prints `8, 9, 10` and everything is fine.\n\nBut imagine that later on we write more and more code, and forget that `my_vec` can only be three things. Now `my_vec` in this part has six things:\n\n```rust\nfn prints_three_things(vector: Vec<i32>) {\n  println!(\"{}, {}, {}\", vector[0], vector[1], vector[2]);\n}\n\nfn main() {\n  let my_vec = vec![8, 9, 10, 10, 55, 99]; // Now my_vec has six things\n  prints_three_things(my_vec);\n}\n```\n\nNo error happens, because [0] and [1] and [2] are all inside this longer `Vec`. But what if it was really important to only have three things? We wouldn't know that there was a problem because the program doesn't panic. We should have done this instead:\n\n```rust\nfn prints_three_things(vector: Vec<i32>) {\n    if vector.len() != 3 {\n        panic!(\"my_vec must always have three items\") // will panic if the length is not 3\n    }\n    println!(\"{}, {}, {}\", vector[0], vector[1], vector[2]);\n}\n\nfn main() {\n    let my_vec = vec![8, 9, 10];\n    prints_three_things(my_vec);\n}\n```\n\nNow we will know if the vector has six items because it panics as it should:\n\n```rust\n    // ⚠️\nfn prints_three_things(vector: Vec<i32>) {\n    if vector.len() != 3 {\n        panic!(\"my_vec must always have three items\")\n    }\n    println!(\"{}, {}, {}\", vector[0], vector[1], vector[2]);\n}\n\nfn main() {\n    let my_vec = vec![8, 9, 10, 10, 55, 99];\n    prints_three_things(my_vec);\n}\n```\n\nThis gives us `thread 'main' panicked at 'my_vec must always have three items', src\\main.rs:8:9`. Thanks to `panic!`, we now remember that `my_vec` should only have three items. So `panic!` is a good macro to create reminders in your code.\n\nThere are three other macros that are similar to `panic!` that you use a lot in testing. They are: `assert!`, `assert_eq!`, and `assert_ne!`.\n\nHere is what they mean:\n\n- `assert!()`: if the part inside `()` is not true, the program will panic.\n- `assert_eq!()`: the two items inside `()` must be equal.\n- `assert_ne!()`: the two items inside `()` must not be equal. (*ne* means not equal)\n\nSome examples:\n\n```rust\nfn main() {\n    let my_name = \"Loki Laufeyson\";\n\n    assert!(my_name == \"Loki Laufeyson\");\n    assert_eq!(my_name, \"Loki Laufeyson\");\n    assert_ne!(my_name, \"Mithridates\");\n}\n```\n\nThis will do nothing, because all three assert macros are okay. (This is what we want)\n\nYou can also add a message if you want.\n\n```rust\nfn main() {\n    let my_name = \"Loki Laufeyson\";\n\n    assert!(\n        my_name == \"Loki Laufeyson\",\n        \"{} should be Loki Laufeyson\",\n        my_name\n    );\n    assert_eq!(\n        my_name, \"Loki Laufeyson\",\n        \"{} and Loki Laufeyson should be equal\",\n        my_name\n    );\n    assert_ne!(\n        my_name, \"Mithridates\",\n        \"You entered {}. Input must not equal Mithridates\",\n        my_name\n    );\n}\n```\n\nThese messages will only display if the program panics. So if you run this:\n\n```rust\nfn main() {\n    let my_name = \"Mithridates\";\n\n    assert_ne!(\n        my_name, \"Mithridates\",\n        \"You enter {}. Input must not equal Mithridates\",\n        my_name\n    );\n}\n```\n\nIt will display:\n\n```text\nthread 'main' panicked at 'assertion failed: `(left != right)`\n  left: `\"Mithridates\"`,\n right: `\"Mithridates\"`: You entered Mithridates. Input must not equal Mithridates', src\\main.rs:4:5\n```\n\nSo it is saying \"you said that left != right, but left == right\". And it displays our message that says `You entered Mithridates. Input must not equal Mithridates`.\n\n`unwrap` is also good when you are writing your program and you want it to crash when there is a problem. Later, when your code is finished it is good to change `unwrap` to something else that won't crash.\n\nYou can also use `expect`, which is like `unwrap` but a bit better because you give it your own message. Textbooks usually give this advice: \"If you use `.unwrap()` a lot, at least use `.expect()` for better error messages.\"\n\nThis will crash:\n\n```rust\n   // ⚠️\nfn get_fourth(input: &Vec<i32>) -> i32 {\n    let fourth = input.get(3).unwrap();\n    *fourth\n}\n\nfn main() {\n    let my_vec = vec![9, 0, 10];\n    let fourth = get_fourth(&my_vec);\n}\n```\n\nThe error message is `thread 'main' panicked at 'called Option::unwrap() on a None value', src\\main.rs:7:18`.\n\nNow we write our own message with `expect`:\n\n```rust\n   // ⚠️\nfn get_fourth(input: &Vec<i32>) -> i32 {\n    let fourth = input.get(3).expect(\"Input vector needs at least 4 items\");\n    *fourth\n}\n\nfn main() {\n    let my_vec = vec![9, 0, 10];\n    let fourth = get_fourth(&my_vec);\n}\n```\n\nIt crashes again, but the error is better: `thread 'main' panicked at 'Input vector needs at least 4 items', src\\main.rs:7:18`. `.expect()` is a little better than `.unwrap()` because of this, but it will still panic on `None`. Now here is an example of a bad practice, a function that tries to unwrap two times. It takes a `Vec<Option<i32>>`, so maybe each part will have a `Some<i32>` or maybe a `None`.\n\n```rust\nfn try_two_unwraps(input: Vec<Option<i32>>) {\n    println!(\"Index 0 is: {}\", input[0].unwrap());\n    println!(\"Index 1 is: {}\", input[1].unwrap());\n}\n\nfn main() {\n    let vector = vec![None, Some(1000)]; // This vector has a None, so it will panic\n    try_two_unwraps(vector);\n}\n```\n\nThe message is: ``thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', src\\main.rs:2:32``. We're not sure if it was the first `.unwrap()` or the second `.unwrap()` until we check the line. It would be better to check the length and also to not unwrap. But with `.expect()` at least it will be a *little* better. Here it is with `.expect()`:\n\n```rust\nfn try_two_unwraps(input: Vec<Option<i32>>) {\n    println!(\"Index 0 is: {}\", input[0].expect(\"The first unwrap had a None!\"));\n    println!(\"Index 1 is: {}\", input[1].expect(\"The second unwrap had a None!\"));\n}\n\nfn main() {\n    let vector = vec![None, Some(1000)];\n    try_two_unwraps(vector);\n}\n```\n\nSo that is a bit better: `thread 'main' panicked at 'The first unwrap had a None!', src\\main.rs:2:32`. We have the line number as well so we can find it.\n\n\nYou can also use `unwrap_or` if you want to always have a value that you want to choose. If you do this it will never panic. That's:\n\n- 1) good because your program won't panic, but\n- 2) maybe not good if you want the program to panic if there's a problem.\n\nBut usually we don't want our program to panic, so `unwrap_or` is a good method to use.\n\n```rust\nfn main() {\n    let my_vec = vec![8, 9, 10];\n\n    let fourth = my_vec.get(3).unwrap_or(&0); // If .get doesn't work, we will make the value &0.\n                                              // .get returns a reference, so we need &0 and not 0\n                                              // You can write \"let *fourth\" with a * if you want fourth to be\n                                              // a 0 and not a &0, but here we just print so it doesn't matter\n\n    println!(\"{}\", fourth);\n}\n```\n\nThis prints `0` because `.unwrap_or(&0)` gives a 0 even if it is a `None`.\n\n## Traits\n\nWe have seen traits before: `Debug`, `Copy`, `Clone` are all traits. To give a type a trait, you have to implement it. Because `Debug` and the others are so common, we have attributes that automatically do it. That's what happens when you write `#[derive(Debug)]`: you are automatically implementing `Debug`.\n\n```rust\n#[derive(Debug)]\nstruct MyStruct {\n    number: usize,\n}\n\nfn main() {}\n```\n\nBut other traits are more difficult, so you need to implement them manually with `impl`. For example, `Add` (found at `std::ops::Add`) is used to add two things. But Rust doesn't know exactly how you want to add things, so you have to tell it.\n\n```rust\nstruct ThingsToAdd {\n    first_thing: u32,\n    second_thing: f32,\n}\n\nfn main() {}\n```\n\nWe can add `first_thing` and `second_thing`, but we need to give more information. Maybe we want an `f32`, so something like this:\n\n```rust\n// 🚧\nlet result = self.second_thing + self.first_thing as f32\n```\n\nBut maybe we want an integer, so like this:\n\n```rust\n// 🚧\nlet result = self.second_thing as u32 + self.first_thing\n```\n\nOr maybe we want to just put `self.first_thing` next to `self.second_thing` and say that this is how we want to add. So if we add 55 to 33.4, we want to see 5533.4, not 88.4.\n\nSo first let's look at how to make a trait. The important thing to remember about `trait`s is that they are about behaviour. To make a trait, write `trait` and then create some functions.\n\n```rust\nstruct Animal { // A simple struct - an Animal only has a name\n    name: String,\n}\n\ntrait Dog { // The dog trait gives some functionality\n    fn bark(&self) { // It can bark\n        println!(\"Woof woof!\");\n    }\n    fn run(&self) { // and it can run\n        println!(\"The dog is running!\");\n    }\n}\n\nimpl Dog for Animal {} // Now Animal has the trait Dog\n\nfn main() {\n    let rover = Animal {\n        name: \"Rover\".to_string(),\n    };\n\n    rover.bark(); // Now Animal can use bark()\n    rover.run();  // and it can use run()\n}\n```\n\nThis is okay, but we don't want to print \"The dog is running\". You can change the methods that a `trait` gives you if you want, but you have to have the same signature. That means that it needs to take the same things, and return the same things. For example, we can change the method `.run()`, but we have to follow the signature. The signature says:\n\n```rust\n// 🚧\nfn run(&self) {\n    println!(\"The dog is running!\");\n}\n```\n\n`fn run(&self)` means \"fn `run()` takes `&self`, and returns nothing\". So you can't do this:\n\n```rust\nfn run(&self) -> i32 { // ⚠️\n    5\n}\n```\n\nRust will say:\n\n```text\n   = note: expected fn pointer `fn(&Animal)`\n              found fn pointer `fn(&Animal) -> i32`\n```\n\nBut we can do this:\n\n```rust\nstruct Animal { // A simple struct - an Animal only has a name\n    name: String,\n}\n\ntrait Dog { // The dog trait gives some functionality\n    fn bark(&self) { // It can bark\n        println!(\"Woof woof!\");\n    }\n    fn run(&self) { // and it can run\n        println!(\"The dog is running!\");\n    }\n}\n\nimpl Dog for Animal {\n    fn run(&self) {\n        println!(\"{} is running!\", self.name);\n    }\n}\n\nfn main() {\n    let rover = Animal {\n        name: \"Rover\".to_string(),\n    };\n\n    rover.bark(); // Now Animal can use bark()\n    rover.run();  // and it can use run()\n}\n```\n\nNow it prints `Rover is running!`. This is okay because we are returning `()`, or nothing, which is what the trait says.\n\n\nWhen you are writing a trait, you can just write the function signature. But if you do that, the user will have to write the function. Let's try that. Now we change `bark()` and `run()` to just say `fn bark(&self);` and `fn run(&self);`. This is not a full function, so the user must write it.\n\n```rust\nstruct Animal {\n    name: String,\n}\n\ntrait Dog {\n    fn bark(&self); // bark() says it needs a &self and returns nothing\n    fn run(&self); // run() says it needs a &self and returns nothing.\n                   // So now we have to write them ourselves.\n}\n\nimpl Dog for Animal {\n    fn bark(&self) {\n        println!(\"{}, stop barking!!\", self.name);\n    }\n    fn run(&self) {\n        println!(\"{} is running!\", self.name);\n    }\n}\n\nfn main() {\n    let rover = Animal {\n        name: \"Rover\".to_string(),\n    };\n\n    rover.bark();\n    rover.run();\n}\n```\n\nSo when you create a trait, you must think: \"Which functions should I write? And which functions should the user write?\" If you think the user should use the function the same way every time, then write out the function. If you think the user will use it differently, then just write the function signature.\n\nSo let's try implementing the Display trait for our struct. First we will make a simple struct:\n\n```rust\nstruct Cat {\n    name: String,\n    age: u8,\n}\n\nfn main() {\n    let mr_mantle = Cat {\n        name: \"Reggie Mantle\".to_string(),\n        age: 4,\n    };\n}\n```\n\nNow we want to print `mr_mantle`. Debug is easy to derive:\n\n```rust\n#[derive(Debug)]\nstruct Cat {\n    name: String,\n    age: u8,\n}\n\nfn main() {\n    let mr_mantle = Cat {\n        name: \"Reggie Mantle\".to_string(),\n        age: 4,\n    };\n\n    println!(\"Mr. Mantle is a {:?}\", mr_mantle);\n}\n```\n\nbut Debug print is not the prettiest way to print, because it looks like this.\n\n```text\nMr. Mantle is a Cat { name: \"Reggie Mantle\", age: 4 }\n```\n\nSo we need to implement `Display` for `Cat` if we want nicer printing. On [https://doc.rust-lang.org/std/fmt/trait.Display.html](https://doc.rust-lang.org/std/fmt/trait.Display.html) we can see the information for Display, and one example. It says:\n\n```rust\nuse std::fmt;\n\nstruct Position {\n    longitude: f32,\n    latitude: f32,\n}\n\nimpl fmt::Display for Position {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        write!(f, \"({}, {})\", self.longitude, self.latitude)\n    }\n}\n\nfn main() {}\n```\n\nSome parts of this we don't understand yet, like `<'_>` and what `f` is doing. But we understand the `Position` struct: it is just two `f32`s. We also understand that `self.longitude` and `self.latitude` are the fields in the struct. So maybe we can just use this code for our struct, with `self.name` and `self.age`. Also, `write!` looks a lot like `println!` so it is pretty familiar. So we write this:\n\n```rust\nuse std::fmt;\n\nstruct Cat {\n    name: String,\n    age: u8,\n}\n\nimpl fmt::Display for Cat {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        write!(f, \"{} is a cat who is {} years old.\", self.name, self.age)\n    }\n}\n\nfn main() {}\n```\n\nLet's add a `fn main()`. Now our code looks like this:\n\n```rust\nuse std::fmt;\n\nstruct Cat {\n    name: String,\n    age: u8,\n}\n\nimpl fmt::Display for Cat {\n  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n      write!(f, \"{} is a cat who is {} years old.\", self.name, self.age)\n  }\n}\n\nfn main() {\n    let mr_mantle = Cat {\n        name: \"Reggie Mantle\".to_string(),\n        age: 4,\n    };\n\n    println!(\"{}\", mr_mantle);\n}\n```\n\nSuccess! Now when we use `{}` to print, we get `Reggie Mantle is a cat who is 4 years old.`. This looks much better.\n\n\nBy the way, if you implement `Display` then you get the `ToString` trait for free. That's because you use the `format!` macro for the `.fmt()` function, which lets you make a `String` with `.to_string()`. So we could do something like this where we pass `reggie_mantle` to a function that wants a `String`, or anything else.\n\n```rust\nuse std::fmt;\nstruct Cat {\n    name: String,\n    age: u8,\n}\n\nimpl fmt::Display for Cat {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        write!(f, \"{} is a cat who is {} years old.\", self.name, self.age)\n    }\n}\n\nfn print_cats(pet: String) {\n    println!(\"{}\", pet);\n}\n\nfn main() {\n    let mr_mantle = Cat {\n        name: \"Reggie Mantle\".to_string(),\n        age: 4,\n    };\n\n    print_cats(mr_mantle.to_string()); // Turn him into a String here\n    println!(\"Mr. Mantle's String is {} letters long.\", mr_mantle.to_string().chars().count()); // Turn him into chars and count them\n}\n```\n\nThis prints:\n\n```text\nReggie Mantle is a cat who is 4 years old.\nMr. Mantle's String is 42 letters long.\n```\n\n\n\n\nThe thing to remember about traits is that they are about the behaviour of something. How does your `struct` act? What can it do? That's what traits are for. If you think of some of the traits we've seen so far, they are all about behaviour: `Copy` is something that a type can do. `Display` is also something that a type can do. `ToString` is another trait, and it's also something that a type can do: it can change into a `String`. In our `Dog` trait the word *dog* doesn't mean something you can do, but it gives some methods that let it do things. You could also implement it for a `struct Poodle` or `struct Beagle` and they would all get `Dog` methods.\n\nLet's look at another example that is even more connected to just behaviour. We'll imagine a fantasy game with some simple characters. One is a `Monster`, the other two are `Wizard` and `Ranger`. The `Monster` just has `health` so we can attack it, the other two don't have anything yet. But we made two traits. One is called `FightClose`, and lets you fight up close. The other is `FightFromDistance`, and lets you fight from far away. Only `Ranger` can use `FightFromDistance`. Here's what it looks like:\n\n```rust\nstruct Monster {\n    health: i32,\n}\n\nstruct Wizard {}\nstruct Ranger {}\n\ntrait FightClose {\n    fn attack_with_sword(&self, opponent: &mut Monster) {\n        opponent.health -= 10;\n        println!(\n            \"You attack with your sword. Your opponent now has {} health left.\",\n            opponent.health\n        );\n    }\n    fn attack_with_hand(&self, opponent: &mut Monster) {\n        opponent.health -= 2;\n        println!(\n            \"You attack with your hand. Your opponent now has {} health left.\",\n            opponent.health\n        );\n    }\n}\nimpl FightClose for Wizard {}\nimpl FightClose for Ranger {}\n\ntrait FightFromDistance {\n    fn attack_with_bow(&self, opponent: &mut Monster, distance: u32) {\n        if distance < 10 {\n            opponent.health -= 10;\n            println!(\n                \"You attack with your bow. Your opponent now has {} health left.\",\n                opponent.health\n            );\n        }\n    }\n    fn attack_with_rock(&self, opponent: &mut Monster, distance: u32) {\n        if distance < 3 {\n            opponent.health -= 4;\n        }\n        println!(\n            \"You attack with your rock. Your opponent now has {} health left.\",\n            opponent.health\n        );\n    }\n}\nimpl FightFromDistance for Ranger {}\n\nfn main() {\n    let radagast = Wizard {};\n    let aragorn = Ranger {};\n\n    let mut uruk_hai = Monster { health: 40 };\n\n    radagast.attack_with_sword(&mut uruk_hai);\n    aragorn.attack_with_bow(&mut uruk_hai, 8);\n}\n```\n\nThis prints:\n\n```text\nYou attack with your sword. Your opponent now has 30 health left.\nYou attack with your bow. Your opponent now has 20 health left.\n```\n\nWe pass `self` inside our trait all the time, but we can't do much with it right now. That's because Rust doesn't know what type is going to use it. It could be a `Wizard`, it could be a `Ranger`, it could be a new struct called `Toefocfgetobjtnode` or anything else. To give `self` some functionality, we can add necessary traits to the trait. If we want to print with `{:?}` for example then we need `Debug`. You can add it to the trait just by writing it after `:` (a colon). Now our code looks like this:\n\n\n```rust\nstruct Monster {\n    health: i32,\n}\n\n#[derive(Debug)] // Now Wizard has Debug\nstruct Wizard {\n    health: i32, // Now Wizard has health\n}\n#[derive(Debug)] // So does Ranger\nstruct Ranger {\n    health: i32, // So does Ranger\n}\n\ntrait FightClose: std::fmt::Debug { // Now a type needs Debug to use FightClose\n    fn attack_with_sword(&self, opponent: &mut Monster) {\n        opponent.health -= 10;\n        println!(\n            \"You attack with your sword. Your opponent now has {} health left. You are now at: {:?}\", // We can now print self with {:?} because we have Debug\n            opponent.health, &self\n        );\n    }\n    fn attack_with_hand(&self, opponent: &mut Monster) {\n        opponent.health -= 2;\n        println!(\n            \"You attack with your hand. Your opponent now has {} health left.  You are now at: {:?}\",\n            opponent.health, &self\n        );\n    }\n}\nimpl FightClose for Wizard {}\nimpl FightClose for Ranger {}\n\ntrait FightFromDistance: std::fmt::Debug { // We could also do trait FightFromDistance: FightClose because FightClose needs Debug\n    fn attack_with_bow(&self, opponent: &mut Monster, distance: u32) {\n        if distance < 10 {\n            opponent.health -= 10;\n            println!(\n                \"You attack with your bow. Your opponent now has {} health left.  You are now at: {:?}\",\n                opponent.health, self\n            );\n        }\n    }\n    fn attack_with_rock(&self, opponent: &mut Monster, distance: u32) {\n        if distance < 3 {\n            opponent.health -= 4;\n        }\n        println!(\n            \"You attack with your rock. Your opponent now has {} health left.  You are now at: {:?}\",\n            opponent.health, self\n        );\n    }\n}\nimpl FightFromDistance for Ranger {}\n\nfn main() {\n    let radagast = Wizard { health: 60 };\n    let aragorn = Ranger { health: 80 };\n\n    let mut uruk_hai = Monster { health: 40 };\n\n    radagast.attack_with_sword(&mut uruk_hai);\n    aragorn.attack_with_bow(&mut uruk_hai, 8);\n}\n```\n\nNow this prints:\n\n```text\nYou attack with your sword. Your opponent now has 30 health left. You are now at: Wizard { health: 60 }\nYou attack with your bow. Your opponent now has 20 health left.  You are now at: Ranger { health: 80 }\n```\n\nIn a real game it might be better to rewrite this for each type, because `You are now at: Wizard { health: 60 }` looks funny. That's also why methods inside traits are usually simple, because you don't know what type is going to use it. You can't write things like `self.0 += 10` for example. But this example shows that we can use other traits inside a trait we are writing. And when we do that, we get some methods that we can use.\n\n\n\nOne other way to use a trait is with what are called `trait bounds`. That means \"limitations by a trait\". Trait bounds are easy because a trait actually doesn't need any methods, or anything at all. Let's rewrite our code with something similar but different. This time our trait doesn't have any methods, but we have other functions that require traits to use.\n\n```rust\nuse std::fmt::Debug;  // So we don't have to write std::fmt::Debug every time now\n\nstruct Monster {\n    health: i32,\n}\n\n#[derive(Debug)]\nstruct Wizard {\n    health: i32,\n}\n#[derive(Debug)]\nstruct Ranger {\n    health: i32,\n}\n\ntrait Magic{} // No methods for any of these traits. They are just trait bounds\ntrait FightClose {}\ntrait FightFromDistance {}\n\nimpl FightClose for Ranger{} // Each type gets FightClose,\nimpl FightClose for Wizard {}\nimpl FightFromDistance for Ranger{} // but only Ranger gets FightFromDistance\nimpl Magic for Wizard{}  // and only Wizard gets Magic\n\nfn attack_with_bow<T: FightFromDistance + Debug>(character: &T, opponent: &mut Monster, distance: u32) {\n    if distance < 10 {\n        opponent.health -= 10;\n        println!(\n            \"You attack with your bow. Your opponent now has {} health left.  You are now at: {:?}\",\n            opponent.health, character\n        );\n    }\n}\n\nfn attack_with_sword<T: FightClose + Debug>(character: &T, opponent: &mut Monster) {\n    opponent.health -= 10;\n    println!(\n        \"You attack with your sword. Your opponent now has {} health left. You are now at: {:?}\",\n        opponent.health, character\n    );\n}\n\nfn fireball<T: Magic + Debug>(character: &T, opponent: &mut Monster, distance: u32) {\n    if distance < 15 {\n        opponent.health -= 20;\n        println!(\"You raise your hands and cast a fireball! Your opponent now has {} health left. You are now at: {:?}\",\n    opponent.health, character);\n    }\n}\n\nfn main() {\n    let radagast = Wizard { health: 60 };\n    let aragorn = Ranger { health: 80 };\n\n    let mut uruk_hai = Monster { health: 40 };\n\n    attack_with_sword(&radagast, &mut uruk_hai);\n    attack_with_bow(&aragorn, &mut uruk_hai, 8);\n    fireball(&radagast, &mut uruk_hai, 8);\n}\n```\n\nThis prints almost the same thing:\n\n```text\nYou attack with your sword. Your opponent now has 30 health left. You are now at: Wizard { health: 60 }\nYou attack with your bow. Your opponent now has 20 health left.  You are now at: Ranger { health: 80 }\nYou raise your hands and cast a fireball! Your opponent now has 0 health left. You are now at: Wizard { health: 60 }\n```\n\nSo you can see there are many ways to do the same thing when you use traits. It all depends on what makes the most sense for the program that you are writing.\n\nNow let's look at how to implement some of the main traits you will use in Rust.\n\n### The From trait\n\n*From* is a very convenient trait to use, and you know this because you have seen it so much already. With *From* you can make a `String` from a `&str`, but you can make many types from many other types. For example, Vec uses *From* for the following:\n\n```text\nFrom<&'_ [T]>\nFrom<&'_ mut [T]>\nFrom<&'_ str>\nFrom<&'a Vec<T>>\nFrom<[T; N]>\nFrom<BinaryHeap<T>>\nFrom<Box<[T]>>\nFrom<CString>\nFrom<Cow<'a, [T]>>\nFrom<String>\nFrom<Vec<NonZeroU8>>\nFrom<Vec<T>>\nFrom<VecDeque<T>>\n```\n\nThat is a lot of `Vec::from()` that we have not tried yet. Let's make a few and see what happens.\n\n```rust\nuse std::fmt::Display; // We will make a generic function to print them so we want Display\n\nfn print_vec<T: Display>(input: &Vec<T>) { // Take any Vec<T> if type T has Display\n    for item in input {\n        print!(\"{} \", item);\n    }\n    println!();\n}\n\nfn main() {\n\n    let array_vec = Vec::from([8, 9, 10]); // Try from an array\n    print_vec(&array_vec);\n\n    let str_vec = Vec::from(\"What kind of vec will I be?\"); // An array from a &str? This will be interesting\n    print_vec(&str_vec);\n\n    let string_vec = Vec::from(\"What kind of vec will a String be?\".to_string()); // Also from a String\n    print_vec(&string_vec);\n}\n```\n\nIt prints the following:\n\n```text\n8 9 10\n87 104 97 116 32 107 105 110 100 32 111 102 32 118 101 99 32 119 105 108 108 32 73 32 98 101 63\n87 104 97 116 32 107 105 110 100 32 111 102 32 118 101 99 32 119 105 108 108 32 97 32 83 116 114 105 110 103 32 98 101 63\n```\n\nIf you look at the type, the second and third vectors are `Vec<u8>`, which means the bytes of the `&str` and the `String`. So you can see that `From` is very flexible and used a lot. Let's try it with our own types.\n\nWe'll make two structs and then implement `From` for one of them. One struct will be `City`, and the other will be `Country`. We want to be able to do this: `let country_name = Country::from(vector_of_cities)`.\n\nIt looks like this:\n\n```rust\n#[derive(Debug)] // So we can print City\nstruct City {\n    name: String,\n    population: u32,\n}\n\nimpl City {\n    fn new(name: &str, population: u32) -> Self { // just a new function\n        Self {\n            name: name.to_string(),\n            population,\n        }\n    }\n}\n#[derive(Debug)] // Country also needs to be printed\nstruct Country {\n    cities: Vec<City>, // Our cities go in here\n}\n\nimpl From<Vec<City>> for Country { // Note: we don't have to write From<City>, we can also do\n                                   // From<Vec<City>>. So we can also implement on a type that\n                                   // we didn't create\n    fn from(cities: Vec<City>) -> Self {\n        Self { cities }\n    }\n}\n\nimpl Country {\n    fn print_cities(&self) { // function to print the cities in Country\n        for city in &self.cities {\n            // & because Vec<City> isn't Copy\n            println!(\"{:?} has a population of {:?}.\", city.name, city.population);\n        }\n    }\n}\n\nfn main() {\n    let helsinki = City::new(\"Helsinki\", 631_695);\n    let turku = City::new(\"Turku\", 186_756);\n\n    let finland_cities = vec![helsinki, turku]; // This is the Vec<City>\n    let finland = Country::from(finland_cities); // So now we can use From\n\n    finland.print_cities();\n}\n```\n\nThis prints:\n\n```text\n\"Helsinki\" has a population of 631695.\n\"Turku\" has a population of 186756.\n```\n\nYou can see that `From` is easy to implement from types you didn't create like `Vec`, `i32`, and so on. Here is one more example where we create a vector that has two vectors. The first vector holds even numbers, and the second holds odd numbers. With `From` you can give it a vector of `i32`s and it will turn it into a `Vec<Vec<i32>>`: a vector that holds vectors of `i32`.\n\n```rust\nuse std::convert::From;\n\nstruct EvenOddVec(Vec<Vec<i32>>);\n\nimpl From<Vec<i32>> for EvenOddVec {\n    fn from(input: Vec<i32>) -> Self {\n        let mut even_odd_vec: Vec<Vec<i32>> = vec![vec![], vec![]]; // A vec with two empty vecs inside\n                                                                    // This is the return value but first we must fill it\n        for item in input {\n            if item % 2 == 0 {\n                even_odd_vec[0].push(item);\n            } else {\n                even_odd_vec[1].push(item);\n            }\n        }\n        Self(even_odd_vec) // Now it is done so we return it as Self (Self = EvenOddVec)\n    }\n}\n\nfn main() {\n    let bunch_of_numbers = vec![8, 7, -1, 3, 222, 9787, -47, 77, 0, 55, 7, 8];\n    let new_vec = EvenOddVec::from(bunch_of_numbers);\n\n    println!(\"Even numbers: {:?}\\nOdd numbers: {:?}\", new_vec.0[0], new_vec.0[1]);\n}\n```\n\nThis prints:\n\n```text\nEven numbers: [8, 222, 0, 8]\nOdd numbers: [7, -1, 3, 9787, -47, 77, 55, 7]\n```\n\nA type like `EvenOddVec` is probably better as a generic `T` so we can use many number types. You can try to make the example generic if you want for practice.\n\n### Taking a String and a &str in a function\n\nSometimes you want a function that can take both a `String` and a `&str`. You can do this with generics and the `AsRef` trait. `AsRef` is used to give a reference from one type to another type. If you look at the documentation for `String`, you can see that it has `AsRef` for many types:\n\n[https://doc.rust-lang.org/std/string/struct.String.html](https://doc.rust-lang.org/std/string/struct.String.html)\n\nHere are some function signatures for them.\n\n`AsRef<str>`:\n\n```rust\n// 🚧\nimpl AsRef<str> for String\n\nfn as_ref(&self) -> &str\n```\n\n`AsRef<[u8]>`:\n\n```rust\n// 🚧\nimpl AsRef<[u8]> for String\n\nfn as_ref(&self) -> &[u8]\n```\n\n`AsRef<OsStr>`:\n\n```rust\n// 🚧\nimpl AsRef<OsStr> for String\n\nfn as_ref(&self) -> &OsStr\n```\n\nYou can see that it takes `&self` and gives a reference to the other type. This means that if you have a generic type T, you can say that it needs `AsRef<str>`. If you do that, it will be able to take a `&str` and a `String`.\n\nLet's start with the generic function. This doesn't work yet:\n\n```rust\nfn print_it<T>(input: T) {\n    println!(\"{}\", input) // ⚠️\n}\n\nfn main() {\n    print_it(\"Please print me\");\n}\n```\n\nRust says `error[E0277]: T doesn't implement std::fmt::Display`. So we will require T to implement Display.\n\n```rust\nuse std::fmt::Display;\n\nfn print_it<T: Display>(input: T) {\n    println!(\"{}\", input)\n}\n\nfn main() {\n    print_it(\"Please print me\");\n}\n```\n\nNow it works and prints `Please print me`. That is good, but T can still be too many things. It can be an `i8`, an `f32` and anything else with just `Display`. So we add `AsRef<str>`, and now T needs both `AsRef<str>` and `Display`.\n\n```rust\nuse std::fmt::Display;\n\nfn print_it<T: AsRef<str> + Display>(input: T) {\n    println!(\"{}\", input)\n}\n\nfn main() {\n    print_it(\"Please print me\");\n    print_it(\"Also, please print me\".to_string());\n    // print_it(7); <- This will not print\n}\n```\n\nNow it won't take types like `i8`.\n\nDon't forget that you can use `where` to write the function differently when it gets long. If we add Debug then it becomes `fn print_it<T: AsRef<str> + Display + Debug>(input: T)` which is long for one line. So we can write it like this:\n\n```rust\nuse std::fmt::{Debug, Display}; // add Debug\n\nfn print_it<T>(input: T) // Now this line is easy to read\nwhere\n    T: AsRef<str> + Debug + Display, // and these traits are easy to read\n{\n    println!(\"{}\", input)\n}\n\nfn main() {\n    print_it(\"Please print me\");\n    print_it(\"Also, please print me\".to_string());\n}\n```\n\n## Chaining methods\n\nRust is a systems programming language like C and C++, and its code can be written as separate commands in separate lines, but it also has a functional style. Both styles are okay, but functional style is usually shorter. Here is an example of the non-functional style (called \"imperative style\") to make a `Vec` from 1 to 10:\n\n```rust\nfn main() {\n    let mut new_vec = Vec::new();\n    let mut counter = 1;\n\n    while counter < 11 {\n        new_vec.push(counter);\n        counter += 1;\n    }\n\n    println!(\"{:?}\", new_vec);\n}\n```\n\nThis prints `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`.\n\nAnd here is an example of functional style:\n\n```rust\nfn main() {\n    let new_vec = (1..=10).collect::<Vec<i32>>();\n    // Or you can write it like this:\n    // let new_vec: Vec<i32> = (1..=10).collect();\n    println!(\"{:?}\", new_vec);\n}\n```\n\n`.collect()` can make collections of many types, so we have to tell it the type.\n\nWith functional style you can chain methods. \"Chaining methods\" means to put many methods together in a single statement. Here is an example of many methods chained together:\n\n```rust\nfn main() {\n    let my_vec = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n\n    let new_vec = my_vec.into_iter().skip(3).take(4).collect::<Vec<i32>>();\n\n    println!(\"{:?}\", new_vec);\n}\n```\n\nThis creates a Vec with `[3, 4, 5, 6]`. This is a lot of information for one line, so it can help to put each method on a new line. Let's do that to make it easier to read:\n\n```rust\nfn main() {\n    let my_vec = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n\n    let new_vec = my_vec\n        .into_iter() // \"iterate\" over the items (iterate = work with each item inside it). into_iter() gives us owned values, not references\n        .skip(3) // skip over three items: 0, 1, and 2\n        .take(4) // take the next four: 3, 4, 5, and 6\n        .collect::<Vec<i32>>(); // put them in a new Vec<i32>\n\n    println!(\"{:?}\", new_vec);\n}\n```\n\nYou can use this functional style best when you understand closures and iterators. So we will learn them next.\n\n## Iterators\n\nAn iterator is a construct that can give you the items in the collection, one at a time. Actually, we have already used iterators a lot: the `for` loop gives you an iterator. When you want to use an iterator other times, you have to choose what kind:\n\n- `.iter()` for an iterator of references\n- `.iter_mut()` for an iterator of mutable references\n- `.into_iter()` for an iterator of values (not references)\n\nA `for` loop is actually just an iterator that owns its values. That's why it can make it mutable and then you can change the values when you use it.\n\nWe can use iterators like this:\n\n```rust\nfn main() {\n    let vector1 = vec![1, 2, 3]; // we will use .iter() and .into_iter() on this one\n    let vector1_a = vector1.iter().map(|x| x + 1).collect::<Vec<i32>>();\n    let vector1_b = vector1.into_iter().map(|x| x * 10).collect::<Vec<i32>>();\n\n    let mut vector2 = vec![10, 20, 30]; // we will use .iter_mut() on this one\n    vector2.iter_mut().for_each(|x| *x +=100);\n\n    println!(\"{:?}\", vector1_a);\n    println!(\"{:?}\", vector2);\n    println!(\"{:?}\", vector1_b);\n}\n```\n\nThis prints:\n\n```text\n[2, 3, 4]\n[110, 120, 130]\n[10, 20, 30]\n```\n\nThe first two we used a method called `.map()`. This method lets you do something to every item, then pass it on. The last one we used is one called `.for_each()`. This method just lets you do something to every item. `.iter_mut()` plus `for_each()` is basically just a `for` loop. Inside each method we can give a name to every item (we just called it `x`) and use that to change it. These are called closures and we will learn about them in the next section.\n\nLet's go over them again, one at a time.\n\nFirst we used `.iter()` on `vector1` to get references. We added 1 to each, and made it into a new Vec. `vector1` is still alive because we only used references: we didn't take by value. Now we have `vector1`, and a new Vec called `vector1_a`. Because `.map()` just passes it on, we needed to use `.collect()` to make it into a `Vec`.\n\nThen we used `into_iter` to get an iterator by value from `vector1`. This destroys `vector1`, because that's what `into_iter()` does. So after we make `vector1_b` we can't use `vector1` again.\n\nFinally we used `.iter_mut()` for `vector2`. It is mutable, so we don't need to use `.collect()` to create a new Vec. Instead, we change the values in the same Vec with mutable references. So `vector2` is still there. Because we don't need a new Vec, we use `for_each`: it's just like a `for` loop.\n\n\n### How an iterator works\n\nAn iterator works by using a method called `.next()`, which gives an `Option`. When you use an iterator, Rust calls `next()` over and over again. If it gets `Some`, it keeps going. If it gets `None`, it stops.\n\nDo you remember the `assert_eq!` macro? In documentation, you see it all the time. Here it is showing how an iterator works.\n\n```rust\nfn main() {\n    let my_vec = vec!['a', 'b', '거', '柳']; // Just a regular Vec\n\n    let mut my_vec_iter = my_vec.iter(); // This is an Iterator type now, but we haven't called it yet\n\n    assert_eq!(my_vec_iter.next(), Some(&'a'));  // Call the first item with .next()\n    assert_eq!(my_vec_iter.next(), Some(&'b'));  // Call the next\n    assert_eq!(my_vec_iter.next(), Some(&'거')); // Again\n    assert_eq!(my_vec_iter.next(), Some(&'柳')); // Again\n    assert_eq!(my_vec_iter.next(), None);        // Nothing is left: just None\n    assert_eq!(my_vec_iter.next(), None);        // You can keep calling .next() but it will always be None\n}\n```\n\nImplementing `Iterator` for your own struct or enum is not too hard. First let's make a book library and think about it.\n\n```rust\n#[derive(Debug)] // we want to print it with {:?}\nstruct Library {\n    library_type: LibraryType, // this is our enum\n    books: Vec<String>, // list of books\n}\n\n#[derive(Debug)]\nenum LibraryType { // libraries can be city libraries or country libraries\n    City,\n    Country,\n}\n\nimpl Library {\n    fn add_book(&mut self, book: &str) { // we use add_book to add new books\n        self.books.push(book.to_string()); // we take a &str and turn it into a String, then add it to the Vec\n    }\n\n    fn new() -> Self { // this creates a new Library\n        Self {\n            library_type: LibraryType::City, // most are in the city so we'll choose City\n                                             // most of the time\n            books: Vec::new(),\n        }\n    }\n}\n\nfn main() {\n    let mut my_library = Library::new(); // make a new library\n    my_library.add_book(\"The Doom of the Darksword\"); // add some books\n    my_library.add_book(\"Demian - die Geschichte einer Jugend\");\n    my_library.add_book(\"구운몽\");\n    my_library.add_book(\"吾輩は猫である\");\n\n    println!(\"{:?}\", my_library.books); // we can print our list of books\n}\n```\n\nThat works well. Now we want to implement `Iterator` for the library so we can use it in a `for` loop. Right now if we try a `for` loop, it doesn't work:\n\n```rust\nfor item in my_library {\n    println!(\"{}\", item); // ⚠️\n}\n```\n\nIt says:\n\n```text\nerror[E0277]: `Library` is not an iterator\n  --> src\\main.rs:47:16\n   |\n47 |    for item in my_library {\n   |                ^^^^^^^^^^ `Library` is not an iterator\n   |\n   = help: the trait `std::iter::Iterator` is not implemented for `Library`\n   = note: required by `std::iter::IntoIterator::into_iter`\n```\n\nBut we can make library into an iterator with `impl Iterator for Library`. Information on the `Iterator` trait is here in the standard library: [https://doc.rust-lang.org/std/iter/trait.Iterator.html](https://doc.rust-lang.org/std/iter/trait.Iterator.html)\n\nOn the top left of the page it says: `Associated Types: Item` and `Required Methods: next`. An \"associated type\" means \"a type that goes together\". Our associated type will be `String`, because we want the iterator to give us Strings.\n\nIn the page it has an example that looks like this:\n\n```rust\n// an iterator which alternates between Some and None\nstruct Alternate {\n    state: i32,\n}\n\nimpl Iterator for Alternate {\n    type Item = i32;\n\n    fn next(&mut self) -> Option<i32> {\n        let val = self.state;\n        self.state = self.state + 1;\n\n        // if it's even, Some(i32), else None\n        if val % 2 == 0 {\n            Some(val)\n        } else {\n            None\n        }\n    }\n}\n\nfn main() {}\n```\n\nYou can see that under `impl Iterator for Alternate` it says `type Item = i32`. This is the associated type. Our iterator will be for our list of books, which is a `Vec<String>`. When we call next, it will give us a `String`. So we will write `type Item = String;`. That is the associated item.\n\nTo implement `Iterator`, you need to write the `fn next()` function. This is where you decide what the iterator should do. For our `Library`, we want it to give us the last books first. So we will `match` with `.pop()` which takes the last item off if it is `Some`. We also want to print \" is found!\" for each item. Now it looks like this:\n\n```rust\n#[derive(Debug, Clone)]\nstruct Library {\n    library_type: LibraryType,\n    books: Vec<String>,\n}\n\n#[derive(Debug, Clone)]\nenum LibraryType {\n    City,\n    Country,\n}\n\nimpl Library {\n    fn add_book(&mut self, book: &str) {\n        self.books.push(book.to_string());\n    }\n\n    fn new() -> Self {\n        Self {\n            library_type: LibraryType::City,\n            // most of the time\n            books: Vec::new(),\n        }\n    }\n}\n\nimpl Iterator for Library {\n    type Item = String;\n\n    fn next(&mut self) -> Option<String> {\n        match self.books.pop() {\n            Some(book) => Some(book + \" is found!\"), // Rust allows String + &str\n            None => None,\n        }\n    }\n}\n\nfn main() {\n    let mut my_library = Library::new();\n    my_library.add_book(\"The Doom of the Darksword\");\n    my_library.add_book(\"Demian - die Geschichte einer Jugend\");\n    my_library.add_book(\"구운몽\");\n    my_library.add_book(\"吾輩は猫である\");\n\n    for item in my_library.clone() { // we can use a for loop now. Give it a clone so Library won't be destroyed\n        println!(\"{}\", item);\n    }\n}\n```\n\nThis prints:\n\n```text\n吾輩は猫である is found!\n구운몽 is found!\nDemian - die Geschichte einer Jugend is found!\nThe Doom of the Darksword is found!\n```\n\n## Closures\n\nClosures are like quick functions that don't need a name. Sometimes they are called lambdas. Closures are easy to find because they use `||` instead of `()`. They are very common in Rust, and once you learn to use them you will wonder how you lived without them.\n\nYou can bind a closure to a variable, and then it looks exactly like a function when you use it:\n\n```rust\nfn main() {\n    let my_closure = || println!(\"This is a closure\");\n    my_closure();\n}\n```\n\nSo this closure takes nothing: `||` and prints a message: `This is a closure`.\n\nIn between the `||` we can add input variables and types, like inside `()` for a function:\n\n```rust\nfn main() {\n    let my_closure = |x: i32| println!(\"{}\", x);\n\n    my_closure(5);\n    my_closure(5+5);\n}\n```\n\nThis prints:\n\n```text\n5\n10\n```\n\nWhen the closure becomes more complicated, you can add a code block. Then it can be as long as you want.\n\n```rust\nfn main() {\n    let my_closure = || {\n        let number = 7;\n        let other_number = 10;\n        println!(\"The two numbers are {} and {}.\", number, other_number);\n          // This closure can be as long as we want, just like a function.\n    };\n\n    my_closure();\n}\n```\n\nBut closures are special because they can take variables that are outside the closure even if you only write `||`. So you can do this:\n\n```rust\nfn main() {\n    let number_one = 6;\n    let number_two = 10;\n\n    let my_closure = || println!(\"{}\", number_one + number_two);\n    my_closure();\n}\n```\n\nSo this prints `16`. You didn't need to put anything in `||` because it can just take `number_one` and `number_two` and add them.\n\nBy the way, that is where the name **closure** comes from, because they take variables and \"enclose\" them inside. And if you want to be very correct:\n\n- a `||` that doesn't enclose a variable from outside is an \"anonymous function\". Anonymous means \"doesn't have a name\". It works more like a regular function.\n- a `||` that does enclose a variable from outside is a \"closure\". It \"encloses\" the variables around it to use them.\n\nBut people will often call all `||` functions closures, so you don't have to worry about the name. We will just say \"closure\" for anything with a `||`, but remember that it can mean an \"anonymous function\".\n\nWhy is it good to know the difference? It's because an anonymous function actually makes the same machine code as a function with a name. They feel \"high level\", so sometimes people think that the machine code will be complicated. But the machine code that Rust makes from it is just as fast as a regular function.\n\n\nSo let's look at some more things that closures can do. You can also do this:\n\n```rust\nfn main() {\n    let number_one = 6;\n    let number_two = 10;\n\n    let my_closure = |x: i32| println!(\"{}\", number_one + number_two + x);\n    my_closure(5);\n}\n```\n\nThis closure takes `number_one` and `number_two`. We also gave it a new variable `x` and said that `x` is 5. Then it adds all three together to print `21`.\n\nUsually you see closures in Rust inside of a method, because it is very convenient to have a closure inside. We saw closures in the last section with `.map()` and `.for_each()`. In that section we wrote `|x|` to bring in the next item in an iterator, and that was a closure.\n\nHere is another example: the `unwrap_or` method that we know that you can use to give a value if `unwrap` doesn't work. Before, we wrote: `let fourth = my_vec.get(3).unwrap_or(&0);`. But there is also an `unwrap_or_else` method that has a closure inside. So you can do this:\n\n```rust\nfn main() {\n    let my_vec = vec![8, 9, 10];\n\n    let fourth = my_vec.get(3).unwrap_or_else(|| { // try to unwrap. If it doesn't work,\n        if my_vec.get(0).is_some() {               // see if my_vec has something at index [0]\n            &my_vec[0]                             // Give the number at index 0 if there is something\n        } else {\n            &0 // otherwise give a &0\n        }\n    });\n\n    println!(\"{}\", fourth);\n}\n```\n\nOf course, a closure can be very simple. You can just write `let fourth = my_vec.get(3).unwrap_or_else(|| &0);` for example. You don't always need to use a `{}` and write complicated code just because there is a closure. As long as you put the `||` in, the compiler knows that you have put in the closure that you need.\n\nThe most frequent closure method is maybe `.map()`. Let's take a look at it again. Here is one way to use it:\n\n```rust\nfn main() {\n    let num_vec = vec![2, 4, 6];\n\n    let double_vec = num_vec        // take num_vec\n        .iter()                     // iterate over it\n        .map(|number| number * 2)   // for each item, multiply by two\n        .collect::<Vec<i32>>();     // then make a new Vec from this\n    println!(\"{:?}\", double_vec);\n}\n```\n\nAnother good example is with `.for_each()` after `.enumerate()`. The `.enumerate()` method gives an iterator with the index number and the item. For example: `[10, 9, 8]` becomes `(0, 10), (1, 9), (2, 8)`. The type for each item here is `(usize, i32)`. So you can do this:\n\n```rust\nfn main() {\n    let num_vec = vec![10, 9, 8];\n\n    num_vec\n        .iter()      // iterate over num_vec\n        .enumerate() // get (index, number)\n        .for_each(|(index, number)| println!(\"Index number {} has number {}\", index, number)); // do something for each one\n}\n```\n\nThis prints:\n\n```text\nIndex number 0 has number 10\nIndex number 1 has number 9\nIndex number 2 has number 8\n```\n\nIn this case we use `for_each` instead of `map`. `map` is for **doing something to** each item and passing it on, and `for_each` is **doing something when you see each item**. Also, `map` doesn't do anything unless you use a method like `collect`.\n\nActually, this is the interesting thing about iterators. If you try to `map` without a method like `collect`, the compiler will tell you that it doesn't do anything. It won't panic, but the compiler will tell you that you didn't do anything.\n\n```rust\nfn main() {\n    let num_vec = vec![10, 9, 8];\n\n    num_vec\n        .iter()\n        .enumerate()\n        .map(|(index, number)| println!(\"Index number {} has number {}\", index, number));\n\n}\n```\n\nIt says:\n\n```text\nwarning: unused `std::iter::Map` that must be used\n --> src\\main.rs:4:5\n  |\n4 | /     num_vec\n5 | |         .iter()\n6 | |         .enumerate()\n7 | |         .map(|(index, number)| println!(\"Index number {} has number {}\", index, number));\n  | |_________________________________________________________________________________________^\n  |\n  = note: `#[warn(unused_must_use)]` on by default\n  = note: iterators are lazy and do nothing unless consumed\n```\n\nThis is a **warning**, so it's not an error: the program runs fine. But why doesn't num_vec do anything? We can look at the types to see.\n\n- `let num_vec = vec![10, 9, 8];` Right now it is a `Vec<i32>`.\n- `.iter()` Now it is an `Iter<i32>`. So it is an iterator with items of `i32`.\n- `.enumerate()` Now it is an `Enumerate<Iter<i32>>`. So it is a type `Enumerate` of type `Iter` of `i32`s.\n- `.map()` Now it is a type `Map<Enumerate<Iter<i32>>>`. So it is a type `Map` of type `Enumerate` of type `Iter` of `i32`s.\n\nAll we did was make a more and more complicated structure. So this `Map<Enumerate<Iter<i32>>>` is a structure that is ready to go, but only when we tell it what to do. Rust does this because it needs to be fast. It doesn't want to do this:\n\n- iterate over all the `i32`s in the Vec\n- then enumerate over all the `i32`s from the iterator\n- then map over all the enumerated `i32`s\n\nRust only wants to do one calculation, so it creates the structure and waits. Then if we say `.collect::<Vec<i32>>()` it knows what to do, and starts moving. This is what `iterators are lazy and do nothing unless consumed` means. The iterators don't do anything until you \"consume\" them (use them up).\n\n\nYou can even create complicated things like `HashMap` using `.collect()`, so it is very powerful. Here is an example of how to put two vecs into a `HashMap`. First we make the two vectors, and then we will use `.into_iter()` on them to get an iterator of values. Then we use the `.zip()` method. This method takes two iterators and attaches them together, like a zipper. Finally, we use `.collect()` to make the `HashMap`.\n\nHere is the code:\n\n```rust\nuse std::collections::HashMap;\n\nfn main() {\n    let some_numbers = vec![0, 1, 2, 3, 4, 5]; // a Vec<i32>\n    let some_words = vec![\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\"]; // a Vec<&str>\n\n    let number_word_hashmap = some_numbers\n        .into_iter()                 // now it is an iter\n        .zip(some_words.into_iter()) // inside .zip() we put in the other iter. Now they are together.\n        .collect::<HashMap<_, _>>();\n\n    println!(\"For key {} we get {}.\", 2, number_word_hashmap.get(&2).unwrap());\n}\n```\n\nThis prints:\n\n```text\nFor key 2 we get two.\n```\n\nYou can see that we wrote `<HashMap<_, _>>` because that is enough information for Rust to decide on the type `HashMap<i32, &str>`. You can write `.collect::<HashMap<i32, &str>>();` if you want, or you can write it like this if you prefer:\n\n```rust\nuse std::collections::HashMap;\n\nfn main() {\n    let some_numbers = vec![0, 1, 2, 3, 4, 5]; // a Vec<i32>\n    let some_words = vec![\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\"]; // a Vec<&str>\n    let number_word_hashmap: HashMap<_, _> = some_numbers  // Because we tell it the type here...\n        .into_iter()\n        .zip(some_words.into_iter())\n        .collect(); // we don't have to tell it here\n}\n```\n\nThere is another method that is like `.enumerate()` for `char`s: `char_indices()`. (Indices means \"indexes\"). You use it in the same way. Let's pretend we have a big string that made of 3-digit numbers.\n\n```rust\nfn main() {\n    let numbers_together = \"140399923481800622623218009598281\";\n\n    for (index, number) in numbers_together.char_indices() {\n        match (index % 3, number) {\n            (0..=1, number) => print!(\"{}\", number), // just print the number if there is a remainder\n            _ => print!(\"{}\\t\", number), // otherwise print the number with a tab space\n        }\n    }\n}\n```\n\nThis prints `140     399     923     481     800     622     623     218     009     598    281`.\n\n\n### |_| in a closure\n\nSometimes you see `|_|` in a closure. This means that the closure needs an argument (like `x`), but you don't want to use it. So `|_|` means \"Okay, this closure takes an argument but I won't give it a name because I don't care about it\".\n\nHere is an example of an error when you don't do that:\n\n```rust\nfn main() {\n    let my_vec = vec![8, 9, 10];\n\n    println!(\"{:?}\", my_vec.iter().for_each(|| println!(\"We didn't use the variables at all\"))); // ⚠️\n}\n```\n\nRust says that\n\n```text\nerror[E0593]: closure is expected to take 1 argument, but it takes 0 arguments\n  --> src\\main.rs:28:36\n   |\n28 |     println!(\"{:?}\", my_vec.iter().for_each(|| println!(\"We didn't use the variables at all\")));\n   |                                    ^^^^^^^^ -- takes 0 arguments\n   |                                    |\n   |                                    expected closure that takes 1 argument\n```\n\nThe compiler actually gives you some help:\n\n```text\nhelp: consider changing the closure to take and ignore the expected argument\n   |\n28 |     println!(\"{:?}\", my_vec.iter().for_each(|_| println!(\"We didn't use the variables at all\")));\n```\n\nThis is good advice. If you change `||` to `|_|` then it will work.\n\n### Helpful methods for closures and iterators\n\nRust becomes a very fun to language once you become comfortable with closures. With closures you can *chain* methods to each other and do a lot of things with very little code. Here are some closures and methods used with closures that we didn't see yet.\n\n`.filter()`: This lets you keep the items in an iterator that you want to keep. Let's filter the months of the year.\n\n```rust\nfn main() {\n    let months = vec![\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"];\n\n    let filtered_months = months\n        .into_iter()                         // make an iter\n        .filter(|month| month.len() < 5)     // We don't want months more than 5 bytes in length.\n                                             // We know that each letter is one byte so .len() is fine\n        .filter(|month| month.contains(\"u\")) // Also we only like months with the letter u\n        .collect::<Vec<&str>>();\n\n    println!(\"{:?}\", filtered_months);\n}\n```\n\nThis prints `[\"June\", \"July\"]`.\n\n\n\n`.filter_map()`. This is called `filter_map()` because it does `.filter()` and `.map()`. The closure must return an `Option<T>`, and then `filter_map()` takes the value out of each `Option` if it is `Some`. So for example if you were to `.filter_map()` a `vec![Some(2), None, Some(3)]`, it would return `[2, 3]`.\n\nWe will write an example with a `Company` struct. Each company has a `name` so that field is `String`, but the CEO might have recently quit. So the `ceo` field is `Option<String>`. We will `.filter_map()` over some companies to just keep the CEO names.\n\n```rust\nstruct Company {\n    name: String,\n    ceo: Option<String>,\n}\n\nimpl Company {\n    fn new(name: &str, ceo: &str) -> Self {\n        let ceo = match ceo {\n            \"\" => None,\n            ceo => Some(ceo.to_string()),\n        }; // ceo is decided, so now we return Self\n        Self {\n            name: name.to_string(),\n            ceo,\n        }\n    }\n\n    fn get_ceo(&self) -> Option<String> {\n        self.ceo.clone() // Just returns a clone of the CEO (struct is not Copy)\n    }\n}\n\nfn main() {\n    let company_vec = vec![\n        Company::new(\"Umbrella Corporation\", \"Unknown\"),\n        Company::new(\"Ovintiv\", \"Doug Suttles\"),\n        Company::new(\"The Red-Headed League\", \"\"),\n        Company::new(\"Stark Enterprises\", \"\"),\n    ];\n\n    let all_the_ceos = company_vec\n        .into_iter()\n        .filter_map(|company| company.get_ceo()) // filter_map needs Option<T>\n        .collect::<Vec<String>>();\n\n    println!(\"{:?}\", all_the_ceos);\n}\n```\n\nThis prints `[\"Unknown\", \"Doug Suttles\"]`.\n\nSince `.filter_map()` needs an `Option`, what about `Result`? No problem: there is a method called `.ok()` that turns `Result` into `Option`. It is called `.ok()` because all it can send is the `Ok` result (the `Err` information is gone). You remember that `Option` is `Option<T>` while `Result` is `Result<T, E>` with information for both `Ok` and `Err`. So when you use `.ok()`, any `Err` information is lost and it becomes `None`.\n\nUsing `.parse()` is an easy example for this, where we try to parse some user input. `.parse()` here takes a `&str` and tries to turn it into an `f32`. It returns a `Result`, but we are using `filter_map()` so we just throw out the errors. Anything that is `Err` becomes `None` and is filtered out by `.filter_map()`.\n\n```rust\nfn main() {\n    let user_input = vec![\"8.9\", \"Nine point nine five\", \"8.0\", \"7.6\", \"eleventy-twelve\"];\n\n    let actual_numbers = user_input\n        .into_iter()\n        .filter_map(|input| input.parse::<f32>().ok())\n        .collect::<Vec<f32>>();\n\n    println!(\"{:?}\", actual_numbers);\n}\n```\n\nThis prints `[8.9, 8.0, 7.6]`.\n\nOn the opposite side of `.ok()` is `.ok_or()` and `ok_or_else()`. This turns an `Option` into a `Result`. It is called `.ok_or()` because a `Result` gives an `Ok` **or** an `Err`, so you have to let it know what the `Err` value will be. That is because `None` in an `Option` doesn't have any information. Also, you can see now that the *else* part in the names of these methods means that it has a closure.\n\nWe can take our `Option` from the `Company` struct and turn it into a `Result` this way. For long-term error handling it is good to create your own type of error. But for now we just give it an error message, so it becomes a `Result<String, &str>`.\n\n```rust\n// Everything before main() is exactly the same\nstruct Company {\n    name: String,\n    ceo: Option<String>,\n}\n\nimpl Company {\n    fn new(name: &str, ceo: &str) -> Self {\n        let ceo = match ceo {\n            \"\" => None,\n            ceo => Some(ceo.to_string()),\n        };\n        Self {\n            name: name.to_string(),\n            ceo,\n        }\n    }\n\n    fn get_ceo(&self) -> Option<String> {\n        self.ceo.clone()\n    }\n}\n\nfn main() {\n    let company_vec = vec![\n        Company::new(\"Umbrella Corporation\", \"Unknown\"),\n        Company::new(\"Ovintiv\", \"Doug Suttles\"),\n        Company::new(\"The Red-Headed League\", \"\"),\n        Company::new(\"Stark Enterprises\", \"\"),\n    ];\n\n    let mut results_vec = vec![]; // Pretend we need to gather error results too\n\n    company_vec\n        .iter()\n        .for_each(|company| results_vec.push(company.get_ceo().ok_or(\"No CEO found\")));\n\n    for item in results_vec {\n        println!(\"{:?}\", item);\n    }\n}\n```\n\nThis line is the biggest change:\n\n```rust\n// 🚧\n.for_each(|company| results_vec.push(company.get_ceo().ok_or(\"No CEO found\")));\n```\n\nIt means: \"For each company, use `get_ceo()`. If you get it, then pass on the value inside `Ok`. And if you don't, pass on \"No CEO found\" inside `Err`. Then push this into the vec.\"\n\nSo when we print `results_vec` we get this:\n\n```text\nOk(\"Unknown\")\nOk(\"Doug Suttles\")\nErr(\"No CEO found\")\nErr(\"No CEO found\")\n```\n\nSo now we have all four entries. Now let's use `.ok_or_else()` so we can use a closure and get a better error message. Now we have space to use `format!` to create a `String`, and put the company name in that. Then we return the `String`.\n\n```rust\n// Everything before main() is exactly the same\nstruct Company {\n    name: String,\n    ceo: Option<String>,\n}\n\nimpl Company {\n    fn new(name: &str, ceo: &str) -> Self {\n        let ceo = match ceo {\n            \"\" => None,\n            name => Some(name.to_string()),\n        };\n        Self {\n            name: name.to_string(),\n            ceo,\n        }\n    }\n\n    fn get_ceo(&self) -> Option<String> {\n        self.ceo.clone()\n    }\n}\n\nfn main() {\n    let company_vec = vec![\n        Company::new(\"Umbrella Corporation\", \"Unknown\"),\n        Company::new(\"Ovintiv\", \"Doug Suttles\"),\n        Company::new(\"The Red-Headed League\", \"\"),\n        Company::new(\"Stark Enterprises\", \"\"),\n    ];\n\n    let mut results_vec = vec![];\n\n    company_vec.iter().for_each(|company| {\n        results_vec.push(company.get_ceo().ok_or_else(|| {\n            let err_message = format!(\"No CEO found for {}\", company.name);\n            err_message\n        }))\n    });\n\n    for item in results_vec {\n        println!(\"{:?}\", item);\n    }\n}\n```\n\nThis gives us:\n\n```text\nOk(\"Unknown\")\nOk(\"Doug Suttles\")\nErr(\"No CEO found for The Red-Headed League\")\nErr(\"No CEO found for Stark Enterprises\")\n```\n\n\n`.and_then()` is a helpful method that takes an `Option`, then lets you do something to its value and pass it on. So its input is an `Option`, and its output is also an `Option`. It is sort of like a safe \"unwrap, then do something, then wrap again\".\n\nAn easy example is a number that we get from a vec using `.get()`, because that returns an `Option`. Now we can pass it to `and_then()`, and do some math on it if it is `Some`. If it is `None`, then the `None` just gets passed through.\n\n```rust\nfn main() {\n    let new_vec = vec![8, 9, 0]; // just a vec with numbers\n\n    let number_to_add = 5;       // use this in the math later\n    let mut empty_vec = vec![];  // results go in here\n\n\n    for index in 0..5 {\n        empty_vec.push(\n            new_vec\n               .get(index)\n                .and_then(|number| Some(number + 1))\n                .and_then(|number| Some(number + number_to_add))\n        );\n    }\n    println!(\"{:?}\", empty_vec);\n}\n```\n\nThis prints `[Some(14), Some(15), Some(6), None, None]`. You can see that `None` isn't filtered out, just passed on.\n\n\n\n\n`.and()` is sort of like a `bool` for `Option`. You can match many `Option`s to each other, and if they are all `Some` then it will give the last one. And if one of them is a `None`, then it will give `None`.\n\nFirst here is a `bool` example to help imagine. You can see that if you are using `&&` (and), even one `false` makes everything `false`.\n\n```rust\nfn main() {\n    let one = true;\n    let two = false;\n    let three = true;\n    let four = true;\n\n    println!(\"{}\", one && three); // prints true\n    println!(\"{}\", one && two && three && four); // prints false\n}\n```\n\nNow here is the same thing with `.and()`. Imagine we did five operations and put the results in a Vec<Option<&str>>. If we get a value, we push `Some(\"success!\")` to the vec. Then we do this two more times. After that we use `.and()` to only show the indexes that got `Some` every time.\n\n```rust\nfn main() {\n    let first_try = vec![Some(\"success!\"), None, Some(\"success!\"), Some(\"success!\"), None];\n    let second_try = vec![None, Some(\"success!\"), Some(\"success!\"), Some(\"success!\"), Some(\"success!\")];\n    let third_try = vec![Some(\"success!\"), Some(\"success!\"), Some(\"success!\"), Some(\"success!\"), None];\n\n    for i in 0..first_try.len() {\n        println!(\"{:?}\", first_try[i].and(second_try[i]).and(third_try[i]));\n    }\n}\n```\n\nThis prints:\n\n```text\nNone\nNone\nSome(\"success!\")\nSome(\"success!\")\nNone\n```\n\nThe first one (index 0) is `None` because there is a `None` for index 0 in `second_try`. The second is `None` because there is a `None` in `first_try`. The next is `Some(\"success!\")` because there is no `None` for `first_try`, `second try`, or `third_try`.\n\n\n\n`.any()` and `.all()` are very easy to use in iterators. They return a `bool` depending on your input. In this example we make a very large vec (about 20,000 items) with all the characters from `'a'` to `'働'`. Then we make a function to check if a character is inside it.\n\nNext we make a smaller vec and ask it whether it is all alphabetic (with the `.is_alphabetic()` method). Then we ask it if all the characters are less than the Korean character `'행'`.\n\nAlso note that you put a reference in, because `.iter()` gives a reference and you need a `&` to compare with another `&`.\n\n```rust\nfn in_char_vec(char_vec: &Vec<char>, check: char) {\n    println!(\"Is {} inside? {}\", check, char_vec.iter().any(|&char| char == check));\n}\n\nfn main() {\n    let char_vec = ('a'..'働').collect::<Vec<char>>();\n    in_char_vec(&char_vec, 'i');\n    in_char_vec(&char_vec, '뷁');\n    in_char_vec(&char_vec, '鑿');\n\n    let smaller_vec = ('A'..'z').collect::<Vec<char>>();\n    println!(\"All alphabetic? {}\", smaller_vec.iter().all(|&x| x.is_alphabetic()));\n    println!(\"All less than the character 행? {}\", smaller_vec.iter().all(|&x| x < '행'));\n}\n```\n\nThis prints:\n\n```text\nIs i inside? true\nIs 뷁 inside? false\nIs 鑿 inside? false\nAll alphabetic? false\nAll less than the character 행? true\n```\n\nBy the way, `.any()` only checks until it finds one matching item, and then it stops. It won't check them all if it has already found a match. If you are going to use `.any()` on a `Vec`, it might be a good idea to push the items that might match near the front. Or you can use `.rev()` after `.iter()` to reverse the iterator. Here's one vec like that:\n\n```rust\nfn main() {\n    let mut big_vec = vec![6; 1000];\n    big_vec.push(5);\n}\n```\n\nSo this `Vec` has 1000 `6` followed by one `5`. Let's pretend that we want to use `.any()` to see if it contains 5. First let's make sure that `.rev()` is working. Remember, an `Iterator` always has `.next()` that lets you check what it does every time.\n\n```rust\nfn main() {\n    let mut big_vec = vec![6; 1000];\n    big_vec.push(5);\n\n    let mut iterator = big_vec.iter().rev();\n    println!(\"{:?}\", iterator.next());\n    println!(\"{:?}\", iterator.next());\n}\n```\n\nIt prints:\n\n```text\nSome(5)\nSome(6)\n```\n\nWe were right: there is one `Some(5)` and then the 1000 `Some(6)` start. So we can write this:\n\n```rust\nfn main() {\n    let mut big_vec = vec![6; 1000];\n    big_vec.push(5);\n\n    println!(\"{:?}\", big_vec.iter().rev().any(|&number| number == 5));\n}\n```\n\nAnd because it's `.rev()`, it only calls `.next()` one time and stops. If we don't use `.rev()` then it will call `.next()` 1001 times before it stops. This code shows it:\n\n```rust\nfn main() {\n    let mut big_vec = vec![6; 1000];\n    big_vec.push(5);\n\n    let mut counter = 0; // Start counting\n    let mut big_iter = big_vec.into_iter(); // Make it an Iterator\n\n    loop {\n        counter +=1;\n        if big_iter.next() == Some(5) { // Keep calling .next() until we get Some(5)\n            break;\n        }\n    }\n    println!(\"Final counter is: {}\", counter);\n}\n```\n\nThis prints `Final counter is: 1001` so we know that it had to call `.next()` 1001 times before it found 5.\n\n\n\n\n`.find()` tells you if an iterator has something, and `.position()` tells you where it is. `.find()` is different from `.any()` because it returns an `Option` with the value inside (or `None`). Meanwhile, `.position()` is also an `Option` with the position number, or `None`. In other words:\n\n- `.find()`: \"I'll try to get it for you\"\n- `.position()`: \"I'll try to find where it is for you\"\n\nHere is a simple example:\n\n```rust\nfn main() {\n    let num_vec = vec![10, 20, 30, 40, 50, 60, 70, 80, 90, 100];\n\n    println!(\"{:?}\", num_vec.iter().find(|&number| number % 3 == 0)); // find takes a reference, so we give it &number\n    println!(\"{:?}\", num_vec.iter().find(|&number| number * 2 == 30));\n\n    println!(\"{:?}\", num_vec.iter().position(|&number| number % 3 == 0));\n    println!(\"{:?}\", num_vec.iter().position(|&number| number * 2 == 30));\n\n}\n```\n\nThis prints:\n\n```text\nSome(30) // This is the number itself\nNone // No number inside times 2 == 30\nSome(2) // This is the position\nNone\n```\n\n\n\nWith `.cycle()` you can create an iterator that loops forever. This type of iterator works well with `.zip()` to create something new, like this example which creates a `Vec<(i32, &str)>`:\n\n```rust\nfn main() {\n    let even_odd = vec![\"even\", \"odd\"];\n\n    let even_odd_vec = (0..6)\n        .zip(even_odd.into_iter().cycle())\n        .collect::<Vec<(i32, &str)>>();\n    println!(\"{:?}\", even_odd_vec);\n}\n```\n\nSo even though `.cycle()` might never end, the other iterator only runs six times when zipping them together. That means that the iterator made by `.cycle()` doesn't get a `.next()` call again so it is done after six times. The output is:\n\n```\n[(0, \"even\"), (1, \"odd\"), (2, \"even\"), (3, \"odd\"), (4, \"even\"), (5, \"odd\")]\n```\n\nSomething similar can be done with a range that doesn't have an ending. If you write `0..` then you create a range that never stops. You can use this very easily:\n\n```rust\nfn main() {\n    let ten_chars = ('a'..).take(10).collect::<Vec<char>>();\n    let skip_then_ten_chars = ('a'..).skip(1300).take(10).collect::<Vec<char>>();\n\n    println!(\"{:?}\", ten_chars);\n    println!(\"{:?}\", skip_then_ten_chars);\n}\n```\n\nBoth print ten characters, but the second one skipped 1300 places and prints ten letters in Armenian.\n\n```\n['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']\n['յ', 'ն', 'շ', 'ո', 'չ', 'պ', 'ջ', 'ռ', 'ս', 'վ']\n```\n\n\nAnother popular method is called `.fold()`. This method is used a lot to add together the items in an iterator, but you can also do a lot more. It is somewhat similar to `.for_each()`. In `.fold()`, you first add a starting value (if you are adding items together, then 0), then a comma, then the closure. The closure gives you two items: the total so far, and the next item. First here is a simple example showing `.fold()` to add items together.\n\n```rust\nfn main() {\n    let some_numbers = vec![9, 6, 9, 10, 11];\n\n    println!(\"{}\", some_numbers\n        .iter()\n        .fold(0, |total_so_far, next_number| total_so_far + next_number)\n    );\n}\n```\n\nSo:\n\n- on step 1 it starts with 0 and adds the next number: 9.\n- Then it takes that 9 and adds the 6: 15.\n- Then it takes that 15, and adds the 9: 24.\n- Then it takes that 24, and adds the 10: 34.\n- Finally it takes that 34, and adds the 11: 45. So it prints `45`.\n\n\nBut you don't just need to add things with it. Here is an example where we add a '-' to every character to make a `String`.\n\n```rust\nfn main() {\n    let a_string = \"I don't have any dashes in me.\";\n\n    println!(\n        \"{}\",\n        a_string\n            .chars() // Now it's an iterator\n            .fold(\"-\".to_string(), |mut string_so_far, next_char| { // Start with a String \"-\". Bring it in as mutable each time along with the next char\n                string_so_far.push(next_char); // Push the char on, then '-'\n                string_so_far.push('-');\n                string_so_far} // Don't forget to pass it on to the next loop\n            ));\n}\n```\n\nThis prints:\n\n```text\n-I- -d-o-n-'-t- -h-a-v-e- -a-n-y- -d-a-s-h-e-s- -i-n- -m-e-.-\n```\n\n\n\nThere are many other convenient methods like:\n\n- `.take_while()` which takes into an iterator as long as it gets `true` (`take while x > 5` for example)\n- `.cloned()` which makes a clone inside the iterator. This turns a reference into a value.\n- `.by_ref()` which makes an iterator take a reference. This is good to make sure that you can use a `Vec` or something similar after you use it to make an iterator.\n- Many other `_while` methods: `.skip_while()`, `.map_while()`, and so on\n- `.sum()`: just adds everything together.\n\n\n\n`.chunks()` and `.windows()` are two ways of cutting up a vector into a size you want. You put the size you want into the brackets. Let's say you have a vector with 10 items, and you want a size of 3. It will work like this:\n\n- `.chunks()` will give you four slices: [0, 1, 2], then [3, 4, 5], then [6, 7, 8], and finally [9]. So it will try to make a slice of three items, but if it doesn't have three then it won't panic. It will just give you what is left.\n\n- `.windows()` will first give you a slice of [0, 1, 2]. Then it will move over one and give you [1, 2, 3]. It will do that until it finally reaches the last slice of three and stop.\n\nSo let's use them on a simple vector of numbers. It looks like this:\n\n```rust\nfn main() {\n    let num_vec = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 0];\n\n    for chunk in num_vec.chunks(3) {\n        println!(\"{:?}\", chunk);\n    }\n    println!();\n    for window in num_vec.windows(3) {\n        println!(\"{:?}\", window);\n    }\n}\n```\n\nThis prints:\n\n```text\n[1, 2, 3]\n[4, 5, 6]\n[7, 8, 9]\n[0]\n\n[1, 2, 3]\n[2, 3, 4]\n[3, 4, 5]\n[4, 5, 6]\n[5, 6, 7]\n[6, 7, 8]\n[7, 8, 9]\n[8, 9, 0]\n```\n\nBy the way, `.chunks()` will panic if you give it nothing. You can write `.chunks(1000)` for a vector with one item, but you can't write `.chunks()` with anything with a length of 0. You can see that right in the function if you click on [src] because it says `assert!(chunk_size != 0);`.\n\n\n\n`.match_indices()` lets you pull out everything inside a `String` or `&str` that matches your input, and gives you the index too. It is similar to `.enumerate()` because it returns a tuple with two items.\n\n```rust\nfn main() {\n    let rules = \"Rule number 1: No fighting. Rule number 2: Go to bed at 8 pm. Rule number 3: Wake up at 6 am.\";\n    let rule_locations = rules.match_indices(\"Rule\").collect::<Vec<(_, _)>>(); // This is Vec<usize, &str> but we just tell Rust to do it\n    println!(\"{:?}\", rule_locations);\n}\n```\n\nThis prints:\n\n```text\n[(0, \"Rule\"), (28, \"Rule\"), (62, \"Rule\")]\n```\n\n\n\n`.peekable()` lets you make an iterator where you can see (peek at) the next item. It's like calling `.next()` (it gives an `Option`) except that the iterator doesn't move, so you can use it as many times as you want. You can actually think of peekable as \"stoppable\", because you can stop for as long as you want. Here is an example of us using `.peek()` three times for every item. We can use `.peek()` forever until we use `.next()` to move to the next item.\n\n```rust\nfn main() {\n    let just_numbers = vec![1, 5, 100];\n    let mut number_iter = just_numbers.iter().peekable(); // This actually creates a type of iterator called Peekable\n\n    for _ in 0..3 {\n        println!(\"I love the number {}\", number_iter.peek().unwrap());\n        println!(\"I really love the number {}\", number_iter.peek().unwrap());\n        println!(\"{} is such a nice number\", number_iter.peek().unwrap());\n        number_iter.next();\n    }\n}\n```\n\nThis prints:\n\n```text\nI love the number 1\nI really love the number 1\n1 is such a nice number\nI love the number 5\nI really love the number 5\n5 is such a nice number\nI love the number 100\nI really love the number 100\n100 is such a nice number\n```\n\nHere is another example where we use `.peek()` to match on an item. After we are done using it, we call `.next()`.\n\n\n```rust\nfn main() {\n    let locations = vec![\n        (\"Nevis\", 25),\n        (\"Taber\", 8428),\n        (\"Markerville\", 45),\n        (\"Cardston\", 3585),\n    ];\n    let mut location_iter = locations.iter().peekable();\n    while location_iter.peek().is_some() {\n        match location_iter.peek() {\n            Some((name, number)) if *number < 100 => { // .peek() gives us a reference so we need *\n                println!(\"Found a hamlet: {} with {} people\", name, number)\n            }\n            Some((name, number)) => println!(\"Found a town: {} with {} people\", name, number),\n            None => break,\n        }\n        location_iter.next();\n    }\n}\n```\n\nThis prints:\n\n```text\nFound a hamlet: Nevis with 25 people\nFound a town: Taber with 8428 people\nFound a hamlet: Markerville with 45 people\nFound a town: Cardston with 3585 people\n```\n\nFinally, here is an example where we also use `.match_indices()`. In this example we put names into a `struct` depending on the number of spaces in the `&str`.\n\n```rust\n#[derive(Debug)]\nstruct Names {\n    one_word: Vec<String>,\n    two_words: Vec<String>,\n    three_words: Vec<String>,\n}\n\nfn main() {\n    let vec_of_names = vec![\n        \"Caesar\",\n        \"Frodo Baggins\",\n        \"Bilbo Baggins\",\n        \"Jean-Luc Picard\",\n        \"Data\",\n        \"Rand Al'Thor\",\n        \"Paul Atreides\",\n        \"Barack Hussein Obama\",\n        \"Bill Jefferson Clinton\",\n    ];\n\n    let mut iter_of_names = vec_of_names.iter().peekable();\n\n    let mut all_names = Names { // start an empty Names struct\n        one_word: vec![],\n        two_words: vec![],\n        three_words: vec![],\n    };\n\n    while iter_of_names.peek().is_some() {\n        let next_item = iter_of_names.next().unwrap(); // We can use .unwrap() because we know it is Some\n        match next_item.match_indices(' ').collect::<Vec<_>>().len() { // Create a quick vec using .match_indices and check the length\n            0 => all_names.one_word.push(next_item.to_string()),\n            1 => all_names.two_words.push(next_item.to_string()),\n            _ => all_names.three_words.push(next_item.to_string()),\n        }\n    }\n\n    println!(\"{:?}\", all_names);\n}\n```\n\nThis will print:\n\n```text\nNames { one_word: [\"Caesar\", \"Data\"], two_words: [\"Frodo Baggins\", \"Bilbo Baggins\", \"Jean-Luc Picard\", \"Rand Al\\'Thor\", \"Paul Atreides\"], three_words:\n[\"Barack Hussein Obama\", \"Bill Jefferson Clinton\"] }\n```\n\n\n## The dbg! macro and .inspect\n\n`dbg!` is a very useful macro that prints quick information. It is a good alternative to `println!` because it is faster to type and gives more information:\n\n```rust\nfn main() {\n    let my_number = 8;\n    dbg!(my_number);\n}\n```\n\nThis prints `[src\\main.rs:4] my_number = 8`.\n\nBut actually, you can put `dbg!` in many other places, and even wrap code in it. Look at this code for example:\n\n```rust\nfn main() {\n    let mut my_number = 9;\n    my_number += 10;\n\n    let new_vec = vec![8, 9, 10];\n\n    let double_vec = new_vec.iter().map(|x| x * 2).collect::<Vec<i32>>();\n}\n```\n\nThis code creates a new mutable number and changes it. Then it creates a vec, and uses `iter` and `map` and `collect` to create a new vec. We can put `dbg!` almost everywhere in this code. `dbg!` asks the compiler: \"What are you doing at this moment?\" and tells you.\n\n```rust\nfn main() {\n    let mut my_number = dbg!(9);\n    dbg!(my_number += 10);\n\n    let new_vec = dbg!(vec![8, 9, 10]);\n\n    let double_vec = dbg!(new_vec.iter().map(|x| x * 2).collect::<Vec<i32>>());\n\n    dbg!(double_vec);\n}\n```\n\nSo this prints:\n\n```text\n[src\\main.rs:3] 9 = 9\n```\n\nand:\n\n```text\n[src\\main.rs:4] my_number += 10 = ()\n```\n\nand:\n\n```text\n[src\\main.rs:6] vec![8, 9, 10] = [\n    8,\n    9,\n    10,\n]\n```\n\nand this one, which even shows you the value of the expression:\n\n```text\n[src\\main.rs:8] new_vec.iter().map(|x| x * 2).collect::<Vec<i32>>() = [\n    16,\n    18,\n    20,\n]\n```\n\nand:\n\n```text\n[src\\main.rs:10] double_vec = [\n    16,\n    18,\n    20,\n]\n```\n\n`.inspect` is a bit similar to `dbg!` but you use it like `map` in an iterator. It gives you the iterator item and you can print it or do whatever you want. For example, let's look at our `double_vec` again.\n\n```rust\nfn main() {\n    let new_vec = vec![8, 9, 10];\n\n    let double_vec = new_vec\n        .iter()\n        .map(|x| x * 2)\n        .collect::<Vec<i32>>();\n}\n```\n\nWe want to know more information about what the code is doing. So we add `inspect()` in two places:\n\n```rust\nfn main() {\n    let new_vec = vec![8, 9, 10];\n\n    let double_vec = new_vec\n        .iter()\n        .inspect(|first_item| println!(\"The item is: {}\", first_item))\n        .map(|x| x * 2)\n        .inspect(|next_item| println!(\"Then it is: {}\", next_item))\n        .collect::<Vec<i32>>();\n}\n```\n\nThis prints:\n\n```text\nThe item is: 8\nThen it is: 16\nThe item is: 9\nThen it is: 18\nThe item is: 10\nThen it is: 20\n```\n\nAnd because `.inspect` takes a closure, we can write as much as we want:\n\n```rust\nfn main() {\n    let new_vec = vec![8, 9, 10];\n\n    let double_vec = new_vec\n        .iter()\n        .inspect(|first_item| {\n            println!(\"The item is: {}\", first_item);\n            match **first_item % 2 { // first item is a &&i32 so we use **\n                0 => println!(\"It is even.\"),\n                _ => println!(\"It is odd.\"),\n            }\n            println!(\"In binary it is {:b}.\", first_item);\n        })\n        .map(|x| x * 2)\n        .collect::<Vec<i32>>();\n}\n```\n\nThis prints:\n\n```text\nThe item is: 8\nIt is even.\nIn binary it is 1000.\nThe item is: 9\nIt is odd.\nIn binary it is 1001.\nThe item is: 10\nIt is even.\nIn binary it is 1010.\n```\n\n## Types of &str\n\nThere is more than one type of `&str`. We have:\n\n- String literals: you make these when you write `let my_str = \"I am a &str\"`. They last for the whole program, because they are written directly into the binary. They have the type `&'static str`. `'` means its lifetime, and string literal have a lifetime called `static`.\n- Borrowed str: This is the regular `&str` form without a `static` lifetime. If you create a `String` and get a reference to it, Rust will convert it to a `&str` when you need it. For example:\n\n```rust\nfn prints_str(my_str: &str) { // it can use &String like a &str\n    println!(\"{}\", my_str);\n}\n\nfn main() {\n    let my_string = String::from(\"I am a string\");\n    prints_str(&my_string); // we give prints_str a &String\n}\n```\n\nSo what is a lifetime? We will learn that now.\n\n## Lifetimes\n\nA lifetime means \"how long the variable lives\". You only need to think about lifetimes with references. This is because references can't live longer than the object they come from. For example, this function does not work:\n\n```rust\nfn returns_reference() -> &str {\n    let my_string = String::from(\"I am a string\");\n    &my_string // ⚠️\n}\n\nfn main() {}\n```\n\nThe problem is that `my_string` only lives inside `returns_reference`. We try to return `&my_string`, but `&my_string` can't exist without `my_string`. So the compiler says no.\n\nThis code also doesn't work:\n\n```rust\nfn returns_str() -> &str {\n    let my_string = String::from(\"I am a string\");\n    \"I am a str\" // ⚠️\n}\n\nfn main() {\n    let my_str = returns_str();\n    println!(\"{}\", my_str);\n}\n```\n\nBut it almost works. The compiler says:\n\n```text\nerror[E0106]: missing lifetime specifier\n --> src\\main.rs:6:21\n  |\n6 | fn returns_str() -> &str {\n  |                     ^ expected named lifetime parameter\n  |\n  = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from\nhelp: consider using the `'static` lifetime\n  |\n6 | fn returns_str() -> &'static str {\n  |                     ^^^^^^^^\n```\n\n`missing lifetime specifier` means that we need to add a `'` with the lifetime. Then it says that it `contains a borrowed value, but there is no value for it to be borrowed from`. That means that `I am a str` isn't borrowed from anything. It says `consider using the 'static lifetime` by writing `&'static str`. So it thinks we should try saying that this is a string literal.\n\nNow it works:\n\n```rust\nfn returns_str() -> &'static str {\n    let my_string = String::from(\"I am a string\");\n    \"I am a str\"\n}\n\nfn main() {\n    let my_str = returns_str();\n    println!(\"{}\", my_str);\n}\n```\n\nThat's because we returned a `&str` with a lifetime of `static`. Meanwhile, `my_string` can only be returned as a `String`: we can't return a reference to it because it is going to die in the next line.\n\nSo now `fn returns_str() -> &'static str` tells Rust: \"don't worry, we will only return a string literal\". String literals live for the whole program, so Rust is happy. You'll notice that this is similar to generics. When we tell the compiler something like `<T: Display>`, we promise that we will only use inputs with `Display`. Lifetimes are similar: we are not changing any variable lifetimes. We are just telling the compiler what the lifetimes of the inputs will be.\n\nBut `'static` is not the only lifetime. Actually, every variable has a lifetime, but usually we don't have to write it. The compiler is pretty smart and can usually figure out for itself. We only have to write the lifetime when the compiler doesn't know.\n\nHere is an example of another lifetime. Imagine we want to create a `City` struct and give it a `&str` for the name. We might want to do that because it gives faster performance than with `String`. So we write it like this, but it won't work yet:\n\n```rust\n#[derive(Debug)]\nstruct City {\n    name: &str, // ⚠️\n    date_founded: u32,\n}\n\nfn main() {\n    let my_city = City {\n        name: \"Ichinomiya\",\n        date_founded: 1921,\n    };\n}\n```\n\nThe compiler says:\n\n```text\nerror[E0106]: missing lifetime specifier\n --> src\\main.rs:3:11\n  |\n3 |     name: &str,\n  |           ^ expected named lifetime parameter\n  |\nhelp: consider introducing a named lifetime parameter\n  |\n2 | struct City<'a> {\n3 |     name: &'a str,\n  |\n```\n\nRust needs a lifetime for `&str` because `&str` is a reference. What happens when the value that `name` points to is dropped? That would be unsafe.\n\nWhat about `'static`, will that work? We used it before. Let's try:\n\n```rust\n#[derive(Debug)]\nstruct City {\n    name: &'static str, // change &str to &'static str\n    date_founded: u32,\n}\n\nfn main() {\n    let my_city = City {\n        name: \"Ichinomiya\",\n        date_founded: 1921,\n    };\n\n    println!(\"{} was founded in {}\", my_city.name, my_city.date_founded);\n}\n```\n\nOkay, that works. And maybe this is what you wanted for the struct. However, note that we can only take \"string literals\", so not references to something else. So this will not work:\n\n```rust\n#[derive(Debug)]\nstruct City {\n    name: &'static str, // must live for the whole program\n    date_founded: u32,\n}\n\nfn main() {\n    let city_names = vec![\"Ichinomiya\".to_string(), \"Kurume\".to_string()]; // city_names does not live for the whole program\n\n    let my_city = City {\n        name: &city_names[0], // ⚠️ This is a &str, but not a &'static str. It is a reference to a value inside city_names\n        date_founded: 1921,\n    };\n\n    println!(\"{} was founded in {}\", my_city.name, my_city.date_founded);\n}\n```\n\nThe compiler says:\n\n```text\nerror[E0597]: `city_names` does not live long enough\n  --> src\\main.rs:12:16\n   |\n12 |         name: &city_names[0],\n   |                ^^^^^^^^^^\n   |                |\n   |                borrowed value does not live long enough\n   |                requires that `city_names` is borrowed for `'static`\n...\n18 | }\n   | - `city_names` dropped here while still borrowed\n```\n\nThis is important to understand, because the reference we gave it actually lives long enough. But we promised that we would only give it a `&'static str`, and that is the problem.\n\nSo now we will try what the compiler suggested before. It said to try writing `struct City<'a>` and `name: &'a str`. This means that it will only take a reference for `name` if it lives as long as `City`.\n\n```rust\n#[derive(Debug)]\nstruct City<'a> { // City has lifetime 'a\n    name: &'a str, // and name also has lifetime 'a.\n    date_founded: u32,\n}\n\nfn main() {\n    let city_names = vec![\"Ichinomiya\".to_string(), \"Kurume\".to_string()];\n\n    let my_city = City {\n        name: &city_names[0],\n        date_founded: 1921,\n    };\n\n    println!(\"{} was founded in {}\", my_city.name, my_city.date_founded);\n}\n```\n\nAlso remember that you can write anything instead of `'a` if you want. This is also similar to generics where we write `T` and `U` but can actually write anything.\n\n```rust\n#[derive(Debug)]\nstruct City<'city> { // The lifetime is now called 'city\n    name: &'city str, // and name has the 'city lifetime\n    date_founded: u32,\n}\n\nfn main() {}\n```\n\nSo usually you will write `'a, 'b, 'c` etc. because it is quick and the usual way to write. But you can always change it if you want. One good tip is that changing the lifetime to a \"human-readable\" name can help you read code if it is very complicated.\n\nLet's look at the comparison to traits for generics again. For example:\n\n```rust\nuse std::fmt::Display;\n\nfn prints<T: Display>(input: T) {\n    println!(\"T is {}\", input);\n}\n\nfn main() {}\n```\n\nWhen you write `T: Display`, it means \"please only take T if it has Display\".\nIt does not mean: \"I am giving Display to T\".\n\nThe same is true for lifetimes. When you write 'a here:\n\n```rust\n#[derive(Debug)]\nstruct City<'a> {\n    name: &'a str,\n    date_founded: u32,\n}\n\nfn main() {}\n```\n\nIt means \"please only take an input for `name` if it lives at least as long as `City`\".\nIt does not mean: \"I will make the input for `name` live as long as `City`\".\n\nNow we can learn about `<'_>` that we saw before. This is called the \"anonymous lifetime\" and is an indicator that references are being used. Rust will suggest it to you when you are implementing structs, for example. Here is one struct that almost works, but not yet:\n\n```rust\n    // ⚠️\nstruct Adventurer<'a> {\n    name: &'a str,\n    hit_points: u32,\n}\n\nimpl Adventurer {\n    fn take_damage(&mut self) {\n        self.hit_points -= 20;\n        println!(\"{} has {} hit points left!\", self.name, self.hit_points);\n    }\n}\n\nfn main() {}\n```\n\nSo we did what we needed to do for the `struct`: first we said that `name` comes from a `&str`. That means we need a lifetime, so we gave it `<'a>`. Then we had to do the same for the `struct` to show that they are at least as long as this lifetime. But then Rust tells us to do this:\n\n```text\nerror[E0726]: implicit elided lifetime not allowed here\n --> src\\main.rs:6:6\n  |\n6 | impl Adventurer {\n  |      ^^^^^^^^^^- help: indicate the anonymous lifetime: `<'_>`\n```\n\nIt wants us to add that anonymous lifetime to show that there is a reference being used. So if we write that, it will be happy:\n\n```rust\nstruct Adventurer<'a> {\n    name: &'a str,\n    hit_points: u32,\n}\n\nimpl Adventurer<'_> {\n    fn take_damage(&mut self) {\n        self.hit_points -= 20;\n        println!(\"{} has {} hit points left!\", self.name, self.hit_points);\n    }\n}\n\nfn main() {}\n```\n\nThis lifetime was made so that you don't always have to write things like `impl<'a> Adventurer<'a>`, because the struct already shows the lifetime.\n\nLifetimes can be difficult in Rust, but here are some tips to avoid getting too stressed about them:\n\n- You can stay with owned types, use clones etc. if you want to avoid them for the time being.\n- Much of the time, when the compiler wants a lifetime you will just end up writing <'a> here and there and then it will work. It's just a way of saying \"don't worry, I won't give you anything that doesn't live long enough\".\n- You can explore lifetimes just a bit at a time. Write some code with owned values, then make one a reference. The compiler will start to complain, but also give some suggestions. And if it gets too complicated, you can undo it and try again next time.\n\nLet's do this with our code and see what the compiler says. First we'll go back and take the lifetimes out, and also implement `Display`. `Display` will just print the `Adventurer`'s name.\n\n```rust\n// ⚠️\nstruct Adventurer {\n    name: &str,\n    hit_points: u32,\n}\n\nimpl Adventurer {\n    fn take_damage(&mut self) {\n        self.hit_points -= 20;\n        println!(\"{} has {} hit points left!\", self.name, self.hit_points);\n    }\n}\n\nimpl std::fmt::Display for Adventurer {\n        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n            write!(f, \"{} has {} hit points.\", self.name, self.hit_points)\n        }\n}\n\nfn main() {}\n```\n\nFirst complaint is this:\n\n```text\nerror[E0106]: missing lifetime specifier\n --> src\\main.rs:2:11\n  |\n2 |     name: &str,\n  |           ^ expected named lifetime parameter\n  |\nhelp: consider introducing a named lifetime parameter\n  |\n1 | struct Adventurer<'a> {\n2 |     name: &'a str,\n  |\n```\n\nIt suggests what to do: `<'a>` after Adventurer, and `&'a str`. So we do that:\n\n```rust\n// ⚠️\nstruct Adventurer<'a> {\n    name: &'a str,\n    hit_points: u32,\n}\n\nimpl Adventurer {\n    fn take_damage(&mut self) {\n        self.hit_points -= 20;\n        println!(\"{} has {} hit points left!\", self.name, self.hit_points);\n    }\n}\n\nimpl std::fmt::Display for Adventurer {\n        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n            write!(f, \"{} has {} hit points.\", self.name, self.hit_points)\n        }\n}\n\nfn main() {}\n```\n\nNow it's happy with those parts, but is wondering about the `impl` blocks. It wants us to mention that it's using references:\n\n```text\nerror[E0726]: implicit elided lifetime not allowed here\n --> src\\main.rs:6:6\n  |\n6 | impl Adventurer {\n  |      ^^^^^^^^^^- help: indicate the anonymous lifetime: `<'_>`\n\nerror[E0726]: implicit elided lifetime not allowed here\n  --> src\\main.rs:12:28\n   |\n12 | impl std::fmt::Display for Adventurer {\n   |                            ^^^^^^^^^^- help: indicate the anonymous lifetime: `<'_>`\n```\n\nOkay, so we will write those in...and now it works! Now we can make an `Adventurer` and do some things with it.\n\n```rust\nstruct Adventurer<'a> {\n    name: &'a str,\n    hit_points: u32,\n}\n\nimpl Adventurer<'_> {\n    fn take_damage(&mut self) {\n        self.hit_points -= 20;\n        println!(\"{} has {} hit points left!\", self.name, self.hit_points);\n    }\n}\n\nimpl std::fmt::Display for Adventurer<'_> {\n\n        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n            write!(f, \"{} has {} hit points.\", self.name, self.hit_points)\n        }\n}\n\nfn main() {\n    let mut billy = Adventurer {\n        name: \"Billy\",\n        hit_points: 100_000,\n    };\n    println!(\"{}\", billy);\n    billy.take_damage();\n}\n```\n\nThis prints:\n\n```text\nBilly has 100000 hit points.\nBilly has 99980 hit points left!\n```\n\nSo you can see that lifetimes are often just the compiler wanting to make sure. And it is usually smart enough to almost guess at what lifetimes you want, and just needs you to tell it so it can be certain.\n\n## Interior mutability\n\n### Cell\n\n**Interior mutability** means having a little bit of mutability on the inside. Remember how in Rust you need to use `mut` to change a variable? There are also some ways to change them without the word `mut`. This is because Rust has some ways to let you safely change values inside of a struct that is immutable. Each one of them follows some rules that make sure that changing the values is still safe.\n\nFirst, let's look at a simple example where we would want this. Imagine a `struct` called `PhoneModel` with many fields:\n\n```rust\nstruct PhoneModel {\n    company_name: String,\n    model_name: String,\n    screen_size: f32,\n    memory: usize,\n    date_issued: u32,\n    on_sale: bool,\n}\n\nfn main() {\n    let super_phone_3000 = PhoneModel {\n        company_name: \"YY Electronics\".to_string(),\n        model_name: \"Super Phone 3000\".to_string(),\n        screen_size: 7.5,\n        memory: 4_000_000,\n        date_issued: 2020,\n        on_sale: true,\n    };\n\n}\n```\n\nIt is better for the fields in `PhoneModel` to be immutable, because we don't want the data to change. The `date_issued` and `screen_size` never change, for example.\n\nBut inside is one field called `on_sale`. A phone model will first be on sale (`true`), but later the company will stop selling it. Can we make just this one field mutable? Because we don't want to write `let mut super_phone_3000`. If we do, then every field will become mutable.\n\nRust has many ways to allow some safe mutability inside of something that is immutable. The most simple way is called `Cell`. First we use `use std::cell::Cell` so that we can just write `Cell` instead of `std::cell::Cell` every time.\n\nThen we change `on_sale: bool` to `on_sale: Cell<bool>`. Now it isn't a bool: it's a `Cell` that holds a `bool`.\n\n`Cell` has a method called `.set()` where you can change the value. We use `.set()` to change `on_sale: true` to `on_sale: Cell::new(true)`.\n\n```rust\nuse std::cell::Cell;\n\nstruct PhoneModel {\n    company_name: String,\n    model_name: String,\n    screen_size: f32,\n    memory: usize,\n    date_issued: u32,\n    on_sale: Cell<bool>,\n}\n\nfn main() {\n    let super_phone_3000 = PhoneModel {\n        company_name: \"YY Electronics\".to_string(),\n        model_name: \"Super Phone 3000\".to_string(),\n        screen_size: 7.5,\n        memory: 4_000_000,\n        date_issued: 2020,\n        on_sale: Cell::new(true),\n    };\n\n    // 10 years later, super_phone_3000 is not on sale anymore\n    super_phone_3000.on_sale.set(false);\n}\n```\n\n`Cell` works for all types, but works best for simple Copy types because it gives values, not references. `Cell` has a method called `get()` for example that only works on Copy types.\n\nAnother type you can use is `RefCell`.\n\n### RefCell\n\nA `RefCell` is another way to change values without needing to declare `mut`. It means \"reference cell\", and is like a `Cell` but uses references instead of copies.\n\nWe will create a `User` struct. So far you can see that it is similar to `Cell`:\n\n```rust\nuse std::cell::RefCell;\n\n#[derive(Debug)]\nstruct User {\n    id: u32,\n    year_registered: u32,\n    username: String,\n    active: RefCell<bool>,\n    // Many other fields\n}\n\nfn main() {\n    let user_1 = User {\n        id: 1,\n        year_registered: 2020,\n        username: \"User 1\".to_string(),\n        active: RefCell::new(true),\n    };\n\n    println!(\"{:?}\", user_1.active);\n}\n```\n\nThis prints `RefCell { value: true }`.\n\nThere are many methods for `RefCell`. Two of them are `.borrow()` and `.borrow_mut()`. With these methods, you can do the same thing you do with `&` and `&mut`. The rules are the same:\n\n- Many borrows is fine,\n- one mutable borrow is fine,\n- but mutable and immutable together is not fine.\n\nSo changing the value in a `RefCell` is very easy:\n\n```rust\n// 🚧\nuser_1.active.replace(false);\nprintln!(\"{:?}\", user_1.active);\n```\n\nAnd there are many other methods like `replace_with` that uses a closure:\n\n```rust\n// 🚧\nlet date = 2020;\n\nuser_1\n    .active\n    .replace_with(|_| if date < 2000 { true } else { false });\nprintln!(\"{:?}\", user_1.active);\n```\n\nBut you have to be careful with a `RefCell`, because it checks borrows at runtime, not compilation time. Runtime means when the program is actually running (after compilation). So this will compile, even though it is wrong:\n\n```rust\nuse std::cell::RefCell;\n\n#[derive(Debug)]\nstruct User {\n    id: u32,\n    year_registered: u32,\n    username: String,\n    active: RefCell<bool>,\n    // Many other fields\n}\n\nfn main() {\n    let user_1 = User {\n        id: 1,\n        year_registered: 2020,\n        username: \"User 1\".to_string(),\n        active: RefCell::new(true),\n    };\n\n    let borrow_one = user_1.active.borrow_mut(); // first mutable borrow - okay\n    let borrow_two = user_1.active.borrow_mut(); // second mutable borrow - not okay\n}\n```\n\nBut if you run it, it will immediately panic.\n\n```text\nthread 'main' panicked at 'already borrowed: BorrowMutError', C:\\Users\\mithr\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib/rustlib/src/rust\\src\\libcore\\cell.rs:877:9\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\nerror: process didn't exit successfully: `target\\debug\\rust_book.exe` (exit code: 101)\n```\n\n`already borrowed: BorrowMutError` is the important part. So when you use a `RefCell`, it is good to compile **and** run to check.\n\n### Mutex\n\n`Mutex` is another way to change values without declaring `mut`. Mutex means `mutual exclusion`, which means \"only one at a time\". This is why a `Mutex` is safe, because it only lets one process change it at a time. To do this, it uses `.lock()`. `Lock` is like locking a door from the inside. You go into a room, lock the door, and now you can change things inside the room. Nobody else can come in and stop you, because you locked the door.\n\nA `Mutex` is easier to understand through examples.\n\n```rust\nuse std::sync::Mutex;\n\nfn main() {\n    let my_mutex = Mutex::new(5); // A new Mutex<i32>. We don't need to say mut\n    let mut mutex_changer = my_mutex.lock().unwrap(); // mutex_changer is a MutexGuard\n                                                     // It has to be mut because we will change it\n                                                     // Now it has access to the Mutex\n                                                     // Let's print my_mutex to see:\n\n    println!(\"{:?}\", my_mutex); // This prints \"Mutex { data: <locked> }\"\n                                // So we can't access the data with my_mutex now,\n                                // only with mutex_changer\n\n    println!(\"{:?}\", mutex_changer); // This prints 5. Let's change it to 6.\n\n    *mutex_changer = 6; // mutex_changer is a MutexGuard<i32> so we use * to change the i32\n\n    println!(\"{:?}\", mutex_changer); // Now it says 6\n}\n```\n\nBut `mutex_changer` still has a lock after it is done. How do we stop it? A `Mutex` is unlocked when the `MutexGuard` goes out of scope. \"Go out of scope\" means the code block is finished. For example:\n\n```rust\nuse std::sync::Mutex;\n\nfn main() {\n    let my_mutex = Mutex::new(5);\n    {\n        let mut mutex_changer = my_mutex.lock().unwrap();\n        *mutex_changer = 6;\n    } // mutex_changer goes out of scope - now it is gone. It is not locked anymore\n\n    println!(\"{:?}\", my_mutex); // Now it says: Mutex { data: 6 }\n}\n```\n\nIf you don't want to use a different `{}` code block, you can use `std::mem::drop(mutex_changer)`. `std::mem::drop` means \"make this go out of scope\".\n\n```rust\nuse std::sync::Mutex;\n\nfn main() {\n    let my_mutex = Mutex::new(5);\n    let mut mutex_changer = my_mutex.lock().unwrap();\n    *mutex_changer = 6;\n    std::mem::drop(mutex_changer); // drop mutex_changer - it is gone now\n                                   // and my_mutex is unlocked\n\n    println!(\"{:?}\", my_mutex); // Now it says: Mutex { data: 6 }\n}\n```\n\nYou have to be careful with a `Mutex` because if another variable tries to `lock` it, it will wait:\n\n```rust\nuse std::sync::Mutex;\n\nfn main() {\n    let my_mutex = Mutex::new(5);\n    let mut mutex_changer = my_mutex.lock().unwrap(); // mutex_changer has the lock\n    let mut other_mutex_changer = my_mutex.lock().unwrap(); // other_mutex_changer wants the lock\n                                                            // the program is waiting\n                                                            // and waiting\n                                                            // and will wait forever.\n\n    println!(\"This will never print...\");\n}\n```\n\nOne other method is `try_lock()`. Then it will try once, and if it doesn't get the lock it will give up. Don't do `try_lock().unwrap()`, because it will panic if it doesn't work. `if let` or `match` is better:\n\n```rust\nuse std::sync::Mutex;\n\nfn main() {\n    let my_mutex = Mutex::new(5);\n    let mut mutex_changer = my_mutex.lock().unwrap();\n    let mut other_mutex_changer = my_mutex.try_lock(); // try to get the lock\n\n    if let Ok(value) = other_mutex_changer {\n        println!(\"The MutexGuard has: {}\", value)\n    } else {\n        println!(\"Didn't get the lock\")\n    }\n}\n```\n\nAlso, you don't need to make a variable to change the `Mutex`. You can just do this:\n\n```rust\nuse std::sync::Mutex;\n\nfn main() {\n    let my_mutex = Mutex::new(5);\n\n    *my_mutex.lock().unwrap() = 6;\n\n    println!(\"{:?}\", my_mutex);\n}\n```\n\n`*my_mutex.lock().unwrap() = 6;` means \"unlock my_mutex and make it 6\". There is no variable that holds it so you don't need to call `std::mem::drop`. You can do it 100 times if you want - it doesn't matter:\n\n```rust\nuse std::sync::Mutex;\n\nfn main() {\n    let my_mutex = Mutex::new(5);\n\n    for _ in 0..100 {\n        *my_mutex.lock().unwrap() += 1; // locks and unlocks 100 times\n    }\n\n    println!(\"{:?}\", my_mutex);\n}\n```\n\n### RwLock\n\n`RwLock` means \"read write lock\". It is like a `Mutex` but also like a `RefCell`. You use `.write().unwrap()` instead of `.lock().unwrap()` to change it. But you can also use `.read().unwrap()` to get read access. It is like `RefCell` because it follows the rules:\n\n- many `.read()` variables is okay,\n- one `.write()` variable is okay,\n- but more than one `.write()` or `.read()` together with `.write()` is not okay.\n\nThe program will run forever if you try to `.write()` when you can't get access:\n\n```rust\nuse std::sync::RwLock;\n\nfn main() {\n    let my_rwlock = RwLock::new(5);\n\n    let read1 = my_rwlock.read().unwrap(); // one .read() is fine\n    let read2 = my_rwlock.read().unwrap(); // two .read()s is also fine\n\n    println!(\"{:?}, {:?}\", read1, read2);\n\n    let write1 = my_rwlock.write().unwrap(); // uh oh, now the program will wait forever\n}\n```\n\nSo we use `std::mem::drop`, just like in a `Mutex`.\n\n```rust\nuse std::sync::RwLock;\nuse std::mem::drop; // We will use drop() many times\n\nfn main() {\n    let my_rwlock = RwLock::new(5);\n\n    let read1 = my_rwlock.read().unwrap();\n    let read2 = my_rwlock.read().unwrap();\n\n    println!(\"{:?}, {:?}\", read1, read2);\n\n    drop(read1);\n    drop(read2); // we dropped both, so we can use .write() now\n\n    let mut write1 = my_rwlock.write().unwrap();\n    *write1 = 6;\n    drop(write1);\n    println!(\"{:?}\", my_rwlock);\n}\n```\n\nAnd you can use `try_read()` and `try_write()` too.\n\n```rust\nuse std::sync::RwLock;\n\nfn main() {\n    let my_rwlock = RwLock::new(5);\n\n    let read1 = my_rwlock.read().unwrap();\n    let read2 = my_rwlock.read().unwrap();\n\n    if let Ok(mut number) = my_rwlock.try_write() {\n        *number += 10;\n        println!(\"Now the number is {}\", number);\n    } else {\n        println!(\"Couldn't get write access, sorry!\")\n    };\n}\n```\n\n## Cow\n\nCow is a very convenient enum. It means \"clone on write\" and lets you return a `&str` if you don't need a `String`, and a `String` if you need it. (It can also do the same with arrays vs. Vecs, etc.)\n\nTo understand it, let's look at the signature. It says:\n\n```rust\npub enum Cow<'a, B>\nwhere\n    B: 'a + ToOwned + ?Sized,\n {\n    Borrowed(&'a B),\n    Owned(<B as ToOwned>::Owned),\n}\n\nfn main() {}\n```\n\nYou know right away that `'a` means it works with references. The `ToOwned` trait means that it is a type that can be turned into an owned type. For example, `str` is usually a reference (`&str`) and you can turn it into an owned `String`.\n\nNext is `?Sized`. This means \"maybe Sized, but maybe not\". Almost every type in Rust is Sized, but types like `str` are not. That is why we need a `&` for a `str`, because the compiler doesn't know the size. So if you want a trait that can use something like a `str`, you add `?Sized.`\n\nNext are the `enum` variants. They are `Borrowed` and `Owned`.\n\nImagine that you have a function that returns `Cow<'static, str>`. If you tell the function to return `\"My message\".into()`, it will look at the type: \"My message\" is a `str`. This is a `Borrowed` type, so it chooses `Borrowed(&'a B)`. So it becomes `Cow::Borrowed(&'static str)`.\n\nAnd if you give it a `format!(\"{}\", \"My message\").into()` then it will look at the type. This time it is a `String`, because `format!` makes a `String`. So this time it will select \"Owned\".\n\nHere is an example to test `Cow`. We will put a number into a function that returns a `Cow<'static, str>`. Depending on the number, it will create a `&str` or a `String`. Then it uses `.into()` to turn it into a `Cow`. When you do that, it will choose either `Cow::Borrowed` or `Cow::Owned`. Then we will match to see which one it chose.\n\n```rust\nuse std::borrow::Cow;\n\nfn modulo_3(input: u8) -> Cow<'static, str> {\n    match input % 3 {\n        0 => \"Remainder is 0\".into(),\n        1 => \"Remainder is 1\".into(),\n        remainder => format!(\"Remainder is {}\", remainder).into(),\n    }\n}\n\nfn main() {\n    for number in 1..=6 {\n        match modulo_3(number) {\n            Cow::Borrowed(message) => println!(\"{} went in. The Cow is borrowed with this message: {}\", number, message),\n            Cow::Owned(message) => println!(\"{} went in. The Cow is owned with this message: {}\", number, message),\n        }\n    }\n}\n```\n\nThis prints:\n\n```text\n1 went in. The Cow is borrowed with this message: Remainder is 1\n2 went in. The Cow is owned with this message: Remainder is 2\n3 went in. The Cow is borrowed with this message: Remainder is 0\n4 went in. The Cow is borrowed with this message: Remainder is 1\n5 went in. The Cow is owned with this message: Remainder is 2\n6 went in. The Cow is borrowed with this message: Remainder is 0\n```\n\n`Cow` has some other methods like `into_owned` or `into_borrowed` so you can change it if you need to.\n\n## Type aliases\n\nA type alias means \"giving a new name to another type\". Type aliases are very easy. Usually you use them when you have a very long type and don't want to write it every time. It is also good when you want to give a type a better name that is easy to remember. Here are two examples of type aliases.\n\nHere is a type that is not difficult, but you want to make your code easier to understand for other people (or for you):\n\n```rust\ntype CharacterVec = Vec<char>;\n\nfn main() {}\n```\n\nHere's a type that is very difficult to read:\n\n```rust\n// this return type is extremely long\nfn returns<'a>(input: &'a Vec<char>) -> std::iter::Take<std::iter::Skip<std::slice::Iter<'a, char>>> {\n    input.iter().skip(4).take(5)\n}\n\nfn main() {}\n```\n\nSo you can change it to this:\n\n```rust\ntype SkipFourTakeFive<'a> = std::iter::Take<std::iter::Skip<std::slice::Iter<'a, char>>>;\n\nfn returns<'a>(input: &'a Vec<char>) -> SkipFourTakeFive {\n    input.iter().skip(4).take(5)\n}\n\nfn main() {}\n```\n\nOf course, you can also import items to make the type shorter:\n\n```rust\nuse std::iter::{Take, Skip};\nuse std::slice::Iter;\n\nfn returns<'a>(input: &'a Vec<char>) -> Take<Skip<Iter<'a, char>>> {\n    input.iter().skip(4).take(5)\n}\n\nfn main() {}\n```\n\nSo you can decide what looks best in your code depending on what you like.\n\nNote that this doesn't create an actual new type. It's just a name to use instead of an existing type. So if you write `type File = String;`, the compiler just sees a `String`. So this will print `true`:\n\n```rust\ntype File = String;\n\nfn main() {\n    let my_file = File::from(\"I am file contents\");\n    let my_string = String::from(\"I am file contents\");\n    println!(\"{}\", my_file == my_string);\n}\n```\n\nSo what if you want an actual new type?\n\nIf you want a new file type that the compiler sees as a `File`, you can put it in a struct. (This is actually called the `newtype` idiom)\n\n```rust\nstruct File(String); // File is a wrapper around String\n\nfn main() {\n    let my_file = File(String::from(\"I am file contents\"));\n    let my_string = String::from(\"I am file contents\");\n}\n```\n\nNow this will not work, because they are two different types:\n\n```rust\nstruct File(String); // File is a wrapper around String\n\nfn main() {\n    let my_file = File(String::from(\"I am file contents\"));\n    let my_string = String::from(\"I am file contents\");\n    println!(\"{}\", my_file == my_string);  // ⚠️ cannot compare File with String\n}\n```\n\nIf you want to compare the String inside, you can use my_file.0:\n\n```rust\nstruct File(String);\n\nfn main() {\n    let my_file = File(String::from(\"I am file contents\"));\n    let my_string = String::from(\"I am file contents\");\n    println!(\"{}\", my_file.0 == my_string); // my_file.0 is a String, so this prints true\n}\n```\n\nAnd now this type doesn't have any traits, so you can implement them yourself. This is not too surprising:\n\n```rust\n#[derive(Clone, Debug)]\nstruct File(String);\n```\n\nSo when you use the `File` type here you can clone it and Debug print it, but it doesn't have the traits of String unless you use `.0` to get to the String inside it. But in other people's code you can only use `.0` if it's marked `pub` for public. And that's why these sorts of types use the `Deref` trait a lot. We will learn about both `pub` and `Deref` later.\n\n### Importing and renaming inside a function\n\nUsually you write `use` at the top of the program, like this:\n\n```rust\nuse std::cell::{Cell, RefCell};\n\nfn main() {}\n```\n\nBut we saw that you can do this anywhere, especially in functions with enums that have long names. Here is an example.\n\n```rust\nenum MapDirection {\n    North,\n    NorthEast,\n    East,\n    SouthEast,\n    South,\n    SouthWest,\n    West,\n    NorthWest,\n}\n\nfn main() {}\n\nfn give_direction(direction: &MapDirection) {\n    match direction {\n        MapDirection::North => println!(\"You are heading north.\"),\n        MapDirection::NorthEast => println!(\"You are heading northeast.\"),\n        // So much more left to type...\n        // ⚠️ because we didn't write every possible variant\n    }\n}\n```\n\nSo now we will import MapDirection inside the function. That means that inside the function you can just write `North` and so on.\n\n```rust\nenum MapDirection {\n    North,\n    NorthEast,\n    East,\n    SouthEast,\n    South,\n    SouthWest,\n    West,\n    NorthWest,\n}\n\nfn main() {}\n\nfn give_direction(direction: &MapDirection) {\n    use MapDirection::*; // Import everything in MapDirection\n    let m = \"You are heading\";\n\n    match direction {\n        North => println!(\"{} north.\", m),\n        NorthEast => println!(\"{} northeast.\", m),\n        // This is a bit better\n        // ⚠️\n    }\n}\n```\n\nWe've seen that `::*` means \"import everything after the ::\". In our case, that means `North`, `NorthEast`...and all the way to `NorthWest`. When you import other people's code you can do that too, but if the code is very large you might have problems. What if it has some items that are the same as your code? So it's usually best to not use `::*` all the time unless you're sure. A lot of times you see  a section called `prelude` in other people's code with all the main items you probably need. So then you will usually use it like this: `name::prelude::*`. We will talk about this more in the sections for `modules` and `crates`.\n\nYou can also use `as` to change the name. For example, maybe you are using someone else's code and you can't change the names in an enum:\n\n```rust\nenum FileState {\n    CannotAccessFile,\n    FileOpenedAndReady,\n    NoSuchFileExists,\n    SimilarFileNameInNextDirectory,\n}\n\nfn main() {}\n```\n\nSo then you can 1) import everything and 2) change the names:\n\n```rust\nenum FileState {\n    CannotAccessFile,\n    FileOpenedAndReady,\n    NoSuchFileExists,\n    SimilarFileNameInNextDirectory,\n}\n\nfn give_filestate(input: &FileState) {\n    use FileState::{\n        CannotAccessFile as NoAccess,\n        FileOpenedAndReady as Good,\n        NoSuchFileExists as NoFile,\n        SimilarFileNameInNextDirectory as OtherDirectory\n    };\n    match input {\n        NoAccess => println!(\"Can't access file.\"),\n        Good => println!(\"Here is your file\"),\n        NoFile => println!(\"Sorry, there is no file by that name.\"),\n        OtherDirectory => println!(\"Please check the other directory.\"),\n    }\n}\n\nfn main() {}\n```\n\nSo now you can write `OtherDirectory` instead of `FileState::SimilarFileNameInNextDirectory`.\n\n## The todo! macro\n\nSometimes you want to write code in general to help you imagine your project. For example, imagine a simple project to do something with books. Here's what you think as you write it:\n\n```rust\nstruct Book {} // Okay, first I need a book struct.\n               // Nothing in there yet - will add later\n\nenum BookType { // A book can be hardcover or softcover, so add an enum\n    HardCover,\n    SoftCover,\n}\n\nfn get_book(book: &Book) -> Option<String> {} // ⚠️ get_book should take a &Book and return an Option<String>\n\nfn delete_book(book: Book) -> Result<(), String> {} // delete_book should take a Book and return a Result...\n                                                    // TODO: impl block and make these functions methods...\nfn check_book_type(book_type: &BookType) { // Let's make sure the match statement works\n    match book_type {\n        BookType::HardCover => println!(\"It's hardcover\"),\n        BookType::SoftCover => println!(\"It's softcover\"),\n    }\n}\n\nfn main() {\n    let book_type = BookType::HardCover;\n    check_book_type(&book_type); // Okay, let's check this function!\n}\n```\n\nBut Rust is not happy with `get_book` and `delete_book`. It says:\n\n```text\nerror[E0308]: mismatched types\n  --> src\\main.rs:32:29\n   |\n32 | fn get_book(book: &Book) -> Option<String> {}\n   |    --------                 ^^^^^^^^^^^^^^ expected enum `std::option::Option`, found `()`\n   |    |\n   |    implicitly returns `()` as its body has no tail or `return` expression\n   |\n   = note:   expected enum `std::option::Option<std::string::String>`\n           found unit type `()`\n\nerror[E0308]: mismatched types\n  --> src\\main.rs:34:31\n   |\n34 | fn delete_book(book: Book) -> Result<(), String> {}\n   |    -----------                ^^^^^^^^^^^^^^^^^^ expected enum `std::result::Result`, found `()`\n   |    |\n   |    implicitly returns `()` as its body has no tail or `return` expression\n   |\n   = note:   expected enum `std::result::Result<(), std::string::String>`\n           found unit type `()`\n```\n\nBut you don't care about `get_book` and `delete_book` right now. This is where you can use `todo!()`. If you add that to the function, Rust will not complain, and will compile.\n\n```rust\nstruct Book {}\n\nfn get_book(book: &Book) -> Option<String> {\n    todo!() // todo means \"I will do it later, please be quiet\"\n}\n\nfn delete_book(book: Book) -> Result<(), String> {\n    todo!()\n}\n\nfn main() {}\n```\n\nSo now the code compiles and you can see the result of `check_book_type`: `It's hardcover`.\n\nBut careful, because it only compiles - you can't use the function. If you call a function with `todo!()` inside it, it will panic.\n\nAlso, `todo!()` functions still need real input and output types. If you just write this, it will not compile:\n\n```rust\nstruct Book {}\n\nfn get_book(book: &Book) -> WorldsBestType { // ⚠️\n    todo!()\n}\n\nfn main() {}\n```\n\nIt will say:\n\n```text\nerror[E0412]: cannot find type `WorldsBestType` in this scope\n  --> src\\main.rs:32:29\n   |\n32 | fn get_book(book: &Book) -> WorldsBestType {\n   |                             ^^^^^^^^^^^^^^ not found in this scope\n```\n\n`todo!()` is actually the same as another macro: `unimplemented!()`. Programmers were using `unimplemented!()` a lot but it was long to type, so they created `todo!()` which is shorter.\n\n## Rc\n\nRc means \"reference counter\". You know that in Rust, every variable can only have one owner. That is why this doesn't work:\n\n```rust\nfn takes_a_string(input: String) {\n    println!(\"It is: {}\", input)\n}\n\nfn also_takes_a_string(input: String) {\n    println!(\"It is: {}\", input)\n}\n\nfn main() {\n    let user_name = String::from(\"User MacUserson\");\n\n    takes_a_string(user_name);\n    also_takes_a_string(user_name); // ⚠️\n}\n```\n\nAfter `takes_a_string` takes `user_name`, you can't use it anymore. Here that is no problem: you can just give it `user_name.clone()`. But sometimes a variable is part of a struct, and maybe you can't clone the struct. Or maybe the `String` is really long and you don't want to clone it. These are some reasons for `Rc`, which lets you have more than one owner. An `Rc` is like a good office worker: `Rc` writes down who has ownership, and how many. Then once the number of owners goes down to 0, the variable can disappear.\n\nHere's how you use an `Rc`. First imagine two structs: one called `City`, and another called `CityData`. `City` has information for one city, and `CityData` puts all the cities together in `Vec`s.\n\n```rust\n#[derive(Debug)]\nstruct City {\n    name: String,\n    population: u32,\n    city_history: String,\n}\n\n#[derive(Debug)]\nstruct CityData {\n    names: Vec<String>,\n    histories: Vec<String>,\n}\n\nfn main() {\n    let calgary = City {\n        name: \"Calgary\".to_string(),\n        population: 1_200_000,\n           // Pretend that this string is very very long\n        city_history: \"Calgary began as a fort called Fort Calgary that...\".to_string(),\n    };\n\n    let canada_cities = CityData {\n        names: vec![calgary.name], // This is using calgary.name, which is short\n        histories: vec![calgary.city_history], // But this String is very long\n    };\n\n    println!(\"Calgary's history is: {}\", calgary.city_history);  // ⚠️\n}\n```\n\nOf course, it doesn't work because `canada_cities` now owns the data and `calgary` doesn't. It says:\n\n```text\nerror[E0382]: borrow of moved value: `calgary.city_history`\n  --> src\\main.rs:27:42\n   |\n24 |         histories: vec![calgary.city_history], // But this String is very long\n   |                         -------------------- value moved here\n...\n27 |     println!(\"Calgary's history is: {}\", calgary.city_history);  // ⚠️\n   |                                          ^^^^^^^^^^^^^^^^^^^^ value borrowed here after move\n   |\n   = note: move occurs because `calgary.city_history` has type `std::string::String`, which does not implement the `Copy` trait\n```\n\nWe can clone the name: `names: vec![calgary.name.clone()]` but we don't want to clone the `city_history`, which is long. So we can use an `Rc`.\n\nAdd the `use` declaration:\n\n```rust\nuse std::rc::Rc;\n\nfn main() {}\n```\n\nThen put `Rc` around `String`.\n\n```rust\nuse std::rc::Rc;\n\n#[derive(Debug)]\nstruct City {\n    name: String,\n    population: u32,\n    city_history: Rc<String>,\n}\n\n#[derive(Debug)]\nstruct CityData {\n    names: Vec<String>,\n    histories: Vec<Rc<String>>,\n}\n\nfn main() {}\n```\n\nTo add a new reference, you have to `clone` the `Rc`. But hold on, didn't we want to avoid using `.clone()`? Not exactly: we didn't want to clone the whole String. But a clone of an `Rc` just clones the pointer - it's basically free. It's like putting a name sticker on a box of books to show that two people own it, instead of making a whole new box.\n\nYou can clone an `Rc` called `item` with `item.clone()` or with `Rc::clone(&item)`. So calgary.city_history has 2 owners. We can check the number of owners with `Rc::strong_count(&item)`. Also let's add a new owner. Now our code looks like this:\n\n```rust\nuse std::rc::Rc;\n\n#[derive(Debug)]\nstruct City {\n    name: String,\n    population: u32,\n    city_history: Rc<String>, // String inside an Rc\n}\n\n#[derive(Debug)]\nstruct CityData {\n    names: Vec<String>,\n    histories: Vec<Rc<String>>, // A Vec of Strings inside Rcs\n}\n\nfn main() {\n    let calgary = City {\n        name: \"Calgary\".to_string(),\n        population: 1_200_000,\n           // Pretend that this string is very very long\n        city_history: Rc::new(\"Calgary began as a fort called Fort Calgary that...\".to_string()), // Rc::new() to make the Rc\n    };\n\n    let canada_cities = CityData {\n        names: vec![calgary.name],\n        histories: vec![calgary.city_history.clone()], // .clone() to increase the count\n    };\n\n    println!(\"Calgary's history is: {}\", calgary.city_history);\n    println!(\"{}\", Rc::strong_count(&calgary.city_history));\n    let new_owner = calgary.city_history.clone();\n}\n```\n\nThis prints `2`. And `new_owner` is now an `Rc<String>`. Now if we use `println!(\"{}\", Rc::strong_count(&calgary.city_history));`, we get `3`.\n\nSo if there are strong pointers, are there weak pointers? Yes, there are. Weak pointers are useful because if two `Rc`s point at each other, they can't die. This is called a \"reference cycle\". If item 1 has an Rc to item 2, and item 2 has an Rc to item 1, they can't get to 0. In this case you want to use weak references. Then `Rc` will count the references, but if it only has weak references then it can die. You use `Rc::downgrade(&item)` instead of `Rc::clone(&item)` to make weak references. Also, you use `Rc::weak_count(&item)` to see the weak count.\n\n## Multiple threads\n\nIf you use multiple threads, you can do many things at the same time. Modern computers have more than one core so they can do more than one thing at the same time, and Rust lets you use them. Rust uses threads that are called \"OS threads\". OS thread means the operating system creates the thread on a different core. (Some other languages use \"green threads\", which are less powerful)\n\n\nYou create threads with `std::thread::spawn` and then a closure to tell it what to do. Threads are interesting because they run at the same time, and you can test it to see what happens. Here is a simple example:\n\n```rust\nfn main() {\n    std::thread::spawn(|| {\n        println!(\"I am printing something\");\n    });\n}\n```\n\nIf you run this, it will be different every time. Sometimes it will print, and sometimes it won't print (this depends on your computer speed too). That is because sometimes `main()` finishes before the thread finishes. And when `main()` finishes, the program is over. This is easier to see in a `for` loop:\n\n```rust\nfn main() {\n    for _ in 0..10 { // set up ten threads\n        std::thread::spawn(|| {\n            println!(\"I am printing something\");\n        });\n    }   // Now the threads start.\n}       // How many can finish before main() ends here?\n```\n\nUsually about four threads will print before `main` ends, but it is always different. If your computer is faster then it might not print any. Also, sometimes the threads will panic:\n\n```text\nthread 'thread 'I am printing something\nthread '<unnamed><unnamed>thread '' panicked at '<unnamed>I am printing something\n' panicked at 'thread '<unnamed>cannot access stdout during shutdown' panicked at '<unnamed>thread 'cannot access stdout during\nshutdown\n```\n\nThis is the error when the thread tries to do something right when the program is shutting down.\n\nYou can give the computer something to do so it won't shut down right away:\n\n```rust\nfn main() {\n    for _ in 0..10 {\n        std::thread::spawn(|| {\n            println!(\"I am printing something\");\n        });\n    }\n    for _ in 0..1_000_000 { // make the program declare \"let x = 9\" one million times\n                            // It has to finish this before it can exit the main function\n        let _x = 9;\n    }\n}\n```\n\nBut that is a silly way to give the threads time to finish. The better way is to bind the threads to a variable. If you add `let`, then you will create a `JoinHandle`. You can see this in the signature for `spawn`:\n\n```text\npub fn spawn<F, T>(f: F) -> JoinHandle<T>\nwhere\n    F: FnOnce() -> T,\n    F: Send + 'static,\n    T: Send + 'static,\n```\n\n(`f` is the closure - we will learn how to put closures into our functions later)\n\nSo now we have a `JoinHandle` every time.\n\n```rust\nfn main() {\n    for _ in 0..10 {\n        let handle = std::thread::spawn(|| {\n            println!(\"I am printing something\");\n        });\n\n    }\n}\n```\n\n`handle` is now a `JoinHandle`. What do we do with it? We use a method called `.join()`. This method means \"wait until all the threads are done\" (it waits for the threads to join it). So now just write `handle.join()` and it will wait for each of the threads to finish.\n\n```rust\nfn main() {\n    for _ in 0..10 {\n        let handle = std::thread::spawn(|| {\n            println!(\"I am printing something\");\n        });\n\n        handle.join(); // Wait for the threads to finish\n    }\n}\n```\n\nNow we will learn about the three types of closures. The three types are:\n\n- `FnOnce`: takes the whole value\n- `FnMut`: takes a mutable reference\n- `Fn`: takes a regular reference\n\nA closure will try to use `Fn` if it can. But if it needs to change the value it will use `FnMut`, and if it needs to take the whole value, it will use `FnOnce`. `FnOnce` is a good name because it explains what it does: it takes the value once, and then it can't take it again.\n\nHere is an example:\n\n```rust\nfn main() {\n    let my_string = String::from(\"I will go into the closure\");\n    let my_closure = || println!(\"{}\", my_string);\n    my_closure();\n    my_closure();\n}\n```\n\n`String` is not `Copy`, so `my_closure()` is `Fn`: it takes a reference.\n\nIf we change `my_string`, it will be `FnMut`.\n\n```rust\nfn main() {\n    let mut my_string = String::from(\"I will go into the closure\");\n    let mut my_closure = || {\n        my_string.push_str(\" now\");\n        println!(\"{}\", my_string);\n    };\n    my_closure();\n    my_closure();\n}\n```\n\nThis prints:\n\n```text\nI will go into the closure now\nI will go into the closure now now\n```\n\nAnd if you take by value, then it will be `FnOnce`.\n\n```rust\nfn main() {\n    let my_vec: Vec<i32> = vec![8, 9, 10];\n    let my_closure = || {\n        my_vec\n            .into_iter() // into_iter takes ownership\n            .map(|x| x as u8) // turn it into u8\n            .map(|x| x * 2) // multiply by 2\n            .collect::<Vec<u8>>() // collect into a Vec\n    };\n    let new_vec = my_closure();\n    println!(\"{:?}\", new_vec);\n}\n```\n\nWe took by value, so we can't run `my_closure()` more than once. That is where the name comes from.\n\nSo now back to threads. Let's try to use a value from outside:\n\n```rust\nfn main() {\n    let mut my_string = String::from(\"Can I go inside the thread?\");\n\n    let handle = std::thread::spawn(|| {\n        println!(\"{}\", my_string); // ⚠️\n    });\n\n    handle.join();\n}\n```\n\nThe compiler says that this won't work.\n\n```text\nerror[E0373]: closure may outlive the current function, but it borrows `my_string`, which is owned by the current function\n  --> src\\main.rs:28:37\n   |\n28 |     let handle = std::thread::spawn(|| {\n   |                                     ^^ may outlive borrowed value `my_string`\n29 |         println!(\"{}\", my_string);\n   |                        --------- `my_string` is borrowed here\n   |\nnote: function requires argument type to outlive `'static`\n  --> src\\main.rs:28:18\n   |\n28 |       let handle = std::thread::spawn(|| {\n   |  __________________^\n29 | |         println!(\"{}\", my_string);\n30 | |     });\n   | |______^\nhelp: to force the closure to take ownership of `my_string` (and any other referenced variables), use the `move` keyword\n   |\n28 |     let handle = std::thread::spawn(move || {\n   |                                     ^^^^^^^\n```\n\nIt is a long message, but helpful: it says to ``use the `move` keyword``. The problem is that we can do anything to `my_string` while the thread is using it, but it doesn't own it. That would be unsafe.\n\nLet's try something else that doesn't work:\n\n```rust\nfn main() {\n    let mut my_string = String::from(\"Can I go inside the thread?\");\n\n    let handle = std::thread::spawn(|| {\n        println!(\"{}\", my_string); // now my_string is being used as a reference\n    });\n\n    std::mem::drop(my_string);  // ⚠️ We try to drop it here. But the thread still needs it.\n\n    handle.join();\n}\n```\n\nSo you have to take the value with `move`. Now it is safe:\n\n```rust\nfn main() {\n    let mut my_string = String::from(\"Can I go inside the thread?\");\n\n    let handle = std::thread::spawn(move|| {\n        println!(\"{}\", my_string);\n    });\n\n    std::mem::drop(my_string);  // ⚠️ we can't drop, because handle has it. So this won't work\n\n    handle.join();\n}\n```\n\nSo we delete the `std::mem::drop`, and now it is okay. `handle` takes `my_string` and our code is safe.\n\n```rust\nfn main() {\n    let my_string = String::from(\"Can I go inside the thread?\");\n\n    let handle = std::thread::spawn(move|| {\n        println!(\"{}\", my_string);\n    });\n\n    handle.join().unwrap();\n}\n```\n\nSo just remember: if you need a value in a thread from outside the thread, you need to use `move`.\n\n\n\n## Closures in functions\n\nClosures are great. So how do we put them into our own functions?\n\nYou can make your own functions that take closures, but inside them it is less free and you have to decide the type. Outside a function a closure can decide by itself between `Fn`, `FnMut` and `FnOnce`, but inside you have to choose one. The best way to understand is to look at a few function signatures. Here is the one for `.all()`. We remember that it checks an iterator to see if everything is `true` (depending on what you decide is `true` or `false`). Part of its signature says this:\n\n\n```rust\n    fn all<F>(&mut self, f: F) -> bool    // 🚧\n    where\n        F: FnMut(Self::Item) -> bool,\n```\n\n`fn all<F>`: this tells you that there is a generic type `F`. A closure is always generic because every time it is a different type.\n\n`(&mut self, f: F)`: `&mut self` tells you that it's a method. `f: F` is usually what you see for a closure: this is the variable name and the type.  Of course, there is nothing special about `f` and `F` and they could be different names. You could write `my_closure: Closure` if you wanted - it doesn't matter. But in signatures you almost always see `f: F`.\n\nNext is the part about the closure: `F: FnMut(Self::Item) -> bool`. Here it decides that the closure is `FnMut`, so it can change the values. It changes the values of `Self::Item`, which is the iterator that it takes. And it has to return `true` or `false`.\n\nHere is a much simpler signature with a closure:\n\n```rust\nfn do_something<F>(f: F)    // 🚧\nwhere\n    F: FnOnce(),\n{\n    f();\n}\n```\n\nThis just says that it takes a closure, takes the value (`FnOnce` = takes the value), and doesn't return anything. So now we can call this closure that takes nothing and do whatever we like. We will create a `Vec` and then iterate over it just to show what we can do now.\n\n```rust\nfn do_something<F>(f: F)\nwhere\n    F: FnOnce(),\n{\n    f();\n}\n\nfn main() {\n    let some_vec = vec![9, 8, 10];\n    do_something(|| {\n        some_vec\n            .into_iter()\n            .for_each(|x| println!(\"The number is: {}\", x));\n    })\n}\n```\n\nFor a more real example, we will create a `City` struct again. This time the `City` struct has more data about years and populations. It has a `Vec<u32>` for all the years, and another `Vec<u32>` for all the populations.\n\n`City` has two functions: `new()` to create a new `City`, and `.city_data()` which has a closure. When we use `.city_data()`, it gives us the years and the populations and a closure, so we can do what we want with the data. The closure type is `FnMut` so we can change the data. It looks like this:\n\n```rust\n#[derive(Debug)]\nstruct City {\n    name: String,\n    years: Vec<u32>,\n    populations: Vec<u32>,\n}\n\nimpl City {\n    fn new(name: &str, years: Vec<u32>, populations: Vec<u32>) -> Self {\n\n        Self {\n            name: name.to_string(),\n            years,\n            populations,\n        }\n    }\n\n    fn city_data<F>(&mut self, mut f: F) // We bring in self, but only f is generic F. f is the closure\n\n    where\n        F: FnMut(&mut Vec<u32>, &mut Vec<u32>), // The closure takes mutable vectors of u32\n                                                // which are the year and population data\n    {\n        f(&mut self.years, &mut self.populations) // Finally this is the actual function. It says\n                                                  // \"use a closure on self.years and self.populations\"\n                                                  // We can do whatever we want with the closure\n    }\n}\n\nfn main() {\n    let years = vec![\n        1372, 1834, 1851, 1881, 1897, 1925, 1959, 1989, 2000, 2005, 2010, 2020,\n    ];\n    let populations = vec![\n        3_250, 15_300, 24_000, 45_900, 58_800, 119_800, 283_071, 478_974, 400_378, 401_694,\n        406_703, 437_619,\n    ];\n    // Now we can create our city\n    let mut tallinn = City::new(\"Tallinn\", years, populations);\n\n    // Now we have a .city_data() method that has a closure. We can do anything we want.\n\n    // First let's put the data for 5 years together and print it.\n    tallinn.city_data(|city_years, city_populations| { // We can call the input anything we want\n        let new_vec = city_years\n            .into_iter()\n            .zip(city_populations.into_iter()) // Zip the two together\n            .take(5)                           // but only take the first 5\n            .collect::<Vec<(_, _)>>(); // Tell Rust to decide the type inside the tuple\n        println!(\"{:?}\", new_vec);\n    });\n\n    // Now let's add some data for the year 2030\n    tallinn.city_data(|x, y| { // This time we just call the input x and y\n        x.push(2030);\n        y.push(500_000);\n    });\n\n    // We don't want the 1834 data anymore\n    tallinn.city_data(|x, y| {\n        let position_option = x.iter().position(|x| *x == 1834);\n        if let Some(position) = position_option {\n            println!(\n                \"Going to delete {} at position {:?} now.\",\n                x[position], position\n            ); // Confirm that we delete the right item\n            x.remove(position);\n            y.remove(position);\n        }\n    });\n\n    println!(\n        \"Years left are {:?}\\nPopulations left are {:?}\",\n        tallinn.years, tallinn.populations\n    );\n}\n```\n\nThis will print the result of all the times we called `.city_data().` It is:\n\n```text\n[(1372, 3250), (1834, 15300), (1851, 24000), (1881, 45900), (1897, 58800)]\nGoing to delete 1834 at position 1 now.\nYears left are [1372, 1851, 1881, 1897, 1925, 1959, 1989, 2000, 2005, 2010, 2020, 2030]\nPopulations left are [3250, 24000, 45900, 58800, 119800, 283071, 478974, 400378, 401694, 406703, 437619, 500000]\n```\n\n\n## impl Trait\n\n`impl Trait` is similar to generics. You remember that generics use a type `T` (or any other name) which then gets decided when the program compiles. First let's look at a concrete type:\n\n```rust\nfn gives_higher_i32(one: i32, two: i32) {\n    let higher = if one > two { one } else { two };\n    println!(\"{} is higher.\", higher);\n}\n\nfn main() {\n    gives_higher_i32(8, 10);\n}\n```\n\nThis prints: `10 is higher.`.\n\nBut this only takes `i32`, so now we will make it generic. We need to compare and we need to print with `{}`, so our type T needs `PartialOrd` and `Display`. Remember, this means \"only take types that already have `PartialOrd` and `Display`\".\n\n```rust\nuse std::fmt::Display;\n\nfn gives_higher_i32<T: PartialOrd + Display>(one: T, two: T) {\n    let higher = if one > two { one } else { two };\n    println!(\"{} is higher.\", higher);\n}\n\nfn main() {\n    gives_higher_i32(8, 10);\n}\n```\n\nNow let's look at `impl Trait`, which is similar. Instead of a type `T`, we can bring in a type `impl Trait`. Then it will take in a type that implements that trait. It is almost the same:\n\n```rust\nfn prints_it(input: impl Into<String> + std::fmt::Display) { // Takes anything that can turn into a String and has Display\n    println!(\"You can print many things, including {}\", input);\n}\n\nfn main() {\n    let name = \"Tuon\";\n    let string_name = String::from(\"Tuon\");\n    prints_it(name);\n    prints_it(string_name);\n}\n```\n\nHowever, the more interesting part is that we can return `impl Trait`, and that lets us return closures because their function signatures are traits. You can see this in the signatures for methods that have them. For example, this is the signature for `.map()`:\n\n```rust\nfn map<B, F>(self, f: F) -> Map<Self, F>     // 🚧\n    where\n        Self: Sized,\n        F: FnMut(Self::Item) -> B,\n    {\n        Map::new(self, f)\n    }\n```\n\n`fn map<B, F>(self, f: F)` mean that it takes two generic types. `F` is a function that takes one item from the container implementing `.map()` and `B` is the return type of that function. Then after the `where` we see the trait bounds. (\"Trait bound\" means \"it must have this trait\".) One is `Sized`, and the next is the closure signature. It must be an `FnMut`, and do the closure on `Self::Item`, which is the iterator that you give it. Then it returns `B`.\n\nSo we can do the same thing to return a closure. To return a closure, use `impl` and then the closure signature. Once you return it, you can use it just like a function. Here is a small example of a function that gives you a closure depending on the text you put in. If you put \"double\" or \"triple\" in then it multiplies it by 2 or 3, and otherwise it gives you the same number. Because it's a closure we can do anything we want, so we also print a message.\n\n```rust\nfn returns_a_closure(input: &str) -> impl FnMut(i32) -> i32 {\n    match input {\n        \"double\" => |mut number| {\n            number *= 2;\n            println!(\"Doubling number. Now it is {}\", number);\n            number\n        },\n        \"triple\" => |mut number| {\n            number *= 40;\n            println!(\"Tripling number. Now it is {}\", number);\n            number\n        },\n        _ => |number| {\n            println!(\"Sorry, it's the same: {}.\", number);\n            number\n        },\n    }\n}\n\nfn main() {\n    let my_number = 10;\n\n    // Make three closures\n    let mut doubles = returns_a_closure(\"double\");\n    let mut triples = returns_a_closure(\"triple\");\n    let mut quadruples = returns_a_closure(\"quadruple\");\n\n    doubles(my_number);\n    triples(my_number);\n    quadruples(my_number);\n}\n```\n\nHere is a bit longer example. Let's imagine a game where your character is facing monsters that are stronger at night. We can make an enum called `TimeOfDay` to keep track of the day. Your character is named Simon and has a number called `character_fear`, which is an `f64`. It goes up at night and down during the day. We will make a `change_fear` function that changes his fear, but also does other things like write messages. It could look like this:\n\n\n```rust\nenum TimeOfDay { // just a simple enum\n    Dawn,\n    Day,\n    Sunset,\n    Night,\n}\n\nfn change_fear(input: TimeOfDay) -> impl FnMut(f64) -> f64 { // The function takes a TimeOfDay. It returns a closure.\n                                                             // We use impl FnMut(64) -> f64 to say that it needs to\n                                                             // change the value, and also gives the same type back.\n    use TimeOfDay::*; // So we only have to write Dawn, Day, Sunset, Night\n                      // Instead of TimeOfDay::Dawn, TimeOfDay::Day, etc.\n    match input {\n        Dawn => |x| { // This is the variable character_fear that we give it later\n            println!(\"The morning sun has vanquished the horrible night. You no longer feel afraid.\");\n            println!(\"Your fear is now {}\", x * 0.5);\n            x * 0.5\n        },\n        Day => |x| {\n            println!(\"What a nice day. Maybe put your feet up and rest a bit.\");\n            println!(\"Your fear is now {}\", x * 0.2);\n            x * 0.2\n        },\n        Sunset => |x| {\n            println!(\"The sun is almost down! This is no good.\");\n            println!(\"Your fear is now {}\", x * 1.4);\n            x * 1.4\n        },\n        Night => |x| {\n            println!(\"What a horrible night to have a curse.\");\n            println!(\"Your fear is now {}\", x * 5.0);\n            x * 5.0\n        },\n    }\n}\n\nfn main() {\n    use TimeOfDay::*;\n    let mut character_fear = 10.0; // Start Simon with 10\n\n    let mut daytime = change_fear(Day); // Make four closures here to call every time we want to change Simon's fear.\n    let mut sunset = change_fear(Sunset);\n    let mut night = change_fear(Night);\n    let mut morning = change_fear(Dawn);\n\n    character_fear = daytime(character_fear); // Call the closures on Simon's fear. They give a message and change the fear number.\n                                              // In real life we would have a Character struct and use it as a method instead,\n                                              // like this: character_fear.daytime()\n    character_fear = sunset(character_fear);\n    character_fear = night(character_fear);\n    character_fear = morning(character_fear);\n}\n```\n\nThis prints:\n\n```text\nWhat a nice day. Maybe put your feet up and rest a bit.\nYour fear is now 2\nThe sun is almost down! This is no good.\nYour fear is now 2.8\nWhat a horrible night to have a curse.\nYour fear is now 14\nThe morning sun has vanquished the horrible night. You no longer feel afraid.\nYour fear is now 7\n```\n\n## Arc\n\nYou remember that we used an `Rc` to give a variable more than one owner. If we are doing the same thing in a thread, we need an `Arc`. `Arc` means \"atomic reference counter\". Atomic means that it uses the computer's processor so that data only gets written once each time. This is important because if two threads write data at the same time, you will get the wrong result. For example, imagine if you could do this in Rust:\n\n```rust\n// 🚧\nlet mut x = 10;\n\nfor i in 0..10 { // Thread 1\n    x += 1\n}\nfor i in 0..10 { // Thread 2\n    x += 1\n}\n```\n\nIf Thread 1 and Thread 2 just start together, maybe this will happen:\n\n- Thread 1 sees 10, writes 11. Then Thread 2 sees 11, writes 12. No problem so far.\n- Thread 1 sees 12. At the same time, Thread 2 sees 12. Thread 1 writes 13. And Thread 2 writes 13. Now we have 13, but it should be 14. That's a big problem.\n\nAn `Arc` uses the processor to make sure this doesn't happen, so it is the method you must use when you have threads. You don't want an `Arc` for just one thread though, because `Rc` is a bit faster.\n\nYou can't change data with just an `Arc` though. So you wrap the data in a `Mutex`, and then you wrap the `Mutex` in an `Arc`.\n\nSo let's use a `Mutex` inside an `Arc` to change the value of a number. First let's set up one thread:\n\n```rust\nfn main() {\n\n    let handle = std::thread::spawn(|| {\n        println!(\"The thread is working!\") // Just testing the thread\n    });\n\n    handle.join().unwrap(); // Make the thread wait here until it is done\n    println!(\"Exiting the program\");\n}\n```\n\nSo far this just prints:\n\n```text\nThe thread is working!\nExiting the program\n```\n\nGood. Now let's put it in a `for` loop for `0..5`:\n\n```rust\nfn main() {\n\n    let handle = std::thread::spawn(|| {\n        for _ in 0..5 {\n            println!(\"The thread is working!\")\n        }\n    });\n\n    handle.join().unwrap();\n    println!(\"Exiting the program\");\n}\n```\n\nThis works too. We get the following:\n\n```text\nThe thread is working!\nThe thread is working!\nThe thread is working!\nThe thread is working!\nThe thread is working!\nExiting the program\n```\n\nNow let's make one more thread. Each thread will do the same thing. You can see that the threads are working at the same time. Sometimes it will say `Thread 1 is working!` first, but other times `Thread 2 is working!` is first. This is called **concurrency**, which means \"running together\".\n\n```rust\nfn main() {\n\n    let thread1 = std::thread::spawn(|| {\n        for _ in 0..5 {\n            println!(\"Thread 1 is working!\")\n        }\n    });\n\n    let thread2 = std::thread::spawn(|| {\n        for _ in 0..5 {\n            println!(\"Thread 2 is working!\")\n        }\n    });\n\n    thread1.join().unwrap();\n    thread2.join().unwrap();\n    println!(\"Exiting the program\");\n}\n```\n\nThis will print:\n\n```text\nThread 1 is working!\nThread 1 is working!\nThread 1 is working!\nThread 1 is working!\nThread 1 is working!\nThread 2 is working!\nThread 2 is working!\nThread 2 is working!\nThread 2 is working!\nThread 2 is working!\nExiting the program\n```\n\nNow we want to change the value of `my_number`. Right now it is an `i32`. We will change it to an `Arc<Mutex<i32>>`: an `i32` that can be changed, protected by an `Arc`.\n\n```rust\n// 🚧\nlet my_number = Arc::new(Mutex::new(0));\n```\n\nNow that we have this, we can clone it. Each clone can go into a different thread. We have two threads, so we will make two clones:\n\n```rust\n// 🚧\nlet my_number = Arc::new(Mutex::new(0));\n\nlet my_number1 = Arc::clone(&my_number); // This clone goes into Thread 1\nlet my_number2 = Arc::clone(&my_number); // This clone goes into Thread 2\n```\n\nNow that we have safe clones attached to `my_number`, we can `move` them into other threads with no problem.\n\n```rust\nuse std::sync::{Arc, Mutex};\n\nfn main() {\n    let my_number = Arc::new(Mutex::new(0));\n\n    let my_number1 = Arc::clone(&my_number);\n    let my_number2 = Arc::clone(&my_number);\n\n    let thread1 = std::thread::spawn(move || { // Only the clone goes into Thread 1\n        for _ in 0..10 {\n            *my_number1.lock().unwrap() +=1; // Lock the Mutex, change the value\n        }\n    });\n\n    let thread2 = std::thread::spawn(move || { // Only the clone goes into Thread 2\n        for _ in 0..10 {\n            *my_number2.lock().unwrap() += 1;\n        }\n    });\n\n    thread1.join().unwrap();\n    thread2.join().unwrap();\n    println!(\"Value is: {:?}\", my_number);\n    println!(\"Exiting the program\");\n}\n```\n\nThe program prints:\n\n```text\nValue is: Mutex { data: 20 }\nExiting the program\n```\n\nSo it was a success.\n\nThen we can join the two threads together in a single `for` loop, and make the code smaller.\n\nWe need to save the handles so we can call `.join()` on each one outside of the loop. If we do this inside the loop, it will wait for the first thread to finish before starting the new one.\n\n```rust\nuse std::sync::{Arc, Mutex};\n\nfn main() {\n    let my_number = Arc::new(Mutex::new(0));\n    let mut handle_vec = vec![]; // JoinHandles will go in here\n\n    for _ in 0..2 { // do this twice\n        let my_number_clone = Arc::clone(&my_number); // Make the clone before starting the thread\n        let handle = std::thread::spawn(move || { // Put the clone in\n            for _ in 0..10 {\n                *my_number_clone.lock().unwrap() += 1;\n            }\n        });\n        handle_vec.push(handle); // save the handle so we can call join on it outside of the loop\n                                 // If we don't push it in the vec, it will just die here\n    }\n\n    handle_vec.into_iter().for_each(|handle| handle.join().unwrap()); // call join on all handles\n    println!(\"{:?}\", my_number);\n}\n```\n\nFinally this prints `Mutex { data: 20 }`.\n\nThis looks complicated but `Arc<Mutex<SomeType>>>` is used very often in Rust, so it becomes natural. Also, you can always write your code to make it cleaner. Here is the same code with one more `use` statement and two functions. The functions don't do anything new, but they move some code out of `main()`. You can try rewriting code like this if it is hard to read.\n\n```rust\nuse std::sync::{Arc, Mutex};\nuse std::thread::spawn; // Now we just write spawn\n\nfn make_arc(number: i32) -> Arc<Mutex<i32>> { // Just a function to make a Mutex in an Arc\n    Arc::new(Mutex::new(number))\n}\n\nfn new_clone(input: &Arc<Mutex<i32>>) -> Arc<Mutex<i32>> { // Just a function so we can write new_clone\n    Arc::clone(&input)\n}\n\n// Now main() is easier to read\nfn main() {\n    let mut handle_vec = vec![]; // each handle will go in here\n    let my_number = make_arc(0);\n\n    for _ in 0..2 {\n        let my_number_clone = new_clone(&my_number);\n        let handle = spawn(move || {\n            for _ in 0..10 {\n                let mut value_inside = my_number_clone.lock().unwrap();\n                *value_inside += 1;\n            }\n        });\n        handle_vec.push(handle);    // the handle is done, so put it in the vector\n    }\n\n    handle_vec.into_iter().for_each(|handle| handle.join().unwrap()); // Make each one wait\n\n    println!(\"{:?}\", my_number);\n}\n```\n\n## Channels\n\nA channel is an easy way to use many threads that send to one place. They are fairly popular because they are pretty simple to put together. You can create a channel in Rust with `std::sync::mpsc`. `mpsc` means \"multiple producer, single consumer\", so \"many threads sending to one place\". To start a channel, you use `channel()`. This creates a `Sender` and a `Receiver` that are tied together. You can see this in the function signature:\n\n```rust\n// 🚧\npub fn channel<T>() -> (Sender<T>, Receiver<T>)\n```\n\nSo you have to choose one name for the sender and one for the receiver. Usually you see something like `let (sender, receiver) = channel();` to start. Because it's generic, Rust won't know the type if that is all you write:\n\n```rust\nuse std::sync::mpsc::channel;\n\nfn main() {\n    let (sender, receiver) = channel(); // ⚠️\n}\n```\n\nThe compiler says:\n\n```text\nerror[E0282]: type annotations needed for `(std::sync::mpsc::Sender<T>, std::sync::mpsc::Receiver<T>)`\n  --> src\\main.rs:30:30\n   |\n30 |     let (sender, receiver) = channel();\n   |         ------------------   ^^^^^^^ cannot infer type for type parameter `T` declared on the function `channel`\n   |         |\n   |         consider giving this pattern the explicit type `(std::sync::mpsc::Sender<T>, std::sync::mpsc::Receiver<T>)`, where\nthe type parameter `T` is specified\n```\n\nIt suggests adding a type for the `Sender` and `Receiver`. You can do that if you want:\n\n```rust\nuse std::sync::mpsc::{channel, Sender, Receiver}; // Added Sender and Receiver here\n\nfn main() {\n    let (sender, receiver): (Sender<i32>, Receiver<i32>) = channel();\n}\n```\n\nbut you don't have to. Once you start using the `Sender` and `Receiver`, Rust can guess the type.\n\nSo let's look at the simplest way to use a channel.\n\n```rust\nuse std::sync::mpsc::channel;\n\nfn main() {\n    let (sender, receiver) = channel();\n\n    sender.send(5);\n    receiver.recv(); // recv = receive, not \"rec v\"\n}\n```\n\nNow the compiler knows the type. `sender` is a `Result<(), SendError<i32>>` and `receiver` is a `Result<i32, RecvError>`. So you can use `.unwrap()` to see if the sending works, or use better error handling. Let's add `.unwrap()` and also `println!` to see what we get:\n\n```rust\nuse std::sync::mpsc::channel;\n\nfn main() {\n    let (sender, receiver) = channel();\n\n    sender.send(5).unwrap();\n    println!(\"{}\", receiver.recv().unwrap());\n}\n```\n\nThis prints `5`.\n\nA `channel` is like an `Arc` because you can clone it and send the clones into other threads. Let's make two threads and send values to `receiver`. This code will work, but it is not exactly what we want.\n\n```rust\nuse std::sync::mpsc::channel;\n\nfn main() {\n    let (sender, receiver) = channel();\n    let sender_clone = sender.clone();\n\n    std::thread::spawn(move|| { // move sender in\n        sender.send(\"Send a &str this time\").unwrap();\n    });\n\n    std::thread::spawn(move|| { // move sender_clone in\n        sender_clone.send(\"And here is another &str\").unwrap();\n    });\n\n    println!(\"{}\", receiver.recv().unwrap());\n}\n```\n\nThe two threads start sending, and then we `println!`. It might say `Send a &str this time` or `And here is another &str`, depending on which thread finished first. Let's make a join handle to make them wait.\n\n```rust\nuse std::sync::mpsc::channel;\n\nfn main() {\n    let (sender, receiver) = channel();\n    let sender_clone = sender.clone();\n    let mut handle_vec = vec![]; // Put our handles in here\n\n    handle_vec.push(std::thread::spawn(move|| {  // push this into the vec\n        sender.send(\"Send a &str this time\").unwrap();\n    }));\n\n    handle_vec.push(std::thread::spawn(move|| {  // and push this into the vec\n        sender_clone.send(\"And here is another &str\").unwrap();\n    }));\n\n    for _ in handle_vec { // now handle_vec has 2 items. Let's print them\n        println!(\"{:?}\", receiver.recv().unwrap());\n    }\n}\n```\n\nThis prints:\n\n```text\n\"Send a &str this time\"\n\"And here is another &str\"\n```\n\nNow let's make a `results_vec` instead of printing.\n\n```rust\nuse std::sync::mpsc::channel;\n\nfn main() {\n    let (sender, receiver) = channel();\n    let sender_clone = sender.clone();\n    let mut handle_vec = vec![];\n    let mut results_vec = vec![];\n\n    handle_vec.push(std::thread::spawn(move|| {\n        sender.send(\"Send a &str this time\").unwrap();\n    }));\n\n    handle_vec.push(std::thread::spawn(move|| {\n        sender_clone.send(\"And here is another &str\").unwrap();\n    }));\n\n    for _ in handle_vec {\n        results_vec.push(receiver.recv().unwrap());\n    }\n\n    println!(\"{:?}\", results_vec);\n}\n```\n\nNow the results are in our vec: `[\"Send a &str this time\", \"And here is another &str\"]`.\n\nNow let's pretend that we have a lot of work to do, and want to use threads. We have a big vec with 1 million items, all 0. We want to change each 0 to a 1. We will use ten threads, and each thread will do one tenth of the work. We will create a new vec and use `.extend()` to put the work in.\n\n```rust\nuse std::sync::mpsc::channel;\nuse std::thread::spawn;\n\nfn main() {\n    let (sender, receiver) = channel();\n    let hugevec = vec![0; 1_000_000];\n    let mut newvec = vec![];\n    let mut handle_vec = vec![];\n\n    for i in 0..10 {\n        let sender_clone = sender.clone();\n        let mut work: Vec<u8> = Vec::with_capacity(hugevec.len() / 10); // new vec to put the work in. 1/10th the size\n        work.extend(&hugevec[i*100_000..(i+1)*100_000]); // first part gets 0..100_000, next gets 100_000..200_000, etc.\n        let handle =spawn(move || { // make a handle\n\n            for number in work.iter_mut() { // do the actual work\n                *number += 1;\n            };\n            sender_clone.send(work).unwrap(); // use the sender_clone to send the work to the receiver\n        });\n        handle_vec.push(handle);\n    }\n    \n    for handle in handle_vec { // stop until the threads are done\n        handle.join().unwrap();\n    }\n    \n    while let Ok(results) = receiver.try_recv() {\n        newvec.push(results); // push the results from receiver.recv() into the vec\n    }\n\n    // Now we have a Vec<Vec<u8>>. To put it together we can use .flatten()\n    let newvec = newvec.into_iter().flatten().collect::<Vec<u8>>(); // Now it's one vec of 1_000_000 u8 numbers\n    \n    println!(\"{:?}, {:?}, total length: {}\", // Let's print out some numbers to make sure they are all 1\n        &newvec[0..10], &newvec[newvec.len()-10..newvec.len()], newvec.len() // And show that the length is 1_000_000 items\n    );\n    \n    for number in newvec { // And let's tell Rust that it can panic if even one number is not 1\n        if number != 1 {\n            panic!();\n        }\n    }\n}\n```\n\n## Reading Rust documentation\n\nIt's important to know how to read documentation in Rust so you can understand what other people wrote. Here are some things to know in Rust documentation:\n\n### assert_eq!\n\nYou saw that `assert_eq!` is used when doing testing. You put two items inside the function and the program will panic if they are not equal. Here is a simple example where we need an even number.\n\n```rust\nfn main() {\n    prints_number(56);\n}\n\nfn prints_number(input: i32) {\n    assert_eq!(input % 2, 0); // number must be equal.\n                              // If number % 2 is not 0, it panics\n    println!(\"The number is not odd. It is {}\", input);\n}\n```\n\nMaybe you don't have any plans to use `assert_eq!` in your code, but it is everywhere in Rust documentation. This is because in a document you would need a lot of room to `println!` everything. Also, you would require `Display` or `Debug` for the things you want to print. That's why documentation has `assert_eq!` everywhere. Here is an example from here [https://doc.rust-lang.org/std/vec/struct.Vec.html](https://doc.rust-lang.org/std/vec/struct.Vec.html) showing how to use a Vec:\n\n```rust\nfn main() {\n    let mut vec = Vec::new();\n    vec.push(1);\n    vec.push(2);\n\n    assert_eq!(vec.len(), 2);\n    assert_eq!(vec[0], 1);\n\n    assert_eq!(vec.pop(), Some(2));\n    assert_eq!(vec.len(), 1);\n\n    vec[0] = 7;\n    assert_eq!(vec[0], 7);\n\n    vec.extend([1, 2, 3].iter().copied());\n\n    for x in &vec {\n        println!(\"{}\", x);\n    }\n    assert_eq!(vec, [7, 1, 2, 3]);\n}\n```\n\nIn these examples, you can just think of `assert_eq!(a, b)` as saying \"a is b\". Now look at the same example with comments on the right. The comments show what it actually means.\n\n```rust\nfn main() {\n    let mut vec = Vec::new();\n    vec.push(1);\n    vec.push(2);\n\n    assert_eq!(vec.len(), 2); // \"The vec length is 2\"\n    assert_eq!(vec[0], 1); // \"vec[0] is 1\"\n\n    assert_eq!(vec.pop(), Some(2)); // \"When you use .pop(), you get Some()\"\n    assert_eq!(vec.len(), 1); // \"The vec length is now 1\"\n\n    vec[0] = 7;\n    assert_eq!(vec[0], 7); // \"Vec[0] is 7\"\n\n    vec.extend([1, 2, 3].iter().copied());\n\n    for x in &vec {\n        println!(\"{}\", x);\n    }\n    assert_eq!(vec, [7, 1, 2, 3]); // \"The vec now has [7, 1, 2, 3]\"\n}\n```\n\n### Searching\n\nThe top bar of a Rust document is the search bar. It shows you results as you type. When you go down a page you can't see the search bar anymore, but if you press the **s** key on the keyboard you can search again. So pressing **s** anywhere lets you search right away.\n\n### [src] button\n\nUsually the code for a method, struct, etc. will not be complete. This is because you don't usually need to see the full source to know how it works, and the full code can be confusing. But if you want to know more, you can click on [src] and see everything. For example, on the page for `String` you can see this signature for `.with_capacity()`:\n\n```rust\n// 🚧\npub fn with_capacity(capacity: usize) -> String\n```\n\nOkay, so you put a number in and it gives you a `String`. That's easy, but maybe we are curious and want to see more. If you click on [src] you can see this:\n\n```rust\n// 🚧\npub fn with_capacity(capacity: usize) -> String {\n    String { vec: Vec::with_capacity(capacity) }\n}\n```\n\nInteresting! Now you can see that a String is a kind of `Vec`. And actually a `String` is a vector of `u8` bytes, which is interesting to know. You didn't need to know that to use the `with_capacity` method so you only see it if you click [src]. So clicking on [src] is a good idea if the document doesn't have much detail and you want to know more.\n\n### Information on traits\n\nThe important part of the documentation for a trait is \"Required Methods\" on the left. If you see Required Methods, it probably means that you have to write the method yourself. For example, for `Iterator` you need to write the `.next()` method. And for `From` you need to write the `.from()` method. But some traits can be implemented with just an **attribute**, like we see in `#[derive(Debug)]`. `Debug` needs the `.fmt()` method, but usually you just use `#[derive(Debug)]` unless you want to do it yourself. That's why the page on `std::fmt::Debug` says that \"Generally speaking, you should just derive a Debug implementation.\"\n\n## Attributes\n\nYou have seen code like `#[derive(Debug)]` before: this type of code is called an *attribute*. These attributes are small pieces of code that give information to the compiler. They are not easy to create, but they are very easy to use. If you write an attribute with just `#` then it will affect the code on the next line. But if you write it with `#!` then it will affect everything in its own space.\n\nHere are some attributes you will see a lot:\n\n`#[allow(dead_code)]` and `#[allow(unused_variables)]`. If you write code that you don't use, Rust will still compile but it will let you know. For example, here is a struct with nothing in it and one variable. We don't use either of them.\n\n```rust\nstruct JustAStruct {}\n\nfn main() {\n    let some_char = 'ん';\n}\n```\n\nIf you write this, Rust will remind you that you didn't use them:\n\n```text\nwarning: unused variable: `some_char`\n --> src\\main.rs:4:9\n  |\n4 |     let some_char = 'ん';\n  |         ^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_some_char`\n  |\n  = note: `#[warn(unused_variables)]` on by default\n\nwarning: struct is never constructed: `JustAStruct`\n --> src\\main.rs:1:8\n  |\n1 | struct JustAStruct {}\n  |        ^^^^^^^^^^^\n  |\n  = note: `#[warn(dead_code)]` on by default\n```\n\nWe know that you can write a `_` before the name to make the compiler be quiet:\n\n```rust\nstruct _JustAStruct {}\n\nfn main() {\n    let _some_char = 'ん';\n}\n```\n\nbut you can also use attributes. You'll notice in the message that it uses `#[warn(unused_variables)]` and `#[warn(dead_code)]`. In our code, `JustAStruct` is dead code, and `some_char` is an unused variable. The opposite of `warn` is `allow`, so we can write this and it will not say anything:\n\n```rust\n#![allow(dead_code)]\n#![allow(unused_variables)]\n\nstruct Struct1 {} // Create five structs\nstruct Struct2 {}\nstruct Struct3 {}\nstruct Struct4 {}\nstruct Struct5 {}\n\nfn main() {\n    let char1 = 'ん'; // and four variables. We don't use any of them but the compiler is quiet\n    let char2 = ';';\n    let some_str = \"I'm just a regular &str\";\n    let some_vec = vec![\"I\", \"am\", \"just\", \"a\", \"vec\"];\n}\n```\n\nOf course, dealing with dead code and unused variables is important. But sometimes you want the compiler to be quiet for a while. Or you might need to show some code or teach people Rust and don't want to confuse them with compiler messages.\n\n`#[derive(TraitName)]` lets you derive some traits for structs and enums that you create. This works with many common traits that can be automatically derived. Some like `Display` can't be automatically derived, because for `Display` you have to choose how to display:\n\n```rust\n// ⚠️\n#[derive(Display)]\nstruct HoldsAString {\n    the_string: String,\n}\n\nfn main() {\n    let my_string = HoldsAString {\n        the_string: \"Here I am!\".to_string(),\n    };\n}\n```\n\nThe error message will tell you that.\n\n```text\nerror: cannot find derive macro `Display` in this scope\n --> src\\main.rs:2:10\n  |\n2 | #[derive(Display)]\n  |\n```\n\nBut for traits that you can automatically derive, you can put in as many as you like. Let's give `HoldsAString` seven traits in a single line, just for fun, even though it only needs one.\n\n```rust\n#[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Clone)]\nstruct HoldsAString {\n    the_string: String,\n}\n\nfn main() {\n    let my_string = HoldsAString {\n        the_string: \"Here I am!\".to_string(),\n    };\n    println!(\"{:?}\", my_string);\n}\n```\n\nAlso, you can make a struct `Copy` if (and only if) its fields are all `Copy`. `HoldsAString` has `String` which is not `Copy` so you can't use `#[derive(Copy)]` for it. But for this struct you can:\n\n```rust\n#[derive(Clone, Copy)] // You also need Clone to use Copy\nstruct NumberAndBool {\n    number: i32, // i32 is Copy\n    true_or_false: bool // bool is also Copy. So no problem\n}\n\nfn does_nothing(input: NumberAndBool) {\n\n}\n\nfn main() {\n    let number_and_bool = NumberAndBool {\n        number: 8,\n        true_or_false: true\n    };\n\n    does_nothing(number_and_bool);\n    does_nothing(number_and_bool); // If it didn't have copy, this would make an error\n}\n```\n\n`#[cfg()]` means configuration and tells the compiler whether to run code or not. You see it usually like this: `#[cfg(test)]`. You use that when writing test functions so that it knows not to run them unless you are testing. Then you can have tests next to your code but the compiler won't run them unless you tell it to.\n\nOne other example using `cfg` is `#[cfg(target_os = \"windows\")]`. With that you can tell the compiler to only run the code on Windows, or Linux, or anything else.\n\n`#![no_std]` is an interesting attribute that tells Rust not to bring in the standard library. That means you don't have `Vec`, `String`, and anything else in the standard library. You will see this in code for small devices that don't have much memory or space.\n\nYou can see many more attributes [here](https://doc.rust-lang.org/reference/attributes.html).\n\n\n## Box\n\n`Box` is a very convenient type in Rust. When you use a `Box`, you can put a type on the heap instead of the stack. To make a new `Box`, just use `Box::new()` and put the item inside.\n\n```rust\nfn just_takes_a_variable<T>(item: T) {} // Takes anything and drops it.\n\nfn main() {\n    let my_number = 1; // This is an i32\n    just_takes_a_variable(my_number);\n    just_takes_a_variable(my_number); // Using this function twice is no problem, because it's Copy\n\n    let my_box = Box::new(1); // This is a Box<i32>\n    just_takes_a_variable(my_box.clone()); // Without .clone() the second function would make an error\n    just_takes_a_variable(my_box); // because Box is not Copy\n}\n```\n\nAt first it is hard to imagine where to use it, but you use it in Rust a lot. You remember that `&` is used for `str` because the compiler doesn't know the size of a `str`: it can be any length. But the `&` reference is always the same length, so the compiler can use it. `Box` is similar. Also, you can use `*` on a `Box` to get to the value, just like with `&`:\n\n```rust\nfn main() {\n    let my_box = Box::new(1); // This is a Box<i32>\n    let an_integer = *my_box; // This is an i32\n    println!(\"{:?}\", my_box);\n    println!(\"{:?}\", an_integer);\n}\n```\n\nThis is why Box is called a \"smart pointer\", because it is like a `&` reference (a kind of pointer) but can do more things.\n\nYou can also use a Box to create structs with the same struct inside. These are called *recursive*, which means that inside Struct A is maybe another Struct A. Sometimes you can use Boxes to create linked lists, although these lists are not very popular in Rust. But if you want to create a recursive struct, you can use a `Box`. Here's what happens if you try without a `Box`:\n\n\n```rust\nstruct List {\n    item: Option<List>, // ⚠️\n}\n```\n\nThis simple `List` has one item, that may be `Some<List>` (another list), or `None`. Because you can choose `None`, it will not be recursive forever. But the compiler still doesn't know the size:\n\n```text\nerror[E0072]: recursive type `List` has infinite size\n  --> src\\main.rs:16:1\n   |\n16 | struct List {\n   | ^^^^^^^^^^^ recursive type has infinite size\n17 |     item: Option<List>,\n   |     ------------------ recursive without indirection\n   |\n   = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `List` representable\n```\n\nYou can see that it even suggests trying a `Box`. So let's put a `Box` around List:\n\n```rust\nstruct List {\n    item: Option<Box<List>>,\n}\nfn main() {}\n```\n\nNow the compiler is fine with the `List`, because everything is behind a `Box`, and it knows the size of a `Box`. Then a very simple list might look like this:\n\n```rust\nstruct List {\n    item: Option<Box<List>>,\n}\n\nimpl List {\n    fn new() -> List {\n        List {\n            item: Some(Box::new(List { item: None })),\n        }\n    }\n}\n\nfn main() {\n    let mut my_list = List::new();\n}\n```\n\nEven without data it is a bit complicated, and Rust does not use this type of pattern very much. This is because Rust has strict rules on borrowing and ownership, as you know. But if you want to start a list like this (a linked list), `Box` can help.\n\nA `Box` also lets you use `std::mem::drop` on it, because it's on the heap. That can be convenient sometimes.\n\n## Box around traits\n\n`Box` is very useful for returning traits. You know that you can write traits in generic functions like in this example:\n\n```rust\nuse std::fmt::Display;\n\nstruct DoesntImplementDisplay {}\n\nfn displays_it<T: Display>(input: T) {\n    println!(\"{}\", input);\n}\n\nfn main() {}\n```\n\nThis only takes something with `Display`, so it can't accept our struct `DoesntImplementDisplay`. But it can take in a lot of others like `String`.\n\nYou also saw that we can use `impl Trait` to return other traits, or closures. `Box` can be used in a similar way. You can use a `Box` because otherwise the compiler won't know the size of the value. This example shows that a trait can be used on something of any size:\n\n```rust\n#![allow(dead_code)] // Tell the compiler to be quiet\nuse std::mem::size_of; // This gives the size of a type\n\ntrait JustATrait {} // We will implement this on everything\n\nenum EnumOfNumbers {\n    I8(i8),\n    AnotherI8(i8),\n    OneMoreI8(i8),\n}\nimpl JustATrait for EnumOfNumbers {}\n\nstruct StructOfNumbers {\n    an_i8: i8,\n    another_i8: i8,\n    one_more_i8: i8,\n}\nimpl JustATrait for StructOfNumbers {}\n\nenum EnumOfOtherTypes {\n    I8(i8),\n    AnotherI8(i8),\n    Collection(Vec<String>),\n}\nimpl JustATrait for EnumOfOtherTypes {}\n\nstruct StructOfOtherTypes {\n    an_i8: i8,\n    another_i8: i8,\n    a_collection: Vec<String>,\n}\nimpl JustATrait for StructOfOtherTypes {}\n\nstruct ArrayAndI8 {\n    array: [i8; 1000], // This one will be very large\n    an_i8: i8,\n    in_u8: u8,\n}\nimpl JustATrait for ArrayAndI8 {}\n\nfn main() {\n    println!(\n        \"{}, {}, {}, {}, {}\",\n        size_of::<EnumOfNumbers>(),\n        size_of::<StructOfNumbers>(),\n        size_of::<EnumOfOtherTypes>(),\n        size_of::<StructOfOtherTypes>(),\n        size_of::<ArrayAndI8>(),\n    );\n}\n```\n\nWhen we print the size of these, we get `2, 3, 32, 32, 1002`. So if you were to do this, it would give an error:\n\n```rust\n// ⚠️\nfn returns_just_a_trait() -> JustATrait {\n    let some_enum = EnumOfNumbers::I8(8);\n    some_enum\n}\n```\n\nIt says:\n\n```text\nerror[E0746]: return type cannot have an unboxed trait object\n  --> src\\main.rs:53:30\n   |\n53 | fn returns_just_a_trait() -> JustATrait {\n   |                              ^^^^^^^^^^ doesn't have a size known at compile-time\n```\n\nAnd this is true, because the size could be 2, 3, 32, 1002, or anything else. So we put it in a `Box` instead. Here we also add the keyword `dyn`. `dyn` is a word that shows you that you are talking about a trait, not a struct or anything else.\n\nSo you can change the function to this:\n\n```rust\n// 🚧\nfn returns_just_a_trait() -> Box<dyn JustATrait> {\n    let some_enum = EnumOfNumbers::I8(8);\n    Box::new(some_enum)\n}\n```\n\nAnd now it works, because on the stack is just a `Box` and we know the size of `Box`.\n\nYou see this a lot in the form `Box<dyn Error>`, because sometimes you can have more than one possible error.\n\nWe can quickly create two error types to show this. To make an official error type, you have to implement `std::error::Error` for it. That part is easy: just write `impl std::error::Error {}`. But errors also need `Debug` and `Display` so they can give information on the problem. `Debug` is easy with `#[derive(Debug)]` but `Display` needs the `.fmt()` method. We did this once before.\n\nThe code looks like this:\n\n```rust\nuse std::error::Error;\nuse std::fmt;\n\n#[derive(Debug)]\nstruct ErrorOne;\n\nimpl Error for ErrorOne {} // Now it is an error type with Debug. Time for Display:\n\nimpl fmt::Display for ErrorOne {\n    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n        write!(f, \"You got the first error!\") // All it does is write this message\n    }\n}\n\n\n#[derive(Debug)] // Do the same thing with ErrorTwo\nstruct ErrorTwo;\n\nimpl Error for ErrorTwo {}\n\nimpl fmt::Display for ErrorTwo {\n    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n        write!(f, \"You got the second error!\")\n    }\n}\n\n// Make a function that just returns a String or an error\nfn returns_errors(input: u8) -> Result<String, Box<dyn Error>> { // With Box<dyn Error> you can return anything that has the Error trait\n\n    match input {\n        0 => Err(Box::new(ErrorOne)), // Don't forget to put it in a box\n        1 => Err(Box::new(ErrorTwo)),\n        _ => Ok(\"Looks fine to me\".to_string()), // This is the success type\n    }\n\n}\n\nfn main() {\n\n    let vec_of_u8s = vec![0_u8, 1, 80]; // Three numbers to try out\n\n    for number in vec_of_u8s {\n        match returns_errors(number) {\n            Ok(input) => println!(\"{}\", input),\n            Err(message) => println!(\"{}\", message),\n        }\n    }\n}\n```\n\nThis will print:\n\n```text\nYou got the first error!\nYou got the second error!\nLooks fine to me\n```\n\nIf we didn't have a `Box<dyn Error>` and wrote this, we would have a problem:\n\n```rust\n// ⚠️\nfn returns_errors(input: u8) -> Result<String, Error> {\n    match input {\n        0 => Err(ErrorOne),\n        1 => Err(ErrorTwo),\n        _ => Ok(\"Looks fine to me\".to_string()),\n    }\n}\n```\n\nIt will tell you:\n\n```text\n21  | fn returns_errors(input: u8) -> Result<String, Error> {\n    |                                 ^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time\n```\n\nThis is not surprising, because we know that a trait can work on many things, and they each have different sizes.\n\n## Default and the builder pattern\n\nYou can implement the `Default` trait to give values to a `struct` or `enum` that you think will be most common. The builder pattern works nicely with this to let users easily make changes when they want. First let's look at `Default`. Actually, most general types in Rust already have `Default`. They are not surprising: 0, \"\" (empty strings), `false`, etc.\n\n```rust\nfn main() {\n    let default_i8: i8 = Default::default();\n    let default_str: String = Default::default();\n    let default_bool: bool = Default::default();\n\n    println!(\"'{}', '{}', '{}'\", default_i8, default_str, default_bool);\n}\n```\n\nThis prints `'0', '', 'false'`.\n\nSo `Default` is like the `new` function except you don't have to enter anything. First we will make a `struct` that doesn't implement `Default` yet. It has a `new` function which we use to make a character named Billy with some stats.\n\n```rust\nstruct Character {\n    name: String,\n    age: u8,\n    height: u32,\n    weight: u32,\n    lifestate: LifeState,\n}\n\nenum LifeState {\n    Alive,\n    Dead,\n    NeverAlive,\n    Uncertain\n}\n\nimpl Character {\n    fn new(name: String, age: u8, height: u32, weight: u32, alive: bool) -> Self {\n        Self {\n            name,\n            age,\n            height,\n            weight,\n            lifestate: if alive { LifeState::Alive } else { LifeState::Dead },\n        }\n    }\n}\n\nfn main() {\n    let character_1 = Character::new(\"Billy\".to_string(), 15, 170, 70, true);\n}\n```\n\nBut maybe in our world we want most of the characters to be named Billy, age 15, height 170, weight 70, and alive. We can implement `Default` so that we can just write `Character::default()`. It looks like this:\n\n```rust\n#[derive(Debug)]\nstruct Character {\n    name: String,\n    age: u8,\n    height: u32,\n    weight: u32,\n    lifestate: LifeState,\n}\n\n#[derive(Debug)]\nenum LifeState {\n    Alive,\n    Dead,\n    NeverAlive,\n    Uncertain,\n}\n\nimpl Character {\n    fn new(name: String, age: u8, height: u32, weight: u32, alive: bool) -> Self {\n        Self {\n            name,\n            age,\n            height,\n            weight,\n            lifestate: if alive {\n                LifeState::Alive\n            } else {\n                LifeState::Dead\n            },\n        }\n    }\n}\n\nimpl Default for Character {\n    fn default() -> Self {\n        Self {\n            name: \"Billy\".to_string(),\n            age: 15,\n            height: 170,\n            weight: 70,\n            lifestate: LifeState::Alive,\n        }\n    }\n}\n\nfn main() {\n    let character_1 = Character::default();\n\n    println!(\n        \"The character {:?} is {:?} years old.\",\n        character_1.name, character_1.age\n    );\n}\n```\n\nIt prints `The character \"Billy\" is 15 years old.` Much easier!\n\nNow comes the builder pattern. We will have many Billys, so we will keep the default. But a lot of other characters will be only a bit different. The builder pattern lets us chain very small methods to change one value each time. Here is one such method for `Character`:\n\n```rust\nfn height(mut self, height: u32) -> Self {    // 🚧\n    self.height = height;\n    self\n}\n```\n\nMake sure to notice that it takes a `mut self`. We saw this once before, and it is not a mutable reference (`&mut self`). It takes ownership of `Self` and with `mut` it will be mutable, even if it wasn't mutable before. That's because `.height()` has full ownership and nobody else can touch it, so it is safe to be mutable. Then it just changes `self.height` and returns `Self` (which is `Character`).\n\nSo let's have three of these builder methods. They are almost the same:\n\n```rust\nfn height(mut self, height: u32) -> Self {     // 🚧\n    self.height = height;\n    self\n}\n\nfn weight(mut self, weight: u32) -> Self {\n    self.weight = weight;\n    self\n}\n\nfn name(mut self, name: &str) -> Self {\n    self.name = name.to_string();\n    self\n}\n```\n\nEach one of those changes one variable and gives `Self` back: this is what you see in the builder pattern. So now we can write something like this to make a character: `let character_1 = Character::default().height(180).weight(60).name(\"Bobby\");`. If you are building a library for someone else to use, this can make it easy for them. It's easy for the end user because it almost looks like natural English: \"Give me a default character but with height of 180, weight of 60, and name of Bobby.\" So far our code looks like this:\n\n```rust\n#[derive(Debug)]\nstruct Character {\n    name: String,\n    age: u8,\n    height: u32,\n    weight: u32,\n    lifestate: LifeState,\n}\n\n#[derive(Debug)]\nenum LifeState {\n    Alive,\n    Dead,\n    NeverAlive,\n    Uncertain,\n}\n\nimpl Character {\n    fn new(name: String, age: u8, height: u32, weight: u32, alive: bool) -> Self {\n        Self {\n            name,\n            age,\n            height,\n            weight,\n            lifestate: if alive {\n                LifeState::Alive\n            } else {\n                LifeState::Dead\n            },\n        }\n    }\n\n    fn height(mut self, height: u32) -> Self {\n        self.height = height;\n        self\n    }\n\n    fn weight(mut self, weight: u32) -> Self {\n        self.weight = weight;\n        self\n    }\n\n    fn name(mut self, name: &str) -> Self {\n        self.name = name.to_string();\n        self\n    }\n}\n\nimpl Default for Character {\n    fn default() -> Self {\n        Self {\n            name: \"Billy\".to_string(),\n            age: 15,\n            height: 170,\n            weight: 70,\n            lifestate: LifeState::Alive,\n        }\n    }\n}\n\nfn main() {\n    let character_1 = Character::default().height(180).weight(60).name(\"Bobby\");\n\n    println!(\"{:?}\", character_1);\n}\n```\n\nOne last method to add is usually called `.build()`. This method is a sort of final check. When you give a user a method like `.height()` you can make sure that they only put in a `u32()`, but what if they enter 5000 for height? That might not be okay in the game you are making. We will use a final method called `.build()` that returns a `Result`. Inside it we will check if the user input is okay, and if it is, we will return an `Ok(Self)`.\n\nFirst though let's change the `.new()` method. We don't want users to be free to create any kind of character anymore. So we'll move the values from `impl Default` to `.new()`. And now `.new()` doesn't take any input.\n\n```rust\n    fn new() -> Self {    // 🚧\n        Self {\n            name: \"Billy\".to_string(),\n            age: 15,\n            height: 170,\n            weight: 70,\n            lifestate: LifeState::Alive,\n        }\n    }\n```\n\nThat means we don't need `impl Default` anymore, because `.new()` has all the default values. So we can delete `impl Default`.\n\nNow our code looks like this:\n\n```rust\n#[derive(Debug)]\nstruct Character {\n    name: String,\n    age: u8,\n    height: u32,\n    weight: u32,\n    lifestate: LifeState,\n}\n\n#[derive(Debug)]\nenum LifeState {\n    Alive,\n    Dead,\n    NeverAlive,\n    Uncertain,\n}\n\nimpl Character {\n    fn new() -> Self {\n        Self {\n            name: \"Billy\".to_string(),\n            age: 15,\n            height: 170,\n            weight: 70,\n            lifestate: LifeState::Alive,\n        }\n    }\n\n    fn height(mut self, height: u32) -> Self {\n        self.height = height;\n        self\n    }\n\n    fn weight(mut self, weight: u32) -> Self {\n        self.weight = weight;\n        self\n    }\n\n    fn name(mut self, name: &str) -> Self {\n        self.name = name.to_string();\n        self\n    }\n}\n\nfn main() {\n    let character_1 = Character::new().height(180).weight(60).name(\"Bobby\");\n\n    println!(\"{:?}\", character_1);\n}\n```\n\nThis prints the same thing: `Character { name: \"Bobby\", age: 15, height: 180, weight: 60, lifestate: Alive }`.\n\nWe are almost ready to write the method `.build()`, but there is one problem: how do we make the user use it? Right now a user can write `let x = Character::new().height(76767);` and get a `Character`. There are many ways to do this, and maybe you can imagine your own. But we will add a `can_use: bool` value to `Character`.\n\n```rust\n#[derive(Debug)]       // 🚧\nstruct Character {\n    name: String,\n    age: u8,\n    height: u32,\n    weight: u32,\n    lifestate: LifeState,\n    can_use: bool, // Set whether the user can use the character\n}\n\n\\\\ Cut other code\n\n    fn new() -> Self {\n        Self {\n            name: \"Billy\".to_string(),\n            age: 15,\n            height: 170,\n            weight: 70,\n            lifestate: LifeState::Alive,\n            can_use: true, // .new() always gives a good character, so it's true\n        }\n    }\n```\n\nAnd for the other methods like `.height()`, we will set `can_use` to `false`. Only `.build()` will set it to `true` again, so now the user has to do a final check with `.build()`. We will make sure that `height` is not above 200 and `weight` is not above 300. Also, in our game there is a bad word called `smurf` that we don't want characters to use.\n\nOur `.build()` method looks like this:\n\n```rust\nfn build(mut self) -> Result<Character, String> {      // 🚧\n    if self.height < 200 && self.weight < 300 && !self.name.to_lowercase().contains(\"smurf\") {\n        self.can_use = true;\n        Ok(self)\n    } else {\n        Err(\"Could not create character. Characters must have:\n1) Height below 200\n2) Weight below 300\n3) A name that is not Smurf (that is a bad word)\"\n            .to_string())\n    }\n}\n```\n\n`!self.name.to_lowercase().contains(\"smurf\")` makes sure that the user doesn't write something like \"SMURF\" or \"IamSmurf\" . It makes the whole `String` lowercase (small letters), and checks for `.contains()` instead of `==`. And the `!` in front means \"not\".\n\nIf everything is okay, we set `can_use` to `true`, and give the character to the user inside `Ok`.\n\nNow that our code is done, we will create three characters that don't work, and one character that does work. The final code looks like this:\n\n```rust\n#[derive(Debug)]\nstruct Character {\n    name: String,\n    age: u8,\n    height: u32,\n    weight: u32,\n    lifestate: LifeState,\n    can_use: bool, // Here is the new value\n}\n\n#[derive(Debug)]\nenum LifeState {\n    Alive,\n    Dead,\n    NeverAlive,\n    Uncertain,\n}\n\nimpl Character {\n    fn new() -> Self {\n        Self {\n            name: \"Billy\".to_string(),\n            age: 15,\n            height: 170,\n            weight: 70,\n            lifestate: LifeState::Alive,\n            can_use: true,  // .new() makes a fine character, so it is true\n        }\n    }\n\n    fn height(mut self, height: u32) -> Self {\n        self.height = height;\n        self.can_use = false; // Now the user can't use the character\n        self\n    }\n\n    fn weight(mut self, weight: u32) -> Self {\n        self.weight = weight;\n        self.can_use = false;\n        self\n    }\n\n    fn name(mut self, name: &str) -> Self {\n        self.name = name.to_string();\n        self.can_use = false;\n        self\n    }\n\n    fn build(mut self) -> Result<Character, String> {\n        if self.height < 200 && self.weight < 300 && !self.name.to_lowercase().contains(\"smurf\") {\n            self.can_use = true;   // Everything is okay, so set to true\n            Ok(self)               // and return the character\n        } else {\n            Err(\"Could not create character. Characters must have:\n1) Height below 200\n2) Weight below 300\n3) A name that is not Smurf (that is a bad word)\"\n                .to_string())\n        }\n    }\n}\n\nfn main() {\n    let character_with_smurf = Character::new().name(\"Lol I am Smurf!!\").build(); // This one contains \"smurf\" - not okay\n    let character_too_tall = Character::new().height(400).build(); // Too tall - not okay\n    let character_too_heavy = Character::new().weight(500).build(); // Too heavy - not okay\n    let okay_character = Character::new()\n        .name(\"Billybrobby\")\n        .height(180)\n        .weight(100)\n        .build();   // This character is okay. Name is fine, height and weight are fine\n\n    // Now they are not Character, they are Result<Character, String>. So let's put them in a Vec so we can see them:\n    let character_vec = vec![character_with_smurf, character_too_tall, character_too_heavy, okay_character];\n\n    for character in character_vec { // Now we will print the character if it's Ok, and print the error if it's Err\n        match character {\n            Ok(character_info) => println!(\"{:?}\", character_info),\n            Err(err_info) => println!(\"{}\", err_info),\n        }\n        println!(); // Then add one more line\n    }\n}\n```\n\nThis will print:\n\n```text\nCould not create character. Characters must have:\n1) Height below 200\n2) Weight below 300\n3) A name that is not Smurf (that is a bad word)\n\nCould not create character. Characters must have:\n1) Height below 200\n2) Weight below 300\n3) A name that is not Smurf (that is a bad word)\n\nCould not create character. Characters must have:\n1) Height below 200\n2) Weight below 300\n3) A name that is not Smurf (that is a bad word)\n\nCharacter { name: \"Billybrobby\", age: 15, height: 180, weight: 100, lifestate: Alive, can_use: true }\n```\n\n\n\n## Deref and DerefMut\n\n`Deref` is the trait that lets you use `*` to dereference something. We saw the word `Deref` before when using a tuple struct to make a new type, and now it's time to learn it.\n\nWe know that a reference is not the same as a value:\n\n```rust\n// ⚠️\nfn main() {\n    let value = 7; // This is an i32\n    let reference = &7; // This is a &i32\n    println!(\"{}\", value == reference);\n}\n```\n\nAnd Rust won't even give a `false` because it won't even compare the two.\n\n```text\nerror[E0277]: can't compare `{integer}` with `&{integer}`\n --> src\\main.rs:4:26\n  |\n4 |     println!(\"{}\", value == reference);\n  |                          ^^ no implementation for `{integer} == &{integer}`\n```\n\nOf course, the solution here is `*`. So this will print `true`:\n\n```rust\nfn main() {\n    let value = 7;\n    let reference = &7;\n    println!(\"{}\", value == *reference);\n}\n```\n\n\nNow let's imagine a simple type that just holds a number. It will be like a `Box`, and we have some ideas for some extra functions for it. But if we just give it a number, it won't be able to do much with it.\n\nWe can't use `*` like we can with `Box`:\n\n```rust\n// ⚠️\nstruct HoldsANumber(u8);\n\nfn main() {\n    let my_number = HoldsANumber(20);\n    println!(\"{}\", *my_number + 20);\n}\n```\n\nThe error is:\n\n```text\nerror[E0614]: type `HoldsANumber` cannot be dereferenced\n  --> src\\main.rs:24:22\n   |\n24 |     println!(\"{:?}\", *my_number + 20);\n```\n\nWe can of course do this: `println!(\"{:?}\", my_number.0 + 20);`. But then we are just adding a separate `u8` to the 20. It would be nice if we could just add them together. The message `cannot be dereferenced` gives us a clue: we need to implement `Deref`. Something simple that implements `Deref` is sometimes called a \"smart pointer\". A smart pointer can point to its item, has information about it, and can use its methods. Because right now we can add `my_number.0`, which is a `u8`, but we can't do much else with a `HoldsANumber`: all it has so far is `Debug`.\n\nInteresting fact: `String` is actually a smart pointer to `&str` and `Vec` is a smart pointer to array (or other types). So we have actually been using smart pointers since the beginning.\n\nImplementing `Deref` is not too hard and the examples in the standard library are easy. [Here's the sample code from the standard library](https://doc.rust-lang.org/std/ops/trait.Deref.html):\n\n```rust\nuse std::ops::Deref;\n\nstruct DerefExample<T> {\n    value: T\n}\n\nimpl<T> Deref for DerefExample<T> {\n    type Target = T;\n\n    fn deref(&self) -> &Self::Target {\n        &self.value\n    }\n}\n\nfn main() {\n    let x = DerefExample { value: 'a' };\n    assert_eq!('a', *x);\n}\n```\n\n\nSo we follow that and now our `Deref` looks like this:\n\n```rust\n// 🚧\nimpl Deref for HoldsANumber {\n    type Target = u8; // Remember, this is the \"associated type\": the type that goes together.\n                      // You have to use the right type Target = (the type you want to return)\n\n    fn deref(&self) -> &Self::Target { // Rust calls .deref() when you use *. We just defined Target as a u8 so this is easy to understand\n        &self.0   // We chose &self.0 because it's a tuple struct. In a named struct it would be something like \"&self.number\"\n    }\n}\n```\n\nSo now we can do this with `*`:\n\n```rust\nuse std::ops::Deref;\n#[derive(Debug)]\nstruct HoldsANumber(u8);\n\nimpl Deref for HoldsANumber {\n    type Target = u8;\n\n    fn deref(&self) -> &Self::Target {\n        &self.0\n    }\n}\n\nfn main() {\n    let my_number = HoldsANumber(20);\n    println!(\"{:?}\", *my_number + 20);\n}\n```\n\nSo that will print `40` and we didn't need to write `my_number.0`. That means we get the methods of `u8` and we can write our own methods for `HoldsANumber`. We will add our own simple method and use another method we get from `u8` called `.checked_sub()`. The `.checked_sub()` method is a safe subtraction that returns an `Option`. If it can do the subtraction then it gives it to you inside `Some`, and if it can't do it then it gives a `None`. Remember, a `u8` can't be negative so it's safer to do `.checked_sub()` so we don't panic.\n\n```rust\nuse std::ops::Deref;\n\nstruct HoldsANumber(u8);\n\nimpl HoldsANumber {\n    fn prints_the_number_times_two(&self) {\n        println!(\"{}\", self.0 * 2);\n    }\n}\n\nimpl Deref for HoldsANumber {\n    type Target = u8;\n\n    fn deref(&self) -> &Self::Target {\n        &self.0\n    }\n}\n\nfn main() {\n    let my_number = HoldsANumber(20);\n    println!(\"{:?}\", my_number.checked_sub(100)); // This method comes from u8\n    my_number.prints_the_number_times_two(); // This is our own method\n}\n```\n\nThis prints:\n\n```text\nNone\n40\n```\n\nWe can also implement `DerefMut` so we can change the values through `*`. It looks almost the same. You need `Deref` before you can implement `DerefMut`.\n\n```rust\nuse std::ops::{Deref, DerefMut};\n\nstruct HoldsANumber(u8);\n\nimpl HoldsANumber {\n    fn prints_the_number_times_two(&self) {\n        println!(\"{}\", self.0 * 2);\n    }\n}\n\nimpl Deref for HoldsANumber {\n    type Target = u8;\n\n    fn deref(&self) -> &Self::Target {\n        &self.0\n    }\n}\n\nimpl DerefMut for HoldsANumber { // You don't need type Target = u8; here because it already knows thanks to Deref\n    fn deref_mut(&mut self) -> &mut Self::Target { // Everything else is the same except it says mut everywhere\n        &mut self.0\n    }\n}\n\nfn main() {\n    let mut my_number = HoldsANumber(20);\n    *my_number = 30; // DerefMut lets us do this\n    println!(\"{:?}\", my_number.checked_sub(100));\n    my_number.prints_the_number_times_two();\n}\n```\n\nSo you can see that `Deref` gives your type a lot of power.\n\nThis is also why the standard library says: `Deref should only be implemented for smart pointers to avoid confusion`. That's because you can do some strange things with `Deref` for a complicated type. Let's imagine a really confusing example to understand what they mean. We'll start with `Character` struct for a game. A new `Character` needs some stats like intelligence and strength. So here is our first character:\n\n```rust\nstruct Character {\n    name: String,\n    strength: u8,\n    dexterity: u8,\n    health: u8,\n    intelligence: u8,\n    wisdom: u8,\n    charm: u8,\n    hit_points: i8,\n    alignment: Alignment,\n}\n\nimpl Character {\n    fn new(\n        name: String,\n        strength: u8,\n        dexterity: u8,\n        health: u8,\n        intelligence: u8,\n        wisdom: u8,\n        charm: u8,\n        hit_points: i8,\n        alignment: Alignment,\n    ) -> Self {\n        Self {\n            name,\n            strength,\n            dexterity,\n            health,\n            intelligence,\n            wisdom,\n            charm,\n            hit_points,\n            alignment,\n        }\n    }\n}\n\nenum Alignment {\n    Good,\n    Neutral,\n    Evil,\n}\n\nfn main() {\n    let billy = Character::new(\"Billy\".to_string(), 9, 8, 7, 10, 19, 19, 5, Alignment::Good);\n}\n```\n\nNow let's imagine that we want to keep character hit points in a big vec. Maybe we'll put monster data in there too, and keep it all together. Since `hit_points` is an `i8`, we implement `Deref` so we can do all sorts of math on it. But look at how strange it looks in our `main()` function now:\n\n\n```rust\nuse std::ops::Deref;\n\n// All the other code is the same until after the enum Alignment\nstruct Character {\n    name: String,\n    strength: u8,\n    dexterity: u8,\n    health: u8,\n    intelligence: u8,\n    wisdom: u8,\n    charm: u8,\n    hit_points: i8,\n    alignment: Alignment,\n}\n\nimpl Character {\n    fn new(\n        name: String,\n        strength: u8,\n        dexterity: u8,\n        health: u8,\n        intelligence: u8,\n        wisdom: u8,\n        charm: u8,\n        hit_points: i8,\n        alignment: Alignment,\n    ) -> Self {\n        Self {\n            name,\n            strength,\n            dexterity,\n            health,\n            intelligence,\n            wisdom,\n            charm,\n            hit_points,\n            alignment,\n        }\n    }\n}\n\nenum Alignment {\n    Good,\n    Neutral,\n    Evil,\n}\n\nimpl Deref for Character { // impl Deref for Character. Now we can do any integer math we want!\n    type Target = i8;\n\n    fn deref(&self) -> &Self::Target {\n        &self.hit_points\n    }\n}\n\n\n\nfn main() {\n    let billy = Character::new(\"Billy\".to_string(), 9, 8, 7, 10, 19, 19, 5, Alignment::Good); // Create two characters, billy and brandy\n    let brandy = Character::new(\"Brandy\".to_string(), 9, 8, 7, 10, 19, 19, 5, Alignment::Good);\n\n    let mut hit_points_vec = vec![]; // Put our hit points data in here\n    hit_points_vec.push(*billy);     // Push *billy?\n    hit_points_vec.push(*brandy);    // Push *brandy?\n\n    println!(\"{:?}\", hit_points_vec);\n}\n```\n\nThis just prints `[5, 5]`. Our code is now very strange for someone to read. We can read `Deref` just above `main()` and figure out that `*billy` means `i8`, but what if there was a lot of code? Maybe our code is 2000 lines long, and suddenly we have to figure out why we are `.push()`ing `*billy`. `Character` is certainly more than just a smart pointer for `i8`.\n\nOf course, it is not illegal to write `hit_points_vec.push(*billy)`, but it makes the code look very strange. Probably a simple `.get_hp()` method would be much better, or another struct that holds the characters. Then you could iterate through and push the `hit_points` for each one. `Deref` gives a lot of power but it's good to make sure that the code is logical.\n\n\n\n## Crates and modules\n\nEvery time you write code in Rust, you are writing it in a `crate`. A `crate` is the file, or files, that go together for your code. Inside the file you write you can also make a `mod`. A `mod` is a space for functions, structs, etc. and is used for a few reasons:\n\n- Building your code: it helps you think about the general structure of your code. This can be important as your code gets larger and larger.\n- Reading your code: people can understand your code more easily. For example, the name `std::collections::HashMap` tells you that it's in `std` inside the module `collections`. This gives you a hint that maybe there are more collection types inside `collections` that you can try.\n- Privacy: everything starts out as private. That lets you keep users from using functions directly.\n\nTo make a `mod`, just write `mod` and start a code block with `{}`. We will make a mod called `print_things` that has some printing-related functions.\n\n```rust\nmod print_things {\n    use std::fmt::Display;\n\n    fn prints_one_thing<T: Display>(input: T) { // Print anything that implements Display\n        println!(\"{}\", input)\n    }\n}\n\nfn main() {}\n```\n\nYou can see that we wrote `use std::fmt::Display;` inside `print_things`, because it is a separate space. If you wrote `use std::fmt::Display;` inside `main()` it wouldn't help. Also, we can't call it from `main()` right now. Without the `pub` keyword in front of `fn` it will stay private. Let's try to call it without `pub`. Here's one way to write it:\n\n```rust\n// 🚧\nfn main() {\n    crate::print_things::prints_one_thing(6);\n}\n```\n\n`crate` means \"inside this project\", but for our simple example it's the same as \"inside this file\". Inside that is the mod `print_things`, then finally the `prints_one_thing()` function. You can write that every time, or you can write `use` to import it. Now we can see the error that says that it's private:\n\n```rust\n// ⚠️\nmod print_things {\n    use std::fmt::Display;\n\n    fn prints_one_thing<T: Display>(input: T) {\n        println!(\"{}\", input)\n    }\n}\n\nfn main() {\n    use crate::print_things::prints_one_thing;\n\n    prints_one_thing(6);\n    prints_one_thing(\"Trying to print a string...\".to_string());\n}\n```\n\nHere's the error:\n\n```text\nerror[E0603]: function `prints_one_thing` is private\n  --> src\\main.rs:10:30\n   |\n10 |     use crate::print_things::prints_one_thing;\n   |                              ^^^^^^^^^^^^^^^^ private function\n   |\nnote: the function `prints_one_thing` is defined here\n  --> src\\main.rs:4:5\n   |\n4  |     fn prints_one_thing<T: Display>(input: T) {\n   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n```\nIt's easy to understand that function `prints_one_thing` is private. It also shows us with `src\\main.rs:4:5` where to find the function. This is helpful because you can write `mod`s not just in one file, but over a lot of files as well.\n\nNow we just write `pub fn` instead of `fn` and everything works.\n\n```rust\nmod print_things {\n    use std::fmt::Display;\n\n    pub fn prints_one_thing<T: Display>(input: T) {\n        println!(\"{}\", input)\n    }\n}\n\nfn main() {\n    use crate::print_things::prints_one_thing;\n\n    prints_one_thing(6);\n    prints_one_thing(\"Trying to print a string...\".to_string());\n}\n```\n\nThis prints:\n\n```text\n6\nTrying to print a string...\n```\n\nHow about `pub` for a struct, enum, trait, or module? `pub` works like this for them:\n\n- `pub` for a struct: it makes the struct public, but the items are not public. To make an item public, you have to write `pub` for each one too.\n- `pub` for an enum or trait: everything becomes public. This makes sense because traits are about giving the same behaviour to something. And enums are about choosing between items, and you need to see them all to choose them.\n- `pub` for a module: a top level module will be `pub` because if it isn't pub then nobody can touch anything in it at all. But modules inside modules need `pub` to be public.\n\nSo let's put a struct named `Billy` inside `print_things`. This struct will be almost all public, but not quite. The struct is public so it will say `pub struct Billy`. Inside it will have a `name` and `times_to_print`. `name` will not be public, because we only want the user to create structs named `\"Billy\".to_string()`. But the user can select the number of times to print, so that will be public. It looks like this:\n\n```rust\nmod print_things {\n    use std::fmt::{Display, Debug};\n\n    #[derive(Debug)]\n    pub struct Billy { // Billy is public\n        name: String, // but name is private.\n        pub times_to_print: u32,\n    }\n\n    impl Billy {\n        pub fn new(times_to_print: u32) -> Self { // That means the user needs to use new to create a Billy. The user can only change the number of times_to_print\n            Self {\n                name: \"Billy\".to_string(), // We choose the name - the user can't\n                times_to_print,\n            }\n        }\n\n        pub fn print_billy(&self) { // This function prints a Billy\n            for _ in 0..self.times_to_print {\n                println!(\"{:?}\", self.name);\n            }\n        }\n    }\n\n    pub fn prints_one_thing<T: Display>(input: T) {\n        println!(\"{}\", input)\n    }\n}\n\nfn main() {\n    use crate::print_things::*; // Now we use *. This imports everything from print_things\n\n    let my_billy = Billy::new(3);\n    my_billy.print_billy();\n}\n```\n\nThis will print:\n\n```text\n\"Billy\"\n\"Billy\"\n\"Billy\"\n```\n\nBy the way, the `*` to import everything is called the \"glob operator\". Glob means \"global\", so it means everything.\n\nInside a `mod` you can create other mods. A child mod (a mod inside of a mod) can always use anything inside a parent mod. You can see this in the next example where we have a `mod city` inside a `mod province` inside a `mod country`.\n\nYou can think of the structure like this: even if you are in a country, you might not be in a province. And even if you are in a province, you might not be in a city. But if you are in a city, you are in its province and you are in its country.\n\n\n```rust\nmod country { // The main mod doesn't need pub\n    fn print_country(country: &str) { // Note: this function isn't public\n        println!(\"We are in the country of {}\", country);\n    }\n    pub mod province { // Make this mod public\n\n        fn print_province(province: &str) { // Note: this function isn't public\n            println!(\"in the province of {}\", province);\n        }\n\n        pub mod city { // Make this mod public\n            pub fn print_city(country: &str, province: &str, city: &str) {  // This function is public though\n                crate::country::print_country(country);\n                crate::country::province::print_province(province);\n                println!(\"in the city of {}\", city);\n            }\n        }\n    }\n}\n\nfn main() {\n    crate::country::province::city::print_city(\"Canada\", \"New Brunswick\", \"Moncton\");\n}\n```\n\nThe interesting part is that `print_city` can access `print_province` and `print_country`. That's because `mod city` is inside the other mods. It doesn't need `pub` in front of `print_province` to use it. And that makes sense: a city doesn't need to do anything to be inside a province and inside a country.\n\nYou probably noticed that `crate::country::province::print_province(province);` is very long. When we are inside a module we can use `super` to bring in items from above. Actually the word super itself means \"above\", like in \"superior\". In our example we only used the function once, but if you use it more then it is a good idea to import. It can also be a good idea if it makes your code easier to read, even if you only use the function once. The code is almost the same now, but a bit easier to read:\n\n```rust\nmod country {\n    fn print_country(country: &str) {\n        println!(\"We are in the country of {}\", country);\n    }\n    pub mod province {\n        fn print_province(province: &str) {\n            println!(\"in the province of {}\", province);\n        }\n\n        pub mod city {\n            use super::super::*; // use everything in \"above above\": that means mod country\n            use super::*;        // use everything in \"above\": that means mod province\n\n            pub fn print_city(country: &str, province: &str, city: &str) {\n                print_country(country);\n                print_province(province);\n                println!(\"in the city of {}\", city);\n            }\n        }\n    }\n}\n\nfn main() {\n    use crate::country::province::city::print_city; // bring in the function\n\n    print_city(\"Canada\", \"New Brunswick\", \"Moncton\");\n    print_city(\"Korea\", \"Gyeonggi-do\", \"Gwangju\"); // Now it's less work to use it again\n}\n```\n\n\n\n## Testing\n\nTesting is a good subject to learn now that we understand modules. Testing your code is very easy in Rust, because you can write tests right next to your code.\n\nThe easiest way to start testing is to add `#[test]` above a function. Here is a simple one:\n\n```rust\n#[test]\nfn two_is_two() {\n    assert_eq!(2, 2);\n}\n```\n\nBut if you try to run it in the Playground, it gives an error: ``error[E0601]: `main` function not found in crate `playground``. That's because you don't use _Run_ for tests, you use _Test_. Also, you don't use a `main()` function for tests - they go outside. To run this in the Playground, click on `···` next to _RUN_ and change it to _Test_. Now if you click on it, it will run the test. (If you have Rust installed already, you will type `cargo test` to do this)\n\nHere is the output:\n\n```text\nrunning 1 test\ntest two_is_two ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n```\n\nLet's change `assert_eq!(2, 2)` to `assert_eq!(2, 3)` and see what we get. When a test fails you get a lot more information:\n\n```text\nrunning 1 test\ntest two_is_two ... FAILED\n\nfailures:\n\n---- two_is_two stdout ----\nthread 'two_is_two' panicked at 'assertion failed: `(left == right)`\n  left: `2`,\n right: `3`', src/lib.rs:3:5\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n\n\nfailures:\n    two_is_two\n\ntest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out\n```\n\n`assert_eq!(left, right)` is the main way to test a function in Rust. If it doesn't work, it will show the different values: left has 2, but right has 3.\n\nWhat does `RUST_BACKTRACE=1` mean? This is a setting on your computer to give a lot more information about errors. Luckily the Playground has it too: click on `···` next to `STABLE` and set backtrace to `ENABLED`. If you do that, it will give you *a lot* of information:\n\n```text\nrunning 1 test\ntest two_is_two ... FAILED\n\nfailures:\n\n---- two_is_two stdout ----\nthread 'two_is_two' panicked at 'assertion failed: 2 == 3', src/lib.rs:3:5\nstack backtrace:\n   0: backtrace::backtrace::libunwind::trace\n             at /cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.46/src/backtrace/libunwind.rs:86\n   1: backtrace::backtrace::trace_unsynchronized\n             at /cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.46/src/backtrace/mod.rs:66\n   2: std::sys_common::backtrace::_print_fmt\n             at src/libstd/sys_common/backtrace.rs:78\n   3: <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt\n             at src/libstd/sys_common/backtrace.rs:59\n   4: core::fmt::write\n             at src/libcore/fmt/mod.rs:1076\n   5: std::io::Write::write_fmt\n             at /rustc/c367798cfd3817ca6ae908ce675d1d99242af148/src/libstd/io/mod.rs:1537\n   6: std::io::impls::<impl std::io::Write for alloc::boxed::Box<W>>::write_fmt\n             at src/libstd/io/impls.rs:176\n   7: std::sys_common::backtrace::_print\n             at src/libstd/sys_common/backtrace.rs:62\n   8: std::sys_common::backtrace::print\n             at src/libstd/sys_common/backtrace.rs:49\n   9: std::panicking::default_hook::{{closure}}\n             at src/libstd/panicking.rs:198\n  10: std::panicking::default_hook\n             at src/libstd/panicking.rs:215\n  11: std::panicking::rust_panic_with_hook\n             at src/libstd/panicking.rs:486\n  12: std::panicking::begin_panic\n             at /rustc/c367798cfd3817ca6ae908ce675d1d99242af148/src/libstd/panicking.rs:410\n  13: playground::two_is_two\n             at src/lib.rs:3\n  14: playground::two_is_two::{{closure}}\n             at src/lib.rs:2\n  15: core::ops::function::FnOnce::call_once\n             at /rustc/c367798cfd3817ca6ae908ce675d1d99242af148/src/libcore/ops/function.rs:232\n  16: <alloc::boxed::Box<F> as core::ops::function::FnOnce<A>>::call_once\n             at /rustc/c367798cfd3817ca6ae908ce675d1d99242af148/src/liballoc/boxed.rs:1076\n  17: <std::panic::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once\n             at /rustc/c367798cfd3817ca6ae908ce675d1d99242af148/src/libstd/panic.rs:318\n  18: std::panicking::try::do_call\n             at /rustc/c367798cfd3817ca6ae908ce675d1d99242af148/src/libstd/panicking.rs:297\n  19: std::panicking::try\n             at /rustc/c367798cfd3817ca6ae908ce675d1d99242af148/src/libstd/panicking.rs:274\n  20: std::panic::catch_unwind\n             at /rustc/c367798cfd3817ca6ae908ce675d1d99242af148/src/libstd/panic.rs:394\n  21: test::run_test_in_process\n             at src/libtest/lib.rs:541\n  22: test::run_test::run_test_inner::{{closure}}\n             at src/libtest/lib.rs:450\nnote: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.\n\n\nfailures:\n    two_is_two\n\ntest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out\n```\n\nYou don't need to use a backtrace unless you really can't find where the problem is. But luckily you don't need to understand it all either.  If you keep reading, you will eventually see line 13 where it says `playground` - that's where it talks about your code. Everything else is about what Rust is doing in other libraries to run your program. But these two lines show you that it looked at line 2 and line 3 of playground, which is a hint to check there. Here's that part again:\n\n```text\n  13: playground::two_is_two\n             at src/lib.rs:3\n  14: playground::two_is_two::{{closure}}\n             at src/lib.rs:2\n```\n\nEdit: Rust improved its backtrace messages in early 2021 to only show the most meaningful information. Now it's much easier to read:\n\n```text\nfailures:\n\n---- two_is_two stdout ----\nthread 'two_is_two' panicked at 'assertion failed: `(left == right)`\n  left: `2`,\n right: `3`', src/lib.rs:3:5\nstack backtrace:\n   0: rust_begin_unwind\n             at /rustc/cb75ad5db02783e8b0222fee363c5f63f7e2cf5b/library/std/src/panicking.rs:493:5\n   1: core::panicking::panic_fmt\n             at /rustc/cb75ad5db02783e8b0222fee363c5f63f7e2cf5b/library/core/src/panicking.rs:92:14\n   2: playground::two_is_two\n             at ./src/lib.rs:3:5\n   3: playground::two_is_two::{{closure}}\n             at ./src/lib.rs:2:1\n   4: core::ops::function::FnOnce::call_once\n             at /rustc/cb75ad5db02783e8b0222fee363c5f63f7e2cf5b/library/core/src/ops/function.rs:227:5\n   5: core::ops::function::FnOnce::call_once\n             at /rustc/cb75ad5db02783e8b0222fee363c5f63f7e2cf5b/library/core/src/ops/function.rs:227:5\nnote: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.\n\n\nfailures:\n    two_is_two\n\ntest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.02s\n```\n\nNow let's turn backtrace off again and return to regular tests. Now we'll write some other functions, and use test functions to test them. Here are a few:\n\n```rust\nfn return_two() -> i8 {\n    2\n}\n#[test]\nfn it_returns_two() {\n    assert_eq!(return_two(), 2);\n}\n\nfn return_six() -> i8 {\n    4 + return_two()\n}\n#[test]\nfn it_returns_six() {\n    assert_eq!(return_six(), 6)\n}\n```\n\nNow it runs both:\n\n```text\nrunning 2 tests\ntest it_returns_two ... ok\ntest it_returns_six ... ok\n\ntest result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n```\n\nThat's not too hard.\n\nUsually you will want to put your tests in their own module. To do this, use the same `mod` keyword and add `#[cfg(test)]` above it (remember: `cfg` means \"configure\"). You also want to continue to write `#[test]` above each test. This is because later on when you install Rust, you can do more complicated testing. You will be able to run one test, or all of them, or run a few. Also don't forget to write `use super::*;` because the test module needs to use the functions above it. Now it will look like this:\n\n```rust\nfn return_two() -> i8 {\n    2\n}\nfn return_six() -> i8 {\n    4 + return_two()\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn it_returns_six() {\n        assert_eq!(return_six(), 6)\n    }\n    #[test]\n    fn it_returns_two() {\n        assert_eq!(return_two(), 2);\n    }\n}\n```\n\n### Test-driven development\n\nYou might see the words \"test-driven development\" when reading about Rust or another language. It's one way to write programs, and some people like it while others prefer something else. \"Test-driven development\" means \"writing tests first, then writing the code\". When you do this, you will have a lot of tests for everything you want your code to do. Then you start writing the code, and run the tests to see if you did it right. Then the tests are always there to show you if something goes wrong when you add to and rewrite your code. This is pretty easy in Rust because the compiler gives a lot of information about what to fix. Let's write a small example of test-driven development and see what it looks like.\n\nLet's imagine a calculator that takes user input. It can add (+) and it can subtract (-). If the user writes \"5 + 6\" it should return 11, if the user writes \"5 + 6 - 7\" it should return 4, and so on. So we'll start with test functions. You can also see that function names in tests are usually quite long. That is because you might run a lot of tests, and you want to understand which tests have failed.\n\nWe'll imagine that a single function called `math()` will do everything. It will return an `i32` (we won't use floats). Because it needs to return something, we'll just return `6` every time. Then we will write three test functions. They will all fail, of course. Now the code looks like this:\n\n```rust\nfn math(input: &str) -> i32 {\n    6\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn one_plus_one_is_two() {\n        assert_eq!(math(\"1 + 1\"), 2);\n    }\n    #[test]\n    fn one_minus_two_is_minus_one() {\n        assert_eq!(math(\"1 - 2\"), -1);\n    }\n    #[test]\n    fn one_minus_minus_one_is_two() {\n        assert_eq!(math(\"1 - -1\"), 2);\n    }\n}\n```\n\nIt gives us this information:\n\n```text\nrunning 3 tests\ntest tests::one_minus_minus_one_is_two ... FAILED\ntest tests::one_minus_two_is_minus_one ... FAILED\ntest tests::one_plus_one_is_two ... FAILED\n```\n\nand all the information about ``thread 'tests::one_plus_one_is_two' panicked at 'assertion failed: `(left == right)` ``. We don't need to print it all here.\n\nNow to think about how to make the calculator. We will accept any number, and the symbols `+-`. We will allow spaces, but nothing else. So let's start with a `const` that contains all the values. Then we will use `.chars()` to iterate by character, and `.all()` to make sure they are all inside.\n\nThen we will add a test that should panic. To do that, add `#[should_panic]` attribute: now if it panics the test will succeed.\n\nNow the code looks like this:\n\n```rust\nconst OKAY_CHARACTERS: &str = \"1234567890+- \"; // Don't forget the space at the end\n\nfn math(input: &str) -> i32 {\n    if !input.chars().all(|character| OKAY_CHARACTERS.contains(character)) {\n        panic!(\"Please only input numbers, +-, or spaces\");\n    }\n    6 // we still return a 6 for now\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn one_plus_one_is_two() {\n        assert_eq!(math(\"1 + 1\"), 2);\n    }\n    #[test]\n    fn one_minus_two_is_minus_one() {\n        assert_eq!(math(\"1 - 2\"), -1);\n    }\n    #[test]\n    fn one_minus_minus_one_is_two() {\n        assert_eq!(math(\"1 - -1\"), 2);\n    }\n\n    #[test]\n    #[should_panic]  // Here is our new test - it should panic\n    fn panics_when_characters_not_right() {\n        math(\"7 + seven\");\n    }\n}\n```\n\nNow when we run the tests we get this result:\n\n```text\nrunning 4 tests\ntest tests::one_minus_two_is_minus_one ... FAILED\ntest tests::one_minus_minus_one_is_two ... FAILED\ntest tests::panics_when_characters_not_right ... ok\ntest tests::one_plus_one_is_two ... FAILED\n```\n\nOne succeeded! Our `math()` function will only accept good input now.\n\n\nThe next step is to write the actual calculator. This is the interesting part about having tests first: the actual code starts much later. First we will put the logic together for the calculator. We want the following:\n\n- All empty spaces should be removed. This is easy with `.filter()`\n- The input should turn into a `Vec` with all the inputs. `+` doesn't need to be an input, but when the program sees `+` it should know that the number is done. For example, the input `11+1` should do something like this: 1) See `1`, push it into an empty string. 2) See another 1, push it into the string (it is now \"11\"). 3) See a `+`, know the number has ended. It will push the string into the vec, then clear the string.\n- The program must count the number of `-`. An odd number (1, 3, 5...) will mean subtract, an even number (2, 4, 6...) will mean add. So \"1--9\" should give 10, not -8.\n- The program should remove anything after the last number. `5+5+++++----` is made out of all the characters in `OKAY_CHARACTERS`, but it should turn to `5+5`. This is easy with `.trim_end_matches()`, where you remove anything that matches at the end of a `&str`.\n\n(By the way, `.trim_end_matches()` and `.trim_start_matches()` used to be `trim_right_matches()` and `trim_left_matches()`. But then people noticed that some languages go from right to left (Persian, Hebrew, etc.) so right and left were wrong. You might still see the older names in some code but they are the same thing.)\n\nFirst we just want to pass all the tests. After we pass the tests, we can \"refactor\". Refactor means to make code better, usually through things like structs and enums and methods. Here is our code to make the tests pass:\n\n```rust\nconst OKAY_CHARACTERS: &str = \"1234567890+- \";\n\nfn math(input: &str) -> i32 {\n    if !input.chars().all(|character| OKAY_CHARACTERS.contains(character)) ||\n       !input.chars().take(2).any(|character| character.is_numeric())\n    {\n        panic!(\"Please only input numbers, +-, or spaces.\");\n    }\n\n    let input = input.trim_end_matches(|x| \"+- \".contains(x)).chars().filter(|x| *x != ' ').collect::<String>(); // Remove + and - at the end, and all spaces\n    let mut result_vec = vec![]; // Results go in here\n    let mut push_string = String::new(); // This is the string we push in every time. We will keep reusing it in the loop.\n    for character in input.chars() {\n        match character {\n            '+' => {\n                if !push_string.is_empty() { // If the string is empty, we don't want to push \"\" into result_vec\n                    result_vec.push(push_string.clone()); // But if it's not empty, it will be a number. Push it into the vec\n                    push_string.clear(); // Then clear the string\n                }\n            },\n            '-' => { // If we get a -,\n                if push_string.contains('-') || push_string.is_empty() { // check to see if it's empty or has a -\n                    push_string.push(character) // if so, then push it in\n                } else { // otherwise, it will contain a number\n                result_vec.push(push_string.clone()); // so push the number into result_vec, clear it and then push -\n                push_string.clear();\n                push_string.push(character);\n                }\n            },\n            number => { // number here means \"anything else that matches\". We selected the name here\n                if push_string.contains('-') { // We might have some - characters to push in first\n                    result_vec.push(push_string.clone());\n                    push_string.clear();\n                    push_string.push(number);\n                } else { // But if we don't, that means we can push the number in\n                    push_string.push(number);\n                }\n            },\n        }\n    }\n    result_vec.push(push_string); // Push one last time after the loop is over. Don't need to .clone() because we don't use it anymore\n\n    let mut total = 0; // Now it's time to do math. Start with a total\n    let mut adds = true; // true = add, false = subtract\n    let mut math_iter = result_vec.into_iter();\n    while let Some(entry) = math_iter.next() { // Iter through the items\n        if entry.contains('-') { // If it has a - character, check if it's even or odd\n            if entry.chars().count() % 2 == 1 {\n                adds = match adds {\n                    true => false,\n                    false => true\n                };\n                continue; // Go to the next item\n            } else {\n                continue;\n            }\n        }\n        if adds == true {\n            total += entry.parse::<i32>().unwrap(); // If there is no '-', it must be a number. So we are safe to unwrap\n        } else {\n            total -= entry.parse::<i32>().unwrap();\n            adds = true;  // After subtracting, reset adds to true.\n        }\n    }\n    total // Finally, return the total\n}\n   /// We'll add a few more tests just to make sure\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn one_plus_one_is_two() {\n        assert_eq!(math(\"1 + 1\"), 2);\n    }\n    #[test]\n    fn one_minus_two_is_minus_one() {\n        assert_eq!(math(\"1 - 2\"), -1);\n    }\n    #[test]\n    fn one_minus_minus_one_is_two() {\n        assert_eq!(math(\"1 - -1\"), 2);\n    }\n    #[test]\n    fn nine_plus_nine_minus_nine_minus_nine_is_zero() {\n        assert_eq!(math(\"9+9-9-9\"), 0); // This is a new test\n    }\n    #[test]\n    fn eight_minus_nine_plus_nine_is_eight_even_with_characters_on_the_end() {\n        assert_eq!(math(\"8  - 9     +9-----+++++\"), 8); // This is a new test\n    }\n    #[test]\n    #[should_panic]\n    fn panics_when_characters_not_right() {\n        math(\"7 + seven\");\n    }\n}\n```\n\nAnd now the tests pass!\n\n```text\nrunning 6 tests\ntest tests::one_minus_minus_one_is_two ... ok\ntest tests::nine_plus_nine_minus_nine_minus_nine_is_zero ... ok\ntest tests::one_minus_two_is_minus_one ... ok\ntest tests::eight_minus_nine_plus_nine_is_eight_even_with_characters_on_the_end ... ok\ntest tests::one_plus_one_is_two ... ok\ntest tests::panics_when_characters_not_right ... ok\n\ntest result: ok. 6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n```\n\nYou can see that there is a back and forth process in test-driven development. It's something like this:\n\n- First you write all the tests you can think of.\n- Then you start writing the code.\n- As you write the code, you get ideas for other tests.\n- You add the tests, and your tests grow as you go. The more tests you have, the more times your code gets checked.\n\nOf course, tests don't check everything and it is wrong to think that \"passing all tests = the code is perfect\". But tests are great for when you change your code. If you change your code later on and run the tests, if one of them doesn't work you will know what to fix.\n\nNow we can rewrite (refactor) the code a bit. One good way to start is with clippy. If you installed Rust then you can type `cargo clippy`, and if you're using the Playground then click on `TOOLS` and select Clippy. Clippy will look at your code and give you tips to make it simpler. Our code doesn't have any mistakes, but it could be better.\n\nClippy tells us two things:\n\n```text\nwarning: this loop could be written as a `for` loop\n  --> src/lib.rs:44:5\n   |\n44 |     while let Some(entry) = math_iter.next() { // Iter through the items\n   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for entry in math_iter`\n   |\n   = note: `#[warn(clippy::while_let_on_iterator)]` on by default\n   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#while_let_on_iterator\n\nwarning: equality checks against true are unnecessary\n  --> src/lib.rs:53:12\n   |\n53 |         if adds == true {\n   |            ^^^^^^^^^^^^ help: try simplifying it as shown: `adds`\n   |\n   = note: `#[warn(clippy::bool_comparison)]` on by default\n   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#bool_comparison\n```\n\nThis is true: `for entry in math_iter` is much simpler than `while let Some(entry) = math_iter.next()`. And a `for` loop is actually an iterator so we don't have any reason to write `.iter()`. Thanks, clippy! And also we didn't need to make `math_iter`: we can just write `for entry in result_vec`.\n\nNow we'll start some real refactoring. Instead of separate variables, we will create a `Calculator` struct. This will have all the variables we used together. We will change two names to make it more clear. `result_vec` will become `results`, and `push_string` will become `current_input` (current means \"now\"). And so far it only has one method: new.\n\n```rust\n// 🚧\n#[derive(Clone)]\nstruct Calculator {\n    results: Vec<String>,\n    current_input: String,\n    total: i32,\n    adds: bool,\n}\n\nimpl Calculator {\n    fn new() -> Self {\n        Self {\n            results: vec![],\n            current_input: String::new(),\n            total: 0,\n            adds: true,\n        }\n    }\n}\n```\n\nNow our code is actually a bit longer, but easier to read. For example, `if adds` is now `if calculator.adds`, which is exactly like reading English. It looks like this:\n\n```rust\n#[derive(Clone)]\nstruct Calculator {\n    results: Vec<String>,\n    current_input: String,\n    total: i32,\n    adds: bool,\n}\n\nimpl Calculator {\n    fn new() -> Self {\n        Self {\n            results: vec![],\n            current_input: String::new(),\n            total: 0,\n            adds: true,\n        }\n    }\n}\n\nconst OKAY_CHARACTERS: &str = \"1234567890+- \";\n\nfn math(input: &str) -> i32 {\n    if !input.chars().all(|character| OKAY_CHARACTERS.contains(character)) ||\n       !input.chars().take(2).any(|character| character.is_numeric()) {\n        panic!(\"Please only input numbers, +-, or spaces\");\n    }\n\n    let input = input.trim_end_matches(|x| \"+- \".contains(x)).chars().filter(|x| *x != ' ').collect::<String>();\n    let mut calculator = Calculator::new();\n\n    for character in input.chars() {\n        match character {\n            '+' => {\n                if !calculator.current_input.is_empty() {\n                    calculator.results.push(calculator.current_input.clone());\n                    calculator.current_input.clear();\n                }\n            },\n            '-' => {\n                if calculator.current_input.contains('-') || calculator.current_input.is_empty() {\n                    calculator.current_input.push(character)\n                } else {\n                calculator.results.push(calculator.current_input.clone());\n                calculator.current_input.clear();\n                calculator.current_input.push(character);\n                }\n            },\n            number => {\n                if calculator.current_input.contains('-') {\n                    calculator.results.push(calculator.current_input.clone());\n                    calculator.current_input.clear();\n                    calculator.current_input.push(number);\n                } else {\n                    calculator.current_input.push(number);\n                }\n            },\n        }\n    }\n    calculator.results.push(calculator.current_input);\n\n    for entry in calculator.results {\n        if entry.contains('-') {\n            if entry.chars().count() % 2 == 1 {\n                calculator.adds = match calculator.adds {\n                    true => false,\n                    false => true\n                };\n                continue;\n            } else {\n                continue;\n            }\n        }\n        if calculator.adds {\n            calculator.total += entry.parse::<i32>().unwrap();\n        } else {\n            calculator.total -= entry.parse::<i32>().unwrap();\n            calculator.adds = true;\n        }\n    }\n    calculator.total\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn one_plus_one_is_two() {\n        assert_eq!(math(\"1 + 1\"), 2);\n    }\n    #[test]\n    fn one_minus_two_is_minus_one() {\n        assert_eq!(math(\"1 - 2\"), -1);\n    }\n    #[test]\n    fn one_minus_minus_one_is_two() {\n        assert_eq!(math(\"1 - -1\"), 2);\n    }\n    #[test]\n    fn nine_plus_nine_minus_nine_minus_nine_is_zero() {\n        assert_eq!(math(\"9+9-9-9\"), 0);\n    }\n    #[test]\n    fn eight_minus_nine_plus_nine_is_eight_even_with_characters_on_the_end() {\n        assert_eq!(math(\"8  - 9     +9-----+++++\"), 8);\n    }\n    #[test]\n    #[should_panic]\n    fn panics_when_characters_not_right() {\n        math(\"7 + seven\");\n    }\n}\n```\n\nFinally we add two new methods. One is called `.clear()` and clears the `current_input()`. The other one is called `push_char()` and pushes the input onto `current_input()`. Here is our refactored code:\n\n```rust\n#[derive(Clone)]\nstruct Calculator {\n    results: Vec<String>,\n    current_input: String,\n    total: i32,\n    adds: bool,\n}\n\nimpl Calculator {\n    fn new() -> Self {\n        Self {\n            results: vec![],\n            current_input: String::new(),\n            total: 0,\n            adds: true,\n        }\n    }\n\n    fn clear(&mut self) {\n        self.current_input.clear();\n    }\n\n    fn push_char(&mut self, character: char) {\n        self.current_input.push(character);\n    }\n}\n\nconst OKAY_CHARACTERS: &str = \"1234567890+- \";\n\nfn math(input: &str) -> i32 {\n    if !input.chars().all(|character| OKAY_CHARACTERS.contains(character)) ||\n       !input.chars().take(2).any(|character| character.is_numeric()) {\n        panic!(\"Please only input numbers, +-, or spaces\");\n    }\n\n    let input = input.trim_end_matches(|x| \"+- \".contains(x)).chars().filter(|x| *x != ' ').collect::<String>();\n    let mut calculator = Calculator::new();\n\n    for character in input.chars() {\n        match character {\n            '+' => {\n                if !calculator.current_input.is_empty() {\n                    calculator.results.push(calculator.current_input.clone());\n                    calculator.clear();\n                }\n            },\n            '-' => {\n                if calculator.current_input.contains('-') || calculator.current_input.is_empty() {\n                    calculator.push_char(character)\n                } else {\n                calculator.results.push(calculator.current_input.clone());\n                calculator.clear();\n                calculator.push_char(character);\n                }\n            },\n            number => {\n                if calculator.current_input.contains('-') {\n                    calculator.results.push(calculator.current_input.clone());\n                    calculator.clear();\n                    calculator.push_char(number);\n                } else {\n                    calculator.push_char(number);\n                }\n            },\n        }\n    }\n    calculator.results.push(calculator.current_input);\n\n    for entry in calculator.results {\n        if entry.contains('-') {\n            if entry.chars().count() % 2 == 1 {\n                calculator.adds = match calculator.adds {\n                    true => false,\n                    false => true\n                };\n                continue;\n            } else {\n                continue;\n            }\n        }\n        if calculator.adds {\n            calculator.total += entry.parse::<i32>().unwrap();\n        } else {\n            calculator.total -= entry.parse::<i32>().unwrap();\n            calculator.adds = true;\n        }\n    }\n    calculator.total\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn one_plus_one_is_two() {\n        assert_eq!(math(\"1 + 1\"), 2);\n    }\n    #[test]\n    fn one_minus_two_is_minus_one() {\n        assert_eq!(math(\"1 - 2\"), -1);\n    }\n    #[test]\n    fn one_minus_minus_one_is_two() {\n        assert_eq!(math(\"1 - -1\"), 2);\n    }\n    #[test]\n    fn nine_plus_nine_minus_nine_minus_nine_is_zero() {\n        assert_eq!(math(\"9+9-9-9\"), 0);\n    }\n    #[test]\n    fn eight_minus_nine_plus_nine_is_eight_even_with_characters_on_the_end() {\n        assert_eq!(math(\"8  - 9     +9-----+++++\"), 8);\n    }\n    #[test]\n    #[should_panic]\n    fn panics_when_characters_not_right() {\n        math(\"7 + seven\");\n    }\n}\n```\n\nThis is probably good enough for now. We could write more methods but lines like `calculator.results.push(calculator.current_input.clone());` are already very clear. Refactoring is best when you can still easily read the code after you are done. You don't want to just refactor to make the code short: `clc.clr()` is much worse than `calculator.clear()`, for example.\n\n\n\n## External crates\n\nAn external crate means \"someone else's crate\".\n\nFor this section you *almost* need to install Rust, but we can still use just the Playground. Now we are going to learn how to import crates that other people have written. This is important in Rust because of two reasons:\n\n- It is very easy to import other crates, and\n- The Rust standard library is quite small.\n\nThat means that it is normal in Rust to bring in an external crate for a lot of basic functions. The idea is that if it is easy to use external crates, then you can choose the best one. Maybe one person will make a crate for one function, and then someone else will make a better one.\n\nIn this book we will only look at the most popular crates, the crates that everyone who uses Rust knows.\n\nTo begin learning external crates, we will start with the most common one: `rand`.\n\n### rand\n\nDid you notice that we didn't use any random numbers yet? That's because random numbers aren't in the standard library. But there are a lot of crates that are \"almost standard library\" because everybody uses them. In any case, it's very easy to bring in a crate. If you have Rust on your computer, there is a file called `Cargo.toml` that has this information. A `Cargo.toml` file looks like this when you start:\n\n```text\n[package]\nname = \"rust_book\"\nversion = \"0.1.0\"\nauthors = [\"David MacLeod\"]\nedition = \"2018\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\n```\n\nNow if you want to add the `rand` crate, search for it on `crates.io`, which is where all the crates go. That takes you to `https://crates.io/crates/rand`. And when you click on that, you can see a screen that says `Cargo.toml   rand = \"0.7.3\"`. All you do is add that under [dependencies] like this:\n\n```text\n[package]\nname = \"rust_book\"\nversion = \"0.1.0\"\nauthors = [\"David MacLeod\"]\nedition = \"2018\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\nrand = \"0.7.3\"\n```\n\nAnd then Cargo will do the rest for you. Then you can start writing code like [this example code](https://docs.rs/rand/0.7.3/rand/) on the `rand` document website. To get to the documents you can click on the `docs` button in [the page on crates.io](https://crates.io/crates/rand).\n\nSo that's enough about Cargo: we are still using just the Playground. Luckily, the Playground already has the top 100 crates installed. So you don't need to write in `Cargo.toml` yet. On the Playground you can imagine that it has a long list like this with 100 crates:\n\n```text\n[dependencies]\nrand = \"0.7.3\"\nsome_other_crate = \"0.1.0\"\nanother_nice_crate = \"1.7\"\n```\n\nThat means that to use `rand`, you can just do this.\n\n```rust\nuse rand; // This means the whole crate rand\n          // On your computer you can't just write this;\n          // you need to write in the Cargo.toml file first\n\nfn main() {\n    for _ in 0..5 {\n        let random_u16 = rand::random::<u16>();\n        print!(\"{} \", random_u16);\n    }\n}\n```\n\nIt will print a different `u16` number every time, like `42266 52873 56528 46927 6867`.\n\n\nThe main functions in `rand` are `random` and `thread_rng` (rng means \"random number generator\"). And actually if you look at `random` it says: \"This is simply a shortcut for `thread_rng().gen()`\". So it's actually just `thread_rng` that does almost everything.\n\nHere is a simple example of numbers from 1 to 10. To get those numbers, we use `.gen_range()` between 1 and 11.\n\n```rust\nuse rand::{thread_rng, Rng}; // Or just use rand::*; if we are lazy\n\nfn main() {\n    let mut number_maker = thread_rng();\n    for _ in 0..5 {\n        print!(\"{} \", number_maker.gen_range(1, 11));\n    }\n}\n```\n\nThis will print something like `7 2 4 8 6`.\n\nWith random numbers we can do fun things like make characters for a game. We will use `rand` and some other things we know to make them. In this game our characters have six stats, and you use a d6 for them. A d6 is a cube that gives 1, 2, 3, 4, 5, or 6 when you throw it. Each character rolls a d6 three times, so each stat is between 3 and 18.\n\nBut sometimes it can be unfair if your character has something low like a 3 or 4. If your strength is 3 you can't carry anything, for example. So there is one more method that uses a d6 four times. You roll it four times, and throw away the lowest number. So if you roll 3, 3, 1, 6 then you keep 3, 3, 6 = 12. We will make this method too so the owner of the game can decide.\n\nHere is our simple character creator. We created a `Character` struct for the stats, and even implemented `Display` to print it the way we want.\n\n```rust\nuse rand::{thread_rng, Rng}; // Or just use rand::*; if we are lazy\nuse std::fmt; // Going to impl Display for our character\n\n\nstruct Character {\n    strength: u8,\n    dexterity: u8,    // This means \"body quickness\"\n    constitution: u8, // This means \"health\"\n    intelligence: u8,\n    wisdom: u8,\n    charisma: u8, // This means \"popularity with people\"\n}\n\nfn three_die_six() -> u8 { // A \"die\" is the thing you throw to get the number\n    let mut generator = thread_rng(); // Create our random number generator\n    let mut stat = 0; // This is the total\n    for _ in 0..3 {\n        stat += generator.gen_range(1..=6); // Add each time\n    }\n    stat // Return the total\n}\n\nfn four_die_six() -> u8 {\n    let mut generator = thread_rng();\n    let mut results = vec![]; // First put the numbers in a vec\n    for _ in 0..4 {\n        results.push(generator.gen_range(1..=6));\n    }\n    results.sort(); // Now a result like [4, 3, 2, 6] becomes [2, 3, 4, 6]\n    results.remove(0); // Now it would be [3, 4, 6]\n    results.iter().sum() // Return this result\n}\n\nenum Dice {\n    Three,\n    Four\n}\n\nimpl Character {\n    fn new(dice: Dice) -> Self { // true for three dice, false for four\n        match dice {\n            Dice::Three => Self {\n                strength: three_die_six(),\n                dexterity: three_die_six(),\n                constitution: three_die_six(),\n                intelligence: three_die_six(),\n                wisdom: three_die_six(),\n                charisma: three_die_six(),\n            },\n            Dice::Four => Self {\n                strength: four_die_six(),\n                dexterity: four_die_six(),\n                constitution: four_die_six(),\n                intelligence: four_die_six(),\n                wisdom: four_die_six(),\n                charisma: four_die_six(),\n            },\n        }\n    }\n    fn display(&self) { // We can do this because we implemented Display below\n        println!(\"{}\", self);\n        println!();\n    }\n}\n\nimpl fmt::Display for Character { // Just follow the code for in https://doc.rust-lang.org/std/fmt/trait.Display.html and change it a bit\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        write!(\n            f,\n            \"Your character has these stats:\nstrength: {}\ndexterity: {}\nconstitution: {}\nintelligence: {}\nwisdom: {}\ncharisma: {}\",\n            self.strength,\n            self.dexterity,\n            self.constitution,\n            self.intelligence,\n            self.wisdom,\n            self.charisma\n        )\n    }\n}\n\n\n\nfn main() {\n    let weak_billy = Character::new(Dice::Three);\n    let strong_billy = Character::new(Dice::Four);\n    weak_billy.display();\n    strong_billy.display();\n}\n```\n\nIt will print something like this:\n\n```rust\nYour character has these stats:\nstrength: 9\ndexterity: 15\nconstitution: 15\nintelligence: 8\nwisdom: 11\ncharisma: 9\n\nYour character has these stats:\nstrength: 9\ndexterity: 13\nconstitution: 14\nintelligence: 16\nwisdom: 16\ncharisma: 10\n```\n\nThe character with four dice is usually a bit better at most things.\n\n\n### rayon\n\n`rayon` is a popular crate that lets you speed up your Rust code. It's popular because it creates threads without needing things like `thread::spawn`. In other words, it is popular because it is effective but easy to write. For example:\n\n- `.iter()`, `.iter_mut()`, `into_iter()` in rayon is written like this:\n- `.par_iter()`, `.par_iter_mut()`, `par_into_iter()`. So you just add `par_` and your code becomes much faster. (par means \"parallel\")\n\nOther methods are the same: `.chars()` is `.par_chars()`, and so on.\n\nHere is an example of a simple piece of code that is making the computer do a lot of work:\n```rust\nfn main() {\n    let mut my_vec = vec![0; 200_000];\n    my_vec.iter_mut().enumerate().for_each(|(index, number)| *number+=index+1);\n    println!(\"{:?}\", &my_vec[5000..5005]);\n}\n```\n\nIt creates a vector with 200,000 items: each one is 0. Then it calls `.enumerate()` to get the index for each number, and changes the 0 to the index number. It's too long to print so we only print items 5000 to 5004. This is still very fast in Rust, but if you want you can make it faster with Rayon. The code is almost the same:\n\n```rust\nuse rayon::prelude::*; // Import rayon\n\nfn main() {\n    let mut my_vec = vec![0; 200_000];\n    my_vec.par_iter_mut().enumerate().for_each(|(index, number)| *number+=index+1); // add par_ to iter_mut\n    println!(\"{:?}\", &my_vec[5000..5005]);\n}\n```\n\nAnd that's it. `rayon` has many other methods to customize what you want to do, but at its most simple it is just \"add `_par` to make your program faster\".\n\n### serde\n\n`serde` is a popular crate that lets you convert to and from formats like JSON, YAML, etc. The most common way to use it is by creating a `struct` with two attributes on top. [It looks like this](https://serde.rs/):\n\n```rust\n#[derive(Serialize, Deserialize, Debug)]\nstruct Point {\n    x: i32,\n    y: i32,\n}\n```\n\nThe `Serialize` and `Deserialize` traits are what make the conversion easy. (That's also where the name `serde` comes from) If you have them on your struct, then you can just call a method to turn it into and from JSON or anything else.\n\n### regex\n\nThe [regex](https://crates.io/crates/regex) crate lets you search through text using [regular expressions](https://en.wikipedia.org/wiki/Regular_expression). With that you can get matches for something like `colour`, `color`, `colours` and `colors` through a single search. Regular expressions are a whole other language to learn if you want to use them.\n\n### chrono\n\n[chrono](https://crates.io/crates/chrono) is the main crate for people who need more functionality for time. We will look at the standard library now which has functions for time, but if you need more then this is a good crate to use.\n\n\n## A tour of the standard library\n\nNow that you know a lot of Rust, you will be able to understand most things inside the standard library. The code inside it isn't so scary anymore. Let's take a look at some of the parts in it that we haven't learned yet. This tour will go over most parts of the standard library that you don't need to install Rust for. We will revisit a lot of items we already know so we can learn them with greater understanding.\n\n### Arrays\n\nIn the past (before Rust 1.53), arrays didn't implement `Iterator` and you needed to use methods like `.iter()` on them in for `loops`. (People also used `&` to get a slice in `for` loops). So this didn't work in the past:\n\n```rust\nfn main() {\n    let my_cities = [\"Beirut\", \"Tel Aviv\", \"Nicosia\"];\n\n    for city in my_cities {\n        println!(\"{}\", city);\n    }\n}\n```\n\nThe compiler used to give this message:\n\n```text\nerror[E0277]: `[&str; 3]` is not an iterator\n --> src\\main.rs:5:17\n  |\n  |                 ^^^^^^^^^ borrow the array with `&` or call `.iter()` on it to iterate over it\n```\n\nLuckily, that isn't a problem anymore! So all three of these work:\n\n```rust\nfn main() {\n    let my_cities = [\"Beirut\", \"Tel Aviv\", \"Nicosia\"];\n\n    for city in my_cities {\n        println!(\"{}\", city);\n    }\n    for city in &my_cities {\n        println!(\"{}\", city);\n    }\n    for city in my_cities.iter() {\n        println!(\"{}\", city);\n    }\n}\n```\n\nThis prints:\n\n```text\nBeirut\nTel Aviv\nNicosia\nBeirut\nTel Aviv\nNicosia\nBeirut\nTel Aviv\nNicosia\n```\n\n\n\nIf you want to get variables from an array, you can put their names inside `[]` to destructure it. This is the same as using a tuple in `match` statements or destructuring to get variables from a struct.\n\n```rust\nfn main() {\n    let my_cities = [\"Beirut\", \"Tel Aviv\", \"Nicosia\"];\n    let [city1, city2, city3] = my_cities;\n    println!(\"{}\", city1);\n}\n```\n\nThis prints `Beirut`.\n\n### char\n\nYou can use the `.escape_unicode()` method to get the Unicode number for a `char`:\n\n```rust\nfn main() {\n    let korean_word = \"청춘예찬\";\n    for character in korean_word.chars() {\n        print!(\"{} \", character.escape_unicode());\n    }\n}\n```\n\nThis prints `\\u{ccad} \\u{cd98} \\u{c608} \\u{cc2c}`.\n\n\nYou can get a char from `u8` using the `From` trait, but for a `u32` you use `TryFrom` because it might not work. There are many more numbers in `u32` than characters in Unicode. We can see this with a simple demonstration.\n\n```rust\nuse std::convert::TryFrom; // You need to bring TryFrom in to use it\nuse rand::prelude::*;      // We will use random numbers too\n\nfn main() {\n    let some_character = char::from(99); // This one is easy - no need for TryFrom\n    println!(\"{}\", some_character);\n\n    let mut random_generator = rand::thread_rng();\n    // This will try 40,000 times to make a char from a u32.\n    // The range is 0 (std::u32::MIN) to u32's highest number (std::u32::MAX). If it doesn't work, we will give it '-'.\n    for _ in 0..40_000 {\n        let bigger_character = char::try_from(random_generator.gen_range(std::u32::MIN..std::u32::MAX)).unwrap_or('-');\n        print!(\"{}\", bigger_character)\n    }\n}\n```\n\nAlmost every time it will generate a `-`. This is part of the sort of output you will see:\n\n```text\n------------------------------------------------------------------------𤒰---------------------\n-----------------------------------------------------------------------------------------------\n-----------------------------------------------------------------------------------------------\n-----------------------------------------------------------------------------------------------\n-----------------------------------------------------------------------------------------------\n-----------------------------------------------------------------------------------------------\n-----------------------------------------------------------------------------------------------\n-----------------------------------------------------------------------------------------------\n-------------------------------------------------------------춗--------------------------------\n-----------------------------------------------------------------------------------------------\n-----------------------------------------------------------------------------------------------\n-----------------------------------------------------------------------------------------------\n------------򇍜----------------------------------------------------\n```\n\nSo it's a good thing you need to use `TryFrom`.\n\nAlso, as of late August 2020 you can now get a `String` from a `char`. (`String` implements `From<char>`) Just write `String::from()` and put a `char` inside.\n\n\n### Integers\n\nThere are a lot of math methods for these types, plus some others. Here are some of the most useful ones.\n\n\n\n`.checked_add()`, `.checked_sub()`, `.checked_mul()`, `.checked_div()`. These are good methods if you think you might get a number that won't fit into a type. They return an `Option` so you can safely check that your math works without making the program panic.\n\n```rust\nfn main() {\n    let some_number = 200_u8;\n    let other_number = 200_u8;\n\n    println!(\"{:?}\", some_number.checked_add(other_number));\n    println!(\"{:?}\", some_number.checked_add(1));\n}\n```\n\nThis prints:\n\n```text\nNone\nSome(201)\n```\n\n\nYou'll notice that on the page for integers it says `rhs` a lot. This means \"right hand side\", which is the right hand side when you do some math. For example, in `5 + 6`, `5` is on the left and `6` is on the right, so it's the `rhs`. This is not a keyword, but you will see it a lot so it's good to know.\n\nWhile we are on the subject, let's learn how to implement `Add`. After you implement `Add`, you can use `+` on a type that you create. You need to implement `Add` yourself because add can mean a lot of things. Here's the example in the standard library page:\n\n```rust\nuse std::ops::Add; // first bring in Add\n\n#[derive(Debug, Copy, Clone, PartialEq)] // PartialEq is probably the most important part here. You want to be able to compare numbers\nstruct Point {\n    x: i32,\n    y: i32,\n}\n\nimpl Add for Point {\n    type Output = Self; // Remember, this is called an \"associated type\": a \"type that goes together\".\n                        // In this case it's just another Point\n\n    fn add(self, other: Self) -> Self {\n        Self {\n            x: self.x + other.x,\n            y: self.y + other.y,\n        }\n    }\n}\n```\n\nNow let's implement `Add` for our own type. Let's imagine that we want to add two countries together so we can compare their economies. It looks like this:\n\n```rust\nuse std::fmt;\nuse std::ops::Add;\n\n#[derive(Clone)]\nstruct Country {\n    name: String,\n    population: u32,\n    gdp: u32, // This is the size of the economy\n}\n\nimpl Country {\n    fn new(name: &str, population: u32, gdp: u32) -> Self {\n        Self {\n            name: name.to_string(),\n            population,\n            gdp,\n        }\n    }\n}\n\nimpl Add for Country {\n    type Output = Self;\n\n    fn add(self, other: Self) -> Self {\n        Self {\n            name: format!(\"{} and {}\", self.name, other.name), // We will add the names together,\n            population: self.population + other.population, // and the population,\n            gdp: self.gdp + other.gdp,   // and the GDP\n        }\n    }\n}\n\nimpl fmt::Display for Country {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        write!(\n            f,\n            \"In {} are {} people and a GDP of ${}\", // Then we can print them all with just {}\n            self.name, self.population, self.gdp\n        )\n    }\n}\n\nfn main() {\n    let nauru = Country::new(\"Nauru\", 10_670, 160_000_000);\n    let vanuatu = Country::new(\"Vanuatu\", 307_815, 820_000_000);\n    let micronesia = Country::new(\"Micronesia\", 104_468, 367_000_000);\n\n    // We could have given Country a &str instead of a String for the name. But we would have to write lifetimes everywhere\n    // and that would be too much for a small example. Better to just clone them when we call println!.\n    println!(\"{}\", nauru.clone());\n    println!(\"{}\", nauru.clone() + vanuatu.clone());\n    println!(\"{}\", nauru + vanuatu + micronesia);\n}\n```\n\nThis prints:\n\n```text\nIn Nauru are 10670 people and a GDP of $160000000\nIn Nauru and Vanuatu are 318485 people and a GDP of $980000000\nIn Nauru and Vanuatu and Micronesia are 422953 people and a GDP of $1347000000\n```\n\nLater on in this code we could change `.fmt()` to display a number that is easier to read.\n\nThe three others are called `Sub`, `Mul`, and `Div`, and they are basically the same to implement. For `+=`, `-=`, `*=` and `/=`, just add `Assign`: `AddAssign`, `SubAssign`, `MulAssign`, and `DivAssign`. You can see the full list [here](https://doc.rust-lang.org/std/ops/index.html#structs), because there are many more. `%` for example is called `Rem`, `-` is called `Neg`, and so on.\n\n\n### Floats\n\n`f32` and `f64` have a very large number of methods that you use when doing math. We won't look at those, but here are some methods that you might use. They are: `.floor()`, `.ceil()`, `.round()`, and `.trunc()`. All of these return an `f32` or `f64` that is like an integer, with only `0` after the period. They do this:\n\n- `.floor()`: gives you the next lowest integer.\n- `.ceil()`: gives you the next highest integer.\n- `.round()`: gives you a higher number if 0.5 or more, or the same number if less than 0.5. This is called rounding because it gives you a \"round\" number (a number that has a short, simple form).\n- `.trunc()`: just cuts off the part after the period. Truncate means \"to cut off\".\n\nHere is a simple function to print them.\n\n```rust\nfn four_operations(input: f64) {\n    println!(\n\"For the number {}:\nfloor: {}\nceiling: {}\nrounded: {}\ntruncated: {}\\n\",\n        input,\n        input.floor(),\n        input.ceil(),\n        input.round(),\n        input.trunc()\n    );\n}\n\nfn main() {\n    four_operations(9.1);\n    four_operations(100.7);\n    four_operations(-1.1);\n    four_operations(-19.9);\n}\n```\n\nThis prints:\n\n```text\nFor the number 9.1:\nfloor: 9\nceiling: 10\nrounded: 9 // because less than 9.5\ntruncated: 9\n\nFor the number 100.7:\nfloor: 100\nceiling: 101\nrounded: 101 // because more than 100.5\ntruncated: 100\n\nFor the number -1.1:\nfloor: -2\nceiling: -1\nrounded: -1\ntruncated: -1\n\nFor the number -19.9:\nfloor: -20\nceiling: -19\nrounded: -20\ntruncated: -19\n```\n\n`f32` and `f64` have a method called `.max()` and `.min()` that gives you the higher or the lower of two numbers. (For other types you can just use `std::cmp::max` and `std::cmp::min`.) Here is a way to use this with `.fold()` to get the highest or lowest number. You can see again that `.fold()` isn't just for adding numbers.\n\n```rust\nfn main() {\n    let my_vec = vec![8.0_f64, 7.6, 9.4, 10.0, 22.0, 77.345, 10.22, 3.2, -7.77, -10.0];\n    let maximum = my_vec.iter().fold(f64::MIN, |current_number, next_number| current_number.max(*next_number)); // Note: start with the lowest possible number for an f64.\n    let minimum = my_vec.iter().fold(f64::MAX, |current_number, next_number| current_number.min(*next_number)); // And here start with the highest possible number\n    println!(\"{}, {}\", maximum, minimum);\n}\n```\n\n### bool\n\nIn Rust you can turn a `bool` into an integer if you want, because it's safe to do that. But you can't do it the other way around. As you can see, `true` turns to 1 and `false` turns to 0.\n\n```rust\nfn main() {\n    let true_false = (true, false);\n    println!(\"{} {}\", true_false.0 as u8, true_false.1 as i32);\n}\n```\n\nThis prints `1 0`. Or you can use `.into()` if you tell the compiler the type:\n\n```rust\nfn main() {\n    let true_false: (i128, u16) = (true.into(), false.into());\n    println!(\"{} {}\", true_false.0, true_false.1);\n}\n```\n\nThis prints the same thing.\n\nAs of Rust 1.50 (released in February 2021), there is now a method called `then()`, which turns a `bool` into an `Option`. With `then()` you write a closure, and the closure is called if the item is `true`. Also, whatever is returned from the closure goes inside the `Option`. Here's a small example:\n\n```rust\nfn main() {\n\n    let (tru, fals) = (true.then(|| 8), false.then(|| 8));\n    println!(\"{:?}, {:?}\", tru, fals);\n}\n```\n\nThis just prints `Some(8), None`.\n\nAnd now a bit larger example:\n\n```rust\nfn main() {\n    let bool_vec = vec![true, false, true, false, false];\n    \n    let option_vec = bool_vec\n        .iter()\n        .map(|item| {\n            item.then(|| { // Put this inside of map so we can pass it on\n                println!(\"Got a {}!\", item);\n                \"It's true, you know\" // This goes inside Some if it's true\n                                      // Otherwise it just passes on None\n            })\n        })\n        .collect::<Vec<_>>();\n\n    println!(\"Now we have: {:?}\", option_vec);\n\n    // That printed out the Nones too. Let's filter map them out in a new Vec.\n    let filtered_vec = option_vec.into_iter().filter_map(|c| c).collect::<Vec<_>>();\n\n    println!(\"And without the Nones: {:?}\", filtered_vec);\n}\n```\n\nAnd here's what this prints:\n\n```text\nGot a true!\nGot a true!\nNow we have: [Some(\"It\\'s true, you know\"), None, Some(\"It\\'s true, you know\"), None, None]\nAnd without the Nones: [\"It\\'s true, you know\", \"It\\'s true, you know\"]\n```\n\n### Vec\n\nVec has a lot of methods that we haven't looked at yet. Let's start with `.sort()`. `.sort()` is not surprising at all. It uses a `&mut self` to sort a vector.\n\n```rust\nfn main() {\n    let mut my_vec = vec![100, 90, 80, 0, 0, 0, 0, 0];\n    my_vec.sort();\n    println!(\"{:?}\", my_vec);\n}\n```\n\nThis prints `[0, 0, 0, 0, 0, 80, 90, 100]`. But there is one more interesting way to sort called `.sort_unstable()`, and it is usually faster. It can be faster because it doesn't care about the order of numbers if they are the same number. In regular `.sort()`, you know that the last `0, 0, 0, 0, 0` will be in the same order after `.sort()`. But `.sort_unstable()` might move the last zero to index 0, then the third last zero to index 2, etc.\n\n\n`.dedup()` means \"de-duplicate\". It will remove items that are the same in a vector, but only if they are next to each other. This next code will not just print `\"sun\", \"moon\"`:\n\n```rust\nfn main() {\n    let mut my_vec = vec![\"sun\", \"sun\", \"moon\", \"moon\", \"sun\", \"moon\", \"moon\"];\n    my_vec.dedup();\n    println!(\"{:?}\", my_vec);\n}\n```\n\nIt only gets rid of \"sun\" next to the other \"sun\", then \"moon\" next to one \"moon\", and again with \"moon\" next to another \"moon\". The result is: `[\"sun\", \"moon\", \"sun\", \"moon\"]`.\n\nIf you want to remove every duplicate, just `.sort()` first:\n\n```rust\nfn main() {\n    let mut my_vec = vec![\"sun\", \"sun\", \"moon\", \"moon\", \"sun\", \"moon\", \"moon\"];\n    my_vec.sort();\n    my_vec.dedup();\n    println!(\"{:?}\", my_vec);\n}\n```\n\nResult: `[\"moon\", \"sun\"]`.\n\n\n### String\n\nYou will remember that a `String` is kind of like a `Vec`. It is so like a `Vec` that you can do a lot of the same methods. For example, you can start one with `String::with_capacity()`. You want that if you are always going to be pushing a `char` with `.push()` or pushing a `&str` with `.push_str()`. Here's an example of a `String` that has too many allocations.\n\n```rust\nfn main() {\n    let mut push_string = String::new();\n    let mut capacity_counter = 0; // capacity starts at 0\n    for _ in 0..100_000 { // Do this 100,000 times\n        if push_string.capacity() != capacity_counter { // First check if capacity is different now\n            println!(\"{}\", push_string.capacity()); // If it is, print it\n            capacity_counter = push_string.capacity(); // then update the counter\n        }\n        push_string.push_str(\"I'm getting pushed into the string!\"); // and push this in every time\n    }\n}\n```\n\nThis prints:\n\n```text\n35\n70\n140\n280\n560\n1120\n2240\n4480\n8960\n17920\n35840\n71680\n143360\n286720\n573440\n1146880\n2293760\n4587520\n```\n\nWe had to reallocate (copy everything over) 18 times. But now we know the final capacity. So we'll give it the capacity right away, and we don't need to reallocate: just one `String` capacity is enough.\n\n```rust\nfn main() {\n    let mut push_string = String::with_capacity(4587520); // We know the exact number. Some different big number could work too\n    let mut capacity_counter = 0;\n    for _ in 0..100_000 {\n        if push_string.capacity() != capacity_counter {\n            println!(\"{}\", push_string.capacity());\n            capacity_counter = push_string.capacity();\n        }\n        push_string.push_str(\"I'm getting pushed into the string!\");\n    }\n}\n```\n\nAnd this prints `4587520`. Perfect! We never had to allocate again.\n\nOf course, the actual length is certainly smaller than this. If you try 100,001 times, 101,000 times, etc., it'll still say `4587520`. That's because each time the capacity is two times what it was before. We can shrink it though with `.shrink_to_fit()` (same as for a `Vec`). Our `String` is very large and we don't want to add anything more to it, so we can make it a bit smaller. But only do this if you are sure. Here is why:\n\n```rust\nfn main() {\n    let mut push_string = String::with_capacity(4587520);\n    let mut capacity_counter = 0;\n    for _ in 0..100_000 {\n        if push_string.capacity() != capacity_counter {\n            println!(\"{}\", push_string.capacity());\n            capacity_counter = push_string.capacity();\n        }\n        push_string.push_str(\"I'm getting pushed into the string!\");\n    }\n    push_string.shrink_to_fit();\n    println!(\"{}\", push_string.capacity());\n    push_string.push('a');\n    println!(\"{}\", push_string.capacity());\n    push_string.shrink_to_fit();\n    println!(\"{}\", push_string.capacity());\n}\n```\n\nThis prints:\n\n```text\n4587520\n3500000\n7000000\n3500001\n```\n\nSo first we had a size of `4587520`, but we weren't using it all. We used `.shrink_to_fit()` and got the size down to `3500000`. But then we forget that we needed to push an `a` on. When we did that, Rust saw that we needed more space and gave us double: now it's `7000000`. Whoops! So we did `.shrink_to_fit()` again and now it's back down to `3500001`.\n\n`.pop()` works for a `String`, just like for a `Vec`.\n\n```rust\nfn main() {\n    let mut my_string = String::from(\".daer ot drah tib elttil a si gnirts sihT\");\n    loop {\n        let pop_result = my_string.pop();\n        match pop_result {\n            Some(character) => print!(\"{}\", character),\n            None => break,\n        }\n    }\n}\n```\n\nThis prints `This string is a little bit hard to read.` because it starts from the last character.\n\n`.retain()` is a method that uses a closure, which is rare for `String`. It's just like `.filter()` for an iterator.\n\n```rust\nfn main() {\n    let mut my_string = String::from(\"Age: 20 Height: 194 Weight: 80\");\n    my_string.retain(|character| character.is_alphabetic() || character == ' '); // Keep if a letter or a space\n    dbg!(my_string); // Let's use dbg!() for fun this time instead of println!\n}\n```\n\nThis prints:\n\n```text\n[src\\main.rs:4] my_string = \"Age  Height  Weight \"\n```\n\n\n### OsString and CString\n\n`std::ffi` is the part of `std` that helps you use Rust with other languages or operating systems. It has types like `OsString` and `CString`, which are like `String` for the operating system or `String` for the language C. They each have their own `&str` type too: `OsStr` and `CStr`. `ffi` means \"foreign function interface\".\n\nYou can use `OsString` when you have to work with an operating system that doesn't have Unicode. All Rust strings are unicode, but not every operating system has it. Here is the simple English explanation from the standard library on why we have `OsString`:\n\n- A string on Unix (Linux, etc.) might be lots of bytes together that don't have zeros. And sometimes you read them as Unicode UTF-8.\n- A string on Windows might be made of random 16-bit values that don't have zeros. And sometimes you read them as Unicode UTF-16.\n- In Rust, strings are always valid UTF-8, which may contain zeros.\n\nSo an `OsString` is made to be read by all of them.\n\nYou can do all the regular things with an `OsString` like `OsString::from(\"Write something here\")`. It also has an interesting method called `.into_string()` that tries to make it into a regular `String`. It returns a `Result`, but the `Err` part is just the original `OsString`:\n\n```rust\n// 🚧\npub fn into_string(self) -> Result<String, OsString>\n```\n\nSo if it doesn't work then you just get it back. You can't call `.unwrap()` because it will panic, but you can use `match` to get the `OsString` back. Let's test it out by calling methods that don't exist.\n\n```rust\nuse std::ffi::OsString;\n\nfn main() {\n    // ⚠️\n    let os_string = OsString::from(\"This string works for your OS too.\");\n    match os_string.into_string() {\n        Ok(valid) => valid.thth(),           // Compiler: \"What's .thth()??\"\n        Err(not_valid) => not_valid.occg(),  // Compiler: \"What's .occg()??\"\n    }\n}\n```\n\nThen the compiler tells us exactly what we want to know:\n\n```text\nerror[E0599]: no method named `thth` found for struct `std::string::String` in the current scope\n --> src/main.rs:6:28\n  |\n6 |         Ok(valid) => valid.thth(),\n  |                            ^^^^ method not found in `std::string::String`\n\nerror[E0599]: no method named `occg` found for struct `std::ffi::OsString` in the current scope\n --> src/main.rs:7:37\n  |\n7 |         Err(not_valid) => not_valid.occg(),\n  |                                     ^^^^ method not found in `std::ffi::OsString`\n```\n\nWe can see that the type of `valid` is `String` and the type of `not_valid` is `OsString`.\n\n### mem\n\n`std::mem` has some pretty interesting methods. We saw some of them already, such as `.size_of()`, `.size_of_val()` and `.drop()`:\n\n\n```rust\nuse std::mem;\n\nfn main() {\n    println!(\"{}\", mem::size_of::<i32>());\n    let my_array = [8; 50];\n    println!(\"{}\", mem::size_of_val(&my_array));\n    let mut some_string = String::from(\"You can drop a String because it's on the heap\");\n    mem::drop(some_string);\n    // some_string.clear();   If we did this it would panic\n}\n```\n\nThis prints:\n\n```text\n4\n200\n```\n\nHere are some other methods in `mem`:\n\n`swap()`: with this you can change the values between two variables. You use a mutable reference for each to do it. This is helpful when you have two things you want to switch and Rust doesn't let you because of borrowing rules. Or just when you want to quickly switch two things.\n\nHere's one example:\n\n```rust\nuse std::{mem, fmt};\n\nstruct Ring { // Create a ring from Lord of the Rings\n    owner: String,\n    former_owner: String,\n    seeker: String, // seeker means \"person looking for it\"\n}\n\nimpl Ring {\n    fn new(owner: &str, former_owner: &str, seeker: &str) -> Self {\n        Self {\n            owner: owner.to_string(),\n            former_owner: former_owner.to_string(),\n            seeker: seeker.to_string(),\n        }\n    }\n}\n\nimpl fmt::Display for Ring { // Display to show who has it and who wants it\n        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n            write!(f, \"{} has the ring, {} used to have it, and {} wants it\", self.owner, self.former_owner, self.seeker)\n        }\n}\n\nfn main() {\n    let mut one_ring = Ring::new(\"Frodo\", \"Gollum\", \"Sauron\");\n    println!(\"{}\", one_ring);\n    mem::swap(&mut one_ring.owner, &mut one_ring.former_owner); // Gollum got the ring back for a second\n    println!(\"{}\", one_ring);\n}\n```\n\nThis will print:\n\n```text\nFrodo has the ring, Gollum used to have it, and Sauron wants it\nGollum has the ring, Frodo used to have it, and Sauron wants it\n```\n\n`replace()`: this is like swap, and actually uses swap inside it, as you can see:\n\n```rust\npub fn replace<T>(dest: &mut T, mut src: T) -> T {\n    swap(dest, &mut src);\n    src\n}\n```\n\nSo it just does a swap and then returns the other item. With this you replace the value with something else you put in. And since it returns the old value, so you should use it with `let`. Here's a quick example.\n\n```rust\nuse std::mem;\n\nstruct City {\n    name: String,\n}\n\nimpl City {\n    fn change_name(&mut self, name: &str) {\n        let old_name = mem::replace(&mut self.name, name.to_string());\n        println!(\n            \"The city once called {} is now called {}.\",\n            old_name, self.name\n        );\n    }\n}\n\nfn main() {\n    let mut capital_city = City {\n        name: \"Constantinople\".to_string(),\n    };\n    capital_city.change_name(\"Istanbul\");\n}\n```\n\nThis prints `The city once called Constantinople is now called Istanbul.`.\n\nOne function called `.take()` is like `.replace()` but it leaves the default value in the item. You will remember that default values are usually things like 0, \"\", and so on. Here is the signature:\n\n```rust\n// 🚧\npub fn take<T>(dest: &mut T) -> T\nwhere\n    T: Default,\n```\n\nSo you can do something like this:\n\n```rust\nuse std::mem;\n\nfn main() {\n    let mut number_vec = vec![8, 7, 0, 2, 49, 9999];\n    let mut new_vec = vec![];\n\n    number_vec.iter_mut().for_each(|number| {\n        let taker = mem::take(number);\n        new_vec.push(taker);\n    });\n\n    println!(\"{:?}\\n{:?}\", number_vec, new_vec);\n}\n```\n\nAnd as you can see, it replaced all the numbers with 0: no index was deleted.\n\n```text\n[0, 0, 0, 0, 0, 0]\n[8, 7, 0, 2, 49, 9999]\n```\n\n\nOf course, for your own type you can implement `Default` to whatever you want. Let's look at an example where we have a `Bank` and a `Robber`. Every time he robs the `Bank`, he gets the money at the desk. But the desk can take money from the back any time, so it always has 50. We will make our own type for this so it will always have 50. Here is how it works:\n\n```rust\nuse std::mem;\nuse std::ops::{Deref, DerefMut}; // We will use this to get the power of u32\n\nstruct Bank {\n    money_inside: u32,\n    money_at_desk: DeskMoney, // This is our \"smart pointer\" type. It has its own default, but it will use u32\n}\n\nstruct DeskMoney(u32);\n\nimpl Default for DeskMoney {\n    fn default() -> Self {\n        Self(50) // default is always 50, not 0\n    }\n}\n\nimpl Deref for DeskMoney { // With this we can access the u32 using *\n    type Target = u32;\n\n    fn deref(&self) -> &Self::Target {\n        &self.0\n    }\n}\n\nimpl DerefMut for DeskMoney { // And with this we can add, subtract, etc.\n    fn deref_mut(&mut self) -> &mut Self::Target {\n        &mut self.0\n    }\n}\n\nimpl Bank {\n    fn check_money(&self) {\n        println!(\n            \"There is ${} in the back and ${} at the desk.\\n\",\n            self.money_inside, *self.money_at_desk // Use * so we can just print the u32\n        );\n    }\n}\n\nstruct Robber {\n    money_in_pocket: u32,\n}\n\nimpl Robber {\n    fn check_money(&self) {\n        println!(\"The robber has ${} right now.\\n\", self.money_in_pocket);\n    }\n\n    fn rob_bank(&mut self, bank: &mut Bank) {\n        let new_money = mem::take(&mut bank.money_at_desk); // Here it takes the money, and leaves 50 because that is the default\n        self.money_in_pocket += *new_money; // Use * because we can only add u32. DeskMoney can't add\n        bank.money_inside -= *new_money;    // Same here\n        println!(\"She robbed the bank. She now has ${}!\\n\", self.money_in_pocket);\n    }\n}\n\nfn main() {\n    let mut bank_of_klezkavania = Bank { // Set up our bank\n        money_inside: 5000,\n        money_at_desk: DeskMoney(50),\n    };\n    bank_of_klezkavania.check_money();\n\n    let mut robber = Robber { // Set up our robber\n        money_in_pocket: 50,\n    };\n    robber.check_money();\n\n    robber.rob_bank(&mut bank_of_klezkavania); // Rob, then check money\n    robber.check_money();\n    bank_of_klezkavania.check_money();\n\n    robber.rob_bank(&mut bank_of_klezkavania); // Do it again\n    robber.check_money();\n    bank_of_klezkavania.check_money();\n\n}\n```\n\nThis will print:\n\n```text\nThere is $5000 in the back and $50 at the desk.\n\nThe robber has $50 right now.\n\nShe robbed the bank. She now has $100!\n\nThe robber has $100 right now.\n\nThere is $4950 in the back and $50 at the desk.\n\nShe robbed the bank. She now has $150!\n\nThe robber has $150 right now.\n\nThere is $4900 in the back and $50 at the desk.\n```\n\nYou can see that there is always $50 at the desk.\n\n\n### prelude\n\nThe standard library has a prelude too, which is why you don't have to write things like `use std::vec::Vec` to create a `Vec`. You can see all the items [here](https://doc.rust-lang.org/std/prelude/index.html#prelude-contents), and will already know almost all of them:\n\n- `std::marker::{Copy, Send, Sized, Sync, Unpin}`. You haven't seen `Unpin` before, because it is used for almost every type (like `Sized`, which is also very common). To \"pin\" means to not let something move. In this case a `Pin` means that it can't move in memory, but most items have `Unpin` so you can. That's why functions like `std::mem::replace` work, because they aren't pinned.\n- `std::ops::{Drop, Fn, FnMut, FnOnce}`.\n- `std::mem::drop`\n- `std::boxed::Box`.\n- `std::borrow::ToOwned`. You saw this before a bit with `Cow`, which can take borrowed content and make it owned. It uses `.to_owned()` to do this. You can also use `.to_owned()` on a `&str` to get a `String`, and the same for other borrowed values.\n- `std::clone::Clone`\n- `std::cmp::{PartialEq, PartialOrd, Eq, Ord}`.\n- `std::convert::{AsRef, AsMut, Into, From}`.\n- `std::default::Default`.\n- `std::iter::{Iterator, Extend, IntoIterator, DoubleEndedIterator, ExactSizeIterator}`. We used `.rev()` for an iterator before: this actually makes a `DoubleEndedIterator`. An `ExactSizeIterator` is just something like `0..10`: it already knows that it has a `.len()` of 10. Other iterators don't know their length for sure.\n- `std::option::Option::{self, Some, None}`.\n- `std::result::Result::{self, Ok, Err}`.\n- `std::string::{String, ToString}`.\n- `std::vec::Vec`.\n\nWhat if you don't want the prelude for some reason? Just add the attribute `#![no_implicit_prelude]`. Let's give it a try and watch the compiler complain:\n\n```rust\n// ⚠️\n#![no_implicit_prelude]\nfn main() {\n    let my_vec = vec![8, 9, 10];\n    let my_string = String::from(\"This won't work\");\n    println!(\"{:?}, {}\", my_vec, my_string);\n}\n```\n\nNow Rust has no idea what you are trying to do:\n\n```text\nerror: cannot find macro `println` in this scope\n --> src/main.rs:5:5\n  |\n5 |     println!(\"{:?}, {}\", my_vec, my_string);\n  |     ^^^^^^^\n\nerror: cannot find macro `vec` in this scope\n --> src/main.rs:3:18\n  |\n3 |     let my_vec = vec![8, 9, 10];\n  |                  ^^^\n\nerror[E0433]: failed to resolve: use of undeclared type or module `String`\n --> src/main.rs:4:21\n  |\n4 |     let my_string = String::from(\"This won't work\");\n  |                     ^^^^^^ use of undeclared type or module `String`\n\nerror: aborting due to 3 previous errors\n```\n\nSo for this simple code you need to tell Rust to use the `extern` (external) crate called `std`, and then the items you want. Here is everything we have to do just to create a Vec and a String and print it:\n\n```rust\n#![no_implicit_prelude]\n\nextern crate std; // Now you have to tell Rust that you want to use a crate called std\nuse std::vec; // We need the vec macro\nuse std::string::String; // and string\nuse std::convert::From; // and this to convert from a &str to the String\nuse std::println; // and this to print\n\nfn main() {\n    let my_vec = vec![8, 9, 10];\n    let my_string = String::from(\"This won't work\");\n    println!(\"{:?}, {}\", my_vec, my_string);\n}\n```\n\nAnd now it finally works, printing `[8, 9, 10], This won't work`. So you can see why Rust uses the prelude. But if you want, you don't need to use it. And you can even use `#![no_std]` (we saw this once) for when you can't even use something like stack memory. But most of the time you don't have to think about not using the prelude or `std` at all.\n\nSo why didn't we see the `extern` keyword before? It's because you don't need it that much anymore. Before, when bringing in an external crate you had to use it. So to use `rand` in the past, you had to write:\n\n```rust\nextern crate rand;\n```\n\nand then `use` statements for the mods, traits, etc. that you wanted to use. But the Rust compiler now doesn't need this help anymore - you can just use `use` and it knows where to find it. So you almost never need `extern crate` anymore, but in other people's Rust code you might still see it on the top.\n\n\n\n### time\n\n`std::time` is where you can get functions for time. (If you want even more functions, a crate like `chrono` can work.) The simplest function is just getting the system time with `Instant::now()`.\n\n```rust\nuse std::time::Instant;\n\nfn main() {\n    let time = Instant::now();\n    println!(\"{:?}\", time);\n}\n```\n\nIf you print it, you'll get something like this: `Instant { tv_sec: 2738771, tv_nsec: 685628140 }`. That's talking about seconds and nanoseconds, but it's not very useful. If you look at 2738771 seconds for example (written in August), it is 31.70 days. That doesn't have anything to do with the month or the day of the year. But the page on `Instant` tells us that it isn't supposed to be useful on its own. It says that it is \"opaque and useful only with Duration.\" Opaque means \"you can't figure it out\", and duration means \"how much time passed\". So it's only useful when doing things like comparing times.\n\nIf you look at the traits on the left, one of them is `Sub<Instant>`. That means we can use `-` to subtract one from another. And when we click on [src] to see what it does, it says:\n\n```rust\nimpl Sub<Instant> for Instant {\n    type Output = Duration;\n\n    fn sub(self, other: Instant) -> Duration {\n        self.duration_since(other)\n    }\n}\n```\n\nSo it takes an `Instant` and uses `.duration_since()` to give a `Duration`. Let's try printing that. We'll make two `Instant::now()`s right next to each other, then we'll make the program busy for a while. Then we'll make one more `Instant::now()`. Finally, we'll see how long it took.\n\n```rust\nuse std::time::Instant;\n\nfn main() {\n    let time1 = Instant::now();\n    let time2 = Instant::now(); // These two are right next to each other\n\n    let mut new_string = String::new();\n    loop {\n        new_string.push('წ'); // Make Rust push this Georgian letter onto the String\n        if new_string.len() > 100_000 { //  until it is 100,000 bytes long\n            break;\n        }\n    }\n    let time3 = Instant::now();\n    println!(\"{:?}\", time2 - time1);\n    println!(\"{:?}\", time3 - time1);\n}\n```\n\nThis will print something like this:\n\n```text\n1.025µs\n683.378µs\n```\n\nSo that's just over 1 microsecond vs. 683 microseconds. We can see that Rust did take some time to do it.\n\nThere is one fun thing we can do with just a single `Instant` though. We can turn it into a `String` with `format!(\"{:?}\", Instant::now());`. It looks like this:\n\n```rust\nuse std::time::Instant;\n\nfn main() {\n    let time1 = format!(\"{:?}\", Instant::now());\n    println!(\"{}\", time1);\n}\n```\n\nThat prints something like `Instant { tv_sec: 2740773, tv_nsec: 632821036 }`. That's not useful, but if we use `.iter()` and `.rev()` and `.skip(2)`, we can skip the `}` and ` ` at the end. We can use it to make a random number generator.\n\n```rust\nuse std::time::Instant;\n\nfn bad_random_number(digits: usize) {\n    if digits > 9 {\n        panic!(\"Random number can only be up to 9 digits\");\n    }\n    let now = Instant::now();\n    let output = format!(\"{:?}\", now);\n\n    output\n        .chars()\n        .rev()\n        .skip(2)\n        .take(digits)\n        .for_each(|character| print!(\"{}\", character));\n    println!();\n}\n\nfn main() {\n    bad_random_number(1);\n    bad_random_number(1);\n    bad_random_number(3);\n    bad_random_number(3);\n}\n```\n\nThis will print something like:\n\n```text\n6\n4\n967\n180\n```\n\nThe function is called `bad_random_number` because it's not a very good random number generator. Rust has better crates that make random numbers with less code than `rand` like `fastrand`. But it's a good example of how you can use your imagination to do something with `Instant`.\n\nWhen you have a thread, you can use `std::thread::sleep` to make it stop for a while. When you do this, you have to give it a duration. You don't have to make more than one thread to do this because every program is on at least one thread. `sleep` needs a `Duration` though, so it can know how long to sleep. You can pick the unit like this: `Duration::from_millis()`, `Duration::from_secs`, etc. Here's one example:\n\n```rust\nuse std::time::Duration;\nuse std::thread::sleep;\n\nfn main() {\n    let three_seconds = Duration::from_secs(3);\n    println!(\"I must sleep now.\");\n    sleep(three_seconds);\n    println!(\"Did I miss anything?\");\n}\n```\n\nThis will just print\n\n```text\nI must sleep now.\nDid I miss anything?\n```\n\nbut the thread will do nothing for three seconds. You usually use `.sleep()` when you have many threads that need to try something a lot, like connecting. You don't want the thread to use your processor to try 100,000 times in a second when you just want it to check sometimes. So then you can set a `Duration`, and it will try to do its task every time it wakes up.\n\n\n### Other macros\n\n\nLet's take a look at some other macros.\n\n`unreachable!()`\n\nThis macro is kind of like `todo!()` except it's for code that you will never do. Maybe you have a `match` in an enum that you know will never choose one of the arms, so the code can never be reached. If that's so, you can write `unreachable!()` so the compiler knows that it can ignore that part.\n\nFor example, let's say you have a program that writes something when you choose a place to live in. They are in Ukraine, and all of them are nice except Chernobyl. Your program doesn't let anyone choose Chernobyl, because it's not a good place to live right now. But the enum was made a long time ago in someone else's code, and you can't change it. So in the `match` arm you can use the macro here. It looks like this:\n\n```rust\nenum UkrainePlaces {\n    Kiev,\n    Kharkiv,\n    Chernobyl, // Pretend we can't change the enum - Chernobyl will always be here\n    Odesa,\n    Dnipro,\n}\n\nfn choose_city(place: &UkrainePlaces) {\n    use UkrainePlaces::*;\n    match place {\n        Kiev => println!(\"You will live in Kiev\"),\n        Kharkiv => println!(\"You will live in Kharkiv\"),\n        Chernobyl => unreachable!(),\n        Odesa => println!(\"You will live in Odesa\"),\n        Dnipro => println!(\"You will live in Dnipro\"),\n    }\n}\n\nfn main() {\n    let user_input = UkrainePlaces::Kiev; // Pretend the user input is made from some other function. The user can't choose Chernobyl, no matter what\n    choose_city(&user_input);\n}\n```\n\nThis will print `You will live in Kiev`.\n\n`unreachable!()` is also nice for you to read because it reminds you that some part of the code is unreachable. You have to be sure that the code is actually unreachable though. If the compiler ever calls `unreachable!()`, the program will panic.\n\nAlso, if you ever have unreachable code that the compiler knows about, it will tell you. Here is a quick example:\n\n```rust\nfn main() {\n    let true_or_false = true;\n\n    match true_or_false {\n        true => println!(\"It's true\"),\n        false => println!(\"It's false\"),\n        true => println!(\"It's true\"), // Whoops, we wrote true again\n    }\n}\n```\n\nIt will say:\n\n```text\nwarning: unreachable pattern\n --> src/main.rs:7:9\n  |\n7 |         true => println!(\"It's true\"),\n  |         ^^^^\n  |\n```\n\nBut `unreachable!()` is for when the compiler can't know, like our other example.\n\n\n\n`column!`, `line!`, `file!`, `module_path!`\n\nThese four macros are kind of like `dbg!()` because you just put them in to give you debug information. But they don't take any variables - you just use them with the brackets and nothing else. They are easy to learn together:\n\n- `column!()` gives you the column where you wrote it,\n- `file!()` gives you the name of the file where you wrote it,\n- `line!()` gives you the line where you wrote it, and\n- `module_path!()` gives you the module where it is.\n\nThe next code shows all three in a simple example. We will pretend there is a lot more code (mods inside mods), because that is why we would want to use these macros. You can imagine a big Rust program over many mods and files.\n\n```rust\npub mod something {\n    pub mod third_mod {\n        pub fn print_a_country(input: &mut Vec<&str>) {\n            println!(\n                \"The last country is {} inside the module {}\",\n                input.pop().unwrap(),\n                module_path!()\n            );\n        }\n    }\n}\n\nfn main() {\n    use something::third_mod::*;\n    let mut country_vec = vec![\"Portugal\", \"Czechia\", \"Finland\"];\n    \n    // do some stuff\n    println!(\"Hello from file {}\", file!());\n\n    // do some stuff\n    println!(\n        \"On line {} we got the country {}\",\n        line!(),\n        country_vec.pop().unwrap()\n    );\n\n    // do some more stuff\n\n    println!(\n        \"The next country is {} on line {} and column {}.\",\n        country_vec.pop().unwrap(),\n        line!(),\n        column!(),\n    );\n\n    // lots more code\n\n    print_a_country(&mut country_vec);\n}\n```\n\nIt prints this:\n\n```text\nHello from file src/main.rs\nOn line 23 we got the country Finland\nThe next country is Czechia on line 32 and column 9.\nThe last country is Portugal inside the module rust_book::something::third_mod\n```\n\n\n\n`cfg!`\n\nWe know that you can use attributes like `#[cfg(test)]` and `#[cfg(windows)]` to tell the compiler what to do in certain cases. When you have `test`, it will run the code when you run Rust under testing mode (if it's on your computer you type `cargo test`). And when you use `windows`, it will run the code if the user is using Windows. But maybe you just want to change one tiny bit of code depending on the operating system, etc. That's when this macro is useful. It returns a `bool`.\n\n```rust\nfn main() {\n    let helpful_message = if cfg!(target_os = \"windows\") { \"backslash\" } else { \"slash\" };\n\n    println!(\n        \"...then in your hard drive, type the directory name followed by a {}. Then you...\",\n        helpful_message\n    );\n}\n```\n\nThis will print differently, depending on your system. The Rust Playground runs on Linux, so it will print:\n\n```text\n...then in your hard drive, type the directory name followed by a slash. Then you...\n```\n\n`cfg!()` works for any kind of configuration. Here is an example of a function that runs differently when you use it inside a test.\n\n```rust\n#[cfg(test)] // cfg! will know to look for the word test\nmod testing {\n    use super::*;\n    #[test]\n    fn check_if_five() {\n        assert_eq!(bring_number(true), 5); // This bring_number() function should return 5\n    }\n}\n\nfn bring_number(should_run: bool) -> u32 { // This function takes a bool as to whether it should run\n    if cfg!(test) && should_run { // if it should run and has the configuration test, return 5\n        5\n    } else if should_run { // if it's not a test but it should run, print something. When you run a test it ignores println! statements\n        println!(\"Returning 5. This is not a test\");\n        5\n    } else {\n        println!(\"This shouldn't run, returning 0.\"); // otherwise return 0\n        0\n    }\n}\n\nfn main() {\n    bring_number(true);\n    bring_number(false);\n}\n```\n\nNow it will run differently depending on the configuration. If you just run the program, it will give you this:\n\n```text\nReturning 5. This is not a test\nThis shouldn't run, returning 0.\n```\n\nBut if you run it in test mode (`cargo test` for Rust on your computer), it will actually run the test. And because the test always returns 5 in this case, it will pass.\n\n```text\nrunning 1 test\ntest testing::check_if_five ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n```\n\n\n\n## Writing macros\n\nWriting macros can be very complicated. You almost never need to write one, but sometimes you might want to because they are very convenient. Writing macros is interesting because they are almost a different language. To write one, you actually use another macro called `macro_rules!`. Then you add your macro name and open a `{}` block. Inside is sort of like a `match` statement.\n\nHere's one that only takes `()`, then just returns 6:\n\n```rust\nmacro_rules! give_six {\n    () => {\n        6\n    };\n}\n\nfn main() {\n    let six = give_six!();\n    println!(\"{}\", six);\n}\n```\n\nBut it's not the same as a `match` statement, because a macro actually doesn't compile anything. It just takes an input and gives an output. Then the compiler checks to see if it makes sense. That's why a macro is like \"code that writes code\". You will remember that a true `match` statement needs to give the same type, so this won't work:\n\n```rust\nfn main() {\n// ⚠️\n    let my_number = 10;\n    match my_number {\n        10 => println!(\"You got a ten\"),\n        _ => 10,\n    }\n}\n```\n\nIt will complain that you want to return `()` in one case, and `i32` in the other.\n\n```text\nerror[E0308]: `match` arms have incompatible types\n --> src\\main.rs:5:14\n  |\n3 | /     match my_number {\n4 | |         10 => println!(\"You got a ten\"),\n  | |               ------------------------- this is found to be of type `()`\n5 | |         _ => 10,\n  | |              ^^ expected `()`, found integer\n6 | |     }\n  | |_____- `match` arms have incompatible types\n```\n\nBut a macro doesn't care, because it's just giving an output. It's not a compiler - it's code before code. So you can do this:\n\n```rust\nmacro_rules! six_or_print {\n    (6) => {\n        6\n    };\n    () => {\n        println!(\"You didn't give me 6.\");\n    };\n}\n\nfn main() {\n    let my_number = six_or_print!(6);\n    six_or_print!();\n}\n```\n\nThis is just fine, and prints `You didn't give me 6.`. You can also see that it's not a match arm because there's no `_` case. We can only give it `(6)`, or `()`. Anything else will make an error. And the `6` we give it isn't even an `i32`, it's just an input 6. You can actually set anything as the input for a macro, because it's just looking at input to see what it gets. For example:\n\n```rust\nmacro_rules! might_print {\n    (THis is strange input 하하はは哈哈 but it still works) => {\n        println!(\"You guessed the secret message!\")\n    };\n    () => {\n        println!(\"You didn't guess it\");\n    };\n}\n\nfn main() {\n    might_print!(THis is strange input 하하はは哈哈 but it still works);\n    might_print!();\n}\n```\n\nSo this strange macro only responds to two things: `()` and `(THis is strange input 하하はは哈哈 but it still works)`. Nothing else. It prints:\n\n```text\nYou guessed the secret message!\nYou didn't guess it\n```\n\nSo a macro isn't exactly Rust syntax. But a macro can also understand different types of input that you give it. Take this example:\n\n```rust\nmacro_rules! might_print {\n    ($input:expr) => {\n        println!(\"You gave me: {}\", $input);\n    }\n}\n\nfn main() {\n    might_print!(6);\n}\n```\n\nThis will print `You gave me: 6`. The `$input:expr` part is important. It means \"for an expression, give it the variable name $input\". In macros, variables start with a `$`. In this macro, if you give it one expression, it will print it. Let's try it out some more:\n\n```rust\nmacro_rules! might_print {\n    ($input:expr) => {\n        println!(\"You gave me: {:?}\", $input); // Now we'll use {:?} because we will give it different kinds of expressions\n    }\n}\n\nfn main() {\n    might_print!(()); // give it a ()\n    might_print!(6); // give it a 6\n    might_print!(vec![8, 9, 7, 10]); // give it a vec\n}\n```\n\nThis will print:\n\n```text\nYou gave me: ()\nYou gave me: 6\nYou gave me: [8, 9, 7, 10]\n```\n\nAlso note that we wrote `{:?}`, but it won't check to see if `&input` implements `Debug`. It'll just write the code and try to make it compile, and if it doesn't then it gives an error.\n\nSo what can a macro see besides `expr`? They are: `block | expr | ident | item | lifetime | literal  | meta | pat | path | stmt | tt | ty | vis`. This is the complicated part. You can see what each of them means [here](https://doc.rust-lang.org/beta/reference/macros-by-example.html), where it says:\n\n```text\nitem: an Item\nblock: a BlockExpression\nstmt: a Statement without the trailing semicolon (except for item statements that require semicolons)\npat: a Pattern\nexpr: an Expression\nty: a Type\nident: an IDENTIFIER_OR_KEYWORD\npath: a TypePath style path\ntt: a TokenTree (a single token or tokens in matching delimiters (), [], or {})\nmeta: an Attr, the contents of an attribute\nlifetime: a LIFETIME_TOKEN\nvis: a possibly empty Visibility qualifier\nliteral: matches -?LiteralExpression\n```\n\nThere is another good site called cheats.rs that explains them [here](https://cheats.rs/#macros-attributes) and gives examples for each.\n\nHowever, for most macros you will use `expr`, `ident`, and `tt`. `ident` means identifier and is for variable or function names. `tt` means token tree and sort of means any type of input. Let's try a simple macro with both.\n\n```rust\nmacro_rules! check {\n    ($input1:ident, $input2:expr) => {\n        println!(\n            \"Is {:?} equal to {:?}? {:?}\",\n            $input1,\n            $input2,\n            $input1 == $input2\n        );\n    };\n}\n\nfn main() {\n    let x = 6;\n    let my_vec = vec![7, 8, 9];\n    check!(x, 6);\n    check!(my_vec, vec![7, 8, 9]);\n    check!(x, 10);\n}\n```\n\nSo this will take one `ident` (like a variable name) and an expression and see if they are the same. It prints:\n\n```text\nIs 6 equal to 6? true\nIs [7, 8, 9] equal to [7, 8, 9]? true\nIs 6 equal to 10? false\n```\n\nAnd here's one macro that takes a `tt` and prints it. It uses a macro called `stringify!` to make a string first.\n\n```rust\nmacro_rules! print_anything {\n    ($input:tt) => {\n        let output = stringify!($input);\n        println!(\"{}\", output);\n    };\n}\n\nfn main() {\n    print_anything!(ththdoetd);\n    print_anything!(87575oehq75onth);\n}\n```\n\nThis prints:\n\n```text\nththdoetd\n87575oehq75onth\n```\n\nBut it won't print if we give it something with spaces, commas, etc. It will think that we are giving it more than one item or extra information, so it will be confused.\n\nThis is where macros start to get difficult.\n\nTo give a macro more than one item at a time, we have to use a different syntax. Instead of `$input`, it will be `$($input1),*`. This means zero or more (this is what * means), separated by a comma. If you want one or more, use `+` instead of `*`.\n\nNow our macro looks like this:\n\n```rust\nmacro_rules! print_anything {\n    ($($input1:tt),*) => {\n        let output = stringify!($($input1),*);\n        println!(\"{}\", output);\n    };\n}\n\n\nfn main() {\n    print_anything!(ththdoetd, rcofe);\n    print_anything!();\n    print_anything!(87575oehq75onth, ntohe, 987987o, 097);\n}\n```\n\nSo it takes any token tree separated by commas, and uses `stringify!` to make it into a string. Then it prints it. It prints:\n\n```text\nththdoetd, rcofe\n\n87575oehq75onth, ntohe, 987987o, 097\n```\n\nIf we used `+` instead of `*` it would give an error, because one time we gave it no input. So `*` is a bit safer option.\n\nSo now we can start to see the power of macros. In this next example we can actually make our own functions:\n\n```rust\nmacro_rules! make_a_function {\n    ($name:ident, $($input:tt),*) => { // First you give it one name for the function, then it checks everything else\n        fn $name() {\n            let output = stringify!($($input),*); // It makes everything else into a string\n            println!(\"{}\", output);\n        }\n    };\n}\n\n\nfn main() {\n    make_a_function!(print_it, 5, 5, 6, I); // We want a function called print_it() that prints everything else we give it\n    print_it();\n    make_a_function!(say_its_nice, this, is, really, nice); // Same here but we change the function name\n    say_its_nice();\n}\n```\n\nThis prints:\n\n```text\n5, 5, 6, I\nthis, is, really, nice\n```\n\n\nSo now we can start to understand other macros. You can see that some of the macros we've already been using are pretty simple. Here's the one for `write!` that we used to write to files:\n\n```rust\nmacro_rules! write {\n    ($dst:expr, $($arg:tt)*) => ($dst.write_fmt($crate::format_args!($($arg)*)))\n}\n```\n\nSo to use it, you enter this:\n\n- an expression (`expr`) that gets the variable name `$dst`.\n- everything after that. If it wrote `$arg:tt` then it would only take one, but because it wrote `$($arg:tt)*` it takes zero, one, or any number.\n\nThen it takes `$dst` and uses a method called `write_fmt` on it. Inside that, it uses another macro called `format_args!` that takes all `$($arg)*`, or all the arguments we put in.\n\n\n\nNow let's take a look at the `todo!` macro. That's the one you use when you want the program to compile but haven't written your code yet. It looks like this:\n\n```rust\nmacro_rules! todo {\n    () => (panic!(\"not yet implemented\"));\n    ($($arg:tt)+) => (panic!(\"not yet implemented: {}\", $crate::format_args!($($arg)+)));\n}\n```\n\nThis one has two options: you can enter `()`, or a number of token trees (`tt`).\n\n- If you enter `()`, it just uses `panic!` with a message. So you could actually just write `panic!(\"not yet implemented\")` instead of `todo!` and it would be the same.\n- If you enter some arguments, it will try to print them. You can see the same `format_args!` macro inside, which works like `println!`.\n\nSo if you write this, it will work too:\n\n```rust\nfn not_done() {\n    let time = 8;\n    let reason = \"lack of time\";\n    todo!(\"Not done yet because of {}. Check back in {} hours\", reason, time);\n}\n\nfn main() {\n    not_done();\n}\n```\n\nThis will print:\n\n```text\nthread 'main' panicked at 'not yet implemented: Not done yet because of lack of time. Check back in 8 hours', src/main.rs:4:5\n```\n\n\nInside a macro you can even call the same macro. Here's one:\n\n```rust\nmacro_rules! my_macro {\n    () => {\n        println!(\"Let's print this.\");\n    };\n    ($input:expr) => {\n        my_macro!();\n    };\n    ($($input:expr),*) => {\n        my_macro!();\n    }\n}\n\nfn main() {\n    my_macro!(vec![8, 9, 0]);\n    my_macro!(toheteh);\n    my_macro!(8, 7, 0, 10);\n    my_macro!();\n}\n```\n\nThis one takes either `()`, or one expression, or many expressions. But it ignores all the expressions no matter what you put in, and just calls `my_macro!` on `()`. So the output is just `Let's print this`, four times.\n\nYou can see the same thing in the `dbg!` macro, which also calls itself.\n\n```rust\nmacro_rules! dbg {\n    () => {\n        $crate::eprintln!(\"[{}:{}]\", $crate::file!(), $crate::line!()); //$crate means the crate that it's in.\n    };\n    ($val:expr) => {\n        // Use of `match` here is intentional because it affects the lifetimes\n        // of temporaries - https://stackoverflow.com/a/48732525/1063961\n        match $val {\n            tmp => {\n                $crate::eprintln!(\"[{}:{}] {} = {:#?}\",\n                    $crate::file!(), $crate::line!(), $crate::stringify!($val), &tmp);\n                tmp\n            }\n        }\n    };\n    // Trailing comma with single argument is ignored\n    ($val:expr,) => { $crate::dbg!($val) };\n    ($($val:expr),+ $(,)?) => {\n        ($($crate::dbg!($val)),+,)\n    };\n}\n```\n\n(`eprintln!` is the same as `println!` except it prints to `io::stderr` instead of `io::stdout`. There is also `eprint!` that doesn't add a new line)\n\nSo we can try this out ourself.\n\n```rust\nfn main() {\n    dbg!();\n}\n```\n\nThat matches the first arm, so it will print the file name and line name with the `file!` and `line!` macros. It prints `[src/main.rs:2]`.\n\nLet's try it with this:\n\n```rust\nfn main() {\n    dbg!(vec![8, 9, 10]);\n}\n```\n\nThis will match the next arm, because it's one expression. It will then call the input `tmp` and use this code: ` $crate::eprintln!(\"[{}:{}] {} = {:#?}\", $crate::file!(), $crate::line!(), $crate::stringify!($val), &tmp);`. So it will print with `file!` and `line!`, then `$val` made into a `String`, and pretty print with `{:#?}` for `tmp`. So for our input it will write this:\n\n```text\n[src/main.rs:2] vec![8, 9, 10] = [\n    8,\n    9,\n    10,\n]\n```\n\nAnd for the rest of it it just calls `dbg!` on itself even if you put in an extra comma.\n\nAs you can see, macros are very complicated! Usually you only want a macro to automatically do something that a simple function can't do very well. The best way to learn about macros is to look at other macro examples. Not many people can quickly write macros without problems. So don't think that you need to know everything about macros to know how to write in Rust. But if you read other macros, and change them a little, you can easily borrow their power. Then you might start to get comfortable with writing your own.\n\n\n# Part 2 - Rust on your computer\n\nYou saw that we can learn almost anything in Rust just using the Playground. But if you learned everything so far, you will probably want Rust on your computer now. There are always things that you can't do with the Playground like using files or code in more than just one file. Some other things you need Rust on your computer for are input and flags. But most important is that with Rust on your computer you can use crates. We already learned about crates, but in the Playground you could only use the most popular ones. But with Rust on your computer you can use any crate in your program.\n\n## cargo\n\n`rustc` means Rust compiler, and it's what does the actual compiling. A rust file ends with an `.rs`. But most people don't write something like `rustc main.rs` to compile. They use something called `cargo`, which is the main package manager for Rust.\n\nOne note about the name: it's called `cargo` because when you put crates together, you get cargo. A crate is a wooden box that you see on ships or trucks, but you remember that every Rust project is also called a crate. Then when you put them together you get the whole cargo.\n\nYou can see this when you use cargo to run a project. Let's try something simple with `rand`: we'll just randomly choose between eight letters.\n\n```rust\nuse rand::seq::SliceRandom; // Use this for .choose over slices\n\nfn main() {\n\n    let my_letters = vec!['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];\n\n    let mut rng = rand::thread_rng();\n    for _ in 0..6 {\n        print!(\"{} \", my_letters.choose(&mut rng).unwrap());\n    }\n}\n```\n\nThis will print something like `b c g h e a`. But we want to see what `cargo` does first. To use `cargo` and run our program, usually we type `cargo run`. This will build our program and run it for us. But when it starts compiling, it does something like this:\n\n```text\n   Compiling getrandom v0.1.14\n   Compiling cfg-if v0.1.10\n   Compiling ppv-lite86 v0.2.8\n   Compiling rand_core v0.5.1\n   Compiling rand_chacha v0.2.2\n   Compiling rand v0.7.3\n   Compiling rust_book v0.1.0 (C:\\Users\\mithr\\OneDrive\\Documents\\Rust\\rust_book)\n    Finished dev [unoptimized + debuginfo] target(s) in 13.13s\n     Running `C:\\Users\\mithr\\OneDrive\\Documents\\Rust\\rust_book\\target\\debug\\rust_book.exe`\ng f c f h b\n```\n\nSo it looks like it didn't just bring in `rand`, but some others too. That's because we need `rand` for our crate, but `rand` also has some code that needs other crates too. So `cargo` will find all the crates we need and put them together. In our case we only had seven, but on very big projects you may have 200 or more crates to bring in.\n\nThis is where you can see the tradeoff for Rust. Rust is extremely fast, because it compiles ahead of time. It does this by looking through the code and looking to see what the code you write actually does. For example, you might write this generic code:\n\n```rust\nuse std::fmt::Display;\n\nfn print_and_return_thing<T: Display>(input: T) -> T {\n    println!(\"You gave me {} and now I will give it back.\", input);\n    input\n}\n\nfn main() {\n    let my_name = print_and_return_thing(\"Windy\");\n    let small_number = print_and_return_thing(9.0);\n}\n```\n\nThis function can take anything with `Display`, so we gave it a `&str` and next gave it a `f64` and that is no problem for us. But the compiler doesn't look at generics, because it doesn't want to do anything at runtime. It wants to put together a program that can run by itself as fast as possible. So when it looks at the first part with `\"Windy\"`, it doesn't see `fn print_and_return_thing<T: Display>(input: T) -> T`. It sees something like `fn print_and_return_thing(input: &str) -> &str`. And next it sees `fn print_and_return_thing(input: f64) -> f64`. All the checking about traits and so on is done during compile time. That's why generics take longer to compile, because it needs to figure them out, and make it concrete.\n\nOne more thing: Rust in 2020 is working hard on compile time, because this part takes the longest. Every version of Rust is a little bit faster at compiling, and there are some other plans to speed it up. But in the meantime, here's what you should know:\n\n- `cargo build` will build your program so you can run it\n- `cargo run` will build your program and run it\n- `cargo build --release` and `cargo run --release` will do the same but in release mode. What's that? Release mode is for when your code is finally done. Then Rust will take even longer to compile, but it does this because it uses everything it knows to make it faster. Release mode is actually a *lot* faster than the regular mode, which is called debug mode. That's because it compiles quicker and has more debug information. The regular `cargo build` is called a \"debug build\" and `cargo build --release` is called a \"release build\".\n- `cargo check` is a way to check your code. It's like compiling except that it won't actually make your program. This is a good way to check your code a lot because it doesn't take as long as `build` or `run`.\n\nBy the way, the `--release` part of the command is called a `flag`. That means extra information in a command.\n\nSome other things you need to know are:\n\n- `cargo new`. You do this to create a new Rust project. After `new`, write the name of the project and `cargo` will make the folder and all the files you need.\n- `cargo clean`. When you add crates to `Cargo.toml`, the computer will download all the files it needs and they can take a lot of space. If you don't want them on your computer anymore, type `cargo clean`.\n\nOne more thing about the compiler: it only takes the most time when you use `cargo build` or `cargo run` the first time. After that it will remember, and it will compile fast again. But if you use `cargo clean` and then run `cargo build`, it will have to compile slowly one more time.\n\n\n## Taking user input\n\nOne easy way to take input from the user is with `std::io::stdin`. This means \"standard in\", which is the input from the keyboard. With `stdin()` you can get user input, but then you will want to put it in a `&mut String` with `.read_line()`. Here is a simple example of that, but it both works and doesn't work:\n\n```rust\nuse std::io;\n\nfn main() {\n    println!(\"Please type something, or x to escape:\");\n    let mut input_string = String::new();\n\n    while input_string != \"x\" { // This is the part that doesn't work right\n        input_string.clear(); // First clear the String. Otherwise it will keep adding to it\n        io::stdin().read_line(&mut input_string).unwrap(); // Get the stdin from the user, and put it in read_string\n        println!(\"You wrote {}\", input_string);\n    }\n    println!(\"See you later!\");\n}\n```\n\nHere is what an output looks like:\n\n```text\nPlease type something, or x to escape:\nsomething\nYou wrote something\n\nSomething else\nYou wrote Something else\n\nx\nYou wrote x\n\nx\nYou wrote x\n\nx\nYou wrote x\n```\n\nIt takes our input and gives it back, and it even knows that we typed `x`. But it doesn't exit the program. The only way to get out is to close the window, or type ctrl and c. Let's change the `{}` to `{:?}` in `println!` to get more information (or you could use `dbg!(&input_string)` if you like that macro). Now it says:\n\n```text\nPlease type something, or x to escape:\nsomething\nYou wrote \"something\\r\\n\"\nSomething else\nYou wrote \"Something else\\r\\n\"\nx\nYou wrote \"x\\r\\n\"\nx\nYou wrote \"x\\r\\n\"\n```\n\n\n\nThis is because the keyboard input is actually not just `something`, it is `something` and the `Enter` key. There is an easy method to fix this called `.trim()`, which removes all the whitespace. Whitespace, by the way, is all [these characters](https://doc.rust-lang.org/reference/whitespace.html):\n\n```text\nU+0009 (horizontal tab, '\\t')\nU+000A (line feed, '\\n')\nU+000B (vertical tab)\nU+000C (form feed)\nU+000D (carriage return, '\\r')\nU+0020 (space, ' ')\nU+0085 (next line)\nU+200E (left-to-right mark)\nU+200F (right-to-left mark)\nU+2028 (line separator)\nU+2029 (paragraph separator)\n```\n\nSo that will turn `x\\r\\n` into just `x`. Now it works:\n\n```rust\nuse std::io;\n\nfn main() {\n    println!(\"Please type something, or x to escape:\");\n    let mut input_string = String::new();\n\n    while input_string.trim() != \"x\" {\n        input_string.clear();\n        io::stdin().read_line(&mut input_string).unwrap();\n        println!(\"You wrote {}\", input_string);\n    }\n    println!(\"See you later!\");\n}\n```\n\nNow it will print:\n\n```text\nPlease type something, or x to escape:\nsomething\nYou wrote something\n\nSomething\nYou wrote Something\n\nx\nYou wrote x\n\nSee you later!\n```\n\n\n\nThere is another kind of user input called `std::env::Args` (env means environment). `Args` is what the user types when starting the program. There is actually always at least one `Arg` in a program. Let's write a program that only prints them using `std::env::args()` to see what they are.\n\n```rust\nfn main() {\n    println!(\"{:?}\", std::env::args());\n}\n```\n\nIf we write `cargo run` then it prints something like this:\n\n```text\nArgs { inner: [\"target\\\\debug\\\\rust_book.exe\"] }\n```\n\nLet's give it more input and see what it does. We'll type `cargo run but with some extra words`. It gives us:\n\n```text\nArgs { inner: [\"target\\\\debug\\\\rust_book.exe\", \"but\", \"with\", \"some\", \"extra\", \"words\"] }\n```\n\nInteresting. And when we look at [the page for Args](https://doc.rust-lang.org/std/env/struct.Args.html), we see that it implements `IntoIterator`. That means we can do all the things we know about iterators to read and change it. Let's try this:\n\n```rust\nuse std::env::args;\n\nfn main() {\n    let input = args();\n\n    for entry in input {\n        println!(\"You entered: {}\", entry);\n    }\n}\n```\n\nNow it says:\n\n```text\nYou entered: target\\debug\\rust_book.exe\nYou entered: but\nYou entered: with\nYou entered: some\nYou entered: extra\nYou entered: words\n```\n\nYou can see that the first argument is always the program name, so you will often want to skip it, like this:\n\n```rust\nuse std::env::args;\n\nfn main() {\n    let input = args();\n\n    input.skip(1).for_each(|item| {\n        println!(\"You wrote {}, which in capital letters is {}\", item, item.to_uppercase());\n    })\n}\n```\n\nThat will print:\n\n```text\nYou wrote but, which in capital letters is BUT\nYou wrote with, which in capital letters is WITH\nYou wrote some, which in capital letters is SOME\nYou wrote extra, which in capital letters is EXTRA\nYou wrote words, which in capital letters is WORDS\n```\n\nOne common use for `Args` is for user settings. You can make sure that the user writes the input you need, and only run the program if it's right. Here's a small program that either makes letters big (capital) or small (lowercase):\n\n```rust\nuse std::env::args;\n\nenum Letters {\n    Capitalize,\n    Lowercase,\n    Nothing,\n}\n\nfn main() {\n    let mut changes = Letters::Nothing;\n    let input = args().collect::<Vec<_>>();\n\n    if input.len() > 2 {\n        match input[1].as_str() {\n            \"capital\" => changes = Letters::Capitalize,\n            \"lowercase\" => changes = Letters::Lowercase,\n            _ => {}\n        }\n    }\n\n    for word in input.iter().skip(2) {\n      match changes {\n        Letters::Capitalize => println!(\"{}\", word.to_uppercase()),\n        Letters::Lowercase => println!(\"{}\", word.to_lowercase()),\n        _ => println!(\"{}\", word)\n      }\n    }\n    \n}\n```\n\nHere are some examples of what it gives:\n\nInput: `cargo run please make capitals`:\n\n```text\nmake capitals\n```\n\nInput: `cargo run capital`:\n\n```text\n// Nothing here...\n```\n\nInput: `cargo run capital I think I understand now`:\n\n```text\nI\nTHINK\nI\nUNDERSTAND\nNOW\n```\n\nInput: `cargo run lowercase Does this work too?`\n\n```text\ndoes\nthis\nwork\ntoo?\n```\n\n\n\nBesides `Args` given by the user, available in `std::env::args()`, there are also `Vars` which are the system variables. Those are the basic settings for the program that the user didn't type in. You can use `std::env::vars()` to see them all as a `(String, String)`. There are very many. For example:\n\n```rust\nfn main() {\n    for item in std::env::vars() {\n        println!(\"{:?}\", item);\n    }\n}\n```\n\nJust doing this shows you all the information about your user session. It will show information like this:\n\n```text\n(\"CARGO\", \"/playground/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/bin/cargo\")\n(\"CARGO_HOME\", \"/playground/.cargo\")\n(\"CARGO_MANIFEST_DIR\", \"/playground\")\n(\"CARGO_PKG_AUTHORS\", \"The Rust Playground\")\n(\"CARGO_PKG_DESCRIPTION\", \"\")\n(\"CARGO_PKG_HOMEPAGE\", \"\")\n(\"CARGO_PKG_NAME\", \"playground\")\n(\"CARGO_PKG_REPOSITORY\", \"\")\n(\"CARGO_PKG_VERSION\", \"0.0.1\")\n(\"CARGO_PKG_VERSION_MAJOR\", \"0\")\n(\"CARGO_PKG_VERSION_MINOR\", \"0\")\n(\"CARGO_PKG_VERSION_PATCH\", \"1\")\n(\"CARGO_PKG_VERSION_PRE\", \"\")\n(\"DEBIAN_FRONTEND\", \"noninteractive\")\n(\"HOME\", \"/playground\")\n(\"HOSTNAME\", \"f94c15b8134b\")\n(\"LD_LIBRARY_PATH\", \"/playground/target/debug/build/backtrace-sys-3ec4c973f371c302/out:/playground/target/debug/build/libsqlite3-sys-fbddfbb9b241dacb/out:/playground/target/debug/build/ring-cadba5e583648abb/out:/playground/target/debug/deps:/playground/target/debug:/playground/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/lib:/playground/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib\")\n(\"PATH\", \"/playground/.cargo/bin:/playground/.cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\")\n(\"PLAYGROUND_EDITION\", \"2018\")\n(\"PLAYGROUND_TIMEOUT\", \"10\")\n(\"PWD\", \"/playground\")\n(\"RUSTUP_HOME\", \"/playground/.rustup\")\n(\"RUSTUP_TOOLCHAIN\", \"stable-x86_64-unknown-linux-gnu\")\n(\"RUST_RECURSION_COUNT\", \"1\")\n(\"SHLVL\", \"1\")\n(\"SSL_CERT_DIR\", \"/usr/lib/ssl/certs\")\n(\"SSL_CERT_FILE\", \"/usr/lib/ssl/certs/ca-certificates.crt\")\n(\"USER\", \"playground\")\n(\"_\", \"/usr/bin/timeout\")\n```\n\nSo if you need this information, `Vars` is what you want.\n\nThe easiest way to get a single `Var` is by using the `env!` macro. You just give it the name of the variable, and it will give you a `&str` with the value. It won't work if the variable is spelled wrong or does not exist, so if you aren't sure then use `option_env!` instead. If we write this on the Playground:\n\n```rust\nfn main() {\n    println!(\"{}\", env!(\"USER\"));\n    println!(\"{}\", option_env!(\"ROOT\").unwrap_or(\"Can't find ROOT\"));\n    println!(\"{}\", option_env!(\"CARGO\").unwrap_or(\"Can't find CARGO\"));\n}\n```\n\nthen we get the output:\n\n```text\nplayground\nCan't find ROOT\n/playground/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/bin/cargo\n```\n\nSo `option_env!` is always going to be the safer macro. `env!` is better if you actually want the program to crash when you can't find the environment variable.\n\n\n\n## Using files\n\nNow that we are using Rust on the computer, we can start working with files. You will notice that now we will start to see more and more `Result`s in our code. That is because once you start working with files and similar things, many things can go wrong. A file might not be there, or maybe the computer can't read it.\n\nYou might remember that if you want to use the `?` operator, it has to return a `Result` in the function it is in. If you can't remember the error type, you can just give it nothing and let the compiler tell you. Let's try that with a function that tries to make a number with `.parse()`.\n\n```rust\n// ⚠️\nfn give_number(input: &str) -> Result<i32, ()> {\n    input.parse::<i32>()\n}\n\nfn main() {\n    println!(\"{:?}\", give_number(\"88\"));\n    println!(\"{:?}\", give_number(\"5\"));\n}\n```\n\nThe compiler tells us exactly what to do:\n\n```text\nerror[E0308]: mismatched types\n --> src\\main.rs:4:5\n  |\n3 | fn give_number(input: &str) -> Result<i32, ()> {\n  |                                --------------- expected `std::result::Result<i32, ()>` because of return type\n4 |     input.parse::<i32>()\n  |     ^^^^^^^^^^^^^^^^^^^^ expected `()`, found struct `std::num::ParseIntError`\n  |\n  = note: expected enum `std::result::Result<_, ()>`\n             found enum `std::result::Result<_, std::num::ParseIntError>`\n```\n\nGreat! So we just change the return to what the compiler says:\n\n```rust\nuse std::num::ParseIntError;\n\nfn give_number(input: &str) -> Result<i32, ParseIntError> {\n    input.parse::<i32>()\n}\n\nfn main() {\n    println!(\"{:?}\", give_number(\"88\"));\n    println!(\"{:?}\", give_number(\"5\"));\n}\n```\n\nNow the program works!\n\n```text\nOk(88)\nOk(5)\n```\n\nSo now we want to use `?` to just give us the value if it works, and the error if it doesn't. But how to do this in `fn main()`? If we try to use `?` in main, it won't work.\n\n```rust\n// ⚠️\nuse std::num::ParseIntError;\n\nfn give_number(input: &str) -> Result<i32, ParseIntError> {\n    input.parse::<i32>()\n}\n\nfn main() {\n    println!(\"{:?}\", give_number(\"88\")?);\n    println!(\"{:?}\", give_number(\"5\")?);\n}\n```\n\nIt says:\n\n```text\nerror[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)\n  --> src\\main.rs:8:22\n   |\n7  | / fn main() {\n8  | |     println!(\"{:?}\", give_number(\"88\")?);\n   | |                      ^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()`\n9  | |     println!(\"{:?}\", give_number(\"5\")?);\n10 | | }\n   | |_- this function should return `Result` or `Option` to accept `?`\n```\n\nBut actually `main()` can return a `Result`, just like any other function. If our function works, we don't want to return anything (main() isn't giving anything to anything else). And if it doesn't work, we will return the same error. So we can write it like this:\n\n```rust\nuse std::num::ParseIntError;\n\nfn give_number(input: &str) -> Result<i32, ParseIntError> {\n    input.parse::<i32>()\n}\n\nfn main() -> Result<(), ParseIntError> {\n    println!(\"{:?}\", give_number(\"88\")?);\n    println!(\"{:?}\", give_number(\"5\")?);\n    Ok(())\n}\n```\n\nDon't forget the `Ok(())` at the end: this is very common in Rust. It means `Ok`, inside of which is `()`, which is our return value. Now it prints:\n\n```text\n88\n5\n```\n\n\nThis wasn't very useful when just using `.parse()`, but it will be with files. That's because `?` also changes error types for us. Here's what [the page for the ? operator](https://doc.rust-lang.org/std/macro.try.html) says in simple English:\n\n```text\nIf you get an `Err`, it will get the inner error. Then `?` does a conversion using `From`. With that it can change specialized errors to more general ones. The error it gets is then returned.\n```\n\nAlso, Rust has a convenient `Result` type when using `File`s and similar things. It's called `std::io::Result`, and this is what you usually see in `main()` when you are using `?` to open and do things to files. It's actually a type alias. It looks like this:\n\n```text\ntype Result<T> = Result<T, Error>;\n```\n\nSo it is a `Result<T, Error>`, but we only need to write the `Result<T>` part.\n\nNow let's try working with files for the first time. `std::fs` is where the methods are for working with files, and with `std::io::Write` you can write in them. With that we can use `.write_all()` to write into the file.\n\n```rust\nuse std::fs;\nuse std::io::Write;\n\nfn main() -> std::io::Result<()> {\n    let mut file = fs::File::create(\"myfilename.txt\")?; // Create a file with this name.\n                                                        // CAREFUL! If you have a file with this name already,\n                                                        // it will delete everything in it.\n    file.write_all(b\"Let's put this in the file\")?;     // Don't forget the b in front of \". That's because files take bytes.\n    Ok(())\n}\n```\n\nThen if you click on the new file `myfilename.txt`, it will say `Let's put this in the file`.\n\nWe don't need to do this on two lines though, because we have the `?` operator. It will pass on the result we want if it works, kind of like when you use lots of methods on an iterator. This is when `?` becomes very convenient.\n\n```rust\nuse std::fs;\nuse std::io::Write;\n\nfn main() -> std::io::Result<()> {\n    fs::File::create(\"myfilename.txt\")?.write_all(b\"Let's put this in the file\")?;\n    Ok(())\n}\n```\n\nSo this is saying \"Please try to create a file and check if it worked. If it did, then use `.write_all()` and then check if that worked.\"\n\nAnd in fact, there is also a function that does both of these things together. It's called `std::fs::write`. Inside it you give it the file name you want, and the content you want to put inside. Again, careful! It will delete everything in that file if it already exists. Also, it lets you write a `&str` without `b` in front, because of this:\n\n```rust\npub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()>\n```\n\n`AsRef<[u8]>` is why you can give it either one.\n\nIt's very simple:\n\n```rust\nuse std::fs;\n\nfn main() -> std::io::Result<()> {\n    fs::write(\"calvin_with_dad.txt\", \n\"Calvin: Dad, how come old photographs are always black and white? Didn't they have color film back then?\nDad: Sure they did. In fact, those photographs *are* in color. It's just the *world* was black and white then.\nCalvin: Really?\nDad: Yep. The world didn't turn color until sometimes in the 1930s...\")?;\n\n    Ok(())\n}\n```\n\nSo that's the file we will use. It's a conversation with a comic book character named Calvin and his dad, who is not serious about his question. With this we can create a file to use every time.\n\n\n\nOpening a file is just as easy as creating one. You just use `open()` instead of `create()`. After that (if it finds your file), you can do things like `read_to_string()`. To do that you can create a mutable `String` and read the file into there. It looks like this:\n\n```rust\nuse std::fs;\nuse std::fs::File;\nuse std::io::Read; // this is to use the function .read_to_string()\n\nfn main() -> std::io::Result<()> {\n     fs::write(\"calvin_with_dad.txt\", \n\"Calvin: Dad, how come old photographs are always black and white? Didn't they have color film back then?\nDad: Sure they did. In fact, those photographs *are* in color. It's just the *world* was black and white then.\nCalvin: Really?\nDad: Yep. The world didn't turn color until sometimes in the 1930s...\")?;\n\n\n    let mut calvin_file = File::open(\"calvin_with_dad.txt\")?; // Open the file we just made\n    let mut calvin_string = String::new(); // This String will hold it\n    calvin_file.read_to_string(&mut calvin_string)?; // Read the file into it\n\n    calvin_string.split_whitespace().for_each(|word| print!(\"{} \", word.to_uppercase())); // Do things with the String now\n\n    Ok(())\n}\n```\n\nThat will print:\n\n```rust\nCALVIN: DAD, HOW COME OLD PHOTOGRAPHS ARE ALWAYS BLACK AND WHITE? DIDN'T THEY HAVE COLOR FILM BACK THEN? DAD: SURE THEY DID. IN \nFACT, THOSE PHOTOGRAPHS *ARE* IN COLOR. IT'S JUST THE *WORLD* WAS BLACK AND WHITE THEN. CALVIN: REALLY? DAD: YEP. THE WORLD DIDN'T TURN COLOR UNTIL SOMETIMES IN THE 1930S...\n```\n\nOkay, what if we want to create a file but not do it if there is already another file with the same name? Maybe you don't want to delete the other file if it's already there just to make a new one. To do this, there is a struct called `OpenOptions`. Actually, we've been using `OpenOptions` all this time and didn't know it. Take a look at the source for `File::open`:\n\n```rust\npub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {\n        OpenOptions::new().read(true).open(path.as_ref())\n    }\n```\n\nInteresting, that looks like the builder pattern that we learned. It's the same for `File::create`:\n\n```rust\npub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {\n        OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())\n    }\n```\n\nIf you go to [the page for OpenOptions](https://doc.rust-lang.org/std/fs/struct.OpenOptions.html), you can see all the methods that you can choose from. Most take a `bool`:\n\n- `append()`: This means \"add to the content that's already there instead of deleting\".\n- `create()`: This lets `OpenOptions` create a file.\n- `create_new()`: This means it will only create a file if it's not there already.\n- `read()`: Set this to `true` if you want it to be able to read a file.\n- `truncate()`: Set this to true if you want to cut the file content to 0 (delete the contents) when you open it.\n- `write()`: This lets it write to a file.\n\nThen at the end you use `.open()` with the file name, and that will give you a `Result`. Let's look at one example:\n\n```rust\n// ⚠️\nuse std::fs;\nuse std::fs::OpenOptions;\n\nfn main() -> std::io::Result<()> {\n     fs::write(\"calvin_with_dad.txt\", \n\"Calvin: Dad, how come old photographs are always black and white? Didn't they have color film back then?\nDad: Sure they did. In fact, those photographs *are* in color. It's just the *world* was black and white then.\nCalvin: Really?\nDad: Yep. The world didn't turn color until sometimes in the 1930s...\")?;\n\n    let calvin_file = OpenOptions::new().write(true).create_new(true).open(\"calvin_with_dad.txt\")?;\n\n    Ok(())\n}\n```\n\nFirst we made an `OpenOptions` with `new` (always start with `new`). Then we gave it the ability to `write`. After that we set `create_new()` to `true`, and tried to open the file we made. It won't work, which is what we want:\n\n```text\nError: Os { code: 80, kind: AlreadyExists, message: \"The file exists.\" }\n```\n\nLet's try using `.append()` so we can write to a file. To write to the file we can use `.write_all()`, which is a method that tries to write in everything you give it.\n\nAlso, we will use the `write!` macro to do the same thing. You will remember this macro from when we did `impl Display` for our structs. This time we are using it on a file though instead of a buffer.\n\n```rust\nuse std::fs;\nuse std::fs::OpenOptions;\nuse std::io::Write;\n\nfn main() -> std::io::Result<()> {\n    fs::write(\"calvin_with_dad.txt\", \n\"Calvin: Dad, how come old photographs are always black and white? Didn't they have color film back then?\nDad: Sure they did. In fact, those photographs *are* in color. It's just the *world* was black and white then.\nCalvin: Really?\nDad: Yep. The world didn't turn color until sometimes in the 1930s...\")?;\n\n    let mut calvin_file = OpenOptions::new()\n        .append(true) // Now we can write without deleting it\n        .read(true)\n        .open(\"calvin_with_dad.txt\")?;\n    calvin_file.write_all(b\"And it was a pretty grainy color for a while too.\\n\")?;\n    write!(&mut calvin_file, \"That's really weird.\\n\")?;\n    write!(&mut calvin_file, \"Well, truth is stranger than fiction.\")?;\n\n    println!(\"{}\", fs::read_to_string(\"calvin_with_dad.txt\")?);\n\n    Ok(())\n}\n```\n\nThis prints:\n\n```text\nCalvin: Dad, how come old photographs are always black and white? Didn't they have color film back then?\nDad: Sure they did. In fact, those photographs *are* in color. It's just the *world* was black and white then.\nCalvin: Really?\nDad: Yep. The world didn't turn color until sometimes in the 1930s...And it was a pretty grainy color for a while too.\nThat's really weird.\nWell, truth is stranger than fiction.\n```\n\n## cargo doc\n\nYou might have noticed that Rust documentation always looks almost the same. On the left side you can see `struct`s and `trait`s, code examples are on the right, etc. This is because you can automatically make documentation just by typing `cargo doc`.\n\nEven making a project with nothing can help you learn about traits in Rust. For example, here are two structs that do almost nothing, and a `fn main()` that also does nothing.\n\n```rust\nstruct DoesNothing {}\nstruct PrintThing {}\n\nimpl PrintThing {\n    fn prints_something() {\n        println!(\"I am printing something\");\n    }\n}\n\nfn main() {}\n```\n\n\nBut if you type `cargo doc --open`, you can see a lot more information than you expected. First it shows you this:\n\n```text\nCrate rust_book\n\nStructs\nDoesNothing\nPrintThing\n\nFunctions\nmain\n```\n\nBut if you click on one of the structs, it will show you a lot of traits that you didn't think were there:\n\n```text\nStruct rust_book::DoesNothing\n[+] Show declaration\nAuto Trait Implementations\nimpl RefUnwindSafe for DoesNothing\nimpl Send for DoesNothing\nimpl Sync for DoesNothing\nimpl Unpin for DoesNothing\nimpl UnwindSafe for DoesNothing\nBlanket Implementations\nimpl<T> Any for T\nwhere\n    T: 'static + ?Sized,\n[src]\n[+]\nimpl<T> Borrow<T> for T\nwhere\n    T: ?Sized,\n[src]\n[+]\nimpl<T> BorrowMut<T> for T\nwhere\n    T: ?Sized,\n[src]\n[+]\nimpl<T> From<T> for T\n[src]\n[+]\nimpl<T, U> Into<U> for T\nwhere\n    U: From<T>,\n[src]\n[+]\nimpl<T, U> TryFrom<U> for T\nwhere\n    U: Into<T>,\n[src]\n[+]\nimpl<T, U> TryInto<U> for T\nwhere\n    U: TryFrom<T>,\n```\n\nThis is because of all the traits that Rust automatically makes for every type.\n\nThen if we add some documentation comments you can see them when you type `cargo doc`.\n\n```rust\n/// This is a struct that does nothing\nstruct DoesNothing {}\n/// This struct only has one method.\nstruct PrintThing {}\n/// It just prints the same message.\nimpl PrintThing {\n    fn prints_something() {\n        println!(\"I am printing something\");\n    }\n}\n\nfn main() {}\n```\n\n\nNow it will print:\n\n```text\nCrate rust_book\nStructs\nDoesNothing This is a struct that does nothing\nPrintThing  This struct only has one method.\nFunctions\nmain\n```\n\n`cargo doc` is very nice when you use a lot of other people's crates. Because these crates are all on different websites, it can take some time to search them all. But if you use `cargo doc`, you will have them all in the same place on your hard drive.\n\n## The end?\n\nThis is the end of Rust in Easy English. But I am still here, and you can let me know if you have any questions. Feel free to [contact me on Twitter](https://twitter.com/mithridates) or add a pull request, issue, etc. You can also tell me if some parts weren't easy to understand. Rust in Easy English needs to be very easy to understand, so please let me know where the English is too difficult. Of course, Rust itself can be difficult to understand, but we can at least make sure that the English is easy.\n"
  },
  {
    "path": "book.toml",
    "content": "[book]\nauthors = [\"David MacLeod\"]\nlanguage = \"en\"\nmultilingual = false\nsrc = \"src\"\ntitle = \"Easy Rust\" "
  },
  {
    "path": "createBookFromReadme.sh",
    "content": "#!/usr/bin/env bash\n\n# Execute this script to generate a mdBook version from the single Readme.md file present in this repository.\n# Usage: ./createBookFromReadme.sh\n\n# -------------------- Utility Methods --------------------\n# Check for binaries\nfunction checkEnvironment(){\n    type gcsplit >/dev/null 2>&1 || { echo \"Install 'gcsplit' first (e.g. via 'brew install coreutils').\" >&2 && exit 1 ; }\n    type mdbook >/dev/null 2>&1 || { echo \"Install 'mdbook' first (e.g. via 'cargo install mdbook').\" >&2 && exit 1 ; }\n}\n\n# Cleanup the src directory before starting\nfunction cleanupBeforeStarting(){\n    rm -rf ./src\n    mkdir src\n}\n\n# Splits the Readme.md file based on the header in markdown and creates chapters\n# Note:\n#   Get gcsplit via homebrew on mac: brew install coreutils\nfunction splitIntoChapters(){\n    gcsplit --prefix='Chapter_' --suffix-format='%d.md' --elide-empty-files README.md '/^## /' '{*}' -q\n}\n\n# Moves generated chapters into src directory\nfunction moveChaptersToSrcDir(){\n    for f in Chapter_*.md; do \n        mv $f src/$f\n    done\n}\n\n# Creates the summary from the generated chapters\nfunction createSummary(){\n    cd ./src\n    touch SUMMARY.md\n    echo '# Summary' > SUMMARY.md\n    echo \"\" >> SUMMARY.md\n    for f in $(ls -tr | grep Chapter_); do\n        # Get the first line of the file\n        local firstLine=$(sed -n '1p' $f)\n        local cleanTitle=$(echo $firstLine | cut -c 3-)\n        echo \"- [$cleanTitle](./$f)\" >> SUMMARY.md;\n    done\n    cd ..\n}\n\n# Builds the mdBook version from src directory and starts serving locally.\n# Note:\n#     Install mdBook as per instructions in their repo https://github.com/rust-lang/mdBook\nfunction buildAndServeBookLocally(){\n    mdbook build && mdbook serve --open\n}\n\n# -------------------- Steps to create the mdBook version --------------------\ncheckEnvironment\ncleanupBeforeStarting\nsplitIntoChapters\nmoveChaptersToSrcDir\ncreateSummary\nbuildAndServeBookLocally\n"
  },
  {
    "path": "createGithubPagesFromReadme.sh",
    "content": "#!/usr/bin/env bash\n\n# A modified version of createBookFromReadme.sh for Github Pages\n# Usage: ./createGithunPagesFromReadme.sh\n\n# -------------------- Utility Methods --------------------\n# Check for binaries\nfunction checkEnvironment(){\n    type gcsplit >/dev/null 2>&1 || { echo \"Install 'gcsplit' first (e.g. via 'brew install coreutils').\" >&2 && exit 1 ; }\n}\n\n# Cleanup the src directory before starting\nfunction cleanupBeforeStarting(){\n    rm -rf ./src\n    mkdir src\n}\n\n# Splits the Readme.md file based on the header in markdown and creates chapters\n# Note:\n#   Get gcsplit via homebrew on mac: brew install coreutils\nfunction splitIntoChapters(){\n    gcsplit --prefix='Chapter_' --suffix-format='%d.md' --elide-empty-files README.md '/^## /' '{*}' -q\n}\n\n# Moves generated chapters into src directory\nfunction moveChaptersToSrcDir(){\n    for f in Chapter_*.md; do \n        mv $f src/$f\n    done\n}\n\n# Creates the summary from the generated chapters\nfunction createSummary(){\n    cd ./src\n    touch SUMMARY.md\n    echo '# Summary' > SUMMARY.md\n    echo \"\" >> SUMMARY.md\n    for f in $(ls -tr | grep Chapter_ | sort -V); do\n        # Get the first line of the file\n        local firstLine=$(sed -n '1p' $f)\n        local cleanTitle=$(echo $firstLine | cut -c 3-)\n        echo \"- [$cleanTitle](./$f)\" >> SUMMARY.md;\n    done\n    cd ..\n}\n\n# -------------------- Steps to generate separate Markdown chapters --------------------\ncheckEnvironment\ncleanupBeforeStarting\nsplitIntoChapters\nmoveChaptersToSrcDir\ncreateSummary"
  },
  {
    "path": "createPdfFromReadme.sh",
    "content": "#!/usr/bin/env bash\n\n# Execute this script to generate a PDF version from the single Readme.md file present in this repository.\n# Usage: ./createPdfFromReadme.sh\n\n# -------------------- Utility Methods --------------------\n# Check for binaries\nfunction checkEnvironment(){\n    type pandoc >/dev/null 2>&1 || { echo \"Install 'pandoc' first (e.g. via 'brew install pandoc' or 'apt-get install pandoc').\" >&2 && exit 1 ; }\n    type xelatex >/dev/null 2>&1 || { echo \"Install 'xelatex' first\" >&2 && exit 1 ; }\n}\n\n# Cleanup the src directory before starting\nfunction cleanupBeforeStarting(){\n    rm -rf ./latex\n    mkdir latex\n}\n\n\n# Creates the summary from the generated chapters\nfunction convertToLatex(){\n    cd ./latex\n    cp ../*.png .   # copy Easy_Rust_sample_image.png in the current folder in order to be found.\n\n    # Step 1: run pandoc on README.md which generates the `.tex` file.\n\n    # Commands used previously (didn't require metadata.yaml). Left here for reference...\n    # pandoc ../README.md -V geometry:margin=0.7in -V colorlinks=true -V linkcolor=blue -V urlcolor=blue -V toccolor=gray --standalone --from markdown --to latex > easy_rust.tex\n    # pandoc ../README.md --standalone --from markdown --to latex > easy_rust.tex\n\n    # generates `easy_rust.tex` in the current folder using the instructions given inside `../pdf_metadata.yaml`.\n    pandoc ../README.md ../pdf_metadata.yaml -s -o easy_rust.tex # --toc    # The `toc` flag can be added or not depending on personal preferences.\n                                                                            # If added, the `xelatex` command right below needs to be run twice (the first time.)\n    echo \"Generated easy_rust.tex file.\"\n\n\n    # Step 2: run `xelatex` on the `.tex` file to geneate the PDF.\n    xelatex --interaction=nonstopmode easy_rust.tex \n    # to generate the TOC you need to run this twice\n    # xelatex --interaction=nonstopmode easy_rust.tex\n    \n    echo \"Generated PDF file easy_rust.pdf\"    \n    cd ..\n}\n\n\n\n# -------------------- Steps to create the mdBook version --------------------\ncheckEnvironment\ncleanupBeforeStarting\nconvertToLatex\n"
  },
  {
    "path": "pdf_metadata.yaml",
    "content": "---\ntitle: 'Easy Rust'\nauthor:\n- https://github.com/Dhghomon/easy_rust\nkeywords: [rust, easy-rust]\n# abstract: |\n#   Rust explained using easy English\n\ngeometry: margin=0.7in #left=1cm,right=1cm,top=2cm,bottom=2cm\n\ncolorlinks: true\nlinkcolor: blue \nurlcolor: blue \ntoccolor: gray\n\n...\n"
  }
]