For our first project, we’ll implement a classic beginner programming problem: the guessing game. Here’s how it works: Our program will generate a random integer between one and a hundred. It will then prompt us to enter a guess. Upon entering our guess, it will tell us if we’re too low or too high. Once we guess correctly, it will congratulate us. Sounds good?
Let’s set up a new project. Go to your projects directory. Remember how we had
to create our directory structure and a Cargo.toml
`Cargo.tomlfor
` for hello_world
`hello_world`? Cargo
has a command that does that for us. Let’s give it a shot:
$ cd ~/projects
$ cargo new guessing_game --bin
$ cd guessing_game
We pass the name of our project to cargo new
`cargo new, and then the
`, and then the --bin
`--bin` flag,
since we’re making a binary, rather than a library.
Check out the generated Cargo.toml
`Cargo.toml`:
[package]
name = "guessing_game"
version = "0.1.0"
authors = ["Your Name <you@example.com>"]
Cargo gets this information from your environment. If it’s not correct, go ahead and fix that.
Finally, Cargo generated a ‘Hello, world!’ for us. Check out src/main.rs
`src/main.rs`:
fn main() { println!("Hello, world!") }
Let’s try compiling what Cargo gave us:
$ cargo build
Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
Excellent! Open up your src/main.rs
`src/main.rs` again. We’ll be writing all of
our code in this file.
Before we move on, let me show you one more Cargo command: run
`run.
`. cargo run
`cargo runis kind of like
`
is kind of like cargo build
`cargo build`, but it also then runs the produced executable.
Try it out:
$ cargo run
Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
Running `target/debug/guessing_game`
Hello, world!
Great! The run
`run` command comes in handy when you need to rapidly iterate on a
project. Our game is just such a project, we need to quickly test each
iteration before moving on to the next one.
Let’s get to it! The first thing we need to do for our guessing game is
allow our player to input a guess. Put this in your src/main.rs
`src/main.rs`:
use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .ok() .expect("Failed to read line"); println!("You guessed: {}", guess); }
There’s a lot here! Let’s go over it, bit by bit.
fn main() { use std::io; }use std::io;
We’ll need to take user input, and then print the result as output. As such, we
need the io
`iolibrary from the standard library. Rust only imports a few things into every program, [the ‘prelude’][prelude]. If it’s not in the prelude, you’ll have to
` library from the standard library. Rust only imports a few things
into every program, the ‘prelude’. If it’s not in the prelude,
you’ll have to use
`use` it directly.
fn main() {
As you’ve seen before, the main()
`main()function is the entry point into your program. The
` function is the entry point into your
program. The fn
`fnsyntax declares a new function, the
` syntax declares a new function, the ()
`()s indicate that there are no arguments, and
`s indicate that
there are no arguments, and {
`{starts the body of the function. Because we didn’t include a return type, it’s assumed to be
` starts the body of the function. Because
we didn’t include a return type, it’s assumed to be ()
`()`, an empty
tuple.
println!("Guess the number!"); println!("Please input your guess.");
We previously learned that println!()
`println!()` is a macro that
prints a string to the screen.
let mut guess = String::new();
Now we’re getting interesting! There’s a lot going on in this little line. The first thing to notice is that this is a let statement, which is used to create ‘variable bindings’. They take this form:
fn main() { let foo = bar; }let foo = bar;
This will create a new binding named foo
`foo, and bind it to the value
`, and bind it to the value bar
`bar`. In
many languages, this is called a ‘variable’, but Rust’s variable bindings have
a few tricks up their sleeves.
For example, they’re immutable by default. That’s why our example
uses mut
`mut: it makes a binding mutable, rather than immutable.
`: it makes a binding mutable, rather than immutable. let
`let` doesn’t
take a name on the left hand side, it actually accepts a
‘pattern’. We’ll use patterns more later. It’s easy enough
to use for now:
let foo = 5; // immutable. let mut bar = 5; // mutable
Oh, and //
`//` will start a comment, until the end of the line. Rust ignores
everything in comments.
So now we know that let mut guess
`let mut guesswill introduce a mutable binding named
` will introduce a mutable binding named
guess
`guess, but we have to look at the other side of the
`, but we have to look at the other side of the =
`=for what it’s bound to:
` for what it’s
bound to: String::new()
`String::new()`.
String
`Stringis a string type, provided by the standard library. A [
` is a string type, provided by the standard library. A
String
`String` is a growable, UTF-8 encoded bit of text.
The ::new()
`::new()syntax uses
` syntax uses ::
`::because this is an ‘associated function’ of a particular type. That is to say, it’s associated with
` because this is an ‘associated function’ of
a particular type. That is to say, it’s associated with String
`Stringitself, rather than a particular instance of a
` itself,
rather than a particular instance of a String
`String`. Some languages call this a
‘static method’.
This function is named new()
`new(), because it creates a new, empty
`, because it creates a new, empty String
`String. You’ll find a
`.
You’ll find a new()
`new()` function on many types, as it’s a common name for making
a new value of some kind.
Let’s move forward:
fn main() { io::stdin().read_line(&mut guess) .ok() .expect("Failed to read line"); }io::stdin().read_line(&mut guess) .ok() .expect("Failed to read line");
That’s a lot more! Let’s go bit-by-bit. The first line has two parts. Here’s the first:
fn main() { io::stdin() }io::stdin()
Remember how we use
`used
`d std::io
`std::ioon the first line of the program? We’re now calling an associated function on it. If we didn’t
` on the first line of the program? We’re now
calling an associated function on it. If we didn’t use std::io
`use std::io, we could have written this line as
`, we could
have written this line as std::io::stdin()
`std::io::stdin()`.
This particular function returns a handle to the standard input for your terminal. More specifically, a std::io::Stdin.
The next part will use this handle to get input from the user:
fn main() { .read_line(&mut guess) }.read_line(&mut guess)
Here, we call the read_line()
`read_line()` method on our handle.
Methods are like associated functions, but are only available on a
particular instance of a type, rather than the type itself. We’re also passing
one argument to read_line()
`read_line():
`: &mut guess
`&mut guess`.
Remember how we bound guess
`guessabove? We said it was mutable. However,
` above? We said it was mutable. However,
read_line
`read_linedoesn’t take a
` doesn’t take a String
`Stringas an argument: it takes a
` as an argument: it takes a &mut String
`&mut String. Rust has a feature called ‘[references][references]’, which allows you to have multiple references to one piece of data, which can reduce copying. References are a complex feature, as one of Rust’s major selling points is how safe and easy it is to use references. We don’t need to know a lot of those details to finish our program right now, though. For now, all we need to know is that like
`.
Rust has a feature called ‘references’, which allows you to have
multiple references to one piece of data, which can reduce copying. References
are a complex feature, as one of Rust’s major selling points is how safe and
easy it is to use references. We don’t need to know a lot of those details to
finish our program right now, though. For now, all we need to know is that
like let
`letbindings, references are immutable by default. Hence, we need to write
` bindings, references are immutable by default. Hence, we need to
write &mut guess
`&mut guess, rather than
`, rather than &guess
`&guess`.
Why does read_line()
`read_line()` take a mutable reference to a string? Its job is
to take what the user types into standard input, and place that into a
string. So it takes that string as an argument, and in order to add
the input, it needs to be mutable.
But we’re not quite done with this line of code, though. While it’s a single line of text, it’s only the first part of the single logical line of code:
fn main() { .ok() .expect("Failed to read line"); }.ok() .expect("Failed to read line");
When you call a method with the .foo()
`.foo()` syntax, you may introduce a newline
and other whitespace. This helps you split up long lines. We could have
done:
io::stdin().read_line(&mut guess).ok().expect("failed to read line");
But that gets hard to read. So we’ve split it up, three lines for three
method calls. We already talked about read_line()
`read_line(), but what about
`, but what about ok()
`ok()and
`
and expect()
`expect()? Well, we already mentioned that
`? Well, we already mentioned that read_line()
`read_line()puts what the user types into the
` puts what
the user types into the &mut String
`&mut Stringwe pass it. But it also returns a value: in this case, an [
` we pass it. But it also returns
a value: in this case, an io::Result
`io::Result`. Rust has a number of
types named Result
`Resultin its standard library: a generic [
` in its standard library: a generic Result
`Result`,
and then specific versions for sub-libraries, like io::Result
`io::Result`.
The purpose of these Result
`Resulttypes is to encode error handling information. Values of the
` types is to encode error handling information.
Values of the Result
`Resulttype, like any type, have methods defined on them. In this case,
` type, like any type, have methods defined on them. In
this case, io::Result
`io::Resulthas an
` has an ok()
`ok()method, which says ‘we want to assume this value is a successful one. If not, just throw away the error information’. Why throw it away? Well, for a basic program, we just want to print a generic error, as basically any issue means we can’t continue. The [
` method, which says ‘we want to assume
this value is a successful one. If not, just throw away the error
information’. Why throw it away? Well, for a basic program, we just want to
print a generic error, as basically any issue means we can’t continue. The
ok()
`ok()` method returns a value which has another method defined on it:
expect()
`expect(). The [
`. The expect()
`expect()` method takes a value it’s called on, and
if it isn’t a successful one, panic!
`panic!`s with a message you
passed it. A panic!
`panic!` like this will cause our program to crash, displaying
the message.
If we leave off calling these two methods, our program will compile, but we’ll get a warning:
$ cargo build
Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
src/main.rs:10:5: 10:39 warning: unused result which must be used,
#[warn(unused_must_use)] on by default
src/main.rs:10 io::stdin().read_line(&mut guess);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Rust warns us that we haven’t used the Result
`Resultvalue. This warning comes from a special annotation that
` value. This warning comes from
a special annotation that io::Result
`io::Result` has. Rust is trying to tell you that
you haven’t handled a possible error. The right way to suppress the error is
to actually write error handling. Luckily, if we just want to crash if there’s
a problem, we can use these two little methods. If we can recover from the
error somehow, we’d do something else, but we’ll save that for a future
project.
There’s just one line of this first example left:
fn main() { println!("You guessed: {}", guess); } }println!("You guessed: {}", guess); }
This prints out the string we saved our input in. The {}
`{}s are a placeholder, and so we pass it
`s are a placeholder,
and so we pass it guess
`guessas an argument. If we had multiple
` as an argument. If we had multiple {}
`{}`s, we would
pass multiple arguments:
let x = 5; let y = 10; println!("x and y: {} and {}", x, y);
Easy.
Anyway, that’s the tour. We can run what we have with cargo run
`cargo run`:
$ cargo run
Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
Running `target/debug/guessing_game`
Guess the number!
Please input your guess.
6
You guessed: 6
All right! Our first part is done: we can get input from the keyboard, and then print it back out.
Next, we need to generate a secret number. Rust does not yet include random
number functionality in its standard library. The Rust team does, however,
provide a rand
`rand` crate. A ‘crate’ is a package of Rust code.
We’ve been building a ‘binary crate’, which is an executable. rand
`rand` is a
‘library crate’, which contains code that’s intended to be used with other
programs.
Using external crates is where Cargo really shines. Before we can write
the code using rand
`rand, we need to modify our
`, we need to modify our Cargo.toml
`Cargo.toml`. Open it up, and
add these few lines at the bottom:
[dependencies]
rand="0.3.0"
The [dependencies]
`[dependencies]section of
` section of Cargo.toml
`Cargo.tomlis like the
` is like the [package]
`[package]section: everything that follows it is part of it, until the next section starts. Cargo uses the dependencies section to know what dependencies on external crates you have, and what versions you require. In this case, we’ve used version
` section:
everything that follows it is part of it, until the next section starts.
Cargo uses the dependencies section to know what dependencies on external
crates you have, and what versions you require. In this case, we’ve used version 0.3.0
`0.3.0. Cargo understands [Semantic Versioning][semver], which is a standard for writing version numbers. If we wanted to use the latest version we could use
`.
Cargo understands Semantic Versioning, which is a standard for writing version
numbers. If we wanted to use the latest version we could use *
`*` or we could use a range
of versions. Cargo’s documentation contains more details.
Now, without changing any of our code, let’s build our project:
$ cargo build
Updating registry `https://github.com/rust-lang/crates.io-index`
Downloading rand v0.3.8
Downloading libc v0.1.6
Compiling libc v0.1.6
Compiling rand v0.3.8
Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
(You may see different versions, of course.)
Lots of new output! Now that we have an external dependency, Cargo fetches the latest versions of everything from the registry, which is a copy of data from Crates.io. Crates.io is where people in the Rust ecosystem post their open source Rust projects for others to use.
After updating the registry, Cargo checks our [dependencies]
`[dependencies]and downloads any we don’t have yet. In this case, while we only said we wanted to depend on
` and downloads
any we don’t have yet. In this case, while we only said we wanted to depend on
rand
`rand, we’ve also grabbed a copy of
`, we’ve also grabbed a copy of libc
`libc. This is because
`. This is because rand
`randdepends on
` depends on
libc
`libc` to work. After downloading them, it compiles them, and then compiles
our project.
If we run cargo build
`cargo build` again, we’ll get different output:
$ cargo build
That’s right, no output! Cargo knows that our project has been built, and that
all of its dependencies are built, and so there’s no reason to do all that
stuff. With nothing to do, it simply exits. If we open up src/main.rs
`src/main.rs` again,
make a trivial change, and then save it again, we’ll just see one line:
$ cargo build
Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
So, we told Cargo we wanted any 0.3.x
`0.3.xversion of
` version of rand
`rand, and so it fetched the latest version at the time this was written,
`, and so it fetched the latest
version at the time this was written, v0.3.8
`v0.3.8. But what happens when next week, version
`. But what happens when next
week, version v0.3.9
`v0.3.9comes out, with an important bugfix? While getting bugfixes is important, what if
` comes out, with an important bugfix? While getting
bugfixes is important, what if 0.3.9
`0.3.9` contains a regression that breaks our
code?
The answer to this problem is the Cargo.lock
`Cargo.lockfile you’ll now find in your project directory. When you build your project for the first time, Cargo figures out all of the versions that fit your criteria, and then writes them to the
` file you’ll now find in your
project directory. When you build your project for the first time, Cargo
figures out all of the versions that fit your criteria, and then writes them
to the Cargo.lock
`Cargo.lockfile. When you build your project in the future, Cargo will see that the
` file. When you build your project in the future, Cargo
will see that the Cargo.lock
`Cargo.lockfile exists, and then use that specific version rather than do all the work of figuring out versions again. This lets you have a repeatable build automatically. In other words, we’ll stay at
` file exists, and then use that specific version
rather than do all the work of figuring out versions again. This lets you
have a repeatable build automatically. In other words, we’ll stay at 0.3.8
`0.3.8`
until we explicitly upgrade, and so will anyone who we share our code with,
thanks to the lock file.
What about when we do want to use v0.3.9
`v0.3.9? Cargo has another command,
`? Cargo has another command,
update
`update, which says ‘ignore the lock, figure out all the latest versions that fit what we’ve specified. If that works, write those versions out to the lock file’. But, by default, Cargo will only look for versions larger than
`, which says ‘ignore the lock, figure out all the latest versions that
fit what we’ve specified. If that works, write those versions out to the lock
file’. But, by default, Cargo will only look for versions larger than 0.3.0
`0.3.0and smaller than
`
and smaller than 0.4.0
`0.4.0. If we want to move to
`. If we want to move to 0.4.x
`0.4.x, we’d have to update the
`, we’d have to update
the Cargo.toml
`Cargo.tomldirectly. When we do, the next time we
` directly. When we do, the next time we cargo build
`cargo build, Cargo will update the index and re-evaluate our
`, Cargo
will update the index and re-evaluate our rand
`rand` requirements.
There’s a lot more to say about Cargo and its ecosystem, but for now, that’s all we need to know. Cargo makes it really easy to re-use libraries, and so Rustaceans tend to write smaller projects which are assembled out of a number of sub-packages.
Let’s get on to actually using rand
`rand`. Here’s our next step:
extern crate rand; use std::io; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is: {}", secret_number); println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .ok() .expect("failed to read line"); println!("You guessed: {}", guess); }
The first thing we’ve done is change the first line. It now says
extern crate rand
`extern crate rand. Because we declared
`. Because we declared rand
`randin our
` in our [dependencies]
`[dependencies], we can use
`, we
can use extern crate
`extern crateto let Rust know we’ll be making use of it. This also does the equivalent of a
` to let Rust know we’ll be making use of it. This also
does the equivalent of a use rand;
`use rand;as well, so we can make use of anything in the
` as well, so we can make use of anything
in the rand
`randcrate by prefixing it with
` crate by prefixing it with rand::
`rand::`.
Next, we added another use
`useline:
` line: use rand::Rng
`use rand::Rng. We’re going to use a method in a moment, and it requires that
`. We’re going to use a
method in a moment, and it requires that Rng
`Rng` be in scope to work. The basic
idea is this: methods are defined on something called ‘traits’, and for the
method to work, it needs the trait to be in scope. For more about the
details, read the traits section.
There are two other lines we added, in the middle:
fn main() { let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is: {}", secret_number); }let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is: {}", secret_number);
We use the rand::thread_rng()
`rand::thread_rng()function to get a copy of the random number generator, which is local to the particular [thread][concurrency] of execution we’re in. Because we
` function to get a copy of the random number
generator, which is local to the particular thread of execution
we’re in. Because we use rand::Rng
`use rand::Rng’d above, it has a
`’d above, it has a gen_range()
`gen_range()method available. This method takes two arguments, and generates a number between them. It’s inclusive on the lower bound, but exclusive on the upper bound, so we need
` method
available. This method takes two arguments, and generates a number between
them. It’s inclusive on the lower bound, but exclusive on the upper bound,
so we need 1
`1and
` and 101
`101` to get a number between one and a hundred.
The second line just prints out the secret number. This is useful while we’re developing our program, so we can easily test it out. But we’ll be deleting it for the final version. It’s not much of a game if it prints out the answer when you start it up!
Try running our new program a few times:
$ cargo run
Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
Running `target/debug/guessing_game`
Guess the number!
The secret number is: 7
Please input your guess.
4
You guessed: 4
$ cargo run
Running `target/debug/guessing_game`
Guess the number!
The secret number is: 83
Please input your guess.
5
You guessed: 5
Great! Next up: let’s compare our guess to the secret guess.
Now that we’ve got user input, let’s compare our guess to the random guess. Here’s our next step, though it doesn’t quite work yet:
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is: {}", secret_number); println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .ok() .expect("failed to read line"); println!("You guessed: {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => println!("You win!"), } }extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is: {}", secret_number); println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .ok() .expect("failed to read line"); println!("You guessed: {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => println!("You win!"), } }
A few new bits here. The first is another use
`use. We bring a type called
`. We bring a type called
std::cmp::Ordering
`std::cmp::Ordering` into scope. Then, five new lines at the bottom that use
it:
match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => println!("You win!"), }
The cmp()
`cmp()method can be called on anything that can be compared, and it takes a reference to the thing you want to compare it to. It returns the
` method can be called on anything that can be compared, and it
takes a reference to the thing you want to compare it to. It returns the
Ordering
`Orderingtype we
` type we use
`used earlier. We use a [
`d earlier. We use a match
`match` statement to
determine exactly what kind of Ordering
`Orderingit is.
` it is. Ordering
`Orderingis an [
` is an
enum
`enum`, short for ‘enumeration’, which looks like this:
enum Foo { Bar, Baz, }
With this definition, anything of type Foo
`Foocan be either a
` can be either a
Foo::Bar
`Foo::Baror a
` or a Foo::Baz
`Foo::Baz. We use the
`. We use the ::
`::to indicate the namespace for a particular
` to indicate the
namespace for a particular enum
`enum` variant.
The Ordering
`Ordering` enum has three possible variants: Less
`Less,
`, Equal
`Equal, and
`,
and Greater
`Greater. The
`. The match
`matchstatement takes a value of a type, and lets you create an ‘arm’ for each possible value. Since we have three types of
` statement takes a value of a type, and lets you
create an ‘arm’ for each possible value. Since we have three types of
Ordering
`Ordering`, we have three arms:
match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => println!("You win!"), }
If it’s Less
`Less, we print
`, we print Too small!
`Too small!, if it’s
`, if it’s Greater
`Greater,
`, Too big!
`Too big!, and if
`, and if
Equal
`Equal,
`, You win!
`You win!.
`. match
`match` is really useful, and is used often in Rust.
I did mention that this won’t quite work yet, though. Let’s try it:
$ cargo build
Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
src/main.rs:28:21: 28:35 error: mismatched types:
expected `&collections::string::String`,
found `&_`
(expected struct `collections::string::String`,
found integral variable) [E0308]
src/main.rs:28 match guess.cmp(&secret_number) {
^~~~~~~~~~~~~~
error: aborting due to previous error
Could not compile `guessing_game`.
Whew! This is a big error. The core of it is that we have ‘mismatched types’.
Rust has a strong, static type system. However, it also has type inference.
When we wrote let guess = String::new()
`let guess = String::new(), Rust was able to infer that
`, Rust was able to infer that guess
`guessshould be a
`
should be a String
`String, and so it doesn’t make us write out the type. And with our
`, and so it doesn’t make us write out the type. And with
our secret_number
`secret_number, there are a number of types which can have a value between one and a hundred:
`, there are a number of types which can have a value
between one and a hundred: i32
`i32, a thirty-two-bit number, or
`, a thirty-two-bit number, or u32
`u32, an unsigned thirty-two-bit number, or
`, an
unsigned thirty-two-bit number, or i64
`i64, a sixty-four-bit number. Or others. So far, that hasn’t mattered, and so Rust defaults to an
`, a sixty-four-bit number. Or others.
So far, that hasn’t mattered, and so Rust defaults to an i32
`i32. However, here, Rust doesn’t know how to compare the
`. However, here,
Rust doesn’t know how to compare the guess
`guessand the
` and the secret_number
`secret_number. They need to be the same type. Ultimately, we want to convert the
`. They
need to be the same type. Ultimately, we want to convert the String
`String` we
read as input into a real number type, for comparison. We can do that
with three more lines. Here’s our new program:
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is: {}", secret_number); println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .ok() .expect("failed to read line"); let guess: u32 = guess.trim().parse() .ok() .expect("Please type a number!"); println!("You guessed: {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => println!("You win!"), } }
The new three lines:
fn main() { let guess: u32 = guess.trim().parse() .ok() .expect("Please type a number!"); }let guess: u32 = guess.trim().parse() .ok() .expect("Please type a number!");
Wait a minute, I thought we already had a guess
`guess? We do, but Rust allows us to ‘shadow’ the previous
`? We do, but Rust allows us
to ‘shadow’ the previous guess
`guesswith a new one. This is often used in this exact situation, where
` with a new one. This is often used in this
exact situation, where guess
`guessstarts as a
` starts as a String
`String, but we want to convert it to an
`, but we want to convert it
to an u32
`u32. Shadowing lets us re-use the
`. Shadowing lets us re-use the guess
`guessname, rather than forcing us to come up with two unique names like
` name, rather than forcing us
to come up with two unique names like guess_str
`guess_strand
` and guess
`guess`, or something
else.
We bind guess
`guess` to an expression that looks like something we wrote earlier:
guess.trim().parse()
Followed by an ok().expect()
`ok().expect()invocation. Here,
` invocation. Here, guess
`guessrefers to the old
` refers to the old
guess
`guess, the one that was a
`, the one that was a String
`Stringwith our input in it. The
` with our input in it. The trim()
`trim()method on
`
method on String
`Strings will eliminate any white space at the beginning and end of our string. This is important, as we had to press the ‘return’ key to satisfy
`s will eliminate any white space at the beginning and end of
our string. This is important, as we had to press the ‘return’ key to satisfy
read_line()
`read_line(). This means that if we type
`. This means that if we type 5
`5and hit return,
` and hit return, guess
`guesslooks like this:
` looks
like this: 5\n
`5\n. The
`. The \n
`\nrepresents ‘newline’, the enter key.
` represents ‘newline’, the enter key. trim()
`trim()gets rid of this, leaving our string with just the
` gets
rid of this, leaving our string with just the 5
`5. The [
`. The parse()
`parse()` method on
strings parses a string into some kind of number. Since it can parse a
variety of numbers, we need to give Rust a hint as to the exact type of number
we want. Hence, let guess: u32
`let guess: u32. The colon (
`. The colon (:
`:) after
`) after guess
`guesstells Rust we’re going to annotate its type.
` tells Rust
we’re going to annotate its type. u32
`u32is an unsigned, thirty-two bit integer. Rust has [a number of built-in number types][number], but we’ve chosen
` is an unsigned, thirty-two bit
integer. Rust has a number of built-in number types, but we’ve
chosen u32
`u32`. It’s a good default choice for a small positive number.
Just like read_line()
`read_line(), our call to
`, our call to parse()
`parse()could cause an error. What if our string contained
` could cause an error. What if
our string contained A👍%
`A👍%? There’d be no way to convert that to a number. As such, we’ll do the same thing we did with
`? There’d be no way to convert that to a number. As
such, we’ll do the same thing we did with read_line()
`read_line(): use the
`: use the ok()
`ok()and
` and
expect()
`expect()` methods to crash if there’s an error.
Let’s try our program out!
$ cargo run
Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
Running `target/guessing_game`
Guess the number!
The secret number is: 58
Please input your guess.
76
You guessed: 76
Too big!
Nice! You can see I even added spaces before my guess, and it still figured out that I guessed 76. Run the program a few times, and verify that guessing the number works, as well as guessing a number too small.
Now we’ve got most of the game working, but we can only make one guess. Let’s change that by adding loops!
The loop
`loop` keyword gives us an infinite loop. Let’s add that in:
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is: {}", secret_number); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .ok() .expect("failed to read line"); let guess: u32 = guess.trim().parse() .ok() .expect("Please type a number!"); println!("You guessed: {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => println!("You win!"), } } }
And try it out. But wait, didn’t we just add an infinite loop? Yup. Remember
our discussion about parse()
`parse()? If we give a non-number answer, we’ll
`? If we give a non-number answer, we’ll return
`return`
and quit. Observe:
$ cargo run
Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
Running `target/guessing_game`
Guess the number!
The secret number is: 59
Please input your guess.
45
You guessed: 45
Too small!
Please input your guess.
60
You guessed: 60
Too big!
Please input your guess.
59
You guessed: 59
You win!
Please input your guess.
quit
thread '<main>' panicked at 'Please type a number!'
Ha! quit
`quit` actually quits. As does any other non-number input. Well, this is
suboptimal to say the least. First, let’s actually quit when you win the game:
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is: {}", secret_number); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .ok() .expect("failed to read line"); let guess: u32 = guess.trim().parse() .ok() .expect("Please type a number!"); println!("You guessed: {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } }
By adding the break
`breakline after the
` line after the You win!
`You win!, we’ll exit the loop when we win. Exiting the loop also means exiting the program, since it’s the last thing in
`, we’ll exit the loop when we
win. Exiting the loop also means exiting the program, since it’s the last
thing in main()
`main()`. We have just one more tweak to make: when someone inputs a
non-number, we don’t want to quit, we just want to ignore it. We can do that
like this:
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is: {}", secret_number); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .ok() .expect("failed to read line"); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; println!("You guessed: {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } }
These are the lines that changed:
fn main() { let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; }let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, };
This is how you generally move from ‘crash on error’ to ‘actually handle the
error’, by switching from ok().expect()
`ok().expect()to a
` to a match
`matchstatement. The
` statement. The Result
`Resultreturned by
`
returned by parse()
`parse()is an enum just like
` is an enum just like Ordering
`Ordering, but in this case, each variant has some data associated with it:
`, but in this case, each
variant has some data associated with it: Ok
`Okis a success, and
` is a success, and Err
`Erris a failure. Each contains more information: the successful parsed integer, or an error type. In this case, we
` is a
failure. Each contains more information: the successful parsed integer, or an
error type. In this case, we match
`matchon
` on Ok(num)
`Ok(num), which sets the inner value of the
`, which sets the inner value
of the Ok
`Okto the name
` to the name num
`num, and then we just return it on the right-hand side. In the
`, and then we just return it on the right-hand
side. In the Err
`Errcase, we don’t care what kind of error it is, so we just use
` case, we don’t care what kind of error it is, so we just
use _
`_instead of a name. This ignores the error, and
` instead of a name. This ignores the error, and continue
`continuecauses us to go to the next iteration of the
` causes us
to go to the next iteration of the loop
`loop`.
Now we should be good! Let’s try:
$ cargo run
Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
Running `target/guessing_game`
Guess the number!
The secret number is: 61
Please input your guess.
10
You guessed: 10
Too small!
Please input your guess.
99
You guessed: 99
Too big!
Please input your guess.
foo
Please input your guess.
61
You guessed: 61
You win!
Awesome! With one tiny last tweak, we have finished the guessing game. Can you think of what it is? That’s right, we don’t want to print out the secret number. It was good for testing, but it kind of ruins the game. Here’s our final source:
extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .ok() .expect("failed to read line"); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; println!("You guessed: {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } }extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .ok() .expect("failed to read line"); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; println!("You guessed: {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } }
At this point, you have successfully built the Guessing Game! Congratulations!
This first project showed you a lot: let
`let,
`, match
`match`, methods, associated
functions, using external crates, and more. Our next project will show off
even more.