<buttonid="sidebar-toggle"class="icon-button"type="button"title="Toggle Table of Contents"aria-label="Toggle Table of Contents"aria-controls="sidebar">
<ahref="print.html"title="Print this book"aria-label="Print this book">
<iid="print-button"class="fa fa-print"></i>
</a>
</div>
</div>
<divid="search-wrapper"class="hidden">
<formid="searchbar-outer"class="searchbar-outer">
<inputtype="search"name="search"id="searchbar"name="searchbar"placeholder="Search this book ..."aria-controls="searchresults-outer"aria-describedby="searchresults-header">
<p>An external crate means "someone else's crate".</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>
<li>It is very easy to import other crates, and</li>
<li>The Rust standard library is quite small.</li>
</ul>
<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>
<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 "almost standard library" because everybody uses them. In any case, it's very easy to bring in a crate. If you have Rust on your computer, there is a file called <code>Cargo.toml</code> that has this information. A <code>Cargo.toml</code> file looks like this when you start:</p>
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
</code></pre>
<p>Now if you want to add the <code>rand</code> crate, search for it on <code>crates.io</code>, which is where all the crates go. That takes you to <code>https://crates.io/crates/rand</code>. And when you click on that, you can see a screen that says <code>Cargo.toml rand = "0.7.3"</code>. All you do is add that under [dependencies] like this:</p>
<pre><codeclass="language-text">[package]
name = "rust_book"
version = "0.1.0"
authors = ["David MacLeod"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.7.3"
</code></pre>
<p>And then Cargo will do the rest for you. Then you can start writing code like <ahref="https://docs.rs/rand/0.7.3/rand/">this example code</a> on the <code>rand</code> document website. To get to the documents you can click on the <code>docs</code> button in <ahref="https://crates.io/crates/rand">the page on crates.io</a>.</p>
<p>So that's enough about Cargo: we are still using just the Playground. Luckily, the Playground already has the top 100 crates installed. So you don't need to write in <code>Cargo.toml</code> yet. On the Playground you can imagine that it has a long list like this with 100 crates:</p>
<p>It will print a different <code>u16</code> number every time, like <code>42266 52873 56528 46927 6867</code>.</p>
<p>The main functions in <code>rand</code> are <code>random</code> and <code>thread_rng</code> (rng means "random number generator"). And actually if you look at <code>random</code> it says: "This is simply a shortcut for <code>thread_rng().gen()</code>". So it's actually just <code>thread_rng</code> that does almost everything.</p>
<p>Here is a simple example of numbers from 1 to 10. To get those numbers, we use <code>.gen_range()</code> between 1 and 11.</p>
<pre><preclass="playground"><codeclass="language-rust">use rand::{thread_rng, Rng}; // Or just use rand::*; if we are lazy
<p>This will print something like <code>7 2 4 8 6</code>.</p>
<p>With random numbers we can do fun things like make characters for a game. We will use <code>rand</code> and some other things we know to make them. In this game our characters have six stats, and you use a d6 for them. A d6 is a cube that gives 1, 2, 3, 4, 5, or 6 when you throw it. Each character rolls a d6 three times, so each stat is between 3 and 18.</p>
<p>But sometimes it can be unfair if your character has something low like a 3 or 4. If your strength is 3 you can't carry anything, for example. So there is one more method that uses a d6 four times. You roll it four times, and throw away the lowest number. So if you roll 3, 3, 1, 6 then you keep 3, 3, 6 = 12. We will make this method too so the owner of the game can decide.</p>
<p>Here is our simple character creator. We created a <code>Character</code> struct for the stats, and even implemented <code>Display</code> to print it the way we want.</p>
<pre><preclass="playground"><codeclass="language-rust">use rand::{thread_rng, Rng}; // Or just use rand::*; if we are lazy
use std::fmt; // Going to impl Display for our character
struct Character {
strength: u8,
dexterity: u8, // This means "body quickness"
constitution: u8, // This means "health"
intelligence: u8,
wisdom: u8,
charisma: u8, // This means "popularity with people"
}
fn three_die_six() -> u8 { // A "die" is the thing you throw to get the number
let mut generator = thread_rng(); // Create our random number generator
let mut stat = 0; // This is the total
for _ in 0..3 {
stat += generator.gen_range(1, 7); // Add each time
}
stat // Return the total
}
fn four_die_six() -> u8 {
let mut generator = thread_rng();
let mut results = vec![]; // First put the numbers in a vec
for _ in 0..4 {
results.push(generator.gen_range(1, 7));
}
results.sort(); // Now a result like [4, 3, 2, 6] becomes [2, 3, 4, 6]
results.remove(0); // Now it would be [3, 4, 6]
results.iter().sum() // Return this result
}
impl Character {
fn new(three_dice: bool) -> Self { // true for three dice, false for four
match three_dice {
true => Self {
strength: three_die_six(),
dexterity: three_die_six(),
constitution: three_die_six(),
intelligence: three_die_six(),
wisdom: three_die_six(),
charisma: three_die_six(),
},
false => Self {
strength: four_die_six(),
dexterity: four_die_six(),
constitution: four_die_six(),
intelligence: four_die_six(),
wisdom: four_die_six(),
charisma: four_die_six(),
},
}
}
fn display(&self) { // We can do this because we implemented Display below
println!("{}", self);
println!();
}
}
impl fmt::Display for Character { // Just follow the code for in https://doc.rust-lang.org/std/fmt/trait.Display.html and change it a bit
<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>
<li><code>.par_iter()</code>, <code>.par_iter_mut()</code>, <code>par_into_iter()</code>. So you just add <code>par_</code> and your code becomes much faster. (par means "parallel")</li>
</ul>
<p>Other methods are the same: <code>.chars()</code> is <code>.par_chars()</code>, and so on.</p>
<p>Here is an example of a simple piece of code that is making the computer do a lot of work:</p>
<p>It creates a vector with 200,000 items: each one is 0. Then it calls <code>.enumerate()</code> to get the index for each number, and changes the 0 to the index number. It's too long to print so we only print items 5000 to 5004. This is still very fast in Rust, but if you want you can make it faster with Rayon. The code is almost the same:</p>
<pre><preclass="playground"><codeclass="language-rust">use rayon::prelude::*; // Import rayon
fn main() {
let mut my_vec = vec![0; 200_000];
my_vec.par_iter_mut().enumerate().for_each(|(index, number)| *number+=index+1); // add par_ to iter_mut
<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 "add <code>_par</code> to make your program faster".</p>
<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. <ahref="https://serde.rs/">It looks like this</a>:</p>
<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>
<p>The <ahref="https://crates.io/crates/regex">regex</a> crate lets you search through text using <ahref="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>
<p><ahref="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>