gh-pages
Dhghomon 3 years ago
parent 8374050d1d
commit 65064fb4eb

@ -165,7 +165,7 @@
<div id="content" class="content">
<main>
<h1><a class="header" href="#document-not-found-404" id="document-not-found-404">Document not found (404)</a></h1>
<h1 id="document-not-found-404"><a class="header" href="#document-not-found-404">Document not found (404)</a></h1>
<p>This URL is invalid, sorry. Please use the navigation bar or search to continue.</p>
</main>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#update" id="update">Update</a></h2>
<h2 id="update"><a class="header" href="#update">Update</a></h2>
<p><img src="https://github.com/Dhghomon/easy_rust/workflows/github%20pages/badge.svg" alt="example workflow name" /></p>
<p>22 December 2020: mdBook can be found <a href="https://dhghomon.github.io/easy_rust">here</a>.</p>
<p>28 November 2020: <a href="https://github.com/kumakichi/easy_rust_chs">Now also available in simplified Chinese</a> thanks to <a href="https://github.com/kumakichi">kumakichi</a>!</p>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#introduction" id="introduction">Introduction</a></h2>
<h2 id="introduction"><a class="header" href="#introduction">Introduction</a></h2>
<p>Rust 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.</p>
<p>Rust 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 &quot;figure it out as you go along&quot;. 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.</p>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#display-and-debug" id="display-and-debug">Display and debug</a></h2>
<h2 id="display-and-debug"><a class="header" href="#display-and-debug">Display and debug</a></h2>
<p><strong><a href="https://youtu.be/jd3pC248c0o">See this chapter on YouTube</a></strong></p>
<p>Simple variables in Rust can be printed with <code>{}</code> inside <code>println!</code>. But some variables can't, and you need to <strong>debug print</strong>. 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.</p>
<p>How do you know if you need <code>{:?}</code> and not <code>{}</code>? The compiler will tell you. For example:</p>
@ -193,7 +193,7 @@
}
</code></pre></pre>
<p>This prints <code>This will not print a new line so this will be on the same line</code>.</p>
<h3><a class="header" href="#smallest-and-largest-numbers" id="smallest-and-largest-numbers">Smallest and largest numbers</a></h3>
<h3 id="smallest-and-largest-numbers"><a class="header" href="#smallest-and-largest-numbers">Smallest and largest numbers</a></h3>
<p>If you want to see the smallest and biggest numbers, you can use MIN and MAX. <code>std</code> means &quot;standard library&quot; and has all the main functions etc. for Rust. We will learn about the standard library later. But in the meantime, you can remember that this is how you get the smallest and largest number for a type.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
println!(&quot;The smallest i8 is {} and the biggest i8 is {}.&quot;, std::i8::MIN, std::i8::MAX); // hint: printing std::i8::MIN means &quot;print MIN inside of the i8 section in the standard library&quot;

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#mutability-changing" id="mutability-changing">Mutability (changing)</a></h2>
<h2 id="mutability-changing"><a class="header" href="#mutability-changing">Mutability (changing)</a></h2>
<p><strong><a href="https://youtu.be/Nyyd6qn7dZY">See this chapter on YouTube</a></strong></p>
<p>When you declare a variable with <code>let</code>, it is immutable (cannot be changed).</p>
<p>This will not work:</p>
@ -187,7 +187,7 @@
}
</code></pre></pre>
<p>You will see the same &quot;expected&quot; message from the compiler: <code>expected integer, found &amp;str</code>. <code>&amp;str</code> is a string type that we will learn soon.</p>
<h3><a class="header" href="#shadowing" id="shadowing">Shadowing</a></h3>
<h3 id="shadowing"><a class="header" href="#shadowing">Shadowing</a></h3>
<p><strong><a href="https://youtu.be/InULHyRGw7g">See this chapter on YouTube</a></strong></p>
<p>Shadowing means using <code>let</code> 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:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#the-stack-the-heap-and-pointers" id="the-stack-the-heap-and-pointers">The stack, the heap, and pointers</a></h2>
<h2 id="the-stack-the-heap-and-pointers"><a class="header" href="#the-stack-the-heap-and-pointers">The stack, the heap, and pointers</a></h2>
<p>The stack, the heap, and pointers are very important in Rust.</p>
<p>The stack and the heap are two places to keep memory in computers. The important differences are:</p>
<ul>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#more-about-printing" id="more-about-printing">More about printing</a></h2>
<h2 id="more-about-printing"><a class="header" href="#more-about-printing">More about printing</a></h2>
<p>In Rust you can print things in almost any way you want. Here are some more things to know about printing.</p>
<p>Adding <code>\n</code> will make a new line, and <code>\t</code> will make a tab:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#strings" id="strings">Strings</a></h2>
<h2 id="strings"><a class="header" href="#strings">Strings</a></h2>
<p><strong><a href="https://youtu.be/pSyaGzGg26o">See this chapter on YouTube</a></strong></p>
<p>Rust has two main types of strings: <code>String</code> and <code>&amp;str</code>. What is the difference?</p>
<ul>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#const-and-static" id="const-and-static">const and static</a></h2>
<h2 id="const-and-static"><a class="header" href="#const-and-static">const and static</a></h2>
<p><strong><a href="https://youtu.be/Ky3HqkWUcI0">See this chapter on YouTube</a></strong></p>
<p>There are two types that don't use <code>let</code> to declare: <code>const</code> and <code>static</code>. Also, Rust won't use type inference: you need to write the type for them. These are for variables that don't change (<code>const</code> means constant). The difference is that:</p>
<ul>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#more-on-references" id="more-on-references">More on references</a></h2>
<h2 id="more-on-references"><a class="header" href="#more-on-references">More on references</a></h2>
<p><strong><a href="https://youtu.be/R13sQ8SNoEQ">See this chapter on YouTube</a></strong></p>
<p>References are very important in Rust. Rust uses references to make sure that all memory access is safe. We know that we use <code>&amp;</code> to create a reference:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#mutable-references" id="mutable-references">Mutable references</a></h2>
<h2 id="mutable-references"><a class="header" href="#mutable-references">Mutable references</a></h2>
<p><strong><a href="https://youtu.be/G48z6Rv76vc">See this chapter on YouTube</a></strong></p>
<p>If you want to use a reference to change data, you can use a mutable reference. For a mutable reference, you write <code>&amp;mut</code> instead of <code>&amp;</code>.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
@ -234,7 +234,7 @@ Second_number = triple_reference? true
</code></pre></pre>
<p>It prints <code>20</code> with no problem. It works because the compiler is smart enough to understand our code. It knows that we used <code>number_change</code> to change <code>number</code>, but didn't use it again. So here there is no problem. We are not using immutable and mutable references together.</p>
<p>Earlier 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.</p>
<h3><a class="header" href="#shadowing-again" id="shadowing-again">Shadowing again</a></h3>
<h3 id="shadowing-again"><a class="header" href="#shadowing-again">Shadowing again</a></h3>
<p>Remember when we said that shadowing doesn't <strong>destroy</strong> a value but <strong>blocks</strong> it? Now we can use references to see this.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let country = String::from(&quot;Austria&quot;);

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#giving-references-to-functions" id="giving-references-to-functions">Giving references to functions</a></h2>
<h2 id="giving-references-to-functions"><a class="header" href="#giving-references-to-functions">Giving references to functions</a></h2>
<p><strong>See this chapter on YouTube: <a href="https://youtu.be/mKWXt9YTavc">immutable references</a> and <a href="https://youtu.be/kJV1wIvAbyk">mutable references</a></strong></p>
<p>References are very useful for functions. The rule in Rust on values is: a value can only have one owner.</p>
<p>This code will not work:</p>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#copy-types" id="copy-types">Copy types</a></h2>
<h2 id="copy-types"><a class="header" href="#copy-types">Copy types</a></h2>
<p>Some types in Rust are very simple. They are called <strong>copy types</strong>. 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.</p>
<p>These simple types include: integers, floats, booleans (<code>true</code> and <code>false</code>), and <code>char</code>.</p>
<p>How do you know if a type <strong>implements</strong> copy? (implements = can use) You can check the documentation. For example, here is the documentation for char:</p>
@ -256,7 +256,7 @@ fn main() {
}
</code></pre></pre>
<p>Instead of 50 clones, it's zero.</p>
<h3><a class="header" href="#variables-without-values" id="variables-without-values">Variables without values</a></h3>
<h3 id="variables-without-values"><a class="header" href="#variables-without-values">Variables without values</a></h3>
<p>A variable without a value is called an &quot;uninitialized&quot; variable. Uninitialized means &quot;hasn't started yet&quot;. They are simple: just write <code>let</code> and the variable name:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let my_variable; // ⚠️

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#who-am-i" id="who-am-i">Who am I?</a></h2>
<h2 id="who-am-i"><a class="header" href="#who-am-i">Who am I?</a></h2>
<p>I 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.</p>
</main>

@ -163,9 +163,9 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#collection-types" id="collection-types">Collection types</a></h2>
<h2 id="collection-types"><a class="header" href="#collection-types">Collection types</a></h2>
<p>Rust 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 <code>&amp;str</code> in that way.</p>
<h3><a class="header" href="#arrays" id="arrays">Arrays</a></h3>
<h3 id="arrays"><a class="header" href="#arrays">Arrays</a></h3>
<p>An array is data inside square brackets: <code>[]</code>. Arrays:</p>
<ul>
<li>must not change their size,</li>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#vectors" id="vectors">Vectors</a></h2>
<h2 id="vectors"><a class="header" href="#vectors">Vectors</a></h2>
<p><strong><a href="https://youtu.be/Eh-DsRnDKmw">See this chapter on YouTube</a></strong></p>
<p>In the same way that we have <code>&amp;str</code> and <code>String</code>, 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<em>er</em> than arrays.) The type is written <code>Vec</code>, and you can also just call it a &quot;vec&quot;.</p>
<p>There are two main ways to declare a vector. One is like with <code>String</code> using <code>new</code>:</p>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#tuples" id="tuples">Tuples</a></h2>
<h2 id="tuples"><a class="header" href="#tuples">Tuples</a></h2>
<p><strong><a href="https://youtu.be/U67Diy6SlTg">See this chapter on YouTube</a></strong></p>
<p>Tuples in Rust use <code>()</code>. We have seen many empty tuples already, because <em>nothing</em> in a function actually means an empty tuple:</p>
<pre><code class="language-text">fn do_something() {}

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#control-flow" id="control-flow">Control flow</a></h2>
<h2 id="control-flow"><a class="header" href="#control-flow">Control flow</a></h2>
<p><strong>See this chapter on YouTube: <a href="https://youtu.be/UAymDOpv_us">Part 1</a> and <a href="https://youtu.be/eqysTfiiQZs">Part 2</a></strong></p>
<p>Control flow means telling your code what to do in different situations. The simplest control flow is <code>if</code>.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#structs" id="structs">Structs</a></h2>
<h2 id="structs"><a class="header" href="#structs">Structs</a></h2>
<p><strong>See this chapter on YouTube: <a href="https://youtu.be/W23uQghBOFk">Part 1</a> and <a href="https://youtu.be/GSVhrjLCuNA">Part 2</a></strong></p>
<p>With 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 <code>struct</code>. 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.</p>
<p>There are three types of structs. One is a &quot;unit struct&quot;. Unit means &quot;doesn't have anything&quot;. For a unit struct, you just write the name and a semicolon.</p>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#enums" id="enums">Enums</a></h2>
<h2 id="enums"><a class="header" href="#enums">Enums</a></h2>
<p><strong>See this chapter on YouTube: <a href="https://youtu.be/SRnqNTJUgjs">Part 1</a>, <a href="https://youtu.be/F_EcbWM63lk">Part 2</a>, <a href="https://youtu.be/2uh64U9JesA">Part 3</a> and <a href="https://youtu.be/LOHVUYTc5Us">Part 4</a></strong></p>
<p>An <code>enum</code> is short for enumerations. They look very similar to a struct, but are different. Here is the difference:</p>
<ul>
@ -337,7 +337,7 @@ This is a good-sized star.
What about DeadStar? It's the number 1001.
</code></pre>
<p><code>DeadStar</code> would have been number 4, but now it's 1001.</p>
<h3><a class="header" href="#enums-to-use-multiple-types" id="enums-to-use-multiple-types">Enums to use multiple types</a></h3>
<h3 id="enums-to-use-multiple-types"><a class="header" href="#enums-to-use-multiple-types">Enums to use multiple types</a></h3>
<p>You know that items in a <code>Vec</code>, array, etc. all need the same type (only tuples are different). But you can actually use an enum to put different types in. Imagine we want to have a <code>Vec</code> with <code>u32</code>s or <code>i32</code>s. Of course, you can make a <code>Vec&lt;(u32, i32)&gt;</code> (a vec with <code>(u32, i32)</code> tuples) but we only want one each time. So here you can use an enum. Here is a simple example:</p>
<pre><pre class="playground"><code class="language-rust">enum Number {
U32(u32),

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#loops" id="loops">Loops</a></h2>
<h2 id="loops"><a class="header" href="#loops">Loops</a></h2>
<p>With loops you can tell Rust to continue something until you want it to stop. You use <code>loop</code> to start a loop that does not stop, unless you tell it when to <code>break</code>.</p>
<pre><pre class="playground"><code class="language-rust">fn main() { // This program will never stop
loop {

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#implementing-structs-and-enums" id="implementing-structs-and-enums">Implementing structs and enums</a></h2>
<h2 id="implementing-structs-and-enums"><a class="header" href="#implementing-structs-and-enums">Implementing structs and enums</a></h2>
<p>This is where you can start to give your structs and enums some real power. To call functions on a <code>struct</code> or an <code>enum</code>, use an <code>impl</code> block. These functions are called <strong>methods</strong>. There are two kinds of methods in an <code>impl</code> block.</p>
<ul>
<li>Regular methods: these take <strong>self</strong> (or <strong>&amp;self</strong> or <strong>&amp;mut self</strong>). Regular methods use a <code>.</code> (a period). <code>.clone()</code> is an example of a regular method.</li>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#destructuring" id="destructuring">Destructuring</a></h2>
<h2 id="destructuring"><a class="header" href="#destructuring">Destructuring</a></h2>
<p>Let's look at some more destructuring. You can get the values from a struct or enum by using <code>let</code> backwards. We learned that this is <code>destructuring</code>, because you get variables that are not part of a structure. Now you have the values separately. First a simple example:</p>
<pre><pre class="playground"><code class="language-rust">struct Person { // make a simple struct for a person
name: String,

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#references-and-the-dot-operator" id="references-and-the-dot-operator">References and the dot operator</a></h2>
<h2 id="references-and-the-dot-operator"><a class="header" href="#references-and-the-dot-operator">References and the dot operator</a></h2>
<p>We learned that when you have a reference, you need to use <code>*</code> to get to the value. A reference is a different type, so this won't work:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let my_number = 9;

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#writing-rust-in-easy-english" id="writing-rust-in-easy-english">Writing Rust in Easy English</a></h2>
<h2 id="writing-rust-in-easy-english"><a class="header" href="#writing-rust-in-easy-english">Writing Rust in Easy English</a></h2>
<p><em>Rust in Easy English</em> was written from July to August 2020, and is over 400 pages long. You can contact me here or <a href="https://www.linkedin.com/in/davemacleod">on LinkedIn</a> or <a href="https://twitter.com/mithridates">on Twitter</a> 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.</p>
<ul>
<li><a href="#part-1---rust-in-your-browser">Part 1 - Rust in your browser</a>
@ -349,7 +349,7 @@
</ul>
</li>
</ul>
<h1><a class="header" href="#part-1---rust-in-your-browser" id="part-1---rust-in-your-browser">Part 1 - Rust in your browser</a></h1>
<h1 id="part-1---rust-in-your-browser"><a class="header" href="#part-1---rust-in-your-browser">Part 1 - Rust in your browser</a></h1>
<p>This 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.</p>
</main>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#generics" id="generics">Generics</a></h2>
<h2 id="generics"><a class="header" href="#generics">Generics</a></h2>
<p>In functions, you write what type to take as input:</p>
<pre><pre class="playground"><code class="language-rust">fn return_number(number: i32) -&gt; i32 {
println!(&quot;Here is your number.&quot;);

@ -163,10 +163,10 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#option-and-result" id="option-and-result">Option and Result</a></h2>
<h2 id="option-and-result"><a class="header" href="#option-and-result">Option and Result</a></h2>
<p>We understand enums and generics now, so we can understand <code>Option</code> and <code>Result</code>. Rust uses these two enums to make code safer.</p>
<p>We will start with <code>Option</code>.</p>
<h3><a class="header" href="#option" id="option">Option</a></h3>
<h3 id="option"><a class="header" href="#option">Option</a></h3>
<p>You use <code>Option</code> when you have a value that might exist, or might not exist. When a value exists it is <code>Some(value)</code> and when it doesn't it's just <code>None</code>, Here is an example of bad code that can be improved with <code>Option</code>.</p>
<pre><pre class="playground"><code class="language-rust"> // ⚠️
fn take_fifth(value: Vec&lt;i32&gt;) -&gt; i32 {
@ -301,7 +301,7 @@ fn main() {
<pre><code class="language-text">We got nothing.
We got: 5
</code></pre>
<h3><a class="header" href="#result" id="result">Result</a></h3>
<h3 id="result"><a class="header" href="#result">Result</a></h3>
<p>Result is similar to Option, but here is the difference:</p>
<ul>
<li>Option is about <code>Some</code> or <code>None</code> (value or no value),</li>

@ -163,9 +163,9 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#other-collections" id="other-collections">Other collections</a></h2>
<h2 id="other-collections"><a class="header" href="#other-collections">Other collections</a></h2>
<p>Rust has many more types of collections. You can see them at https://doc.rust-lang.org/beta/std/collections/ in the standard library. That page has good explanations for why to use one type, so go there if you don't know what type you want. These collections are all inside <code>std::collections</code> in the standard library. The best way to use them is with a <code>use</code> statement, like we did with our <code>enums</code>. We will start with <code>HashMap</code>, which is very common.</p>
<h3><a class="header" href="#hashmap-and-btreemap" id="hashmap-and-btreemap">HashMap (and BTreeMap)</a></h3>
<h3 id="hashmap-and-btreemap"><a class="header" href="#hashmap-and-btreemap">HashMap (and BTreeMap)</a></h3>
<p>A HashMap is a collection made out of <em>keys</em> and <em>values</em>. You use the key to look up the value that matches the key. You can create a new <code>HashMap</code> with just <code>HashMap::new()</code> and use <code>.insert(key, value)</code> to insert items.</p>
<p>A <code>HashMap</code> is not in order, so if you print every key in a <code>HashMap</code> together it will probably print differently. We can see this in an example:</p>
<pre><pre class="playground"><code class="language-rust">use std::collections::HashMap; // This is so we can just write HashMap instead of std::collections::HashMap every time
@ -398,7 +398,7 @@ fn main() {
&quot;male&quot;, [9, 0, 10]
</code></pre>
<p>The important line is: <code>survey_hash.entry(item.0).or_insert(Vec::new()).push(item.1);</code> So if it sees &quot;female&quot; it will check to see if there is &quot;female&quot; already in the <code>HashMap</code>. If not, it will insert a <code>Vec::new()</code>, then push the number in. If it sees &quot;female&quot; already in the <code>HashMap</code>, it will not insert a new Vec, and will just push the number into it.</p>
<h3><a class="header" href="#hashset-and-btreeset" id="hashset-and-btreeset">HashSet and BTreeSet</a></h3>
<h3 id="hashset-and-btreeset"><a class="header" href="#hashset-and-btreeset">HashSet and BTreeSet</a></h3>
<p>A <code>HashSet</code> is actually a <code>HashMap</code> that only has keys. On <a href="https://doc.rust-lang.org/std/collections/struct.HashSet.html">the page for HashSet</a> it explains this on the top:</p>
<p><code>A hash set implemented as a HashMap where the value is ().</code> So it's a <code>HashMap</code> with keys, no values.</p>
<p>You often use a <code>HashSet</code> if you just want to know if a key exists, or doesn't exist.</p>
@ -472,7 +472,7 @@ fn main() {
}
</code></pre></pre>
<p>Now it will print in order: <code>0 3 5 8 10 11 13 14 15 16 17 18 19 20 22 24 25 26 28 29 32 33 34 35 36 37 38 41 42 43 44 46 49 51 54 55 56 57 58 59 60 61 63 64 66 67 68 71 73 74 76 79 80 81 82 84 86 87 89 90 91 92 93 94 95 96</code>.</p>
<h3><a class="header" href="#binaryheap" id="binaryheap">BinaryHeap</a></h3>
<h3 id="binaryheap"><a class="header" href="#binaryheap">BinaryHeap</a></h3>
<p>A <code>BinaryHeap</code> is an interesting collection type, because it is mostly unordered but has a bit of order. It keeps the largest item in the front, but the other items are in any order.</p>
<p>We will use another list of items for an example, but this time smaller.</p>
<pre><pre class="playground"><code class="language-rust">use std::collections::BinaryHeap;
@ -535,7 +535,7 @@ You need to: Tell your team members thanks for always working hard
You need to: Plan who to hire next for the team
You need to: Watch some YouTube
</code></pre>
<h3><a class="header" href="#vecdeque" id="vecdeque">VecDeque</a></h3>
<h3 id="vecdeque"><a class="header" href="#vecdeque">VecDeque</a></h3>
<p>A <code>VecDeque</code> is a <code>Vec</code> that is good at popping items both off the front and the back. Rust has <code>VecDeque</code> because a <code>Vec</code> is great for popping off the back (the last item), but not so great off the front. When you use <code>.pop()</code> on a <code>Vec</code>, it just takes off the last item on the right and nothing else is moved. But if you take it off another part, all the items to the right are moved over one position to the left. You can see this in the description for <code>.remove()</code>:</p>
<pre><code class="language-text">Removes and returns the element at position index within the vector, shifting all elements after it to the left.
</code></pre>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#the--operator" id="the--operator">The ? operator</a></h2>
<h2 id="the--operator"><a class="header" href="#the--operator">The ? operator</a></h2>
<p>There is an even shorter way to deal with <code>Result</code> (and <code>Option</code>), shorter than <code>match</code> and even shorter than <code>if let</code>. It is called the &quot;question mark operator&quot;, and is just <code>?</code>. After a function that returns a result, you can add <code>?</code>. This will:</p>
<ul>
<li>return what is inside the <code>Result</code> if it is <code>Ok</code></li>
@ -235,7 +235,7 @@ fn main() {
</code></pre></pre>
<p>This prints the same thing, but this time we handled three <code>Result</code>s in a single line. Later on we will do this with files, because they always return <code>Result</code>s because many things can go wrong.</p>
<p>Imagine the following: you want to open a file, write to it, and close it. First you need to successfully find the file (that's a <code>Result</code>). Then you need to successfully write to it (that's a <code>Result</code>). With <code>?</code> you can do that on one line.</p>
<h3><a class="header" href="#when-panic-and-unwrap-are-good" id="when-panic-and-unwrap-are-good">When panic and unwrap are good</a></h3>
<h3 id="when-panic-and-unwrap-are-good"><a class="header" href="#when-panic-and-unwrap-are-good">When panic and unwrap are good</a></h3>
<p>Rust has a <code>panic!</code> macro that you can use to make it panic. It is easy to use:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
panic!(&quot;Time to panic!&quot;);

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#traits" id="traits">Traits</a></h2>
<h2 id="traits"><a class="header" href="#traits">Traits</a></h2>
<p>We have seen traits before: <code>Debug</code>, <code>Copy</code>, <code>Clone</code> are all traits. To give a type a trait, you have to implement it. Because <code>Debug</code> and the others are so common, we have attributes that automatically do it. That's what happens you write <code>#[derive(Debug)]</code>: you are automatically implementing <code>Debug</code>.</p>
<pre><pre class="playground"><code class="language-rust">#[derive(Debug)]
struct MyStruct {
@ -627,7 +627,7 @@ You raise your hands and cast a fireball! Your opponent now has 0 health left. Y
</code></pre>
<p>So you can see there are many ways to do the same thing when you use traits. It all depends on what makes the most sense for the program that you are writing.</p>
<p>Now let's look at how to implement some of the main traits you will use in Rust.</p>
<h3><a class="header" href="#the-from-trait" id="the-from-trait">The From trait</a></h3>
<h3 id="the-from-trait"><a class="header" href="#the-from-trait">The From trait</a></h3>
<p><em>From</em> is a very convenient trait to use, and you know this because you have seen it so much already. With <em>From</em> you can make a <code>String</code> from a <code>&amp;str</code>, but you can make many types from many other types. For example, Vec uses <em>From</em> for the following:</p>
<pre><code class="language-text">From&lt;&amp;'_ [T]&gt;
From&lt;&amp;'_ mut [T]&gt;
@ -755,7 +755,7 @@ fn main() {
Odd numbers: [7, -1, 3, 9787, -47, 77, 55, 7]
</code></pre>
<p>A type like <code>EvenOddVec</code> is probably better as a generic <code>T</code> so we can use many number types. You can try to make the example generic if you want for practice.</p>
<h3><a class="header" href="#taking-a-string-and-a-str-in-a-function" id="taking-a-string-and-a-str-in-a-function">Taking a String and a &amp;str in a function</a></h3>
<h3 id="taking-a-string-and-a-str-in-a-function"><a class="header" href="#taking-a-string-and-a-str-in-a-function">Taking a String and a &amp;str in a function</a></h3>
<p>Sometimes you want a function that can take both a <code>String</code> and a <code>&amp;str</code>. You can do this with generics and the <code>AsRef</code> trait. <code>AsRef</code> is used to give a reference from one type to another type. If you look at the documentation for <code>String</code>, you can see that it has <code>AsRef</code> for many types:</p>
<p><a href="https://doc.rust-lang.org/std/string/struct.String.html">https://doc.rust-lang.org/std/string/struct.String.html</a></p>
<p>Here are some function signatures for them.</p>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#chaining-methods" id="chaining-methods">Chaining methods</a></h2>
<h2 id="chaining-methods"><a class="header" href="#chaining-methods">Chaining methods</a></h2>
<p>Rust is a systems programming language like C and C++, and its code can be written as separate commands in separate lines, but it also has a functional style. Both styles are okay, but functional style is usually shorter. Here is an example of the non-functional style (called &quot;imperative style&quot;) to make a <code>Vec</code> from 1 to 10:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let mut new_vec = Vec::new();

@ -163,14 +163,14 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#iterators" id="iterators">Iterators</a></h2>
<h2 id="iterators"><a class="header" href="#iterators">Iterators</a></h2>
<p>An iterator is a construct that can give you the items in the collection, one at a time. Actually, we have already used iterators a lot: the <code>for</code> loop gives you an iterator. When you want to use an iterator other times, you have to choose what kind:</p>
<ul>
<li><code>.iter()</code> for an iterator of references</li>
<li><code>.iter_mut()</code> for an iterator of mutable references</li>
<li><code>.into_iter()</code> for an iterator of values (not references)</li>
</ul>
<p>A <code>for</code> loop is actually just an iterator that uses <code>.iter_mut()</code>. That's why you can change the values when you use it.</p>
<p>A <code>for</code> loop is actually just an iterator that owns its values. That's why it can make it mutable and then you can change the values when you use it.</p>
<p>We can use iterators like this:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let vector1 = vec![1, 2, 3]; // we will use .iter() and .into_iter() on this one
@ -195,7 +195,7 @@
<p>First we used <code>.iter()</code> on <code>vector1</code> to get references. We added 1 to each, and made it into a new Vec. <code>vector1</code> is still alive because we only used references: we didn't take by value. Now we have <code>vector1</code>, and a new Vec called <code>vector1_a</code>. Because <code>.map()</code> just passes it on, we needed to use <code>.collect()</code> to make it into a <code>Vec</code>.</p>
<p>Then we used <code>into_iter</code> to get an iterator by value from <code>vector1</code>. This destroys <code>vector1</code>, because that's what <code>into_iter()</code> does. So after we make <code>vector1_b</code> we can't use <code>vector1</code> again.</p>
<p>Finally we used <code>.iter_mut()</code> for <code>vector2</code>. It is mutable, so we don't need to use <code>.collect()</code> to create a new Vec. Instead, we change the values in the same Vec with mutable references. So <code>vector2</code> is still there. Because we don't need a new Vec, we use <code>for_each</code>: it's just like a <code>for</code> loop.</p>
<h3><a class="header" href="#how-an-iterator-works" id="how-an-iterator-works">How an iterator works</a></h3>
<h3 id="how-an-iterator-works"><a class="header" href="#how-an-iterator-works">How an iterator works</a></h3>
<p>An iterator works by using a method called <code>.next()</code>, which gives an <code>Option</code>. When you use an iterator, Rust calls <code>next()</code> over and over again. If it gets <code>Some</code>, it keeps going. If it gets <code>None</code>, it stops.</p>
<p>Do you remember the <code>assert_eq!</code> macro? In documentation, you see it all the time. Here it is showing how an iterator works.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#closures" id="closures">Closures</a></h2>
<h2 id="closures"><a class="header" href="#closures">Closures</a></h2>
<p>Closures are like quick functions that don't need a name. Sometimes they are called lambdas. Closures are easy to find because they use <code>||</code> instead of <code>()</code>. They are very common in Rust, and once you learn to use them you will wonder how you lived without them.</p>
<p>You can bind a closure to a variable, and then it looks exactly like a function when you use it:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
@ -349,7 +349,7 @@ fn main() {
}
</code></pre></pre>
<p>This prints <code>140 399 923 481 800 622 623 218 009 598 281</code>.</p>
<h3><a class="header" href="#_-in-a-closure" id="_-in-a-closure">|_| in a closure</a></h3>
<h3 id="_-in-a-closure"><a class="header" href="#_-in-a-closure">|_| in a closure</a></h3>
<p>Sometimes you see <code>|_|</code> in a closure. This means that the closure needs an argument (like <code>x</code>), but you don't want to use it. So <code>|_|</code> means &quot;Okay, this closure takes an argument but I won't give it a name because I don't care about it&quot;.</p>
<p>Here is an example of an error when you don't do that:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
@ -373,7 +373,7 @@ fn main() {
28 | println!(&quot;{:?}&quot;, my_vec.iter().for_each(|_| println!(&quot;We didn't use the variables at all&quot;)));
</code></pre>
<p>This is good advice. If you change <code>||</code> to <code>|_|</code> then it will work.</p>
<h3><a class="header" href="#helpful-methods-for-closures-and-iterators" id="helpful-methods-for-closures-and-iterators">Helpful methods for closures and iterators</a></h3>
<h3 id="helpful-methods-for-closures-and-iterators"><a class="header" href="#helpful-methods-for-closures-and-iterators">Helpful methods for closures and iterators</a></h3>
<p>Rust becomes a very fun to language once you become comfortable with closures. With closures you can <em>chain</em> methods to each other and do a lot of things with very little code. Here are some closures and methods used with closures that we didn't see yet.</p>
<p><code>.filter()</code>: This lets you keep the items in an iterator that you want to keep. Let's filter the months of the year.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#the-dbg-macro-and-inspect" id="the-dbg-macro-and-inspect">The dbg! macro and .inspect</a></h2>
<h2 id="the-dbg-macro-and-inspect"><a class="header" href="#the-dbg-macro-and-inspect">The dbg! macro and .inspect</a></h2>
<p><code>dbg!</code> is a very useful macro that prints quick information. It is a good alternative to <code>println!</code> because it is faster to type and gives more information:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let my_number = 8;

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#types-of-str" id="types-of-str">Types of &amp;str</a></h2>
<h2 id="types-of-str"><a class="header" href="#types-of-str">Types of &amp;str</a></h2>
<p>There is more than one type of <code>&amp;str</code>. We have:</p>
<ul>
<li>String literals: you make these when you write <code>let my_str = &quot;I am a &amp;str&quot;</code>. They last for the whole program, because they are written directly into the binary. They have the type <code>&amp;'static str</code>. <code>'</code> means its lifetime, and string literal have a lifetime called <code>static</code>.</li>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#rust-playground" id="rust-playground">Rust Playground</a></h2>
<h2 id="rust-playground"><a class="header" href="#rust-playground">Rust Playground</a></h2>
<p><strong><a href="https://youtu.be/-lYeJeQ11OI">See this chapter on YouTube</a></strong></p>
<p>Maybe you don't want to install Rust yet, and that's okay. You can go to <a href="https://play.rust-lang.org/">https://play.rust-lang.org/</a> 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).</p>
<p>Here are some tips when using the Rust Playground:</p>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#lifetimes" id="lifetimes">Lifetimes</a></h2>
<h2 id="lifetimes"><a class="header" href="#lifetimes">Lifetimes</a></h2>
<p>A lifetime means &quot;how long the variable lives&quot;. You only need to think about lifetimes with references. This is because references can't live longer than the object they come from. For example, this function does not work:</p>
<pre><pre class="playground"><code class="language-rust">fn returns_reference() -&gt; &amp;str {
let my_string = String::from(&quot;I am a string&quot;);

@ -163,8 +163,8 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#interior-mutability" id="interior-mutability">Interior mutability</a></h2>
<h3><a class="header" href="#cell" id="cell">Cell</a></h3>
<h2 id="interior-mutability"><a class="header" href="#interior-mutability">Interior mutability</a></h2>
<h3 id="cell"><a class="header" href="#cell">Cell</a></h3>
<p><strong>Interior mutability</strong> means having a little bit of mutability on the inside. Remember how in Rust you need to use <code>mut</code> to change a variable? There are also some ways to change them without the word <code>mut</code>. This is because Rust has some ways to let you safely change values inside of a struct that is immutable. Each one of them follows some rules that make sure that changing the values is still safe.</p>
<p>First, let's look at a simple example where we would want this. Imagine a <code>struct</code> called <code>PhoneModel</code> with many fields:</p>
<pre><pre class="playground"><code class="language-rust">struct PhoneModel {
@ -220,7 +220,7 @@ fn main() {
</code></pre></pre>
<p><code>Cell</code> works for all types, but works best for simple Copy types because it gives values, not references. <code>Cell</code> has a method called <code>get()</code> for example that only works on Copy types.</p>
<p>Another type you can use is <code>RefCell</code>.</p>
<h3><a class="header" href="#refcell" id="refcell">RefCell</a></h3>
<h3 id="refcell"><a class="header" href="#refcell">RefCell</a></h3>
<p>A <code>RefCell</code> is another way to change values without needing to declare <code>mut</code>. It means &quot;reference cell&quot;, and is like a <code>Cell</code> but uses references instead of copies.</p>
<p>We will create a <code>User</code> struct. So far you can see that it is similar to <code>Cell</code>:</p>
<pre><pre class="playground"><code class="language-rust">use std::cell::RefCell;
@ -304,7 +304,7 @@ note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
error: process didn't exit successfully: `target\debug\rust_book.exe` (exit code: 101)
</code></pre>
<p><code>already borrowed: BorrowMutError</code> is the important part. So when you use a <code>RefCell</code>, it is good to compile <strong>and</strong> run to check.</p>
<h3><a class="header" href="#mutex" id="mutex">Mutex</a></h3>
<h3 id="mutex"><a class="header" href="#mutex">Mutex</a></h3>
<p><code>Mutex</code> is another way to change values without declaring <code>mut</code>. Mutex means <code>mutual exclusion</code>, which means &quot;only one at a time&quot;. This is why a <code>Mutex</code> is safe, because it only lets one process change it at a time. To do this, it uses <code>.lock()</code>. <code>Lock</code> is like locking a door from the inside. You go into a room, lock the door, and now you can change things inside the room. Nobody else can come in and stop you, because you locked the door.</p>
<p>A <code>Mutex</code> is easier to understand through examples.</p>
<pre><pre class="playground"><code class="language-rust">use std::sync::Mutex;
@ -406,7 +406,7 @@ fn main() {
println!(&quot;{:?}&quot;, my_mutex);
}
</code></pre></pre>
<h3><a class="header" href="#rwlock" id="rwlock">RwLock</a></h3>
<h3 id="rwlock"><a class="header" href="#rwlock">RwLock</a></h3>
<p><code>RwLock</code> means &quot;read write lock&quot;. It is like a <code>Mutex</code> but also like a <code>RefCell</code>. You use <code>.write().unwrap()</code> instead of <code>.lock().unwrap()</code> to change it. But you can also use <code>.read().unwrap()</code> to get read access. It is like <code>RefCell</code> because it follows the rules:</p>
<ul>
<li>many <code>.read()</code> variables is okay,</li>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#cow" id="cow">Cow</a></h2>
<h2 id="cow"><a class="header" href="#cow">Cow</a></h2>
<p>Cow is a very convenient enum. It means &quot;clone on write&quot; and lets you return a <code>&amp;str</code> if you don't need a <code>String</code>, and a <code>String</code> if you need it. (It can also do the same with arrays vs. Vecs, etc.)</p>
<p>To understand it, let's look at the signature. It says:</p>
<pre><pre class="playground"><code class="language-rust">pub enum Cow&lt;'a, B&gt;

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#type-aliases" id="type-aliases">Type aliases</a></h2>
<h2 id="type-aliases"><a class="header" href="#type-aliases">Type aliases</a></h2>
<p>A type alias means &quot;giving a new name to another type&quot;. Type aliases are very easy. Usually you use them when you have a very long type and don't want to write it every time. It is also good when you want to give a type a better name that is easy to remember. Here are two examples of type aliases.</p>
<p>Here is a type that is not difficult, but you want to make your code easier to understand for other people (or for you):</p>
<pre><pre class="playground"><code class="language-rust">type CharacterVec = Vec&lt;char&gt;;
@ -234,7 +234,7 @@ fn main() {
println!(&quot;{}&quot;, my_file.0 == my_string); // my_file.0 is a String, so this prints true
}
</code></pre></pre>
<h3><a class="header" href="#importing-and-renaming-inside-a-function" id="importing-and-renaming-inside-a-function">Importing and renaming inside a function</a></h3>
<h3 id="importing-and-renaming-inside-a-function"><a class="header" href="#importing-and-renaming-inside-a-function">Importing and renaming inside a function</a></h3>
<p>Usually you write <code>use</code> at the top of the program, like this:</p>
<pre><pre class="playground"><code class="language-rust">use std::cell::{Cell, RefCell};

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#the-todo-macro" id="the-todo-macro">The todo! macro</a></h2>
<h2 id="the-todo-macro"><a class="header" href="#the-todo-macro">The todo! macro</a></h2>
<p>Sometimes you want to write code in general to help you imagine your project. For example, imagine a simple project to do something with books. Here's what you think as you write it:</p>
<pre><pre class="playground"><code class="language-rust">struct Book {} // Okay, first I need a book struct.
// Nothing in there yet - will add later

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#rc" id="rc">Rc</a></h2>
<h2 id="rc"><a class="header" href="#rc">Rc</a></h2>
<p>Rc means &quot;reference counter&quot;. You know that in Rust, every variable can only have one owner. That is why this doesn't work:</p>
<pre><pre class="playground"><code class="language-rust">fn takes_a_string(input: String) {
println!(&quot;It is: {}&quot;, input)

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#multiple-threads" id="multiple-threads">Multiple threads</a></h2>
<h2 id="multiple-threads"><a class="header" href="#multiple-threads">Multiple threads</a></h2>
<p>If you use multiple threads, you can do many things at the same time. Modern computers have more than one core so they can do more than one thing at the same time, and Rust lets you use them. Rust uses threads that are called &quot;OS threads&quot;. OS thread means the operating system creates the thread on a different core. (Some other languages use &quot;green threads&quot;, which are less powerful)</p>
<p>You create threads with <code>std::thread::spawn</code> and then a closure to tell it what to do. Threads are interesting because they run at the same time, and you can test it to see what happens. Here is a simple example:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#closures-in-functions" id="closures-in-functions">Closures in functions</a></h2>
<h2 id="closures-in-functions"><a class="header" href="#closures-in-functions">Closures in functions</a></h2>
<p>Closures are great. So how do we put them into our own functions?</p>
<p>You can make your own functions that take closures, but inside them it is less free and you have to decide the type. Outside a function a closure can decide by itself between <code>Fn</code>, <code>FnMut</code> and <code>FnOnce</code>, but inside you have to choose one. The best way to understand is to look at a few function signatures. Here is the one for <code>.all()</code>. We remember that it checks an iterator to see if everything is <code>true</code> (depending on what you decide is <code>true</code> or <code>false</code>). Part of its signature says this:</p>
<pre><pre class="playground"><code class="language-rust">

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#impl-trait" id="impl-trait">impl Trait</a></h2>
<h2 id="impl-trait"><a class="header" href="#impl-trait">impl Trait</a></h2>
<p><code>impl Trait</code> is similar to generics. You remember that generics use a type <code>T</code> (or any other name) which then gets decided when the program compiles. First let's look at a concrete type:</p>
<pre><pre class="playground"><code class="language-rust">fn gives_higher_i32(one: i32, two: i32) {
let higher = if one &gt; two { one } else { two };

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#arc" id="arc">Arc</a></h2>
<h2 id="arc"><a class="header" href="#arc">Arc</a></h2>
<p>You remember that we used an <code>Rc</code> to give a variable more than one owner. If we are doing the same thing in a thread, we need an <code>Arc</code>. <code>Arc</code> means &quot;atomic reference counter&quot;. Atomic means that it uses the computer's processor so that data only gets written once each time. This is important because if two threads write data at the same time, you will get the wrong result. For example, imagine if you could do this in Rust:</p>
<pre><pre class="playground"><code class="language-rust">
<span class="boring">#![allow(unused)]

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#-and-" id="-and-">🚧 and ⚠️</a></h2>
<h2 id="-and-"><a class="header" href="#-and-">🚧 and ⚠️</a></h2>
<p>Sometimes 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 &quot;under construction&quot;: it means that the code is not complete. Rust needs a <code>fn main()</code> (a main function) to run, but sometimes we just want to look at small pieces of code so it won't have a <code>fn main()</code>. Those examples are correct, but need a <code>fn main()</code> for you to run them. And some code examples show you a problem that we will fix. Those ones might have a <code>fn main()</code> but generate an error, and so they will have a ⚠️.</p>
</main>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#channels" id="channels">Channels</a></h2>
<h2 id="channels"><a class="header" href="#channels">Channels</a></h2>
<p>A channel is an easy way to use many threads that send to one place. They are fairly popular because they are pretty simple to put together. You can create a channel in Rust with <code>std::sync::mpsc</code>. <code>mpsc</code> means &quot;multiple producer, single consumer&quot;, so &quot;many threads sending to one place&quot;. To start a channel, you use <code>channel()</code>. This creates a <code>Sender</code> and a <code>Receiver</code> that are tied together. You can see this in the function signature:</p>
<pre><pre class="playground"><code class="language-rust">
<span class="boring">#![allow(unused)]

@ -163,9 +163,9 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#reading-rust-documentation" id="reading-rust-documentation">Reading Rust documentation</a></h2>
<h2 id="reading-rust-documentation"><a class="header" href="#reading-rust-documentation">Reading Rust documentation</a></h2>
<p>It's important to know how to read documentation in Rust so you can understand what other people wrote. Here are some things to know in Rust documentation:</p>
<h3><a class="header" href="#assert_eq" id="assert_eq">assert_eq!</a></h3>
<h3 id="assert_eq"><a class="header" href="#assert_eq">assert_eq!</a></h3>
<p>You saw that <code>assert_eq!</code> is used when doing testing. You put two items inside the function and the program will panic if they are not equal. Here is a simple example where we need an even number.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
prints_number(56);
@ -223,9 +223,9 @@ fn prints_number(input: i32) {
assert_eq!(vec, [7, 1, 2, 3]); // &quot;The vec now has [7, 1, 2, 3]&quot;
}
</code></pre></pre>
<h3><a class="header" href="#searching" id="searching">Searching</a></h3>
<h3 id="searching"><a class="header" href="#searching">Searching</a></h3>
<p>The top bar of a Rust document is the search bar. It shows you results as you type. When you go down a page you can't see the search bar anymore, but if you press the <strong>s</strong> key on the keyboard you can search again. So pressing <strong>s</strong> anywhere lets you search right away.</p>
<h3><a class="header" href="#src-button" id="src-button">[src] button</a></h3>
<h3 id="src-button"><a class="header" href="#src-button">[src] button</a></h3>
<p>Usually the code for a method, struct, etc. will not be complete. This is because you don't usually need to see the full source to know how it works, and the full code can be confusing. But if you want to know more, you can click on [src] and see everything. For example, on the page for <code>String</code> you can see this signature for <code>.with_capacity()</code>:</p>
<pre><pre class="playground"><code class="language-rust">
<span class="boring">#![allow(unused)]
@ -245,7 +245,7 @@ pub fn with_capacity(capacity: usize) -&gt; String {
<span class="boring">}
</span></code></pre></pre>
<p>Interesting! Now you can see that a String is a kind of <code>Vec</code>. And actually a <code>String</code> is a vector of <code>u8</code> bytes, which is interesting to know. You didn't need to know that to use the <code>with_capacity</code> method so you only see it if you click [src]. So clicking on [src] is a good idea if the document doesn't have much detail and you want to know more.</p>
<h3><a class="header" href="#information-on-traits" id="information-on-traits">Information on traits</a></h3>
<h3 id="information-on-traits"><a class="header" href="#information-on-traits">Information on traits</a></h3>
<p>The important part of the documentation for a trait is &quot;Required Methods&quot; on the left. If you see Required Methods, it probably means that you have to write the method yourself. For example, for <code>Iterator</code> you need to write the <code>.next()</code> method. And for <code>From</code> you need to write the <code>.from()</code> method. But some traits can be implemented with just an <strong>attribute</strong>, like we see in <code>#[derive(Debug)]</code>. <code>Debug</code> needs the <code>.fmt()</code> method, but usually you just use <code>#[derive(Debug)]</code> unless you want to do it yourself. That's why the page on <code>std::fmt::Debug</code> says that &quot;Generally speaking, you should just derive a Debug implementation.&quot;</p>
</main>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#attributes" id="attributes">Attributes</a></h2>
<h2 id="attributes"><a class="header" href="#attributes">Attributes</a></h2>
<p>You have seen code like <code>#[derive(Debug)]</code> before: this type of code is called an <em>attribute</em>. These attributes are small pieces of code that give information to the compiler. They are not easy to create, but they are very easy to use. If you write an attribute with just <code>#</code> then it will affect the code on the next line. But if you write it with <code>#!</code> then it will affect everything in its own space.</p>
<p>Here are some attributes you will see a lot:</p>
<p><code>#[allow(dead_code)]</code> and <code>#[allow(unused_variables)]</code>. If you write code that you don't use, Rust will still compile but it will let you know. For example, here is a struct with nothing in it and one variable. We don't use either of them.</p>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#box" id="box">Box</a></h2>
<h2 id="box"><a class="header" href="#box">Box</a></h2>
<p><code>Box</code> is a very convenient type in Rust. When you use a <code>Box</code>, you can put a type on the heap instead of the stack. To make a new <code>Box</code>, just use <code>Box::new()</code> and put the item inside.</p>
<pre><pre class="playground"><code class="language-rust">fn just_takes_a_variable&lt;T&gt;(item: T) {} // Takes anything and drops it.

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#box-around-traits" id="box-around-traits">Box around traits</a></h2>
<h2 id="box-around-traits"><a class="header" href="#box-around-traits">Box around traits</a></h2>
<p><code>Box</code> is very useful for returning traits. You know that you can write traits in generic functions like in this example:</p>
<pre><pre class="playground"><code class="language-rust">use std::fmt::Display;

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#default-and-the-builder-pattern" id="default-and-the-builder-pattern">Default and the builder pattern</a></h2>
<h2 id="default-and-the-builder-pattern"><a class="header" href="#default-and-the-builder-pattern">Default and the builder pattern</a></h2>
<p>You can implement the <code>Default</code> trait to give values to a <code>struct</code> or <code>enum</code> that you think will be most common. The builder pattern works nicely with this to let users easily make changes when they want. First let's look at <code>Default</code>. Actually, most general types in Rust already have <code>Default</code>. They are not surprising: 0, &quot;&quot; (empty strings), <code>false</code>, etc.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let default_i8: i8 = Default::default();

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#deref-and-derefmut" id="deref-and-derefmut">Deref and DerefMut</a></h2>
<h2 id="deref-and-derefmut"><a class="header" href="#deref-and-derefmut">Deref and DerefMut</a></h2>
<p><code>Deref</code> is the trait that lets you use <code>*</code> to dereference something. We know that a reference is not the same as a value:</p>
<pre><pre class="playground"><code class="language-rust">// ⚠️
fn main() {

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#crates-and-modules" id="crates-and-modules">Crates and modules</a></h2>
<h2 id="crates-and-modules"><a class="header" href="#crates-and-modules">Crates and modules</a></h2>
<p>Every time you write code in Rust, you are writing it in a <code>crate</code>. A <code>crate</code> is the file, or files, that go together for your code. Inside the file you write you can also make a <code>mod</code>. A <code>mod</code> is a space for functions, structs, etc. and is used for a few reasons:</p>
<ul>
<li>Building your code: it helps you think about the general structure of your code. This can be important as your code gets larger and larger.</li>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#testing" id="testing">Testing</a></h2>
<h2 id="testing"><a class="header" href="#testing">Testing</a></h2>
<p>Testing is a good subject to learn now that we understand modules. Testing your code is very easy in Rust, because you can write tests right next to your code.</p>
<p>The easiest way to start testing is to add <code>#[test]</code> above a function. Here is a simple one:</p>
<pre><pre class="playground"><code class="language-rust">
@ -325,7 +325,7 @@ mod tests {
}
<span class="boring">}
</span></code></pre></pre>
<h3><a class="header" href="#test-driven-development" id="test-driven-development">Test-driven development</a></h3>
<h3 id="test-driven-development"><a class="header" href="#test-driven-development">Test-driven development</a></h3>
<p>You might see the words &quot;test-driven development&quot; when reading about Rust or another language. It's one way to write programs, and some people like it while others prefer something else. &quot;Test-driven development&quot; means &quot;writing tests first, then writing the code&quot;. When you do this, you will have a lot of tests for everything you want your code to do. Then you start writing the code, and run the tests to see if you did it right. Then the tests are always there to show you if something goes wrong when you add to and rewrite your code. This is pretty easy in Rust because the compiler gives a lot of information about what to fix. Let's write a small example of test-driven development and see what it looks like.</p>
<p>Let's imagine a calculator that takes user input. It can add (+) and it can subtract (-). If the user writes &quot;5 + 6&quot; it should return 11, if the user writes &quot;5 + 6 - 7&quot; it should return 4, and so on. So we'll start with test functions. You can also see that function names in tests are usually quite long. That is because you might run a lot of tests, and you want to understand which tests have failed.</p>
<p>We'll imagine that a single function called <code>math()</code> will do everything. It will return an <code>i32</code> (we won't use floats). Because it needs to return something, we'll just return <code>6</code> every time. Then we will write three test functions. They will all fail, of course. Now the code looks like this:</p>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#external-crates" id="external-crates">External crates</a></h2>
<h2 id="external-crates"><a class="header" href="#external-crates">External crates</a></h2>
<p>An external crate means &quot;someone else's crate&quot;.</p>
<p>For this section you <em>almost</em> need to install Rust, but we can still use just the Playground. Now we are going to learn how to import crates that other people have written. This is important in Rust because of two reasons:</p>
<ul>
@ -173,7 +173,7 @@
<p>That means that it is normal in Rust to bring in an external crate for a lot of basic functions. The idea is that if it is easy to use external crates, then you can choose the best one. Maybe one person will make a crate for one function, and then someone else will make a better one.</p>
<p>In this book we will only look at the most popular crates, the crates that everyone who uses Rust knows.</p>
<p>To begin learning external crates, we will start with the most common one: <code>rand</code>.</p>
<h3><a class="header" href="#rand" id="rand">rand</a></h3>
<h3 id="rand"><a class="header" href="#rand">rand</a></h3>
<p>Did you notice that we didn't use any random numbers yet? That's because random numbers aren't in the standard library. But there are a lot of crates that are &quot;almost standard library&quot; because everybody uses them. In any case, it's very easy to bring in a crate. If you have Rust on your computer, there is a file called <code>Cargo.toml</code> that has this information. A <code>Cargo.toml</code> file looks like this when you start:</p>
<pre><code class="language-text">[package]
name = &quot;rust_book&quot;
@ -344,7 +344,7 @@ charisma: 10
<span class="boring">}
</span></code></pre></pre>
<p>The character with four dice is usually a bit better at most things.</p>
<h3><a class="header" href="#rayon" id="rayon">rayon</a></h3>
<h3 id="rayon"><a class="header" href="#rayon">rayon</a></h3>
<p><code>rayon</code> is a popular crate that lets you speed up your Rust code. It's popular because it creates threads without needing things like <code>thread::spawn</code>. In other words, it is popular because it is effective but easy to write. For example:</p>
<ul>
<li><code>.iter()</code>, <code>.iter_mut()</code>, <code>into_iter()</code> in rayon is written like this:</li>
@ -368,7 +368,7 @@ fn main() {
}
</code></pre></pre>
<p>And that's it. <code>rayon</code> has many other methods to customize what you want to do, but at its most simple it is just &quot;add <code>_par</code> to make your program faster&quot;.</p>
<h3><a class="header" href="#serde" id="serde">serde</a></h3>
<h3 id="serde"><a class="header" href="#serde">serde</a></h3>
<p><code>serde</code> is a popular crate that lets you convert to and from formats like JSON, YAML, etc. The most common way to use it is by creating a <code>struct</code> with two attributes on top. <a href="https://serde.rs/">It looks like this</a>:</p>
<pre><pre class="playground"><code class="language-rust">
<span class="boring">#![allow(unused)]
@ -381,9 +381,9 @@ struct Point {
<span class="boring">}
</span></code></pre></pre>
<p>The <code>Serialize</code> and <code>Deserialize</code> traits are what make the conversion easy. (That's also where the name <code>serde</code> comes from) If you have them on your struct, then you can just call a method to turn it into and from JSON or anything else.</p>
<h3><a class="header" href="#regex" id="regex">regex</a></h3>
<h3 id="regex"><a class="header" href="#regex">regex</a></h3>
<p>The <a href="https://crates.io/crates/regex">regex</a> crate lets you search through text using <a href="https://en.wikipedia.org/wiki/Regular_expression">regular expressions</a>. With that you can get matches for something like <code>colour</code>, <code>color</code>, <code>colours</code> and <code>colors</code> through a single search. Regular expressions are a whole other language have to learn that too if you want to use them.</p>
<h3><a class="header" href="#chrono" id="chrono">chrono</a></h3>
<h3 id="chrono"><a class="header" href="#chrono">chrono</a></h3>
<p><a href="https://crates.io/crates/chrono">chrono</a> is the main crate for people who need more functionality for time. We will look at the standard library now which has functions for time, but if you need more then this is a good crate to use.</p>
</main>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#comments" id="comments">Comments</a></h2>
<h2 id="comments"><a class="header" href="#comments">Comments</a></h2>
<p><strong><a href="https://youtu.be/fJ7jBZG_Rpo">See this chapter on YouTube</a></strong></p>
<p>Comments 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 <code>//</code>:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {

@ -163,9 +163,9 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#a-tour-of-the-standard-library" id="a-tour-of-the-standard-library">A tour of the standard library</a></h2>
<h2 id="a-tour-of-the-standard-library"><a class="header" href="#a-tour-of-the-standard-library">A tour of the standard library</a></h2>
<p>Now that you know a lot of Rust, you will be able to understand most things inside the standard library. The code inside it isn't so scary anymore. Let's take a look at some of the parts in it that we haven't learned yet. This tour will go over most parts of the standard library that you don't need to install Rust for. We will revisit a lot of items we already know so we can learn them with greater understanding.</p>
<h3><a class="header" href="#arrays" id="arrays">Arrays</a></h3>
<h3 id="arrays"><a class="header" href="#arrays">Arrays</a></h3>
<p>One thing about arrays to note is that they don't implement <code>Iterator.</code>. That means that if you have an array, you can't use <code>for</code>. But you can use methods like <code>.iter()</code> on them. Or you can use <code>&amp;</code> to get a slice. Actually, the compiler will tell you exactly that if you try to use <code>for</code>:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
// ⚠️
@ -210,7 +210,7 @@ Nicosia
}
</code></pre></pre>
<p>This prints <code>Beirut</code>.</p>
<h3><a class="header" href="#char" id="char">char</a></h3>
<h3 id="char"><a class="header" href="#char">char</a></h3>
<p>You can use the <code>.escape_unicode()</code> method to get the Unicode number for a <code>char</code>:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let korean_word = &quot;청춘예찬&quot;;
@ -254,7 +254,7 @@ fn main() {
</code></pre>
<p>So it's a good thing you need to use <code>TryFrom</code>.</p>
<p>Also, as of late August 2020 you can now get a <code>String</code> from a <code>char</code>. (<code>String</code> implements <code>From&lt;char&gt;</code>) Just write <code>String::from()</code> and put a <code>char</code> inside.</p>
<h3><a class="header" href="#integers" id="integers">Integers</a></h3>
<h3 id="integers"><a class="header" href="#integers">Integers</a></h3>
<p>There are a lot of math methods for these types, plus some others. Here are some of the most useful ones.</p>
<p><code>.checked_add()</code>, <code>.checked_sub()</code>, <code>.checked_mul()</code>, <code>.checked_div()</code>. These are good methods if you think you might get a number that won't fit into a type. They return an <code>Option</code> so you can safely check that your math works without making the program panic.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
@ -357,7 +357,7 @@ In Nauru and Vanuatu and Micronesia are 422953 people and a GDP of $1347000000
</code></pre>
<p>Later on in this code we could change <code>.fmt()</code> to display a number that is easier to read.</p>
<p>The three others are called <code>Sub</code>, <code>Mul</code>, and <code>Div</code>, and they are basically the same to implement. For <code>+=</code>, <code>-=</code>, <code>*=</code> and <code>/=</code>, just add <code>Assign</code>: <code>AddAssign</code>, <code>SubAssign</code>, <code>MulAssign</code>, and <code>DivAssign</code>. You can see the full list <a href="https://doc.rust-lang.org/std/ops/index.html#structs">here</a>, because there are many more. <code>%</code> for example is called <code>Rem</code>, <code>-</code> is called <code>Neg</code>, and so on.</p>
<h3><a class="header" href="#floats" id="floats">Floats</a></h3>
<h3 id="floats"><a class="header" href="#floats">Floats</a></h3>
<p><code>f32</code> and <code>f64</code> have a very large number of methods that you use when doing math. We won't look at those, but here are some methods that you might use. They are: <code>.floor()</code>, <code>.ceil()</code>, <code>.round()</code>, and <code>.trunc()</code>. All of these return an <code>f32</code> or <code>f64</code> that is like an integer, with only <code>0</code> after the period. They do this:</p>
<ul>
<li><code>.floor()</code>: gives you the next lowest integer.</li>
@ -421,7 +421,7 @@ truncated: -19
println!(&quot;{}, {}&quot;, maximum, minimum);
}
</code></pre></pre>
<h3><a class="header" href="#bool" id="bool">bool</a></h3>
<h3 id="bool"><a class="header" href="#bool">bool</a></h3>
<p>In Rust you can turn a <code>bool</code> into an integer if you want, because it's safe to do that. But you can't do it the other way around. As you can see, <code>true</code> turns to 1 and <code>false</code> turns to 0.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let true_false = (true, false);
@ -435,7 +435,7 @@ truncated: -19
}
</code></pre></pre>
<p>This prints the same thing.</p>
<h3><a class="header" href="#vec" id="vec">Vec</a></h3>
<h3 id="vec"><a class="header" href="#vec">Vec</a></h3>
<p>Vec has a lot of methods that we haven't looked at yet. Let's start with <code>.sort()</code>. <code>.sort()</code> is not surprising at all. It uses a <code>&amp;mut self</code> to sort a vector.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let mut my_vec = vec![100, 90, 80, 0, 0, 0, 0, 0];
@ -461,7 +461,7 @@ truncated: -19
}
</code></pre></pre>
<p>Result: <code>[&quot;moon&quot;, &quot;sun&quot;]</code>.</p>
<h3><a class="header" href="#string" id="string">String</a></h3>
<h3 id="string"><a class="header" href="#string">String</a></h3>
<p>You will remember that a <code>String</code> is kind of like a <code>Vec</code>. It is so like a <code>Vec</code> that you can do a lot of the same methods. For example, you can start one with <code>String::with_capacity()</code>. You want that if you are always going to be pushing a <code>char</code> with <code>.push()</code> or pushing a <code>&amp;str</code> with <code>.push_str()</code>. Here's an example of a <code>String</code> that has too many allocations.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let mut push_string = String::new();
@ -558,7 +558,7 @@ truncated: -19
<p>This prints:</p>
<pre><code class="language-text">[src\main.rs:4] my_string = &quot;Age Height Weight &quot;
</code></pre>
<h3><a class="header" href="#osstring-and-cstring" id="osstring-and-cstring">OsString and CString</a></h3>
<h3 id="osstring-and-cstring"><a class="header" href="#osstring-and-cstring">OsString and CString</a></h3>
<p><code>std::ffi</code> is the part of <code>std</code> that helps you use Rust with other languages or operating systems. It has types like <code>OsString</code> and <code>CString</code>, which are like <code>String</code> for the operating system or <code>String</code> for the language C. They each have their own <code>&amp;str</code> type too: <code>OsStr</code> and <code>CStr</code>. <code>ffi</code> means &quot;foreign function interface&quot;.</p>
<p>You can use <code>OsString</code> when you have to work with an operating system that doesn't have Unicode. All Rust strings are unicode, but not every operating system has it. Here is the simple English explanation from the standard library on why we have <code>OsString</code>:</p>
<ul>
@ -601,7 +601,7 @@ error[E0599]: no method named `occg` found for struct `std::ffi::OsString` in th
| ^^^^ method not found in `std::ffi::OsString`
</code></pre>
<p>We can see that the type of <code>valid</code> is <code>String</code> and the type of <code>not_valid</code> is <code>OsString</code>.</p>
<h3><a class="header" href="#mem" id="mem">mem</a></h3>
<h3 id="mem"><a class="header" href="#mem">mem</a></h3>
<p><code>std::mem</code> has some pretty interesting methods. We saw some of them already, such as <code>.size_of()</code>, <code>.size_of_val()</code> and <code>.drop()</code>:</p>
<pre><pre class="playground"><code class="language-rust">use std::mem;
@ -817,7 +817,7 @@ The robber has $150 right now.
There is $4900 in the back and $50 at the desk.
</code></pre>
<p>You can see that there is always $50 at the desk.</p>
<h3><a class="header" href="#prelude" id="prelude">prelude</a></h3>
<h3 id="prelude"><a class="header" href="#prelude">prelude</a></h3>
<p>The standard library has a prelude too, which is why you don't have to write things like <code>use std::vec::Vec</code> to create a <code>Vec</code>. You can see all the items <a href="https://doc.rust-lang.org/std/prelude/index.html#prelude-contents">here</a>, and will already know almost all of them:</p>
<ul>
<li><code>std::marker::{Copy, Send, Sized, Sync, Unpin}</code>. You haven't seen <code>Unpin</code> before, because it is used for almost every type (like <code>Sized</code>, which is also very common). To &quot;pin&quot; means to not let something move. In this case a <code>Pin</code> means that it can't move in memory, but most items have <code>Unpin</code> so you can. That's why functions like <code>std::mem::replace</code> work, because they aren't pinned.</li>
@ -889,7 +889,7 @@ fn main() {
<span class="boring">}
</span></code></pre></pre>
<p>and then <code>use</code> statements for the mods, traits, etc. that you wanted to use. But the Rust compiler now doesn't need this help anymore - you can just use <code>use</code> and it knows where to find it. So you almost never need <code>extern crate</code> anymore, but in other people's Rust code you might still see it on the top.</p>
<h3><a class="header" href="#time" id="time">time</a></h3>
<h3 id="time"><a class="header" href="#time">time</a></h3>
<p><code>std::time</code> is where you can get functions for time. (If you want even more functions, a crate like <code>chrono</code> can work.) The simplest function is just getting the system time with <code>Instant::now()</code>.</p>
<pre><pre class="playground"><code class="language-rust">use std::time::Instant;
@ -993,7 +993,7 @@ fn main() {
Did I miss anything?
</code></pre>
<p>but the thread will do nothing for three seconds. You usually use <code>.sleep()</code> when you have many threads that need to try something a lot, like connecting. You don't want the thread to use your processor to try 100,000 times in a second when you just want it to check sometimes. So then you can set a <code>Duration</code>, and it will try to do its task every time it wakes up.</p>
<h3><a class="header" href="#other-macros" id="other-macros">Other macros</a></h3>
<h3 id="other-macros"><a class="header" href="#other-macros">Other macros</a></h3>
<p>Let's take a look at some other macros.</p>
<p><code>unreachable!()</code></p>
<p>This macro is kind of like <code>todo!()</code> except it's for code that you will never do. Maybe you have a <code>match</code> in an enum that you know will never choose one of the arms, so the code can never be reached. If that's so, you can write <code>unreachable!()</code> so the compiler knows that it can ignore that part.</p>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#writing-macros" id="writing-macros">Writing macros</a></h2>
<h2 id="writing-macros"><a class="header" href="#writing-macros">Writing macros</a></h2>
<p>Writing macros can be very complicated. You almost never need to write one, but sometimes you might want to because they are very convenient. Writing macros is interesting because they are almost a different language. To write one, you actually use another macro called <code>macro_rules!</code>. Then you add your macro name and open a <code>{}</code> block. Inside is sort of like a <code>match</code> statement.</p>
<p>Here's one that only takes <code>()</code>, then just returns 6:</p>
<pre><pre class="playground"><code class="language-rust">macro_rules! give_six {
@ -480,7 +480,7 @@ fn main() {
</code></pre>
<p>And for the rest of it it just calls <code>dbg!</code> on itself even if you put in an extra comma.</p>
<p>As you can see, macros are very complicated! Usually you only want a macro to automatically do something that a simple function can't do very well. The best way to learn about macros is to look at other macro examples. Not many people can quickly write macros without problems. So don't think that you need to know everything about macros to know how to write in Rust. But if you read other macros, and change them a little, you can easily borrow their power. Then you might start to get comfortable with writing your own.</p>
<h1><a class="header" href="#part-2---rust-on-your-computer" id="part-2---rust-on-your-computer">Part 2 - Rust on your computer</a></h1>
<h1 id="part-2---rust-on-your-computer"><a class="header" href="#part-2---rust-on-your-computer">Part 2 - Rust on your computer</a></h1>
<p>You saw that we can learn almost anything in Rust just using the Playground. But if you learned everything so far, you will probably want Rust on your computer now. There are always things that you can't do with the Playground like using files or code in more than just one file. Some other things you need Rust on your computer for are input and flags. But most important is that with Rust on your computer you can use crates. We already learned about crates, but in the Playground you could only use the most popular ones. But with Rust on your computer you can use any crate in your program.</p>
</main>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#cargo" id="cargo">cargo</a></h2>
<h2 id="cargo"><a class="header" href="#cargo">cargo</a></h2>
<p><code>rustc</code> means Rust compiler, and it's what does the actual compiling. A rust file ends with an <code>.rs</code>. But most people don't write something like <code>rustc main.rs</code> to compile. They use something called <code>cargo</code>, which is the main package manager for Rust.</p>
<p>One note about the name: it's called <code>cargo</code> because when you put crates together, you get cargo. A crate is a wooden box that you see on ships or trucks, but you remember that every Rust project is also called a crate. Then when you put them together you get the whole cargo.</p>
<p>You can see this when you use cargo to run a project. Let's try something simple with <code>rand</code>: we'll just randomly choose between eight letters.</p>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#taking-user-input" id="taking-user-input">Taking user input</a></h2>
<h2 id="taking-user-input"><a class="header" href="#taking-user-input">Taking user input</a></h2>
<p>One easy way to take input from the user is with <code>std::io::stdin</code>. This means &quot;standard in&quot;, which is the input from the keyboard. With <code>stdin()</code> you can get user input, but then you will want to put it in a <code>&amp;mut String</code> with <code>.read_line()</code>. Here is a simple example of that, but it both works and doesn't work:</p>
<pre><pre class="playground"><code class="language-rust">use std::io;

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#using-files" id="using-files">Using files</a></h2>
<h2 id="using-files"><a class="header" href="#using-files">Using files</a></h2>
<p>Now that we are using Rust on the computer, we can start working with files. You will notice that now we will start to see more and more <code>Result</code>s in our code. That is because once you start working with files and similar things, many things can go wrong. A file might not be there, or maybe the computer can't read it.</p>
<p>You might remember that if you want to use the <code>?</code> operator, it has to return a <code>Result</code> in the function it is in. If you can't remember the error type, you can just give it nothing and let the compiler tell you. Let's try that with a function that tries to make a number with <code>.parse()</code>.</p>
<pre><pre class="playground"><code class="language-rust">// ⚠️

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#cargo-doc" id="cargo-doc">cargo doc</a></h2>
<h2 id="cargo-doc"><a class="header" href="#cargo-doc">cargo doc</a></h2>
<p>You might have noticed that Rust documentation always looks almost the same. On the left side you can see <code>struct</code>s and <code>trait</code>s, code examples are on the right, etc. This is because you can automatically make documentation just by typing <code>cargo doc</code>.</p>
<p>Even making a project with nothing can help you learn about traits in Rust. For example, here are two structs that do almost nothing, and a <code>fn main()</code> that also does nothing.</p>
<pre><pre class="playground"><code class="language-rust">struct DoesNothing {}

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#the-end" id="the-end">The end?</a></h2>
<h2 id="the-end"><a class="header" href="#the-end">The end?</a></h2>
<p>This is the end of Rust in Easy English. But I am still here, and you can let me know if you have any questions. Feel free to <a href="https://twitter.com/mithridates">contact me on Twitter</a> or add a pull request, issue, etc. You can also tell me if some parts weren't easy to understand. Rust in Easy English needs to be very easy to understand, so please let me know where the English is too difficult. Of course, Rust itself can be difficult to understand, but we can at least make sure that the English is easy.</p>
</main>

@ -163,9 +163,9 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#types" id="types">Types</a></h2>
<h2 id="types"><a class="header" href="#types">Types</a></h2>
<p>Rust 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.</p>
<h3><a class="header" href="#primitive-types" id="primitive-types">Primitive types</a></h3>
<h3 id="primitive-types"><a class="header" href="#primitive-types">Primitive types</a></h3>
<p><strong><a href="https://youtu.be/OxTPU5UGMhs">See this chapter on YouTube</a></strong></p>
<p>Rust has simple types that are called <strong>primitive types</strong> (primitive = very basic). We will start with integers and <code>char</code> (characters). Integers are whole numbers with no decimal point. There are two types of integers:</p>
<ul>

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#type-inference" id="type-inference">Type inference</a></h2>
<h2 id="type-inference"><a class="header" href="#type-inference">Type inference</a></h2>
<p><strong><a href="https://youtu.be/q1D2vpy3kEI">See this chapter on YouTube</a></strong></p>
<p>Type 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 dont always need to tell it. Actually, usually you don't need to tell it. For example, for <code>let my_number = 8</code>, <code>my_number</code> will be an <code>i32</code>. That is because the compiler chooses i32 for integers if you don't tell it. But if you say <code>let my_number: u8 = 8</code>, it will make <code>my_number</code> a <code>u8</code>, because you told it <code>u8</code>.</p>
<p>So usually the compiler can guess. But sometimes you need to tell it, for two reasons:</p>
@ -195,7 +195,7 @@
}
</code></pre></pre>
<p>This prints <code>0, 1624</code>.</p>
<h3><a class="header" href="#floats" id="floats">Floats</a></h3>
<h3 id="floats"><a class="header" href="#floats">Floats</a></h3>
<p>Floats 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.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let my_float = 5.; // Rust sees . and knows that it is a float

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#printing-hello-world" id="printing-hello-world">Printing 'hello, world!'</a></h2>
<h2 id="printing-hello-world"><a class="header" href="#printing-hello-world">Printing 'hello, world!'</a></h2>
<p><strong>See this chapter on YouTube: <a href="https://youtu.be/yYlPHRl2geQ">Video 1</a>, <a href="https://youtu.be/DTCSfBJJZb8">Video 2</a></strong></p>
<p>When you start a new Rust program, it always has this code:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
@ -245,7 +245,7 @@ fn main() {
let multiply_result = multiply(8, 9); // We used multiply() to print and to give the result to multiply_result
}
</code></pre></pre>
<h3><a class="header" href="#declaring-variables-and-code-blocks" id="declaring-variables-and-code-blocks">Declaring variables and code blocks</a></h3>
<h3 id="declaring-variables-and-code-blocks"><a class="header" href="#declaring-variables-and-code-blocks">Declaring variables and code blocks</a></h3>
<p>Use <code>let</code> to declare a variable (declare a variable = tell Rust to make a variable).</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let my_number = 8;

@ -93,7 +93,7 @@ a > .hljs {
.menu-title {
display: inline-block;
font-weight: 200;
font-size: 2rem;
font-size: 2.4rem;
line-height: var(--menu-bar-height);
text-align: center;
margin: 0;

@ -45,20 +45,23 @@ h4, h5 { margin-top: 2em; }
margin-top: 1em;
}
h1 a.header:target::before,
h2 a.header:target::before,
h3 a.header:target::before,
h4 a.header:target::before {
h1:target::before,
h2:target::before,
h3:target::before,
h4:target::before,
h5:target::before,
h6:target::before {
display: inline-block;
content: "»";
margin-left: -30px;
width: 30px;
}
h1 a.header:target,
h2 a.header:target,
h3 a.header:target,
h4 a.header:target {
/* This is broken on Safari as of version 14, but is fixed
in Safari Technology Preview 117 which I think will be Safari 14.2.
https://bugs.webkit.org/show_bug.cgi?id=218076
*/
:target {
scroll-margin-top: calc(var(--menu-bar-height) + 0.5em);
}

@ -92,22 +92,22 @@
.light {
--bg: hsl(0, 0%, 100%);
--fg: #333333;
--fg: hsl(0, 0%, 0%);
--sidebar-bg: #fafafa;
--sidebar-fg: #364149;
--sidebar-fg: hsl(0, 0%, 0%);
--sidebar-non-existant: #aaaaaa;
--sidebar-active: #008cff;
--sidebar-active: #1f1fff;
--sidebar-spacer: #f4f4f4;
--scrollbar: #cccccc;
--scrollbar: #8F8F8F;
--icons: #cccccc;
--icons-hover: #333333;
--icons: #747474;
--icons-hover: #000000;
--links: #4183c4;
--links: #20609f;
--inline-code-color: #6e6b5e;
--inline-code-color: #301900;
--theme-popup-bg: #fafafa;
--theme-popup-border: #cccccc;

@ -1,14 +1,18 @@
/* Base16 Atelier Dune Light - Theme */
/* by Bram de Haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/dune) */
/* Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */
/*
* An increased contrast highlighting scheme loosely based on the
* "Base16 Atelier Dune Light" theme by Bram de Haan
* (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/dune)
* Original Base16 color scheme by Chris Kempson
* (https://github.com/chriskempson/base16)
*/
/* Atelier-Dune Comment */
/* Comment */
.hljs-comment,
.hljs-quote {
color: #AAA;
color: #575757;
}
/* Atelier-Dune Red */
/* Red */
.hljs-variable,
.hljs-template-variable,
.hljs-attribute,
@ -19,10 +23,10 @@
.hljs-name,
.hljs-selector-id,
.hljs-selector-class {
color: #d73737;
color: #d70025;
}
/* Atelier-Dune Orange */
/* Orange */
.hljs-number,
.hljs-meta,
.hljs-built_in,
@ -30,33 +34,33 @@
.hljs-literal,
.hljs-type,
.hljs-params {
color: #b65611;
color: #b21e00;
}
/* Atelier-Dune Green */
/* Green */
.hljs-string,
.hljs-symbol,
.hljs-bullet {
color: #60ac39;
color: #008200;
}
/* Atelier-Dune Blue */
/* Blue */
.hljs-title,
.hljs-section {
color: #6684e1;
color: #0030f2;
}
/* Atelier-Dune Purple */
/* Purple */
.hljs-keyword,
.hljs-selector-tag {
color: #b854d4;
color: #9d00ec;
}
.hljs {
display: block;
overflow-x: auto;
background: #f1f1f1;
color: #6e6b5e;
background: #f6f7f6;
color: #000;
padding: 0.5em;
}

@ -163,7 +163,7 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#update" id="update">Update</a></h2>
<h2 id="update"><a class="header" href="#update">Update</a></h2>
<p><img src="https://github.com/Dhghomon/easy_rust/workflows/github%20pages/badge.svg" alt="example workflow name" /></p>
<p>22 December 2020: mdBook can be found <a href="https://dhghomon.github.io/easy_rust">here</a>.</p>
<p>28 November 2020: <a href="https://github.com/kumakichi/easy_rust_chs">Now also available in simplified Chinese</a> thanks to <a href="https://github.com/kumakichi">kumakichi</a>!</p>

@ -165,18 +165,18 @@
<div id="content" class="content">
<main>
<h2><a class="header" href="#update" id="update">Update</a></h2>
<h2 id="update"><a class="header" href="#update">Update</a></h2>
<p><img src="https://github.com/Dhghomon/easy_rust/workflows/github%20pages/badge.svg" alt="example workflow name" /></p>
<p>22 December 2020: mdBook can be found <a href="https://dhghomon.github.io/easy_rust">here</a>.</p>
<p>28 November 2020: <a href="https://github.com/kumakichi/easy_rust_chs">Now also available in simplified Chinese</a> thanks to <a href="https://github.com/kumakichi">kumakichi</a>!</p>
<p>1 February 2021: <a href="https://www.youtube.com/playlist?list=PLfllocyHVgsRwLkTAhG0E-2QxCf-ozBkk">Now available on YouTube!</a></p>
<p><img src="Easy_Rust_sample_image.png" alt="" /></p>
<h2><a class="header" href="#introduction" id="introduction">Introduction</a></h2>
<h2 id="introduction"><a class="header" href="#introduction">Introduction</a></h2>
<p>Rust 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.</p>
<p>Rust 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 &quot;figure it out as you go along&quot;. 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.</p>
<h2><a class="header" href="#who-am-i" id="who-am-i">Who am I?</a></h2>
<h2 id="who-am-i"><a class="header" href="#who-am-i">Who am I?</a></h2>
<p>I 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.</p>
<h2><a class="header" href="#writing-rust-in-easy-english" id="writing-rust-in-easy-english">Writing Rust in Easy English</a></h2>
<h2 id="writing-rust-in-easy-english"><a class="header" href="#writing-rust-in-easy-english">Writing Rust in Easy English</a></h2>
<p><em>Rust in Easy English</em> was written from July to August 2020, and is over 400 pages long. You can contact me here or <a href="https://www.linkedin.com/in/davemacleod">on LinkedIn</a> or <a href="https://twitter.com/mithridates">on Twitter</a> 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.</p>
<ul>
<li><a href="Chapter_3.html#part-1---rust-in-your-browser">Part 1 - Rust in your browser</a>
@ -362,9 +362,9 @@
</ul>
</li>
</ul>
<h1><a class="header" href="#part-1---rust-in-your-browser" id="part-1---rust-in-your-browser">Part 1 - Rust in your browser</a></h1>
<h1 id="part-1---rust-in-your-browser"><a class="header" href="#part-1---rust-in-your-browser">Part 1 - Rust in your browser</a></h1>
<p>This 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.</p>
<h2><a class="header" href="#rust-playground" id="rust-playground">Rust Playground</a></h2>
<h2 id="rust-playground"><a class="header" href="#rust-playground">Rust Playground</a></h2>
<p><strong><a href="https://youtu.be/-lYeJeQ11OI">See this chapter on YouTube</a></strong></p>
<p>Maybe you don't want to install Rust yet, and that's okay. You can go to <a href="https://play.rust-lang.org/">https://play.rust-lang.org/</a> 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).</p>
<p>Here are some tips when using the Rust Playground:</p>
@ -377,9 +377,9 @@
<li>Config: here you can change your theme to dark mode so you can work at night, and many other configurations.</li>
</ul>
<p>If you want to install Rust, go here <a href="https://www.rust-lang.org/tools/install">https://www.rust-lang.org/tools/install</a> and follow the instructions. Usually you will use <code>rustup</code> to install and update Rust.</p>
<h2><a class="header" href="#-and-" id="-and-">🚧 and ⚠️</a></h2>
<h2 id="-and-"><a class="header" href="#-and-">🚧 and ⚠️</a></h2>
<p>Sometimes 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 &quot;under construction&quot;: it means that the code is not complete. Rust needs a <code>fn main()</code> (a main function) to run, but sometimes we just want to look at small pieces of code so it won't have a <code>fn main()</code>. Those examples are correct, but need a <code>fn main()</code> for you to run them. And some code examples show you a problem that we will fix. Those ones might have a <code>fn main()</code> but generate an error, and so they will have a ⚠️.</p>
<h2><a class="header" href="#comments" id="comments">Comments</a></h2>
<h2 id="comments"><a class="header" href="#comments">Comments</a></h2>
<p><strong><a href="https://youtu.be/fJ7jBZG_Rpo">See this chapter on YouTube</a></strong></p>
<p>Comments 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 <code>//</code>:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
@ -408,9 +408,9 @@
// It's called some_number but actually I think that...
}
</code></pre></pre>
<h2><a class="header" href="#types" id="types">Types</a></h2>
<h2 id="types"><a class="header" href="#types">Types</a></h2>
<p>Rust 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.</p>
<h3><a class="header" href="#primitive-types" id="primitive-types">Primitive types</a></h3>
<h3 id="primitive-types"><a class="header" href="#primitive-types">Primitive types</a></h3>
<p><strong><a href="https://youtu.be/OxTPU5UGMhs">See this chapter on YouTube</a></strong></p>
<p>Rust has simple types that are called <strong>primitive types</strong> (primitive = very basic). We will start with integers and <code>char</code> (characters). Integers are whole numbers with no decimal point. There are two types of integers:</p>
<ul>
@ -511,7 +511,7 @@ Slice2 is 7 bytes.
<pre><code class="language-text">Slice is 6 bytes and also 6 characters.
Slice2 is 7 bytes but only 3 characters.
</code></pre>
<h2><a class="header" href="#type-inference" id="type-inference">Type inference</a></h2>
<h2 id="type-inference"><a class="header" href="#type-inference">Type inference</a></h2>
<p><strong><a href="https://youtu.be/q1D2vpy3kEI">See this chapter on YouTube</a></strong></p>
<p>Type 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 dont always need to tell it. Actually, usually you don't need to tell it. For example, for <code>let my_number = 8</code>, <code>my_number</code> will be an <code>i32</code>. That is because the compiler chooses i32 for integers if you don't tell it. But if you say <code>let my_number: u8 = 8</code>, it will make <code>my_number</code> a <code>u8</code>, because you told it <code>u8</code>.</p>
<p>So usually the compiler can guess. But sometimes you need to tell it, for two reasons:</p>
@ -543,7 +543,7 @@ Slice2 is 7 bytes but only 3 characters.
}
</code></pre></pre>
<p>This prints <code>0, 1624</code>.</p>
<h3><a class="header" href="#floats" id="floats">Floats</a></h3>
<h3 id="floats"><a class="header" href="#floats">Floats</a></h3>
<p>Floats 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.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let my_float = 5.; // Rust sees . and knows that it is a float
@ -598,7 +598,7 @@ Slice2 is 7 bytes but only 3 characters.
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
}
</code></pre></pre>
<h2><a class="header" href="#printing-hello-world" id="printing-hello-world">Printing 'hello, world!'</a></h2>
<h2 id="printing-hello-world"><a class="header" href="#printing-hello-world">Printing 'hello, world!'</a></h2>
<p><strong>See this chapter on YouTube: <a href="https://youtu.be/yYlPHRl2geQ">Video 1</a>, <a href="https://youtu.be/DTCSfBJJZb8">Video 2</a></strong></p>
<p>When you start a new Rust program, it always has this code:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
@ -680,7 +680,7 @@ fn main() {
let multiply_result = multiply(8, 9); // We used multiply() to print and to give the result to multiply_result
}
</code></pre></pre>
<h3><a class="header" href="#declaring-variables-and-code-blocks" id="declaring-variables-and-code-blocks">Declaring variables and code blocks</a></h3>
<h3 id="declaring-variables-and-code-blocks"><a class="header" href="#declaring-variables-and-code-blocks">Declaring variables and code blocks</a></h3>
<p>Use <code>let</code> to declare a variable (declare a variable = tell Rust to make a variable).</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let my_number = 8;
@ -722,7 +722,7 @@ fn main() {
}
</code></pre></pre>
<p>So why did we write <code>{:?}</code> and not <code>{}</code>? We will talk about that now.</p>
<h2><a class="header" href="#display-and-debug" id="display-and-debug">Display and debug</a></h2>
<h2 id="display-and-debug"><a class="header" href="#display-and-debug">Display and debug</a></h2>
<p><strong><a href="https://youtu.be/jd3pC248c0o">See this chapter on YouTube</a></strong></p>
<p>Simple variables in Rust can be printed with <code>{}</code> inside <code>println!</code>. But some variables can't, and you need to <strong>debug print</strong>. 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.</p>
<p>How do you know if you need <code>{:?}</code> and not <code>{}</code>? The compiler will tell you. For example:</p>
@ -752,7 +752,7 @@ fn main() {
}
</code></pre></pre>
<p>This prints <code>This will not print a new line so this will be on the same line</code>.</p>
<h3><a class="header" href="#smallest-and-largest-numbers" id="smallest-and-largest-numbers">Smallest and largest numbers</a></h3>
<h3 id="smallest-and-largest-numbers"><a class="header" href="#smallest-and-largest-numbers">Smallest and largest numbers</a></h3>
<p>If you want to see the smallest and biggest numbers, you can use MIN and MAX. <code>std</code> means &quot;standard library&quot; and has all the main functions etc. for Rust. We will learn about the standard library later. But in the meantime, you can remember that this is how you get the smallest and largest number for a type.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
println!(&quot;The smallest i8 is {} and the biggest i8 is {}.&quot;, std::i8::MIN, std::i8::MAX); // hint: printing std::i8::MIN means &quot;print MIN inside of the i8 section in the standard library&quot;
@ -780,7 +780,7 @@ The smallest u64 is 0 and the biggest u64 is 18446744073709551615.
The smallest i128 is -170141183460469231731687303715884105728 and the biggest i128 is 170141183460469231731687303715884105727.
The smallest u128 is 0 and the biggest u128 is 340282366920938463463374607431768211455.
</code></pre>
<h2><a class="header" href="#mutability-changing" id="mutability-changing">Mutability (changing)</a></h2>
<h2 id="mutability-changing"><a class="header" href="#mutability-changing">Mutability (changing)</a></h2>
<p><strong><a href="https://youtu.be/Nyyd6qn7dZY">See this chapter on YouTube</a></strong></p>
<p>When you declare a variable with <code>let</code>, it is immutable (cannot be changed).</p>
<p>This will not work:</p>
@ -804,7 +804,7 @@ The smallest u128 is 0 and the biggest u128 is 340282366920938463463374607431768
}
</code></pre></pre>
<p>You will see the same &quot;expected&quot; message from the compiler: <code>expected integer, found &amp;str</code>. <code>&amp;str</code> is a string type that we will learn soon.</p>
<h3><a class="header" href="#shadowing" id="shadowing">Shadowing</a></h3>
<h3 id="shadowing"><a class="header" href="#shadowing">Shadowing</a></h3>
<p><strong><a href="https://youtu.be/InULHyRGw7g">See this chapter on YouTube</a></strong></p>
<p>Shadowing means using <code>let</code> 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:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
@ -864,7 +864,7 @@ fn main() {
}
</code></pre></pre>
<p>In 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.</p>
<h2><a class="header" href="#the-stack-the-heap-and-pointers" id="the-stack-the-heap-and-pointers">The stack, the heap, and pointers</a></h2>
<h2 id="the-stack-the-heap-and-pointers"><a class="header" href="#the-stack-the-heap-and-pointers">The stack, the heap, and pointers</a></h2>
<p>The stack, the heap, and pointers are very important in Rust.</p>
<p>The stack and the heap are two places to keep memory in computers. The important differences are:</p>
<ul>
@ -901,7 +901,7 @@ Chapter 5: Future plans 43
}
</code></pre></pre>
<p>These are all different types, just in the same way that &quot;a friend of a friend&quot; is different from &quot;a friend&quot;.</p>
<h2><a class="header" href="#more-about-printing" id="more-about-printing">More about printing</a></h2>
<h2 id="more-about-printing"><a class="header" href="#more-about-printing">More about printing</a></h2>
<p>In Rust you can print things in almost any way you want. Here are some more things to know about printing.</p>
<p>Adding <code>\n</code> will make a new line, and <code>\t</code> will make a tab:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
@ -1105,7 +1105,7 @@ but Tokyo is not in Korea.
| |
SEOUL--------------------TOKYO
</code></pre>
<h2><a class="header" href="#strings" id="strings">Strings</a></h2>
<h2 id="strings"><a class="header" href="#strings">Strings</a></h2>
<p><strong><a href="https://youtu.be/pSyaGzGg26o">See this chapter on YouTube</a></strong></p>
<p>Rust has two main types of strings: <code>String</code> and <code>&amp;str</code>. What is the difference?</p>
<ul>
@ -1184,7 +1184,7 @@ And 'Adrian Fahrenheit Țepeș' is 25 bytes. It is not Sized.
}
</code></pre></pre>
<p>And now you get a String.</p>
<h2><a class="header" href="#const-and-static" id="const-and-static">const and static</a></h2>
<h2 id="const-and-static"><a class="header" href="#const-and-static">const and static</a></h2>
<p><strong><a href="https://youtu.be/Ky3HqkWUcI0">See this chapter on YouTube</a></strong></p>
<p>There are two types that don't use <code>let</code> to declare: <code>const</code> and <code>static</code>. Also, Rust won't use type inference: you need to write the type for them. These are for variables that don't change (<code>const</code> means constant). The difference is that:</p>
<ul>
@ -1194,7 +1194,7 @@ And 'Adrian Fahrenheit Țepeș' is 25 bytes. It is not Sized.
<p>So they are almost the same. Rust programmers almost always use <code>const</code>.</p>
<p>You write them with ALL CAPITAL LETTERS, and usually outside of <code>main</code> so that they can live for the whole program.</p>
<p>Two examples are: <code>const NUMBER_OF_MONTHS: u32 = 12;</code> and <code>static SEASONS: [&amp;str; 4] = [&quot;Spring&quot;, &quot;Summer&quot;, &quot;Fall&quot;, &quot;Winter&quot;];</code></p>
<h2><a class="header" href="#more-on-references" id="more-on-references">More on references</a></h2>
<h2 id="more-on-references"><a class="header" href="#more-on-references">More on references</a></h2>
<p><strong><a href="https://youtu.be/R13sQ8SNoEQ">See this chapter on YouTube</a></strong></p>
<p>References are very important in Rust. Rust uses references to make sure that all memory access is safe. We know that we use <code>&amp;</code> to create a reference:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
@ -1220,7 +1220,7 @@ fn main() {
</code></pre></pre>
<p>The function <code>return_str()</code> creates a String, then it creates a reference to the String. Then it tries to return the reference. But the String <code>country</code> 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, <code>country_ref</code> is referring to memory that is already gone, and that's not okay. Rust prevents us from making a mistake with memory here.</p>
<p>This is the important part about the &quot;owned&quot; type that we talked about above. Because you own a <code>String</code>, you can pass it around. But a <code>&amp;String</code> will die if its <code>String</code> dies, so you don't pass around &quot;ownership&quot; with it.</p>
<h2><a class="header" href="#mutable-references" id="mutable-references">Mutable references</a></h2>
<h2 id="mutable-references"><a class="header" href="#mutable-references">Mutable references</a></h2>
<p><strong><a href="https://youtu.be/G48z6Rv76vc">See this chapter on YouTube</a></strong></p>
<p>If you want to use a reference to change data, you can use a mutable reference. For a mutable reference, you write <code>&amp;mut</code> instead of <code>&amp;</code>.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
@ -1291,7 +1291,7 @@ Second_number = triple_reference? true
</code></pre></pre>
<p>It prints <code>20</code> with no problem. It works because the compiler is smart enough to understand our code. It knows that we used <code>number_change</code> to change <code>number</code>, but didn't use it again. So here there is no problem. We are not using immutable and mutable references together.</p>
<p>Earlier 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.</p>
<h3><a class="header" href="#shadowing-again" id="shadowing-again">Shadowing again</a></h3>
<h3 id="shadowing-again"><a class="header" href="#shadowing-again">Shadowing again</a></h3>
<p>Remember when we said that shadowing doesn't <strong>destroy</strong> a value but <strong>blocks</strong> it? Now we can use references to see this.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let country = String::from(&quot;Austria&quot;);
@ -1308,7 +1308,7 @@ Second_number = triple_reference? true
println!(&quot;{}, {}&quot;, country_ref, country); // country_ref still refers to the data of String::from(&quot;Austria&quot;) that we gave it.
}
</code></pre></pre>
<h2><a class="header" href="#giving-references-to-functions" id="giving-references-to-functions">Giving references to functions</a></h2>
<h2 id="giving-references-to-functions"><a class="header" href="#giving-references-to-functions">Giving references to functions</a></h2>
<p><strong>See this chapter on YouTube: <a href="https://youtu.be/mKWXt9YTavc">immutable references</a> and <a href="https://youtu.be/kJV1wIvAbyk">mutable references</a></strong></p>
<p>References are very useful for functions. The rule in Rust on values is: a value can only have one owner.</p>
<p>This code will not work:</p>
@ -1387,7 +1387,7 @@ fn adds_hungary(mut country: String) { // Here's how: adds_hungary takes the Str
</code></pre></pre>
<p>How is this possible? It is because <code>mut country</code> is not a reference: <code>adds_hungary</code> owns <code>country</code> now. (Remember, it takes <code>String</code> and not <code>&amp;String</code>). The moment you call <code>adds_hungary</code>, it becomes the full owner. <code>country</code> has nothing to do with <code>String::from(&quot;Austria&quot;)</code> anymore. So <code>adds_hungary</code> can take <code>country</code> as mutable, and it is perfectly safe to do so.</p>
<p>Remember 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.</p>
<h2><a class="header" href="#copy-types" id="copy-types">Copy types</a></h2>
<h2 id="copy-types"><a class="header" href="#copy-types">Copy types</a></h2>
<p>Some types in Rust are very simple. They are called <strong>copy types</strong>. 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.</p>
<p>These simple types include: integers, floats, booleans (<code>true</code> and <code>false</code>), and <code>char</code>.</p>
<p>How do you know if a type <strong>implements</strong> copy? (implements = can use) You can check the documentation. For example, here is the documentation for char:</p>
@ -1480,7 +1480,7 @@ fn main() {
}
</code></pre></pre>
<p>Instead of 50 clones, it's zero.</p>
<h3><a class="header" href="#variables-without-values" id="variables-without-values">Variables without values</a></h3>
<h3 id="variables-without-values"><a class="header" href="#variables-without-values">Variables without values</a></h3>
<p>A variable without a value is called an &quot;uninitialized&quot; variable. Uninitialized means &quot;hasn't started yet&quot;. They are simple: just write <code>let</code> and the variable name:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let my_variable; // ⚠️
@ -1533,9 +1533,9 @@ fn main() {
</code></pre></pre>
<p>So it's almost like saying <code>let my_number = { 100 };</code>.</p>
<p>Also note that <code>my_number</code> is not <code>mut</code>. We didn't give it a value until we gave it 50, so it never changed its value. In the end, the real code for <code>my_number</code> is just let <code>my_number = 100;</code>.</p>
<h2><a class="header" href="#collection-types" id="collection-types">Collection types</a></h2>
<h2 id="collection-types"><a class="header" href="#collection-types">Collection types</a></h2>
<p>Rust 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 <code>&amp;str</code> in that way.</p>
<h3><a class="header" href="#arrays" id="arrays">Arrays</a></h3>
<h3 id="arrays"><a class="header" href="#arrays">Arrays</a></h3>
<p>An array is data inside square brackets: <code>[]</code>. Arrays:</p>
<ul>
<li>must not change their size,</li>
@ -1604,7 +1604,7 @@ error[E0599]: no method named `thd` found for array `[&amp;str; 5]` in the curre
</ul>
<p>So <code>[0..2]</code> means the first index and the second index (0 and 1). Or you can call it the &quot;zeroth and first&quot; index. It doesn't have the third item, which is index 2.</p>
<p>You can also have an <strong>inclusive</strong> range, which means it includes the last number too. To do this, add <code>=</code> to write <code>..=</code> instead of <code>..</code>. So instead of <code>[0..2]</code> you can write <code>[0..=2]</code> if you want the first, second, and third item.</p>
<h2><a class="header" href="#vectors" id="vectors">Vectors</a></h2>
<h2 id="vectors"><a class="header" href="#vectors">Vectors</a></h2>
<p><strong><a href="https://youtu.be/Eh-DsRnDKmw">See this chapter on YouTube</a></strong></p>
<p>In the same way that we have <code>&amp;str</code> and <code>String</code>, 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<em>er</em> than arrays.) The type is written <code>Vec</code>, and you can also just call it a &quot;vec&quot;.</p>
<p>There are two main ways to declare a vector. One is like with <code>String</code> using <code>new</code>:</p>
@ -1696,7 +1696,7 @@ everything: {:?}&quot;, three_to_five, start_at_two, end_at_five, everything);
// Rust will choose Vec&lt;i32&gt;
}
</code></pre></pre>
<h2><a class="header" href="#tuples" id="tuples">Tuples</a></h2>
<h2 id="tuples"><a class="header" href="#tuples">Tuples</a></h2>
<p><strong><a href="https://youtu.be/U67Diy6SlTg">See this chapter on YouTube</a></strong></p>
<p>Tuples in Rust use <code>()</code>. We have seen many empty tuples already, because <em>nothing</em> in a function actually means an empty tuple:</p>
<pre><code class="language-text">fn do_something() {}
@ -1762,7 +1762,7 @@ Sixth item: 7.7
</code></pre></pre>
<p>Now it only creates a variable called <code>variable</code> but doesn't make a variable for the others.</p>
<p>There 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.</p>
<h2><a class="header" href="#control-flow" id="control-flow">Control flow</a></h2>
<h2 id="control-flow"><a class="header" href="#control-flow">Control flow</a></h2>
<p><strong>See this chapter on YouTube: <a href="https://youtu.be/UAymDOpv_us">Part 1</a> and <a href="https://youtu.be/eqysTfiiQZs">Part 2</a></strong></p>
<p>Control flow means telling your code what to do in different situations. The simplest control flow is <code>if</code>.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
@ -1960,7 +1960,7 @@ fn main() {
13 is unlucky in North America, lucky in Italy! In bocca al lupo!
4 is an unlucky number in China (sounds close to 死)!
</code></pre>
<h2><a class="header" href="#structs" id="structs">Structs</a></h2>
<h2 id="structs"><a class="header" href="#structs">Structs</a></h2>
<p><strong>See this chapter on YouTube: <a href="https://youtu.be/W23uQghBOFk">Part 1</a> and <a href="https://youtu.be/GSVhrjLCuNA">Part 2</a></strong></p>
<p>With 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 <code>struct</code>. 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.</p>
<p>There are three types of structs. One is a &quot;unit struct&quot;. Unit means &quot;doesn't have anything&quot;. For a unit struct, you just write the name and a semicolon.</p>
@ -2060,7 +2060,7 @@ fn main() {
};
}
</code></pre></pre>
<h2><a class="header" href="#enums" id="enums">Enums</a></h2>
<h2 id="enums"><a class="header" href="#enums">Enums</a></h2>
<p><strong>See this chapter on YouTube: <a href="https://youtu.be/SRnqNTJUgjs">Part 1</a>, <a href="https://youtu.be/F_EcbWM63lk">Part 2</a>, <a href="https://youtu.be/2uh64U9JesA">Part 3</a> and <a href="https://youtu.be/LOHVUYTc5Us">Part 4</a></strong></p>
<p>An <code>enum</code> is short for enumerations. They look very similar to a struct, but are different. Here is the difference:</p>
<ul>
@ -2234,7 +2234,7 @@ This is a good-sized star.
What about DeadStar? It's the number 1001.
</code></pre>
<p><code>DeadStar</code> would have been number 4, but now it's 1001.</p>
<h3><a class="header" href="#enums-to-use-multiple-types" id="enums-to-use-multiple-types">Enums to use multiple types</a></h3>
<h3 id="enums-to-use-multiple-types"><a class="header" href="#enums-to-use-multiple-types">Enums to use multiple types</a></h3>
<p>You know that items in a <code>Vec</code>, array, etc. all need the same type (only tuples are different). But you can actually use an enum to put different types in. Imagine we want to have a <code>Vec</code> with <code>u32</code>s or <code>i32</code>s. Of course, you can make a <code>Vec&lt;(u32, i32)&gt;</code> (a vec with <code>(u32, i32)</code> tuples) but we only want one each time. So here you can use an enum. Here is a simple example:</p>
<pre><pre class="playground"><code class="language-rust">enum Number {
U32(u32),
@ -2275,7 +2275,7 @@ fn main() {
<pre><code class="language-text">It's an i32 with the value -800
It's a u32 with the value 8
</code></pre>
<h2><a class="header" href="#loops" id="loops">Loops</a></h2>
<h2 id="loops"><a class="header" href="#loops">Loops</a></h2>
<p>With loops you can tell Rust to continue something until you want it to stop. You use <code>loop</code> to start a loop that does not stop, unless you tell it when to <code>break</code>.</p>
<pre><pre class="playground"><code class="language-rust">fn main() { // This program will never stop
loop {
@ -2459,7 +2459,7 @@ Each colour has at least 10.
Comparing a colour with 200 red, 50 blue, and 0 green:
Not much green.
</code></pre>
<h2><a class="header" href="#implementing-structs-and-enums" id="implementing-structs-and-enums">Implementing structs and enums</a></h2>
<h2 id="implementing-structs-and-enums"><a class="header" href="#implementing-structs-and-enums">Implementing structs and enums</a></h2>
<p>This is where you can start to give your structs and enums some real power. To call functions on a <code>struct</code> or an <code>enum</code>, use an <code>impl</code> block. These functions are called <strong>methods</strong>. There are two kinds of methods in an <code>impl</code> block.</p>
<ul>
<li>Regular methods: these take <strong>self</strong> (or <strong>&amp;self</strong> or <strong>&amp;mut self</strong>). Regular methods use a <code>.</code> (a period). <code>.clone()</code> is an example of a regular method.</li>
@ -2558,7 +2558,7 @@ fn main() {
}
</code></pre></pre>
<p>This prints <code>Need sleep NOW</code>.</p>
<h2><a class="header" href="#destructuring" id="destructuring">Destructuring</a></h2>
<h2 id="destructuring"><a class="header" href="#destructuring">Destructuring</a></h2>
<p>Let's look at some more destructuring. You can get the values from a struct or enum by using <code>let</code> backwards. We learned that this is <code>destructuring</code>, because you get variables that are not part of a structure. Now you have the values separately. First a simple example:</p>
<pre><pre class="playground"><code class="language-rust">struct Person { // make a simple struct for a person
name: String,
@ -2625,7 +2625,7 @@ fn main() {
}
</code></pre></pre>
<p>This prints <code>The city's two names are [&quot;Tallinn&quot;, &quot;Reval&quot;]</code>.</p>
<h2><a class="header" href="#references-and-the-dot-operator" id="references-and-the-dot-operator">References and the dot operator</a></h2>
<h2 id="references-and-the-dot-operator"><a class="header" href="#references-and-the-dot-operator">References and the dot operator</a></h2>
<p>We learned that when you have a reference, you need to use <code>*</code> to get to the value. A reference is a different type, so this won't work:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let my_number = 9;
@ -2701,7 +2701,7 @@ fn main() {
}
</code></pre></pre>
<p>So just remember: when you use the <code>.</code> operator, you don't need to worry about <code>*</code>.</p>
<h2><a class="header" href="#generics" id="generics">Generics</a></h2>
<h2 id="generics"><a class="header" href="#generics">Generics</a></h2>
<p>In functions, you write what type to take as input:</p>
<pre><pre class="playground"><code class="language-rust">fn return_number(number: i32) -&gt; i32 {
println!(&quot;Here is your number.&quot;);
@ -2864,10 +2864,10 @@ fn main() {
<pre><code class="language-text">I have two things to say: Hello there! and I hate sand.
I have two things to say: Where is Padme? and Is she all right?
</code></pre>
<h2><a class="header" href="#option-and-result" id="option-and-result">Option and Result</a></h2>
<h2 id="option-and-result"><a class="header" href="#option-and-result">Option and Result</a></h2>
<p>We understand enums and generics now, so we can understand <code>Option</code> and <code>Result</code>. Rust uses these two enums to make code safer.</p>
<p>We will start with <code>Option</code>.</p>
<h3><a class="header" href="#option" id="option">Option</a></h3>
<h3 id="option"><a class="header" href="#option">Option</a></h3>
<p>You use <code>Option</code> when you have a value that might exist, or might not exist. When a value exists it is <code>Some(value)</code> and when it doesn't it's just <code>None</code>, Here is an example of bad code that can be improved with <code>Option</code>.</p>
<pre><pre class="playground"><code class="language-rust"> // ⚠️
fn take_fifth(value: Vec&lt;i32&gt;) -&gt; i32 {
@ -3002,7 +3002,7 @@ fn main() {
<pre><code class="language-text">We got nothing.
We got: 5
</code></pre>
<h3><a class="header" href="#result" id="result">Result</a></h3>
<h3 id="result"><a class="header" href="#result">Result</a></h3>
<p>Result is similar to Option, but here is the difference:</p>
<ul>
<li>Option is about <code>Some</code> or <code>None</code> (value or no value),</li>
@ -3178,9 +3178,9 @@ The number is: 50
The number is: 10
The number is: 20
</code></pre>
<h2><a class="header" href="#other-collections" id="other-collections">Other collections</a></h2>
<h2 id="other-collections"><a class="header" href="#other-collections">Other collections</a></h2>
<p>Rust has many more types of collections. You can see them at https://doc.rust-lang.org/beta/std/collections/ in the standard library. That page has good explanations for why to use one type, so go there if you don't know what type you want. These collections are all inside <code>std::collections</code> in the standard library. The best way to use them is with a <code>use</code> statement, like we did with our <code>enums</code>. We will start with <code>HashMap</code>, which is very common.</p>
<h3><a class="header" href="#hashmap-and-btreemap" id="hashmap-and-btreemap">HashMap (and BTreeMap)</a></h3>
<h3 id="hashmap-and-btreemap"><a class="header" href="#hashmap-and-btreemap">HashMap (and BTreeMap)</a></h3>
<p>A HashMap is a collection made out of <em>keys</em> and <em>values</em>. You use the key to look up the value that matches the key. You can create a new <code>HashMap</code> with just <code>HashMap::new()</code> and use <code>.insert(key, value)</code> to insert items.</p>
<p>A <code>HashMap</code> is not in order, so if you print every key in a <code>HashMap</code> together it will probably print differently. We can see this in an example:</p>
<pre><pre class="playground"><code class="language-rust">use std::collections::HashMap; // This is so we can just write HashMap instead of std::collections::HashMap every time
@ -3413,7 +3413,7 @@ fn main() {
&quot;male&quot;, [9, 0, 10]
</code></pre>
<p>The important line is: <code>survey_hash.entry(item.0).or_insert(Vec::new()).push(item.1);</code> So if it sees &quot;female&quot; it will check to see if there is &quot;female&quot; already in the <code>HashMap</code>. If not, it will insert a <code>Vec::new()</code>, then push the number in. If it sees &quot;female&quot; already in the <code>HashMap</code>, it will not insert a new Vec, and will just push the number into it.</p>
<h3><a class="header" href="#hashset-and-btreeset" id="hashset-and-btreeset">HashSet and BTreeSet</a></h3>
<h3 id="hashset-and-btreeset"><a class="header" href="#hashset-and-btreeset">HashSet and BTreeSet</a></h3>
<p>A <code>HashSet</code> is actually a <code>HashMap</code> that only has keys. On <a href="https://doc.rust-lang.org/std/collections/struct.HashSet.html">the page for HashSet</a> it explains this on the top:</p>
<p><code>A hash set implemented as a HashMap where the value is ().</code> So it's a <code>HashMap</code> with keys, no values.</p>
<p>You often use a <code>HashSet</code> if you just want to know if a key exists, or doesn't exist.</p>
@ -3487,7 +3487,7 @@ fn main() {
}
</code></pre></pre>
<p>Now it will print in order: <code>0 3 5 8 10 11 13 14 15 16 17 18 19 20 22 24 25 26 28 29 32 33 34 35 36 37 38 41 42 43 44 46 49 51 54 55 56 57 58 59 60 61 63 64 66 67 68 71 73 74 76 79 80 81 82 84 86 87 89 90 91 92 93 94 95 96</code>.</p>
<h3><a class="header" href="#binaryheap" id="binaryheap">BinaryHeap</a></h3>
<h3 id="binaryheap"><a class="header" href="#binaryheap">BinaryHeap</a></h3>
<p>A <code>BinaryHeap</code> is an interesting collection type, because it is mostly unordered but has a bit of order. It keeps the largest item in the front, but the other items are in any order.</p>
<p>We will use another list of items for an example, but this time smaller.</p>
<pre><pre class="playground"><code class="language-rust">use std::collections::BinaryHeap;
@ -3550,7 +3550,7 @@ You need to: Tell your team members thanks for always working hard
You need to: Plan who to hire next for the team
You need to: Watch some YouTube
</code></pre>
<h3><a class="header" href="#vecdeque" id="vecdeque">VecDeque</a></h3>
<h3 id="vecdeque"><a class="header" href="#vecdeque">VecDeque</a></h3>
<p>A <code>VecDeque</code> is a <code>Vec</code> that is good at popping items both off the front and the back. Rust has <code>VecDeque</code> because a <code>Vec</code> is great for popping off the back (the last item), but not so great off the front. When you use <code>.pop()</code> on a <code>Vec</code>, it just takes off the last item on the right and nothing else is moved. But if you take it off another part, all the items to the right are moved over one position to the left. You can see this in the description for <code>.remove()</code>:</p>
<pre><code class="language-text">Removes and returns the element at position index within the vector, shifting all elements after it to the left.
</code></pre>
@ -3621,7 +3621,7 @@ fn main() {
<pre><code class="language-text">You must: phone Loki back
(&quot;add new product to list&quot;, true) (&quot;send email to customer&quot;, true) (&quot;phone Loki back&quot;, false)
</code></pre>
<h2><a class="header" href="#the--operator" id="the--operator">The ? operator</a></h2>
<h2 id="the--operator"><a class="header" href="#the--operator">The ? operator</a></h2>
<p>There is an even shorter way to deal with <code>Result</code> (and <code>Option</code>), shorter than <code>match</code> and even shorter than <code>if let</code>. It is called the &quot;question mark operator&quot;, and is just <code>?</code>. After a function that returns a result, you can add <code>?</code>. This will:</p>
<ul>
<li>return what is inside the <code>Result</code> if it is <code>Ok</code></li>
@ -3693,7 +3693,7 @@ fn main() {
</code></pre></pre>
<p>This prints the same thing, but this time we handled three <code>Result</code>s in a single line. Later on we will do this with files, because they always return <code>Result</code>s because many things can go wrong.</p>
<p>Imagine the following: you want to open a file, write to it, and close it. First you need to successfully find the file (that's a <code>Result</code>). Then you need to successfully write to it (that's a <code>Result</code>). With <code>?</code> you can do that on one line.</p>
<h3><a class="header" href="#when-panic-and-unwrap-are-good" id="when-panic-and-unwrap-are-good">When panic and unwrap are good</a></h3>
<h3 id="when-panic-and-unwrap-are-good"><a class="header" href="#when-panic-and-unwrap-are-good">When panic and unwrap are good</a></h3>
<p>Rust has a <code>panic!</code> macro that you can use to make it panic. It is easy to use:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
panic!(&quot;Time to panic!&quot;);
@ -3881,7 +3881,7 @@ fn main() {
}
</code></pre></pre>
<p>This prints <code>0</code> because <code>.unwrap_or(&amp;0)</code> gives a 0 even if it is a <code>None</code>.</p>
<h2><a class="header" href="#traits" id="traits">Traits</a></h2>
<h2 id="traits"><a class="header" href="#traits">Traits</a></h2>
<p>We have seen traits before: <code>Debug</code>, <code>Copy</code>, <code>Clone</code> are all traits. To give a type a trait, you have to implement it. Because <code>Debug</code> and the others are so common, we have attributes that automatically do it. That's what happens you write <code>#[derive(Debug)]</code>: you are automatically implementing <code>Debug</code>.</p>
<pre><pre class="playground"><code class="language-rust">#[derive(Debug)]
struct MyStruct {
@ -4345,7 +4345,7 @@ You raise your hands and cast a fireball! Your opponent now has 0 health left. Y
</code></pre>
<p>So you can see there are many ways to do the same thing when you use traits. It all depends on what makes the most sense for the program that you are writing.</p>
<p>Now let's look at how to implement some of the main traits you will use in Rust.</p>
<h3><a class="header" href="#the-from-trait" id="the-from-trait">The From trait</a></h3>
<h3 id="the-from-trait"><a class="header" href="#the-from-trait">The From trait</a></h3>
<p><em>From</em> is a very convenient trait to use, and you know this because you have seen it so much already. With <em>From</em> you can make a <code>String</code> from a <code>&amp;str</code>, but you can make many types from many other types. For example, Vec uses <em>From</em> for the following:</p>
<pre><code class="language-text">From&lt;&amp;'_ [T]&gt;
From&lt;&amp;'_ mut [T]&gt;
@ -4473,7 +4473,7 @@ fn main() {
Odd numbers: [7, -1, 3, 9787, -47, 77, 55, 7]
</code></pre>
<p>A type like <code>EvenOddVec</code> is probably better as a generic <code>T</code> so we can use many number types. You can try to make the example generic if you want for practice.</p>
<h3><a class="header" href="#taking-a-string-and-a-str-in-a-function" id="taking-a-string-and-a-str-in-a-function">Taking a String and a &amp;str in a function</a></h3>
<h3 id="taking-a-string-and-a-str-in-a-function"><a class="header" href="#taking-a-string-and-a-str-in-a-function">Taking a String and a &amp;str in a function</a></h3>
<p>Sometimes you want a function that can take both a <code>String</code> and a <code>&amp;str</code>. You can do this with generics and the <code>AsRef</code> trait. <code>AsRef</code> is used to give a reference from one type to another type. If you look at the documentation for <code>String</code>, you can see that it has <code>AsRef</code> for many types:</p>
<p><a href="https://doc.rust-lang.org/std/string/struct.String.html">https://doc.rust-lang.org/std/string/struct.String.html</a></p>
<p>Here are some function signatures for them.</p>
@ -4557,7 +4557,7 @@ fn main() {
print_it(&quot;Also, please print me&quot;.to_string());
}
</code></pre></pre>
<h2><a class="header" href="#chaining-methods" id="chaining-methods">Chaining methods</a></h2>
<h2 id="chaining-methods"><a class="header" href="#chaining-methods">Chaining methods</a></h2>
<p>Rust is a systems programming language like C and C++, and its code can be written as separate commands in separate lines, but it also has a functional style. Both styles are okay, but functional style is usually shorter. Here is an example of the non-functional style (called &quot;imperative style&quot;) to make a <code>Vec</code> from 1 to 10:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let mut new_vec = Vec::new();
@ -4604,14 +4604,14 @@ fn main() {
}
</code></pre></pre>
<p>You can use this functional style best when you understand closures and iterators. So we will learn them next.</p>
<h2><a class="header" href="#iterators" id="iterators">Iterators</a></h2>
<h2 id="iterators"><a class="header" href="#iterators">Iterators</a></h2>
<p>An iterator is a construct that can give you the items in the collection, one at a time. Actually, we have already used iterators a lot: the <code>for</code> loop gives you an iterator. When you want to use an iterator other times, you have to choose what kind:</p>
<ul>
<li><code>.iter()</code> for an iterator of references</li>
<li><code>.iter_mut()</code> for an iterator of mutable references</li>
<li><code>.into_iter()</code> for an iterator of values (not references)</li>
</ul>
<p>A <code>for</code> loop is actually just an iterator that uses <code>.iter_mut()</code>. That's why you can change the values when you use it.</p>
<p>A <code>for</code> loop is actually just an iterator that owns its values. That's why it can make it mutable and then you can change the values when you use it.</p>
<p>We can use iterators like this:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let vector1 = vec![1, 2, 3]; // we will use .iter() and .into_iter() on this one
@ -4636,7 +4636,7 @@ fn main() {
<p>First we used <code>.iter()</code> on <code>vector1</code> to get references. We added 1 to each, and made it into a new Vec. <code>vector1</code> is still alive because we only used references: we didn't take by value. Now we have <code>vector1</code>, and a new Vec called <code>vector1_a</code>. Because <code>.map()</code> just passes it on, we needed to use <code>.collect()</code> to make it into a <code>Vec</code>.</p>
<p>Then we used <code>into_iter</code> to get an iterator by value from <code>vector1</code>. This destroys <code>vector1</code>, because that's what <code>into_iter()</code> does. So after we make <code>vector1_b</code> we can't use <code>vector1</code> again.</p>
<p>Finally we used <code>.iter_mut()</code> for <code>vector2</code>. It is mutable, so we don't need to use <code>.collect()</code> to create a new Vec. Instead, we change the values in the same Vec with mutable references. So <code>vector2</code> is still there. Because we don't need a new Vec, we use <code>for_each</code>: it's just like a <code>for</code> loop.</p>
<h3><a class="header" href="#how-an-iterator-works" id="how-an-iterator-works">How an iterator works</a></h3>
<h3 id="how-an-iterator-works"><a class="header" href="#how-an-iterator-works">How an iterator works</a></h3>
<p>An iterator works by using a method called <code>.next()</code>, which gives an <code>Option</code>. When you use an iterator, Rust calls <code>next()</code> over and over again. If it gets <code>Some</code>, it keeps going. If it gets <code>None</code>, it stops.</p>
<p>Do you remember the <code>assert_eq!</code> macro? In documentation, you see it all the time. Here it is showing how an iterator works.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
@ -4791,7 +4791,7 @@ fn main() {
Demian - die Geschichte einer Jugend is found!
The Doom of the Darksword is found!
</code></pre>
<h2><a class="header" href="#closures" id="closures">Closures</a></h2>
<h2 id="closures"><a class="header" href="#closures">Closures</a></h2>
<p>Closures are like quick functions that don't need a name. Sometimes they are called lambdas. Closures are easy to find because they use <code>||</code> instead of <code>()</code>. They are very common in Rust, and once you learn to use them you will wonder how you lived without them.</p>
<p>You can bind a closure to a variable, and then it looks exactly like a function when you use it:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
@ -4977,7 +4977,7 @@ fn main() {
}
</code></pre></pre>
<p>This prints <code>140 399 923 481 800 622 623 218 009 598 281</code>.</p>
<h3><a class="header" href="#_-in-a-closure" id="_-in-a-closure">|_| in a closure</a></h3>
<h3 id="_-in-a-closure"><a class="header" href="#_-in-a-closure">|_| in a closure</a></h3>
<p>Sometimes you see <code>|_|</code> in a closure. This means that the closure needs an argument (like <code>x</code>), but you don't want to use it. So <code>|_|</code> means &quot;Okay, this closure takes an argument but I won't give it a name because I don't care about it&quot;.</p>
<p>Here is an example of an error when you don't do that:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
@ -5001,7 +5001,7 @@ fn main() {
28 | println!(&quot;{:?}&quot;, my_vec.iter().for_each(|_| println!(&quot;We didn't use the variables at all&quot;)));
</code></pre>
<p>This is good advice. If you change <code>||</code> to <code>|_|</code> then it will work.</p>
<h3><a class="header" href="#helpful-methods-for-closures-and-iterators" id="helpful-methods-for-closures-and-iterators">Helpful methods for closures and iterators</a></h3>
<h3 id="helpful-methods-for-closures-and-iterators"><a class="header" href="#helpful-methods-for-closures-and-iterators">Helpful methods for closures and iterators</a></h3>
<p>Rust becomes a very fun to language once you become comfortable with closures. With closures you can <em>chain</em> methods to each other and do a lot of things with very little code. Here are some closures and methods used with closures that we didn't see yet.</p>
<p><code>.filter()</code>: This lets you keep the items in an iterator that you want to keep. Let's filter the months of the year.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
@ -5543,7 +5543,7 @@ fn main() {
<pre><code class="language-text">Names { one_word: [&quot;Caesar&quot;, &quot;Data&quot;], two_words: [&quot;Frodo Baggins&quot;, &quot;Bilbo Baggins&quot;, &quot;Jean-Luc Picard&quot;, &quot;Rand Al\'Thor&quot;, &quot;Paul Atreides&quot;], three_words:
[&quot;Barack Hussein Obama&quot;, &quot;Bill Jefferson Clinton&quot;] }
</code></pre>
<h2><a class="header" href="#the-dbg-macro-and-inspect" id="the-dbg-macro-and-inspect">The dbg! macro and .inspect</a></h2>
<h2 id="the-dbg-macro-and-inspect"><a class="header" href="#the-dbg-macro-and-inspect">The dbg! macro and .inspect</a></h2>
<p><code>dbg!</code> is a very useful macro that prints quick information. It is a good alternative to <code>println!</code> because it is faster to type and gives more information:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let my_number = 8;
@ -5659,7 +5659,7 @@ The item is: 10
It is even.
In binary it is 1010.
</code></pre>
<h2><a class="header" href="#types-of-str" id="types-of-str">Types of &amp;str</a></h2>
<h2 id="types-of-str"><a class="header" href="#types-of-str">Types of &amp;str</a></h2>
<p>There is more than one type of <code>&amp;str</code>. We have:</p>
<ul>
<li>String literals: you make these when you write <code>let my_str = &quot;I am a &amp;str&quot;</code>. They last for the whole program, because they are written directly into the binary. They have the type <code>&amp;'static str</code>. <code>'</code> means its lifetime, and string literal have a lifetime called <code>static</code>.</li>
@ -5675,7 +5675,7 @@ fn main() {
}
</code></pre></pre>
<p>So what is a lifetime? We will learn that now.</p>
<h2><a class="header" href="#lifetimes" id="lifetimes">Lifetimes</a></h2>
<h2 id="lifetimes"><a class="header" href="#lifetimes">Lifetimes</a></h2>
<p>A lifetime means &quot;how long the variable lives&quot;. You only need to think about lifetimes with references. This is because references can't live longer than the object they come from. For example, this function does not work:</p>
<pre><pre class="playground"><code class="language-rust">fn returns_reference() -&gt; &amp;str {
let my_string = String::from(&quot;I am a string&quot;);
@ -5999,8 +5999,8 @@ fn main() {
Billy has 99980 hit points left!
</code></pre>
<p>So you can see that lifetimes are often just the compiler wanting to make sure. And it is usually smart enough to almost guess at what lifetimes you want, and just needs you to tell it so it can be certain.</p>
<h2><a class="header" href="#interior-mutability" id="interior-mutability">Interior mutability</a></h2>
<h3><a class="header" href="#cell" id="cell">Cell</a></h3>
<h2 id="interior-mutability"><a class="header" href="#interior-mutability">Interior mutability</a></h2>
<h3 id="cell"><a class="header" href="#cell">Cell</a></h3>
<p><strong>Interior mutability</strong> means having a little bit of mutability on the inside. Remember how in Rust you need to use <code>mut</code> to change a variable? There are also some ways to change them without the word <code>mut</code>. This is because Rust has some ways to let you safely change values inside of a struct that is immutable. Each one of them follows some rules that make sure that changing the values is still safe.</p>
<p>First, let's look at a simple example where we would want this. Imagine a <code>struct</code> called <code>PhoneModel</code> with many fields:</p>
<pre><pre class="playground"><code class="language-rust">struct PhoneModel {
@ -6056,7 +6056,7 @@ fn main() {
</code></pre></pre>
<p><code>Cell</code> works for all types, but works best for simple Copy types because it gives values, not references. <code>Cell</code> has a method called <code>get()</code> for example that only works on Copy types.</p>
<p>Another type you can use is <code>RefCell</code>.</p>
<h3><a class="header" href="#refcell" id="refcell">RefCell</a></h3>
<h3 id="refcell"><a class="header" href="#refcell">RefCell</a></h3>
<p>A <code>RefCell</code> is another way to change values without needing to declare <code>mut</code>. It means &quot;reference cell&quot;, and is like a <code>Cell</code> but uses references instead of copies.</p>
<p>We will create a <code>User</code> struct. So far you can see that it is similar to <code>Cell</code>:</p>
<pre><pre class="playground"><code class="language-rust">use std::cell::RefCell;
@ -6140,7 +6140,7 @@ note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
error: process didn't exit successfully: `target\debug\rust_book.exe` (exit code: 101)
</code></pre>
<p><code>already borrowed: BorrowMutError</code> is the important part. So when you use a <code>RefCell</code>, it is good to compile <strong>and</strong> run to check.</p>
<h3><a class="header" href="#mutex" id="mutex">Mutex</a></h3>
<h3 id="mutex"><a class="header" href="#mutex">Mutex</a></h3>
<p><code>Mutex</code> is another way to change values without declaring <code>mut</code>. Mutex means <code>mutual exclusion</code>, which means &quot;only one at a time&quot;. This is why a <code>Mutex</code> is safe, because it only lets one process change it at a time. To do this, it uses <code>.lock()</code>. <code>Lock</code> is like locking a door from the inside. You go into a room, lock the door, and now you can change things inside the room. Nobody else can come in and stop you, because you locked the door.</p>
<p>A <code>Mutex</code> is easier to understand through examples.</p>
<pre><pre class="playground"><code class="language-rust">use std::sync::Mutex;
@ -6242,7 +6242,7 @@ fn main() {
println!(&quot;{:?}&quot;, my_mutex);
}
</code></pre></pre>
<h3><a class="header" href="#rwlock" id="rwlock">RwLock</a></h3>
<h3 id="rwlock"><a class="header" href="#rwlock">RwLock</a></h3>
<p><code>RwLock</code> means &quot;read write lock&quot;. It is like a <code>Mutex</code> but also like a <code>RefCell</code>. You use <code>.write().unwrap()</code> instead of <code>.lock().unwrap()</code> to change it. But you can also use <code>.read().unwrap()</code> to get read access. It is like <code>RefCell</code> because it follows the rules:</p>
<ul>
<li>many <code>.read()</code> variables is okay,</li>
@ -6301,7 +6301,7 @@ fn main() {
};
}
</code></pre></pre>
<h2><a class="header" href="#cow" id="cow">Cow</a></h2>
<h2 id="cow"><a class="header" href="#cow">Cow</a></h2>
<p>Cow is a very convenient enum. It means &quot;clone on write&quot; and lets you return a <code>&amp;str</code> if you don't need a <code>String</code>, and a <code>String</code> if you need it. (It can also do the same with arrays vs. Vecs, etc.)</p>
<p>To understand it, let's look at the signature. It says:</p>
<pre><pre class="playground"><code class="language-rust">pub enum Cow&lt;'a, B&gt;
@ -6348,7 +6348,7 @@ fn main() {
6 went in. The Cow is borrowed with this message: Remainder is 0
</code></pre>
<p><code>Cow</code> has some other methods like <code>into_owned</code> or <code>into_borrowed</code> so you can change it if you need to.</p>
<h2><a class="header" href="#type-aliases" id="type-aliases">Type aliases</a></h2>
<h2 id="type-aliases"><a class="header" href="#type-aliases">Type aliases</a></h2>
<p>A type alias means &quot;giving a new name to another type&quot;. Type aliases are very easy. Usually you use them when you have a very long type and don't want to write it every time. It is also good when you want to give a type a better name that is easy to remember. Here are two examples of type aliases.</p>
<p>Here is a type that is not difficult, but you want to make your code easier to understand for other people (or for you):</p>
<pre><pre class="playground"><code class="language-rust">type CharacterVec = Vec&lt;char&gt;;
@ -6419,7 +6419,7 @@ fn main() {
println!(&quot;{}&quot;, my_file.0 == my_string); // my_file.0 is a String, so this prints true
}
</code></pre></pre>
<h3><a class="header" href="#importing-and-renaming-inside-a-function" id="importing-and-renaming-inside-a-function">Importing and renaming inside a function</a></h3>
<h3 id="importing-and-renaming-inside-a-function"><a class="header" href="#importing-and-renaming-inside-a-function">Importing and renaming inside a function</a></h3>
<p>Usually you write <code>use</code> at the top of the program, like this:</p>
<pre><pre class="playground"><code class="language-rust">use std::cell::{Cell, RefCell};
@ -6511,7 +6511,7 @@ fn give_filestate(input: &amp;FileState) {
fn main() {}
</code></pre></pre>
<p>So now you can write <code>OtherDirectory</code> instead of <code>FileState::SimilarFileNameInNextDirectory</code>.</p>
<h2><a class="header" href="#the-todo-macro" id="the-todo-macro">The todo! macro</a></h2>
<h2 id="the-todo-macro"><a class="header" href="#the-todo-macro">The todo! macro</a></h2>
<p>Sometimes you want to write code in general to help you imagine your project. For example, imagine a simple project to do something with books. Here's what you think as you write it:</p>
<pre><pre class="playground"><code class="language-rust">struct Book {} // Okay, first I need a book struct.
// Nothing in there yet - will add later
@ -6592,7 +6592,7 @@ fn main() {}
| ^^^^^^^^^^^^^^ not found in this scope
</code></pre>
<p><code>todo!()</code> is actually the same as another macro: <code>unimplemented!()</code>. Programmers were using <code>unimplemented!()</code> a lot but it was long to type, so they created <code>todo!()</code> which is shorter.</p>
<h2><a class="header" href="#rc" id="rc">Rc</a></h2>
<h2 id="rc"><a class="header" href="#rc">Rc</a></h2>
<p>Rc means &quot;reference counter&quot;. You know that in Rust, every variable can only have one owner. That is why this doesn't work:</p>
<pre><pre class="playground"><code class="language-rust">fn takes_a_string(input: String) {
println!(&quot;It is: {}&quot;, input)
@ -6713,7 +6713,7 @@ fn main() {
</code></pre></pre>
<p>This prints <code>2</code>. And <code>new_owner</code> is now an <code>Rc&lt;String&gt;</code>. Now if we use <code>println!(&quot;{}&quot;, Rc::strong_count(&amp;calgary.city_history));</code>, we get <code>3</code>.</p>
<p>So if there are strong pointers, are there weak pointers? Yes, there are. Weak pointers are useful because if two <code>Rc</code>s point at each other, they can't die. This is called a &quot;reference cycle&quot;. If item 1 has an Rc to item 2, and item 2 has an Rc to item 1, they can't get to 0. In this case you want to use weak references. Then <code>Rc</code> will count the references, but if it only has weak references then it can die. You use <code>Rc::downgrade(&amp;item)</code> instead of <code>Rc::clone(&amp;item)</code> to make weak references. Also, you use <code>Rc::weak_count(&amp;item)</code> to see the weak count.</p>
<h2><a class="header" href="#multiple-threads" id="multiple-threads">Multiple threads</a></h2>
<h2 id="multiple-threads"><a class="header" href="#multiple-threads">Multiple threads</a></h2>
<p>If you use multiple threads, you can do many things at the same time. Modern computers have more than one core so they can do more than one thing at the same time, and Rust lets you use them. Rust uses threads that are called &quot;OS threads&quot;. OS thread means the operating system creates the thread on a different core. (Some other languages use &quot;green threads&quot;, which are less powerful)</p>
<p>You create threads with <code>std::thread::spawn</code> and then a closure to tell it what to do. Threads are interesting because they run at the same time, and you can test it to see what happens. Here is a simple example:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
@ -6898,7 +6898,7 @@ help: to force the closure to take ownership of `my_string` (and any other refer
}
</code></pre></pre>
<p>So just remember: if you need a value in a thread from outside the thread, you need to use <code>move</code>.</p>
<h2><a class="header" href="#closures-in-functions" id="closures-in-functions">Closures in functions</a></h2>
<h2 id="closures-in-functions"><a class="header" href="#closures-in-functions">Closures in functions</a></h2>
<p>Closures are great. So how do we put them into our own functions?</p>
<p>You can make your own functions that take closures, but inside them it is less free and you have to decide the type. Outside a function a closure can decide by itself between <code>Fn</code>, <code>FnMut</code> and <code>FnOnce</code>, but inside you have to choose one. The best way to understand is to look at a few function signatures. Here is the one for <code>.all()</code>. We remember that it checks an iterator to see if everything is <code>true</code> (depending on what you decide is <code>true</code> or <code>false</code>). Part of its signature says this:</p>
<pre><pre class="playground"><code class="language-rust">
@ -7026,7 +7026,7 @@ Going to delete 1834 at position 1 now.
Years left are [1372, 1851, 1881, 1897, 1925, 1959, 1989, 2000, 2005, 2010, 2020, 2030]
Populations left are [3250, 24000, 45900, 58800, 119800, 283071, 478974, 400378, 401694, 406703, 437619, 500000]
</code></pre>
<h2><a class="header" href="#impl-trait" id="impl-trait">impl Trait</a></h2>
<h2 id="impl-trait"><a class="header" href="#impl-trait">impl Trait</a></h2>
<p><code>impl Trait</code> is similar to generics. You remember that generics use a type <code>T</code> (or any other name) which then gets decided when the program compiles. First let's look at a concrete type:</p>
<pre><pre class="playground"><code class="language-rust">fn gives_higher_i32(one: i32, two: i32) {
let higher = if one &gt; two { one } else { two };
@ -7173,7 +7173,7 @@ Your fear is now 14
The morning sun has vanquished the horrible night. You no longer feel afraid.
Your fear is now 7
</code></pre>
<h2><a class="header" href="#arc" id="arc">Arc</a></h2>
<h2 id="arc"><a class="header" href="#arc">Arc</a></h2>
<p>You remember that we used an <code>Rc</code> to give a variable more than one owner. If we are doing the same thing in a thread, we need an <code>Arc</code>. <code>Arc</code> means &quot;atomic reference counter&quot;. Atomic means that it uses the computer's processor so that data only gets written once each time. This is important because if two threads write data at the same time, you will get the wrong result. For example, imagine if you could do this in Rust:</p>
<pre><pre class="playground"><code class="language-rust">
<span class="boring">#![allow(unused)]
@ -7373,7 +7373,7 @@ fn main() {
println!(&quot;{:?}&quot;, my_number);
}
</code></pre></pre>
<h2><a class="header" href="#channels" id="channels">Channels</a></h2>
<h2 id="channels"><a class="header" href="#channels">Channels</a></h2>
<p>A channel is an easy way to use many threads that send to one place. They are fairly popular because they are pretty simple to put together. You can create a channel in Rust with <code>std::sync::mpsc</code>. <code>mpsc</code> means &quot;multiple producer, single consumer&quot;, so &quot;many threads sending to one place&quot;. To start a channel, you use <code>channel()</code>. This creates a <code>Sender</code> and a <code>Receiver</code> that are tied together. You can see this in the function signature:</p>
<pre><pre class="playground"><code class="language-rust">
<span class="boring">#![allow(unused)]
@ -7525,9 +7525,9 @@ fn main() {
}
</code></pre></pre>
<p>If you print this you can see 1000 number 1s.</p>
<h2><a class="header" href="#reading-rust-documentation" id="reading-rust-documentation">Reading Rust documentation</a></h2>
<h2 id="reading-rust-documentation"><a class="header" href="#reading-rust-documentation">Reading Rust documentation</a></h2>
<p>It's important to know how to read documentation in Rust so you can understand what other people wrote. Here are some things to know in Rust documentation:</p>
<h3><a class="header" href="#assert_eq" id="assert_eq">assert_eq!</a></h3>
<h3 id="assert_eq"><a class="header" href="#assert_eq">assert_eq!</a></h3>
<p>You saw that <code>assert_eq!</code> is used when doing testing. You put two items inside the function and the program will panic if they are not equal. Here is a simple example where we need an even number.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
prints_number(56);
@ -7585,9 +7585,9 @@ fn prints_number(input: i32) {
assert_eq!(vec, [7, 1, 2, 3]); // &quot;The vec now has [7, 1, 2, 3]&quot;
}
</code></pre></pre>
<h3><a class="header" href="#searching" id="searching">Searching</a></h3>
<h3 id="searching"><a class="header" href="#searching">Searching</a></h3>
<p>The top bar of a Rust document is the search bar. It shows you results as you type. When you go down a page you can't see the search bar anymore, but if you press the <strong>s</strong> key on the keyboard you can search again. So pressing <strong>s</strong> anywhere lets you search right away.</p>
<h3><a class="header" href="#src-button" id="src-button">[src] button</a></h3>
<h3 id="src-button"><a class="header" href="#src-button">[src] button</a></h3>
<p>Usually the code for a method, struct, etc. will not be complete. This is because you don't usually need to see the full source to know how it works, and the full code can be confusing. But if you want to know more, you can click on [src] and see everything. For example, on the page for <code>String</code> you can see this signature for <code>.with_capacity()</code>:</p>
<pre><pre class="playground"><code class="language-rust">
<span class="boring">#![allow(unused)]
@ -7607,9 +7607,9 @@ pub fn with_capacity(capacity: usize) -&gt; String {
<span class="boring">}
</span></code></pre></pre>
<p>Interesting! Now you can see that a String is a kind of <code>Vec</code>. And actually a <code>String</code> is a vector of <code>u8</code> bytes, which is interesting to know. You didn't need to know that to use the <code>with_capacity</code> method so you only see it if you click [src]. So clicking on [src] is a good idea if the document doesn't have much detail and you want to know more.</p>
<h3><a class="header" href="#information-on-traits" id="information-on-traits">Information on traits</a></h3>
<h3 id="information-on-traits"><a class="header" href="#information-on-traits">Information on traits</a></h3>
<p>The important part of the documentation for a trait is &quot;Required Methods&quot; on the left. If you see Required Methods, it probably means that you have to write the method yourself. For example, for <code>Iterator</code> you need to write the <code>.next()</code> method. And for <code>From</code> you need to write the <code>.from()</code> method. But some traits can be implemented with just an <strong>attribute</strong>, like we see in <code>#[derive(Debug)]</code>. <code>Debug</code> needs the <code>.fmt()</code> method, but usually you just use <code>#[derive(Debug)]</code> unless you want to do it yourself. That's why the page on <code>std::fmt::Debug</code> says that &quot;Generally speaking, you should just derive a Debug implementation.&quot;</p>
<h2><a class="header" href="#attributes" id="attributes">Attributes</a></h2>
<h2 id="attributes"><a class="header" href="#attributes">Attributes</a></h2>
<p>You have seen code like <code>#[derive(Debug)]</code> before: this type of code is called an <em>attribute</em>. These attributes are small pieces of code that give information to the compiler. They are not easy to create, but they are very easy to use. If you write an attribute with just <code>#</code> then it will affect the code on the next line. But if you write it with <code>#!</code> then it will affect everything in its own space.</p>
<p>Here are some attributes you will see a lot:</p>
<p><code>#[allow(dead_code)]</code> and <code>#[allow(unused_variables)]</code>. If you write code that you don't use, Rust will still compile but it will let you know. For example, here is a struct with nothing in it and one variable. We don't use either of them.</p>
@ -7719,7 +7719,7 @@ fn main() {
<p>One other example using <code>cfg</code> is <code>#[cfg(target_os = &quot;windows&quot;)]</code>. With that you can tell the compiler to only run the code on Windows, or Linux, or anything else.</p>
<p><code>#![no_std]</code> is an interesting attribute that tells Rust not to bring in the standard library. That means you don't have <code>Vec</code>, <code>String</code>, and anything else in the standard library. You will see this in code for small devices that don't have much memory or space.</p>
<p>You can see many more attributes <a href="https://doc.rust-lang.org/reference/attributes.html">here</a>.</p>
<h2><a class="header" href="#box" id="box">Box</a></h2>
<h2 id="box"><a class="header" href="#box">Box</a></h2>
<p><code>Box</code> is a very convenient type in Rust. When you use a <code>Box</code>, you can put a type on the heap instead of the stack. To make a new <code>Box</code>, just use <code>Box::new()</code> and put the item inside.</p>
<pre><pre class="playground"><code class="language-rust">fn just_takes_a_variable&lt;T&gt;(item: T) {} // Takes anything and drops it.
@ -7787,7 +7787,7 @@ fn main() {
</code></pre></pre>
<p>Even without data it is a bit complicated, and Rust does not use this type of pattern very much. This is because Rust has strict rules on borrowing and ownership, as you know. But if you want to start a list like this (a linked list), <code>Box</code> can help.</p>
<p>A <code>Box</code> also lets you use <code>std::mem::drop</code> on it, because it's on the heap. That can be convenient sometimes.</p>
<h2><a class="header" href="#box-around-traits" id="box-around-traits">Box around traits</a></h2>
<h2 id="box-around-traits"><a class="header" href="#box-around-traits">Box around traits</a></h2>
<p><code>Box</code> is very useful for returning traits. You know that you can write traits in generic functions like in this example:</p>
<pre><pre class="playground"><code class="language-rust">use std::fmt::Display;
@ -7959,7 +7959,7 @@ fn returns_errors(input: u8) -&gt; Result&lt;String, Error&gt; {
| ^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
</code></pre>
<p>This is not surprising, because we know that a trait can work on many things, and they each have different sizes.</p>
<h2><a class="header" href="#default-and-the-builder-pattern" id="default-and-the-builder-pattern">Default and the builder pattern</a></h2>
<h2 id="default-and-the-builder-pattern"><a class="header" href="#default-and-the-builder-pattern">Default and the builder pattern</a></h2>
<p>You can implement the <code>Default</code> trait to give values to a <code>struct</code> or <code>enum</code> that you think will be most common. The builder pattern works nicely with this to let users easily make changes when they want. First let's look at <code>Default</code>. Actually, most general types in Rust already have <code>Default</code>. They are not surprising: 0, &quot;&quot; (empty strings), <code>false</code>, etc.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let default_i8: i8 = Default::default();
@ -8377,7 +8377,7 @@ Could not create character. Characters must have:
Character { name: &quot;Billybrobby&quot;, age: 15, height: 180, weight: 100, lifestate: Alive, can_use: true }
</code></pre>
<h2><a class="header" href="#deref-and-derefmut" id="deref-and-derefmut">Deref and DerefMut</a></h2>
<h2 id="deref-and-derefmut"><a class="header" href="#deref-and-derefmut">Deref and DerefMut</a></h2>
<p><code>Deref</code> is the trait that lets you use <code>*</code> to dereference something. We know that a reference is not the same as a value:</p>
<pre><pre class="playground"><code class="language-rust">// ⚠️
fn main() {
@ -8655,7 +8655,7 @@ fn main() {
</code></pre></pre>
<p>This just prints <code>[5, 5]</code>. Our code is now very strange for someone to read. We can read <code>Deref</code> just above <code>main()</code> and figure out that <code>*billy</code> means <code>i8</code>, but what if there was a lot of code? Maybe our code is 2000 lines long, and suddenly we have to figure out why we are <code>.push()</code>ing <code>*billy</code>. <code>Character</code> is certainly more than just a smart pointer for <code>i8</code>.</p>
<p>Of course, it is not illegal to write <code>hit_points_vec.push(*billy)</code>, but it makes the code look very strange. Probably a simple <code>.get_hp()</code> method would be much better, or another struct that holds the characters. Then you could iterate through and push the <code>hit_points</code> for each one. <code>Deref</code> gives a lot of power but it's good to make sure that the code is logical.</p>
<h2><a class="header" href="#crates-and-modules" id="crates-and-modules">Crates and modules</a></h2>
<h2 id="crates-and-modules"><a class="header" href="#crates-and-modules">Crates and modules</a></h2>
<p>Every time you write code in Rust, you are writing it in a <code>crate</code>. A <code>crate</code> is the file, or files, that go together for your code. Inside the file you write you can also make a <code>mod</code>. A <code>mod</code> is a space for functions, structs, etc. and is used for a few reasons:</p>
<ul>
<li>Building your code: it helps you think about the general structure of your code. This can be important as your code gets larger and larger.</li>
@ -8836,7 +8836,7 @@ fn main() {
print_city(&quot;Korea&quot;, &quot;Gyeonggi-do&quot;, &quot;Gwangju&quot;); // Now it's less work to use it again
}
</code></pre></pre>
<h2><a class="header" href="#testing" id="testing">Testing</a></h2>
<h2 id="testing"><a class="header" href="#testing">Testing</a></h2>
<p>Testing is a good subject to learn now that we understand modules. Testing your code is very easy in Rust, because you can write tests right next to your code.</p>
<p>The easiest way to start testing is to add <code>#[test]</code> above a function. Here is a simple one:</p>
<pre><pre class="playground"><code class="language-rust">
@ -8998,7 +8998,7 @@ mod tests {
}
<span class="boring">}
</span></code></pre></pre>
<h3><a class="header" href="#test-driven-development" id="test-driven-development">Test-driven development</a></h3>
<h3 id="test-driven-development"><a class="header" href="#test-driven-development">Test-driven development</a></h3>
<p>You might see the words &quot;test-driven development&quot; when reading about Rust or another language. It's one way to write programs, and some people like it while others prefer something else. &quot;Test-driven development&quot; means &quot;writing tests first, then writing the code&quot;. When you do this, you will have a lot of tests for everything you want your code to do. Then you start writing the code, and run the tests to see if you did it right. Then the tests are always there to show you if something goes wrong when you add to and rewrite your code. This is pretty easy in Rust because the compiler gives a lot of information about what to fix. Let's write a small example of test-driven development and see what it looks like.</p>
<p>Let's imagine a calculator that takes user input. It can add (+) and it can subtract (-). If the user writes &quot;5 + 6&quot; it should return 11, if the user writes &quot;5 + 6 - 7&quot; it should return 4, and so on. So we'll start with test functions. You can also see that function names in tests are usually quite long. That is because you might run a lot of tests, and you want to understand which tests have failed.</p>
<p>We'll imagine that a single function called <code>math()</code> will do everything. It will return an <code>i32</code> (we won't use floats). Because it needs to return something, we'll just return <code>6</code> every time. Then we will write three test functions. They will all fail, of course. Now the code looks like this:</p>
@ -9493,7 +9493,7 @@ mod tests {
<span class="boring">}
</span></code></pre></pre>
<p>This is probably good enough for now. We could write more methods but lines like <code>calculator.results.push(calculator.current_input.clone());</code> are already very clear. Refactoring is best when you can still easily read the code after you are done. You don't want to just refactor to make the code short: <code>clc.clr()</code> is much worse than <code>calculator.clear()</code>, for example.</p>
<h2><a class="header" href="#external-crates" id="external-crates">External crates</a></h2>
<h2 id="external-crates"><a class="header" href="#external-crates">External crates</a></h2>
<p>An external crate means &quot;someone else's crate&quot;.</p>
<p>For this section you <em>almost</em> need to install Rust, but we can still use just the Playground. Now we are going to learn how to import crates that other people have written. This is important in Rust because of two reasons:</p>
<ul>
@ -9503,7 +9503,7 @@ mod tests {
<p>That means that it is normal in Rust to bring in an external crate for a lot of basic functions. The idea is that if it is easy to use external crates, then you can choose the best one. Maybe one person will make a crate for one function, and then someone else will make a better one.</p>
<p>In this book we will only look at the most popular crates, the crates that everyone who uses Rust knows.</p>
<p>To begin learning external crates, we will start with the most common one: <code>rand</code>.</p>
<h3><a class="header" href="#rand" id="rand">rand</a></h3>
<h3 id="rand"><a class="header" href="#rand">rand</a></h3>
<p>Did you notice that we didn't use any random numbers yet? That's because random numbers aren't in the standard library. But there are a lot of crates that are &quot;almost standard library&quot; because everybody uses them. In any case, it's very easy to bring in a crate. If you have Rust on your computer, there is a file called <code>Cargo.toml</code> that has this information. A <code>Cargo.toml</code> file looks like this when you start:</p>
<pre><code class="language-text">[package]
name = &quot;rust_book&quot;
@ -9674,7 +9674,7 @@ charisma: 10
<span class="boring">}
</span></code></pre></pre>
<p>The character with four dice is usually a bit better at most things.</p>
<h3><a class="header" href="#rayon" id="rayon">rayon</a></h3>
<h3 id="rayon"><a class="header" href="#rayon">rayon</a></h3>
<p><code>rayon</code> is a popular crate that lets you speed up your Rust code. It's popular because it creates threads without needing things like <code>thread::spawn</code>. In other words, it is popular because it is effective but easy to write. For example:</p>
<ul>
<li><code>.iter()</code>, <code>.iter_mut()</code>, <code>into_iter()</code> in rayon is written like this:</li>
@ -9698,7 +9698,7 @@ fn main() {
}
</code></pre></pre>
<p>And that's it. <code>rayon</code> has many other methods to customize what you want to do, but at its most simple it is just &quot;add <code>_par</code> to make your program faster&quot;.</p>
<h3><a class="header" href="#serde" id="serde">serde</a></h3>
<h3 id="serde"><a class="header" href="#serde">serde</a></h3>
<p><code>serde</code> is a popular crate that lets you convert to and from formats like JSON, YAML, etc. The most common way to use it is by creating a <code>struct</code> with two attributes on top. <a href="https://serde.rs/">It looks like this</a>:</p>
<pre><pre class="playground"><code class="language-rust">
<span class="boring">#![allow(unused)]
@ -9711,13 +9711,13 @@ struct Point {
<span class="boring">}
</span></code></pre></pre>
<p>The <code>Serialize</code> and <code>Deserialize</code> traits are what make the conversion easy. (That's also where the name <code>serde</code> comes from) If you have them on your struct, then you can just call a method to turn it into and from JSON or anything else.</p>
<h3><a class="header" href="#regex" id="regex">regex</a></h3>
<h3 id="regex"><a class="header" href="#regex">regex</a></h3>
<p>The <a href="https://crates.io/crates/regex">regex</a> crate lets you search through text using <a href="https://en.wikipedia.org/wiki/Regular_expression">regular expressions</a>. With that you can get matches for something like <code>colour</code>, <code>color</code>, <code>colours</code> and <code>colors</code> through a single search. Regular expressions are a whole other language have to learn that too if you want to use them.</p>
<h3><a class="header" href="#chrono" id="chrono">chrono</a></h3>
<h3 id="chrono"><a class="header" href="#chrono">chrono</a></h3>
<p><a href="https://crates.io/crates/chrono">chrono</a> is the main crate for people who need more functionality for time. We will look at the standard library now which has functions for time, but if you need more then this is a good crate to use.</p>
<h2><a class="header" href="#a-tour-of-the-standard-library" id="a-tour-of-the-standard-library">A tour of the standard library</a></h2>
<h2 id="a-tour-of-the-standard-library"><a class="header" href="#a-tour-of-the-standard-library">A tour of the standard library</a></h2>
<p>Now that you know a lot of Rust, you will be able to understand most things inside the standard library. The code inside it isn't so scary anymore. Let's take a look at some of the parts in it that we haven't learned yet. This tour will go over most parts of the standard library that you don't need to install Rust for. We will revisit a lot of items we already know so we can learn them with greater understanding.</p>
<h3><a class="header" href="#arrays-1" id="arrays-1">Arrays</a></h3>
<h3 id="arrays-1"><a class="header" href="#arrays-1">Arrays</a></h3>
<p>One thing about arrays to note is that they don't implement <code>Iterator.</code>. That means that if you have an array, you can't use <code>for</code>. But you can use methods like <code>.iter()</code> on them. Or you can use <code>&amp;</code> to get a slice. Actually, the compiler will tell you exactly that if you try to use <code>for</code>:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
// ⚠️
@ -9762,7 +9762,7 @@ Nicosia
}
</code></pre></pre>
<p>This prints <code>Beirut</code>.</p>
<h3><a class="header" href="#char" id="char">char</a></h3>
<h3 id="char"><a class="header" href="#char">char</a></h3>
<p>You can use the <code>.escape_unicode()</code> method to get the Unicode number for a <code>char</code>:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let korean_word = &quot;청춘예찬&quot;;
@ -9806,7 +9806,7 @@ fn main() {
</code></pre>
<p>So it's a good thing you need to use <code>TryFrom</code>.</p>
<p>Also, as of late August 2020 you can now get a <code>String</code> from a <code>char</code>. (<code>String</code> implements <code>From&lt;char&gt;</code>) Just write <code>String::from()</code> and put a <code>char</code> inside.</p>
<h3><a class="header" href="#integers" id="integers">Integers</a></h3>
<h3 id="integers"><a class="header" href="#integers">Integers</a></h3>
<p>There are a lot of math methods for these types, plus some others. Here are some of the most useful ones.</p>
<p><code>.checked_add()</code>, <code>.checked_sub()</code>, <code>.checked_mul()</code>, <code>.checked_div()</code>. These are good methods if you think you might get a number that won't fit into a type. They return an <code>Option</code> so you can safely check that your math works without making the program panic.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
@ -9909,7 +9909,7 @@ In Nauru and Vanuatu and Micronesia are 422953 people and a GDP of $1347000000
</code></pre>
<p>Later on in this code we could change <code>.fmt()</code> to display a number that is easier to read.</p>
<p>The three others are called <code>Sub</code>, <code>Mul</code>, and <code>Div</code>, and they are basically the same to implement. For <code>+=</code>, <code>-=</code>, <code>*=</code> and <code>/=</code>, just add <code>Assign</code>: <code>AddAssign</code>, <code>SubAssign</code>, <code>MulAssign</code>, and <code>DivAssign</code>. You can see the full list <a href="https://doc.rust-lang.org/std/ops/index.html#structs">here</a>, because there are many more. <code>%</code> for example is called <code>Rem</code>, <code>-</code> is called <code>Neg</code>, and so on.</p>
<h3><a class="header" href="#floats-1" id="floats-1">Floats</a></h3>
<h3 id="floats-1"><a class="header" href="#floats-1">Floats</a></h3>
<p><code>f32</code> and <code>f64</code> have a very large number of methods that you use when doing math. We won't look at those, but here are some methods that you might use. They are: <code>.floor()</code>, <code>.ceil()</code>, <code>.round()</code>, and <code>.trunc()</code>. All of these return an <code>f32</code> or <code>f64</code> that is like an integer, with only <code>0</code> after the period. They do this:</p>
<ul>
<li><code>.floor()</code>: gives you the next lowest integer.</li>
@ -9973,7 +9973,7 @@ truncated: -19
println!(&quot;{}, {}&quot;, maximum, minimum);
}
</code></pre></pre>
<h3><a class="header" href="#bool" id="bool">bool</a></h3>
<h3 id="bool"><a class="header" href="#bool">bool</a></h3>
<p>In Rust you can turn a <code>bool</code> into an integer if you want, because it's safe to do that. But you can't do it the other way around. As you can see, <code>true</code> turns to 1 and <code>false</code> turns to 0.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let true_false = (true, false);
@ -9987,7 +9987,7 @@ truncated: -19
}
</code></pre></pre>
<p>This prints the same thing.</p>
<h3><a class="header" href="#vec" id="vec">Vec</a></h3>
<h3 id="vec"><a class="header" href="#vec">Vec</a></h3>
<p>Vec has a lot of methods that we haven't looked at yet. Let's start with <code>.sort()</code>. <code>.sort()</code> is not surprising at all. It uses a <code>&amp;mut self</code> to sort a vector.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let mut my_vec = vec![100, 90, 80, 0, 0, 0, 0, 0];
@ -10013,7 +10013,7 @@ truncated: -19
}
</code></pre></pre>
<p>Result: <code>[&quot;moon&quot;, &quot;sun&quot;]</code>.</p>
<h3><a class="header" href="#string" id="string">String</a></h3>
<h3 id="string"><a class="header" href="#string">String</a></h3>
<p>You will remember that a <code>String</code> is kind of like a <code>Vec</code>. It is so like a <code>Vec</code> that you can do a lot of the same methods. For example, you can start one with <code>String::with_capacity()</code>. You want that if you are always going to be pushing a <code>char</code> with <code>.push()</code> or pushing a <code>&amp;str</code> with <code>.push_str()</code>. Here's an example of a <code>String</code> that has too many allocations.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let mut push_string = String::new();
@ -10110,7 +10110,7 @@ truncated: -19
<p>This prints:</p>
<pre><code class="language-text">[src\main.rs:4] my_string = &quot;Age Height Weight &quot;
</code></pre>
<h3><a class="header" href="#osstring-and-cstring" id="osstring-and-cstring">OsString and CString</a></h3>
<h3 id="osstring-and-cstring"><a class="header" href="#osstring-and-cstring">OsString and CString</a></h3>
<p><code>std::ffi</code> is the part of <code>std</code> that helps you use Rust with other languages or operating systems. It has types like <code>OsString</code> and <code>CString</code>, which are like <code>String</code> for the operating system or <code>String</code> for the language C. They each have their own <code>&amp;str</code> type too: <code>OsStr</code> and <code>CStr</code>. <code>ffi</code> means &quot;foreign function interface&quot;.</p>
<p>You can use <code>OsString</code> when you have to work with an operating system that doesn't have Unicode. All Rust strings are unicode, but not every operating system has it. Here is the simple English explanation from the standard library on why we have <code>OsString</code>:</p>
<ul>
@ -10153,7 +10153,7 @@ error[E0599]: no method named `occg` found for struct `std::ffi::OsString` in th
| ^^^^ method not found in `std::ffi::OsString`
</code></pre>
<p>We can see that the type of <code>valid</code> is <code>String</code> and the type of <code>not_valid</code> is <code>OsString</code>.</p>
<h3><a class="header" href="#mem" id="mem">mem</a></h3>
<h3 id="mem"><a class="header" href="#mem">mem</a></h3>
<p><code>std::mem</code> has some pretty interesting methods. We saw some of them already, such as <code>.size_of()</code>, <code>.size_of_val()</code> and <code>.drop()</code>:</p>
<pre><pre class="playground"><code class="language-rust">use std::mem;
@ -10369,7 +10369,7 @@ The robber has $150 right now.
There is $4900 in the back and $50 at the desk.
</code></pre>
<p>You can see that there is always $50 at the desk.</p>
<h3><a class="header" href="#prelude" id="prelude">prelude</a></h3>
<h3 id="prelude"><a class="header" href="#prelude">prelude</a></h3>
<p>The standard library has a prelude too, which is why you don't have to write things like <code>use std::vec::Vec</code> to create a <code>Vec</code>. You can see all the items <a href="https://doc.rust-lang.org/std/prelude/index.html#prelude-contents">here</a>, and will already know almost all of them:</p>
<ul>
<li><code>std::marker::{Copy, Send, Sized, Sync, Unpin}</code>. You haven't seen <code>Unpin</code> before, because it is used for almost every type (like <code>Sized</code>, which is also very common). To &quot;pin&quot; means to not let something move. In this case a <code>Pin</code> means that it can't move in memory, but most items have <code>Unpin</code> so you can. That's why functions like <code>std::mem::replace</code> work, because they aren't pinned.</li>
@ -10441,7 +10441,7 @@ fn main() {
<span class="boring">}
</span></code></pre></pre>
<p>and then <code>use</code> statements for the mods, traits, etc. that you wanted to use. But the Rust compiler now doesn't need this help anymore - you can just use <code>use</code> and it knows where to find it. So you almost never need <code>extern crate</code> anymore, but in other people's Rust code you might still see it on the top.</p>
<h3><a class="header" href="#time" id="time">time</a></h3>
<h3 id="time"><a class="header" href="#time">time</a></h3>
<p><code>std::time</code> is where you can get functions for time. (If you want even more functions, a crate like <code>chrono</code> can work.) The simplest function is just getting the system time with <code>Instant::now()</code>.</p>
<pre><pre class="playground"><code class="language-rust">use std::time::Instant;
@ -10545,7 +10545,7 @@ fn main() {
Did I miss anything?
</code></pre>
<p>but the thread will do nothing for three seconds. You usually use <code>.sleep()</code> when you have many threads that need to try something a lot, like connecting. You don't want the thread to use your processor to try 100,000 times in a second when you just want it to check sometimes. So then you can set a <code>Duration</code>, and it will try to do its task every time it wakes up.</p>
<h3><a class="header" href="#other-macros" id="other-macros">Other macros</a></h3>
<h3 id="other-macros"><a class="header" href="#other-macros">Other macros</a></h3>
<p>Let's take a look at some other macros.</p>
<p><code>unreachable!()</code></p>
<p>This macro is kind of like <code>todo!()</code> except it's for code that you will never do. Maybe you have a <code>match</code> in an enum that you know will never choose one of the arms, so the code can never be reached. If that's so, you can write <code>unreachable!()</code> so the compiler knows that it can ignore that part.</p>
@ -10697,7 +10697,7 @@ test testing::check_if_five ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
</code></pre>
<h2><a class="header" href="#writing-macros" id="writing-macros">Writing macros</a></h2>
<h2 id="writing-macros"><a class="header" href="#writing-macros">Writing macros</a></h2>
<p>Writing macros can be very complicated. You almost never need to write one, but sometimes you might want to because they are very convenient. Writing macros is interesting because they are almost a different language. To write one, you actually use another macro called <code>macro_rules!</code>. Then you add your macro name and open a <code>{}</code> block. Inside is sort of like a <code>match</code> statement.</p>
<p>Here's one that only takes <code>()</code>, then just returns 6:</p>
<pre><pre class="playground"><code class="language-rust">macro_rules! give_six {
@ -11014,9 +11014,9 @@ fn main() {
</code></pre>
<p>And for the rest of it it just calls <code>dbg!</code> on itself even if you put in an extra comma.</p>
<p>As you can see, macros are very complicated! Usually you only want a macro to automatically do something that a simple function can't do very well. The best way to learn about macros is to look at other macro examples. Not many people can quickly write macros without problems. So don't think that you need to know everything about macros to know how to write in Rust. But if you read other macros, and change them a little, you can easily borrow their power. Then you might start to get comfortable with writing your own.</p>
<h1><a class="header" href="#part-2---rust-on-your-computer" id="part-2---rust-on-your-computer">Part 2 - Rust on your computer</a></h1>
<h1 id="part-2---rust-on-your-computer"><a class="header" href="#part-2---rust-on-your-computer">Part 2 - Rust on your computer</a></h1>
<p>You saw that we can learn almost anything in Rust just using the Playground. But if you learned everything so far, you will probably want Rust on your computer now. There are always things that you can't do with the Playground like using files or code in more than just one file. Some other things you need Rust on your computer for are input and flags. But most important is that with Rust on your computer you can use crates. We already learned about crates, but in the Playground you could only use the most popular ones. But with Rust on your computer you can use any crate in your program.</p>
<h2><a class="header" href="#cargo" id="cargo">cargo</a></h2>
<h2 id="cargo"><a class="header" href="#cargo">cargo</a></h2>
<p><code>rustc</code> means Rust compiler, and it's what does the actual compiling. A rust file ends with an <code>.rs</code>. But most people don't write something like <code>rustc main.rs</code> to compile. They use something called <code>cargo</code>, which is the main package manager for Rust.</p>
<p>One note about the name: it's called <code>cargo</code> because when you put crates together, you get cargo. A crate is a wooden box that you see on ships or trucks, but you remember that every Rust project is also called a crate. Then when you put them together you get the whole cargo.</p>
<p>You can see this when you use cargo to run a project. Let's try something simple with <code>rand</code>: we'll just randomly choose between eight letters.</p>
@ -11073,7 +11073,7 @@ fn main() {
<li><code>cargo clean</code>. When you add crates to <code>Cargo.toml</code>, the computer will download all the files it needs and they can take a lot of space. If you don't want them on your computer anymore, type <code>cargo clean</code>.</li>
</ul>
<p>One more thing about the compiler: it only takes the most time when you use <code>cargo build</code> or <code>cargo run</code> the first time. After that it will remember, and it will compile fast again. But if you use <code>cargo clean</code> and then run <code>cargo build</code>, it will have to compile slowly one more time.</p>
<h2><a class="header" href="#taking-user-input" id="taking-user-input">Taking user input</a></h2>
<h2 id="taking-user-input"><a class="header" href="#taking-user-input">Taking user input</a></h2>
<p>One easy way to take input from the user is with <code>std::io::stdin</code>. This means &quot;standard in&quot;, which is the input from the keyboard. With <code>stdin()</code> you can get user input, but then you will want to put it in a <code>&amp;mut String</code> with <code>.read_line()</code>. Here is a simple example of that, but it both works and doesn't work:</p>
<pre><pre class="playground"><code class="language-rust">use std::io;
@ -11297,7 +11297,7 @@ Didn't work
/playground/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/bin/cargo
</code></pre>
<p>So <code>option_env!</code> is always going to be the safer macro. <code>env!</code> is better if you actually want the program to crash when you can't find the environment variable.</p>
<h2><a class="header" href="#using-files" id="using-files">Using files</a></h2>
<h2 id="using-files"><a class="header" href="#using-files">Using files</a></h2>
<p>Now that we are using Rust on the computer, we can start working with files. You will notice that now we will start to see more and more <code>Result</code>s in our code. That is because once you start working with files and similar things, many things can go wrong. A file might not be there, or maybe the computer can't read it.</p>
<p>You might remember that if you want to use the <code>?</code> operator, it has to return a <code>Result</code> in the function it is in. If you can't remember the error type, you can just give it nothing and let the compiler tell you. Let's try that with a function that tries to make a number with <code>.parse()</code>.</p>
<pre><pre class="playground"><code class="language-rust">// ⚠️
@ -11542,7 +11542,7 @@ Dad: Yep. The world didn't turn color until sometimes in the 1930s...And it was
That's really weird.
Well, truth is stranger than fiction.
</code></pre>
<h2><a class="header" href="#cargo-doc" id="cargo-doc">cargo doc</a></h2>
<h2 id="cargo-doc"><a class="header" href="#cargo-doc">cargo doc</a></h2>
<p>You might have noticed that Rust documentation always looks almost the same. On the left side you can see <code>struct</code>s and <code>trait</code>s, code examples are on the right, etc. This is because you can automatically make documentation just by typing <code>cargo doc</code>.</p>
<p>Even making a project with nothing can help you learn about traits in Rust. For example, here are two structs that do almost nothing, and a <code>fn main()</code> that also does nothing.</p>
<pre><pre class="playground"><code class="language-rust">struct DoesNothing {}
@ -11632,7 +11632,7 @@ Functions
main
</code></pre>
<p><code>cargo doc</code> is very nice when you use a lot of other people's crates. Because these crates are all on different websites, it can take some time to search them all. But if you use <code>cargo doc</code>, you will have them all in the same place on your hard drive.</p>
<h2><a class="header" href="#the-end" id="the-end">The end?</a></h2>
<h2 id="the-end"><a class="header" href="#the-end">The end?</a></h2>
<p>This is the end of Rust in Easy English. But I am still here, and you can let me know if you have any questions. Feel free to <a href="https://twitter.com/mithridates">contact me on Twitter</a> or add a pull request, issue, etc. You can also tell me if some parts weren't easy to understand. Rust in Easy English needs to be very easy to understand, so please let me know where the English is too difficult. Of course, Rust itself can be difficult to understand, but we can at least make sure that the English is easy.</p>
</main>

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long
Loading…
Cancel
Save