{"id":13395233,"url":"https://github.com/Dhghomon/easy_rust","last_synced_at":"2025-03-13T20:31:59.943Z","repository":{"id":38305717,"uuid":"278798376","full_name":"Dhghomon/easy_rust","owner":"Dhghomon","description":"Rust explained using easy English","archived":false,"fork":false,"pushed_at":"2024-05-13T14:20:20.000Z","size":5080,"stargazers_count":8012,"open_issues_count":19,"forks_count":377,"subscribers_count":149,"default_branch":"master","last_synced_at":"2024-07-31T17:23:42.364Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Shell","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Dhghomon.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-07-11T05:54:06.000Z","updated_at":"2024-07-31T15:09:58.000Z","dependencies_parsed_at":"2024-10-25T10:17:22.049Z","dependency_job_id":"7d64c570-10bd-4bf4-8c1e-ea9b63f42a7a","html_url":"https://github.com/Dhghomon/easy_rust","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dhghomon%2Feasy_rust","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dhghomon%2Feasy_rust/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dhghomon%2Feasy_rust/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dhghomon%2Feasy_rust/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Dhghomon","download_url":"https://codeload.github.com/Dhghomon/easy_rust/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243478345,"owners_count":20297238,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-30T17:01:47.034Z","updated_at":"2025-03-13T20:31:59.280Z","avatar_url":"https://github.com/Dhghomon.png","language":"Shell","funding_links":["https://www.buymeacoffee.com/mithridates"],"categories":["Shell","4. FullStack","HarmonyOS","Resources","资源 Resources","🔗 Important Resources Links","By Language","others","Rust"],"sub_categories":["4.1. Rust","Windows Manager","Web programming","网络编程 Web programming","Shell","Rust learning"],"readme":"## 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\u0026list=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 \u0026str 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 \u0026str](#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 --\u003e 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::\u003cchar\u003e()); // 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 --\u003e 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() -\u003e 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 `-\u003e` (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() -\u003e i32 {\n    8;  // ⚠️\n}\n```\n\n```text\n5 | fn number() -\u003e 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) -\u003e 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 --\u003e 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 \u0026str`. `\u0026str` 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) -\u003e 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) -\u003e 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 `\u0026` in front of them. So:\n\n- `let my_variable = 8` makes a regular variable, but\n- `let my_reference = \u0026my_variable` makes a reference.\n\nYou read `my_reference = \u0026my_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 = \u0026my_number; //  This is a \u0026i32\n    let double_reference = \u0026single_reference; // This is a \u0026\u0026i32\n    let five_references = \u0026\u0026\u0026\u0026\u0026my_number; // This is a \u0026\u0026\u0026\u0026\u0026i32\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() -\u003e 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 `\u0026str` 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:;\u003c=\u003e?@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 `\u0026str` 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 = \u0026number;\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 `^`. `\u003c` means padding with the character on the left, `\u003e` 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!(\"{: \u003c15}{: \u003e15}\", 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:-\u003c15}{city2:-\u003e15}\", 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 `\u0026str`. What is the difference?\n\n- `\u0026str` is a simple string. When you write `let my_variable = \"Hello, world!\"`, you create a `\u0026str`. A `\u0026str` 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 `\u0026str` has the `\u0026` 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 `\u0026` that it knows the size of, and then it is happy. Also, because you use a `\u0026` 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 `\u0026str` 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 \u0026str 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 `\u0026str`. 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 `\u0026` 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::\u003cString\u003e()); // std::mem::size_of::\u003cType\u003e() gives you the size in bytes of a type\n    println!(\"And an i8 is always {:?} bytes. It is Sized.\", std::mem::size_of::\u003ci8\u003e());\n    println!(\"And an f64 is always {:?} bytes. It is Sized.\", std::mem::size_of::\u003cf64\u003e());\n    println!(\"But a \u0026str? 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 \u0026str? 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 \u0026, because `\u0026` 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 \u0026str 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 `\u0026str`. 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 `\u0026str`. It says, \"I can make a \u0026str into a lot of things. Which one do you want?\"\n\n```text\nerror[E0282]: type annotations needed\n --\u003e 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: [\u0026str; 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 `\u0026` to create a reference:\n\n```rust\nfn main() {\n    let country = String::from(\"Austria\");\n    let ref_one = \u0026country;\n    let ref_two = \u0026country;\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 `\u0026String`, 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() -\u003e \u0026str {\n    let country = String::from(\"Austria\");\n    let country_ref = \u0026country;\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 `\u0026String` 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 `\u0026mut` instead of `\u0026`.\n\n```rust\nfn main() {\n    let mut my_number = 8; // don't forget to write mut here!\n    let num_ref = \u0026mut my_number;\n}\n```\n\nSo what are the two types? `my_number` is an `i32`, and `num_ref` is `\u0026mut 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 `\u0026i32`. 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 `\u0026`. Also, one `*` erases one `\u0026`.\n\n```rust\nfn main() {\n    let mut my_number = 8;\n    let num_ref = \u0026mut 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 = \u0026\u0026\u0026second_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 `\u0026` 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 = \u0026number;\n    let number_change = \u0026mut 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 --\u003e src\\main.rs:4:25\n  |\n3 |     let number_ref = \u0026number;\n  |                      ------- immutable borrow occurs here\n4 |     let number_change = \u0026mut 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 = \u0026mut number; // create a mutable reference\n    *number_change += 10; // use mutable reference to add 10\n    let number_ref = \u0026number; // 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 = \u0026country;\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 = \u0026country; // 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 `-\u003e`, 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) -\u003e 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 `\u0026`.\n\n```rust\nfn print_country(country_name: \u0026String) {\n    println!(\"{}\", country_name);\n}\n\nfn main() {\n    let country = String::from(\"Austria\");\n    print_country(\u0026country); // We print \"Austria\"\n    print_country(\u0026country); // 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 `\u0026String`. Also, we give it a reference to country by writing `\u0026country`. 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: \u0026mut String) { // first we say that the function takes a mutable reference\n    country_name.push_str(\"-Hungary\"); // push_str() adds a \u0026str to a String\n    println!(\"Now it says: {}\", country_name);\n}\n\nfn main() {\n    let mut country = String::from(\"Austria\");\n    add_hungary(\u0026mut 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: \u0026String)` borrows a `String` and can look at it\n- `fn function_name(variable: \u0026mut 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 `\u0026String`). 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 -\u003e 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 --\u003e 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 `\u0026` for a reference is faster, if you can. For example, this code pushes a `\u0026str` 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: \u0026String) {\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(\u0026my_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) -\u003e 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 `\u0026str` 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 `[\u0026str; 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 [\u0026str; 2]\n    let array2 = [\"One\", \"Two\", \"Five\"]; // But this one is type [\u0026str; 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 `[\u0026str; 4]` in the current scope\n --\u003e src\\main.rs:4:13\n  |\n4 |     seasons.ddd(); // \n  |             ^^^ method not found in `[\u0026str; 4]`\n\nerror[E0599]: no method named `thd` found for array `[\u0026str; 5]` in the current scope\n --\u003e src\\main.rs:5:14\n  |\n5 |     seasons2.thd(); // \n  |              ^^^ method not found in `[\u0026str; 5]`\n```\n\nSo it tells you `` method not found in `[\u0026str; 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 \u0026, 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 = \u0026array_of_ten[2..5];\n    let start_at_two = \u0026array_of_ten[1..];\n    let end_at_five = \u0026array_of_ten[..5];\n    let everything = \u0026array_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 `\u0026str` 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\u003cString\u003e\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 `\u003c\u003e` (angle brackets) are for. A `Vec\u003cString\u003e` is a vector with one or more `String`s. You can also have more types inside. For example:\n\n- `Vec\u003c(i32, i32)\u003e` this is a `Vec` where each item is a tuple: `(i32, i32)`.\n- `Vec\u003cVec\u003cString\u003e\u003e` this is a `Vec` that has `Vec`s of `Strings`. Say for example you wanted to save your favourite book as a `Vec\u003cString\u003e`. Then you do it again with another book, and get another `Vec\u003cString\u003e`. To hold both books, you would put them into another `Vec` and that would be a `Vec\u003cVec\u003cString\u003e\u003e`.\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\u003cString\u003e = 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\u003ci32\u003e`. You call it a \"Vec of i32s\". And a `Vec\u003cString\u003e` is a \"Vec of strings\". And a `Vec\u003cVec\u003cString\u003e\u003e` 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 = \u0026vec_of_ten[2..5];\n    let start_at_two = \u0026vec_of_ten[1..];\n    let end_at_five = \u0026vec_of_ten[..5];\n    let everything = \u0026vec_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 `\u0026str` 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\u003c_\u003e`.\n\n```rust\nfn main() {\n    let my_vec: Vec\u003cu8\u003e = [1, 2, 3].into();\n    let my_vec2: Vec\u003c_\u003e = [9, 0, 10].into(); // Vec\u003c_\u003e means \"choose the Vec type for me\"\n                                             // Rust will choose Vec\u003ci32\u003e\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() -\u003e () {}\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 `(\u0026str, i32, Vec\u003cchar\u003e, 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 `\u0026\u0026` (and) and `||` (or).\n\n```rust\nfn main() {\n    let my_number = 5;\n    if my_number % 2 == 1 \u0026\u0026 my_number \u003e 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 =\u003e println!(\"it's zero\"),\n        1 =\u003e println!(\"it's one\"),\n        2 =\u003e 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 --\u003e 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 =\u003e println!(\"it's zero\"),\n        1 =\u003e println!(\"it's one\"),\n        2 =\u003e println!(\"it's two\"),\n        _ =\u003e 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 `=\u003e` 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 =\u003e 0,\n        5 =\u003e 10,\n        _ =\u003e 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\") =\u003e println!(\"It's dark and unpleasant today\"),\n        (\"clear\", \"warm\") =\u003e println!(\"It's a nice day\"),\n        (\"cloudy\", \"warm\") =\u003e println!(\"It's dark but not bad\"),\n        _ =\u003e 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 =\u003e println!(\"Not married with {} children\", children),\n        (children, married) if children == 0 \u0026\u0026 married == true =\u003e println!(\"Married but no children\"),\n        _ =\u003e 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 \u003c 10 =\u003e println!(\"Not much red\"),\n        (_, b, _) if b \u003c 10 =\u003e println!(\"Not much blue\"),\n        (_, _, g) if g \u003c 10 =\u003e println!(\"Not much green\"),\n        _ =\u003e 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 =\u003e 8,\n        _ =\u003e \"Not ten\", // ⚠️\n    };\n}\n```\n\nThe compiler tells you that:\n\n```text\nerror[E0308]: `match` arms have incompatible types\n  --\u003e src\\main.rs:17:14\n   |\n15 |       let some_variable = match my_number {\n   |  _________________________-\n16 | |         10 =\u003e 8,\n   | |               - this is found to be of type `{integer}`\n17 | |         _ =\u003e \"Not ten\",\n   | |              ^^^^^^^^^ expected integer, found `\u0026str`\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 =\u003e println!(\"{} is an unlucky number in China (sounds close to 死)!\", number),\n    number @ 13 =\u003e println!(\"{} is unlucky in North America, lucky in Italy! In bocca al lupo!\", number),\n    _ =\u003e 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) -\u003e ThingsInTheSky {\n    match time {\n        6..=18 =\u003e ThingsInTheSky::Sun, // Between 6 and 18 hours we can see the sun\n        _ =\u003e 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: \u0026ThingsInTheSky) {\n    match state {\n        ThingsInTheSky::Sun =\u003e println!(\"I can see the sun!\"),\n        ThingsInTheSky::Stars =\u003e 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(\u0026skystate); // 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) -\u003e ThingsInTheSky {\n    match time {\n        6..=18 =\u003e ThingsInTheSky::Sun(String::from(\"I can see the sun!\")), // Write the strings here\n        _ =\u003e ThingsInTheSky::Stars(String::from(\"I can see the stars!\")),\n    }\n}\n\nfn check_skystate(state: \u0026ThingsInTheSky) {\n    match state {\n        ThingsInTheSky::Sun(description) =\u003e println!(\"{}\", description), // Give the string the name description so we can use it\n        ThingsInTheSky::Stars(n) =\u003e 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(\u0026skystate); // 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: \u0026Mood) -\u003e i32 {\n    let happiness_level = match mood {\n        Mood::Happy =\u003e 10, // Here we type Mood:: every time\n        Mood::Sleepy =\u003e 6,\n        Mood::NotBad =\u003e 7,\n        Mood::Angry =\u003e 2,\n    };\n    happiness_level\n}\n\nfn main() {\n    let my_mood = Mood::NotBad;\n    let happiness_level = match_mood(\u0026my_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: \u0026Mood) -\u003e 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 =\u003e 10, // We don't have to write Mood:: anymore\n        Sleepy =\u003e 6,\n        NotBad =\u003e 7,\n        Angry =\u003e 2,\n    };\n    happiness_level\n}\n\nfn main() {\n    let my_mood = Mood::Happy;\n    let happiness_level = match_mood(\u0026my_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 \u003c= 80 =\u003e 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 \u003e= 80 =\u003e println!(\"This is a good-sized star.\"),\n            _ =\u003e 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? I","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FDhghomon%2Feasy_rust","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FDhghomon%2Feasy_rust","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FDhghomon%2Feasy_rust/lists"}