Appendix
+The following sections contain reference material you may find useful in your +Rust journey.
+ +diff --git a/appendix-00.html b/appendix-00.html new file mode 100644 index 000000000..6dcef2744 --- /dev/null +++ b/appendix-00.html @@ -0,0 +1,119 @@ + + +
+ +The following sections contain reference material you may find useful in your +Rust journey.
+ +The following keywords are reserved by the Rust language and may not be used as +names of functions, variables, macros, modules, crates, constants, static +values, attributes, struct fields, or arguments.
+abstractalignofasbecomeboxbreakconstcontinuecratedoelseenumexternfalsefinalfnforifimplinletloopmacromatchmodmovemutoffsetofoverrideprivprocpubpurerefreturnSelfselfsizeofstaticstructsupertraittruetypetypeofunsafeunsizedusevirtualwherewhileyieldWelcome to “The Rust Programming Language”, an introductory book about Rust. +Rust is a programming language that’s focused on safety, speed, and +concurrency. Its design lets you create programs that have the performance and +control of a low-level language, but with helpful abstractions that feel like a +high-level language. The Rust community welcomes all programmers who have their +experience in languages like C and are looking for a safer alternative, as well +as programmers from languages like Python who are looking for ways to write more +performant code without losing expressiveness.
+Rust provides the majority of its safety checks at compile time and without a +garbage collector so that your program's runtime isn't impacted. This makes it +useful in a number of use cases that other languages aren’t good at: embedding +in other languages, programs with specific space and time requirements, and +writing low-level code, like device drivers and operating systems. It's also +great for web applications: it powers the Rust package registry site, crates.io! +We're excited to see what you create with Rust.
+This book is written for a reader who already knows how to program in at least +one programming language. After reading this book, you should be comfortable +writing Rust programs. We’ll be learning Rust through small, focused examples +that build on each other to demonstrate how to use various features of Rust as +well as how they work behind the scenes.
+This book is open source. If you find an error, please don’t hesitate to file an +issue or send a pull request on GitHub.
+ +The first step to using Rust is to install it. You’ll need an internet +connection to run the commands in this chapter, as we’ll be downloading Rust +from the internet.
+We’ll be showing off a number of commands using a terminal, and those lines all
+start with $. You don't need to type in the $s; they are there to indicate
+the start of each command. You’ll see many tutorials and examples around the web
+that follow this convention: $ for commands run as a regular user, and #
+for commands you should be running as an administrator. Lines that don't start
+with $ are typically showing the output of the previous command.
If you're on Linux or a Mac, all you need to do is open a terminal and type +this:
+$ curl https://sh.rustup.rs -sSf | sh
+
+This will download a script and start the installation. You may be prompted for +your password. If it all goes well, you’ll see this appear:
+Rust is installed now. Great!
+
+If you're on Windows, please download the appropriate installer.
+Uninstalling Rust is as easy as installing it. On Linux or Mac, just run +the uninstall script:
+$ rustup self uninstall
+
+If you used the Windows installer, you can re-run the .msi and it will give
+you an uninstall option.
If you've got Rust installed, you can open up a shell, and type this:
+$ rustc --version
+
+You should see the version number, commit hash, and commit date in a format +similar to this for the latest stable version at the time you install:
+rustc x.y.z (abcabcabc yyyy-mm-dd)
+
+If you see this, Rust has been installed successfully! +Congrats!
+If you don't and you're on Windows, check that Rust is in your %PATH% system
+variable. If it isn't, run the installer again, select "Change" on the "Change,
+repair, or remove installation" page and ensure "Add to PATH" is checked.
If not, there are a number of places where you can get help. The easiest is +the #rust IRC channel on irc.mozilla.org, which you can access through +Mibbit. Click that link, and you'll be chatting with other Rustaceans +(a silly nickname we call ourselves) who can help you out. Other great resources +include the user’s forum and Stack Overflow.
+The installer also includes a copy of the documentation locally, so you can
+read it offline. On Linux or Mac, run rustup doc to open the local
+documentation in your browser. On Windows, the documentation is in a
+share/doc directory inside the directory where Rust was installed.
Welcome to “The Rust Programming Language”, an introductory book about Rust. -Rust is a programming language that’s focused on safety, concurrency, and -speed. It maintains these goals without having a garbage collector, making it a -useful language for a number of use cases other languages aren’t good at: -embedding in other languages, programs with specific space and time -requirements, and writing low-level code, like device drivers and operating -systems. It improves on current languages targeting this space by having a -number of compile-time safety checks that produce no runtime overhead, while -eliminating all data races. Rust also aims to achieve ‘zero-cost abstractions’ -even though some of these abstractions feel like those of a high-level -language. Even then, Rust still allows precise control like a low-level -language would.
-This book is written for a reader who already knows how to program in at least -one programming language. Which language that is does not matter very much, -though you may have an easier time if you’ve programmed in a low-level language -with manual memory allocation.
-After reading this book, you should be comfortable writing Rust programs. We’ll -be learning Rust through small, focused examples that demonstrate each topic. -The chapters build upon each other, so if you skip ahead, you may have to skip -back to refer to a previous concept.
-This book is open source. If you find an error, please don’t hesitate to file an -issue or send a pull request on GitHub.
- -Now that you have Rust installed, let’s write your first Rust program. It's +traditional when learning a new language to write a little program to print the +text “Hello, world!” to the screen, and in this section, we'll follow that +tradition.
+++Note: This book assumes basic familiarity with the command line. Rust itself +makes no specific demands about your editing, tooling, or where your code +lives, so if you prefer an IDE to the command line, that's an option.
+
First, make a file to put your Rust code in. Rust doesn't care where your code +lives, but for this book, we'd suggest making a projects directory in your +home directory and keeping all your projects there. Open a terminal and enter +the following commands to make a directory for this particular project:
+$ mkdir ~/projects
+$ cd ~/projects
+$ mkdir hello_world
+$ cd hello_world
+
+++Note: If you’re on Windows and not using PowerShell, the
+~that represents +your home directory may not work. +Consult the documentation for your shell for more details.
Next, make a new source file and call it main.rs. Rust files always end with +the .rs extension. If you’re using more than one word in your filename, use +an underscore to separate them. For example, you'd use hello_world.rs rather +than helloworld.rs.
+Now open the main.rs file you just created, and type the following code:
+fn main() {
+ println!("Hello, world!");
+}
+
+Save the file, and go back to your terminal window. On Linux or OSX, enter the +following commands:
+$ rustc main.rs
+$ ./main
+Hello, world!
+
+On Windows, just replace main with main.exe. Regardless of your operating
+system, you should see the string Hello, world! print to the terminal. If you
+did, then congratulations! You've officially written a Rust program. That makes
+you a Rust programmer! Welcome.
Now, let’s go over what just happened in your "Hello, world!" program in +detail. Here's the first piece of the puzzle:
+fn main() {
+
+}
+
+These lines define a function in Rust. The main function is special: it's
+the first thing that is run for every executable Rust program. The first line
+says, “I’m declaring a function named main that takes no arguments and
+returns nothing.” If there were arguments, they would go inside the parentheses
+(( and )). We aren’t returning anything from this function, so we have
+omitted the return type entirely. If there was a return type, there would be a
+-> and the return type after the parentheses.
Also note that the function body is wrapped in curly braces ({ and }). Rust
+requires these around all function bodies. It's considered good style to put
+the opening curly brace on the same line as the function declaration, with one
+space in between.
Inside the main() function:
println!("Hello, world!");
+
+This line does all of the work in this little program: it prints text to the +screen. There are a number of details that are important here. The first is +that it’s indented with four spaces, not tabs.
+The second important part is println!(). This is calling a Rust macro,
+which is how metaprogramming is done in Rust. If it were calling a function
+instead, it would look like this: println() (without the !). We'll discuss
+Rust macros in more detail in Chapter XX, but for now you just need to know
+that when you see a ! that means that you’re calling a macro instead of a
+normal function.
Next is "Hello, world!" which is a string. We pass this string as an
+argument to println!(), which prints the string to the screen. Easy enough!
The line ends with a semicolon (;). The ; indicates that this expression is
+over, and the next one is ready to begin. Most lines of Rust code end with a
+;.
In "Writing and Running a Rust Program", we showed you how to run a newly +created program. We'll break that process down and examine each step now.
+Before running a Rust program, you have to compile it. You can use the Rust
+compiler by entering the rustc command and passing it the name of your source
+file, like this:
$ rustc main.rs
+
+If you come from a C or C++ background, you'll notice that this is similar to
+gcc or clang. After compiling successfully, Rust should output a binary
+executable, which you can see on Linux or OSX by entering the ls command in
+your shell as follows:
$ ls
+main main.rs
+
+On Windows, you'd enter:
+$ dir
+main.exe main.rs
+
+This shows we have two files: the source code, with the .rs extension, and the
+executable (main.exe on Windows, main everywhere else). All that's left to
+do from here is run the main or main.exe file, like this:
$ ./main # or main.exe on Windows
+
+If main.rs were your "Hello, world!" program, this would print Hello, world! to your terminal.
If you come from a dynamic language like Ruby, Python, or JavaScript, you may
+not be used to compiling and running a program being separate steps. Rust is an
+ahead-of-time compiled language, which means that you can compile a program,
+give it to someone else, and they can run it even without having Rust
+installed. If you give someone a .rb, .py, or .js file, on the other
+hand, they need to have a Ruby, Python, or JavaScript implementation installed
+(respectively), but you only need one command to both compile and run your
+program. Everything is a tradeoff in language design.
Just compiling with rustc is fine for simple programs, but as your project
+grows, you'll want to be able to manage all of the options your project has
+and make it easy to share your code with other people and projects. Next, we'll
+introduce you to a tool called Cargo, which will help you write real-world Rust
+programs.
Cargo is Rust’s build system and package manager, and Rustaceans use Cargo to +manage their Rust projects because it makes a lot of tasks easier. For example, +Cargo takes care of building your code, downloading the libraries your code +depends on, and building those libraries. We call libraries your code needs +‘dependencies’ since your code depends on them.
+The simplest Rust programs, like the one we've written so far, don’t have any +dependencies, so right now, you'd only be using the part of Cargo that can take +care of building your code. As you write more complex Rust programs, you’ll +want to add dependencies, and if you start off using Cargo, that will be a lot +easier to do.
+As the vast, vast majority of Rust projects use Cargo, we will assume that +you’re using it for the rest of the book. Cargo comes installed with Rust +itself, if you used the official installers as covered in the Installation +chapter. If you installed Rust through some other means, you can check if you +have Cargo installed by typing the following into your terminal:
+$ cargo --version
+
+If you see a version number, great! If you see an error like command not found, then you should look at the documentation for the way you installed
+Rust to determine how to install Cargo separately.
Let's create a new project using Cargo and look at how it differs from our
+project in hello_world. Go back to your projects directory (or wherever you
+decided to put your code):
$ cd ~/projects
+
+And then run:
+$ cargo new hello_cargo --bin
+$ cd hello_cargo
+
+We passed the --bin argument to cargo new because our goal is to make an
+executable application, as opposed to a library. Executables are often called
+binaries (as in /usr/bin, if you’re on a Unix system). hello_cargo is the
+name we've chosen for our project, and Cargo creates its files in a directory
+of the same name that we can then go into.
If we list the files in the hello_cargo directory, we can see that Cargo has
+generated two files and one directory for us: a Cargo.toml and a src
+directory with a main.rs file inside. It has also initialized a new git
+repository in the hello_cargo directory for us; you can change this to use a
+different version control system, or no version control system, by using the
+--vcs flag.
Open up Cargo.toml in your text editor of choice. It should look something
+like this:
[package]
+name = "hello_cargo"
+version = "0.1.0"
+authors = ["Your Name <you@example.com>"]
+
+[dependencies]
+
+This file is in the TOML (Tom's Obvious, Minimal Language) format. TOML is +similar to INI but has some extra goodies and is used as Cargo’s +configuration format.
+The first line, [package], is a section heading that indicates that the
+following statements are configuring a package. As we add more information to
+this file, we’ll add other sections.
The next three lines set the three bits of configuration that Cargo needs to +see in order to know that it should compile your program: its name, what +version it is, and who wrote it. Cargo gets your name and email information +from your environment. If it’s not correct, go ahead and fix that and save the +file.
+The last line, [dependencies], is the start of a section for you to list any
+crates that your project will depend on so that Cargo knows to download and
+compile those too. We won't need any other crates for this project, but we will
+in the guessing game tutorial in the next chapter.
Now let's look at src/main.rs:
fn main() {
+ println!("Hello, world!");
+}
+
+Cargo has generated a "Hello World!" for you, just like the one we wrote +earlier! So that part is the same. The differences between our previous project +and the project generated by Cargo that we've seen so far are:
+src directoryCargo.toml configuration fileCargo expects your source files to live inside the src directory so that the +top-level project directory is just for READMEs, license information, +configuration files, and anything else not related to your code. In this way, +using Cargo helps you keep your projects nice and tidy. There's a place for +everything, and everything is in its place.
+If you started a project that doesn't use Cargo, as we did with our project in
+the hello_world directory, you can convert it to a project that does use
+Cargo by moving your code into the src directory and creating an appropriate
+Cargo.toml.
Now let's look at what's different about building and running your Hello World +program through Cargo! To do so, enter the following commands:
+$ cargo build
+ Compiling hello_cargo v0.1.0 (file:///home/yourname/projects/hello_cargo)
+
+This should have created an executable file in target/debug/hello_cargo (or target/debug/hello_cargo.exe on Windows), which you can run with this command:
$ ./target/debug/hello_cargo # or ./target/debug/hello_cargo.exe on Windows
+Hello, world!
+
+Bam! If all goes well, Hello, world! should print to the terminal once more.
Running cargo build for the first time also causes Cargo to create a new file
+at the top level called Cargo.lock, which looks like this:
[root]
+name = "hello_cargo"
+version = "0.1.0"
+
+Cargo uses the Cargo.lock file to keep track of dependencies in your +application. This project doesn't have dependencies, so the file is a bit +sparse. Realistically, you won't ever need to touch this file yourself; just +let Cargo handle it.
+We just built a project with cargo build and ran it with
+./target/debug/hello_cargo, but we can actually do both in one step with
+cargo run as follows:
$ cargo run
+ Running `target/debug/hello_cargo`
+Hello, world!
+
+Notice that this time, we didn't see the output that Cargo was compiling
+hello_cargo. Cargo figured out that the files haven’t changed, so it just ran
+the binary. If you had modified your source code, Cargo would have rebuilt the
+project before running it, and you would have seen something like this:
$ cargo run
+ Compiling hello_cargo v0.1.0 (file:///home/yourname/projects/hello_cargo)
+ Running `target/debug/hello_cargo`
+Hello, world!
+
+So a few more differences we've now seen:
+rustc, build a project using cargo build (or build and run it in one step with cargo run)target/debug directory.When your project is finally ready for release, you can use cargo build --release to compile your project with optimizations. This will create an
+executable in target/release instead of target/debug. These optimizations
+make your Rust code run faster, but turning them on makes your program take
+longer to compile. This is why there are two different profiles: one for
+development when you want to be able to rebuild quickly and often, and one for
+building the final program you’ll give to a user that won't be rebuilt and
+that we want to run as fast as possible. If you're benchmarking the running
+time of your code, be sure to run cargo build --release and benchmark with
+the executable in target/release.
With simple projects, Cargo doesn't provide a whole lot of value over just
+using rustc, but it will prove its worth as you continue. With complex
+projects composed of multiple crates, it’s much easier to let Cargo coordinate
+the build. With Cargo, you can just run cargo build, and it should work the
+right way. Even though this project is simple, it now uses much of the real
+tooling you’ll use for the rest of your Rust career. In fact, you can get
+started with virtually all Rust projects you might find that you want to work
+on with the following commands:
$ git clone someurl.com/someproject
+$ cd someproject
+$ cargo build
+
+++ +Note: If you want to look at Cargo in more detail, check out the official +Cargo guide, which covers all of its features.
+
The first step to using Rust is to install it. Generally speaking, you’ll need -an internet connection to run the commands in this chapter, as we’ll be -downloading Rust from the internet.
-We’ll be showing off a number of commands using a terminal, and those lines all
-start with $. You don't need to type in the $s, they are there to indicate
-the start of each command. You’ll see many tutorials and examples around the web
-that follow this convention: $ for commands run as a regular user, and #
-for commands you should be running as an administrator.
If you're on Linux or a Mac, all you need to do is open a terminal and type this:
-$ curl -sSf https://static.rust-lang.org/rustup.sh | sh
-
-This will download a script, and start the installation. You may be prompted for your password. -If it all goes well, you’ll see this appear:
- Rust is ready to roll.
-
-If you're on Windows, please download the appropriate installer.
-Uninstalling Rust is as easy as installing it. On Linux or Mac, just run -the uninstall script:
-$ sudo /usr/local/lib/rustlib/uninstall.sh
-
-If you used the Windows installer, you can re-run the .msi and it will give you
-an uninstall option.
If you've got Rust installed, you can open up a shell, and type this:
-$ rustc --version
-
-You should see the version number, commit hash, and commit date.
-If you do, Rust has been installed successfully! Congrats!
-If you don't and you're on Windows, check that Rust is in your %PATH% system
-variable. If it isn't, run the installer again, select "Change" on the "Change,
-repair, or remove installation" page and ensure "Add to PATH" is checked.
If not, there are a number of places where you can get help. The easiest is -the #rust IRC channel on irc.mozilla.org, which you can access through -Mibbit. Click that link, and you'll be chatting with other Rustaceans -(a silly nickname we call ourselves) who can help you out. Other great resources -include the user’s forum, and Stack Overflow.
-This installer also installs a copy of the documentation locally, so you can
-read it offline. On UNIX systems, /usr/local/share/doc/rust is the location.
-On Windows, it's in a share/doc directory, inside the directory to which Rust
-was installed.
Now that you have Rust installed, let’s write your first Rust program. It's -traditional when learning a new language to write a little program to print the -text “Hello, world!” to the screen, and in this section, we'll follow that -tradition.
-The nice thing about starting with such a simple program is that you can -quickly verify that your compiler is installed, and that it's working properly. -Printing information to the screen is also just a pretty common thing to do, so -practicing it early on is good.
---Note: This book assumes basic familiarity with the command line. Rust itself -makes no specific demands about your editing, tooling, or where your code -lives, so if you prefer an IDE to the command line, that's an option.
-
First, make a file to put your Rust code in. Rust doesn't care where your code -lives, but for this book, I suggest making a projects directory in your home -directory, and keeping all your projects there. Open a terminal and enter the -following commands to make a directory for this particular project:
-$ mkdir ~/projects
-$ cd ~/projects
-$ mkdir hello_world
-$ cd hello_world
-
---Note: If you’re on Windows and not using PowerShell, the
-~may not work. -Consult the documentation for your shell for more details.
Next, make a new source file and call it main.rs. Rust files always end -in a .rs extension. If you’re using more than one word in your filename, use -an underscore to separate them; for example, you'd use hello_world.rs rather -than helloworld.rs.
-Now open the main.rs file you just created, and type the following code:
-fn main() {
- println!("Hello, world!");
-}
-
-Save the file, and go back to your terminal window. On Linux or OSX, enter the -following commands:
-$ rustc main.rs
-$ ./main
-Hello, world!
-
-In Windows, just replace main with main.exe. Regardless of your operating
-system, you should see the string Hello, world! print to the terminal. If you
-did, then congratulations! You've officially written a Rust program. That makes
-you a Rust programmer! Welcome.
Now, let’s go over what just happened in your "Hello, world!" program in -detail. Here's the first piece of the puzzle:
-fn main() {
-
-}
-
-These lines define a function in Rust. The main function is special: it's
-the beginning of every Rust program. The first line says, “I’m declaring a
-function named main that takes no arguments and returns nothing.” If there
-were arguments, they would go inside the parentheses (( and )), and because
-we aren’t returning anything from this function, we can omit the return type
-entirely.
Also note that the function body is wrapped in curly braces ({ and }). Rust
-requires these around all function bodies. It's considered good style to put
-the opening curly brace on the same line as the function declaration, with one
-space in between.
Inside the main() function:
println!("Hello, world!");
-
-This line does all of the work in this little program: it prints text to the -screen. There are a number of details that are important here. The first is -that it’s indented with four spaces, not tabs.
-The second important part is the println!() line. This is calling a Rust
-macro, which is how metaprogramming is done in Rust. If it were calling a
-function instead, it would look like this: println() (without the !). We'll
-discuss Rust macros in more detail later, but for now you just need to
-know that when you see a ! that means that you’re calling a macro instead of
-a normal function.
Next is "Hello, world!" which is a string. We pass this string as an
-argument to println!, which prints the string to the screen. Easy enough!
The line ends with a semicolon (;). Rust is an expression oriented
-language, which means that most things are expressions, rather than statements.
-The ; indicates that this expression is over, and the next one is ready to
-begin. Most lines of Rust code end with a ;.
In "Writing and Running a Rust Program", we showed you how to run a newly -created program. We'll break that process down and examine each step now.
-Before running a Rust program, you have to compile it. You can use the Rust
-compiler by entering the rustc command and passing it the name of your source
-file, like this:
$ rustc main.rs
-
-If you come from a C or C++ background, you'll notice that this is similar to
-gcc or clang. After compiling successfully, Rust should output a binary
-executable, which you can see on Linux or OSX by entering the ls command in
-your shell as follows:
$ ls
-main main.rs
-
-On Windows, you'd enter:
-$ dir
-main.exe main.rs
-
-This shows we have two files: the source code, with an .rs extension, and the
-executable (main.exe on Windows, main everywhere else). All that's left to
-do from here is run the main or main.exe file, like this:
$ ./main # or main.exe on Windows
-
-If main.rs were your "Hello, world!" program, this would print Hello, world! to your terminal.
If you come from a dynamic language like Ruby, Python, or JavaScript, you may
-not be used to compiling and running a program being separate steps. Rust is an
-ahead-of-time compiled language, which means that you can compile a program,
-give it to someone else, and they can run it even without Rust installed. If
-you give someone a .rb or .py or .js file, on the other hand, they need
-to have a Ruby, Python, or JavaScript implementation installed (respectively),
-but you only need one command to both compile and run your program. Everything
-is a tradeoff in language design.
Just compiling with rustc is fine for simple programs, but as your project
-grows, you'll want to be able to manage all of the options your project has,
-and make it easy to share your code with other people and projects. Next, I'll
-introduce you to a tool called Cargo, which will help you write real-world Rust
-programs.
Cargo is Rust’s build system and package manager, and Rustaceans use Cargo to -manage their Rust projects. Cargo manages three things: building your code, -downloading the libraries your code depends on, and building those libraries. -We call libraries your code needs ‘dependencies’ since your code depends on -them.
-The simplest Rust programs don’t have any dependencies, so right now, you'd -only use the first part of its functionality. As you write more complex Rust -programs, you’ll want to add dependencies, and if you start off using Cargo, -that will be a lot easier to do.
-As the vast, vast majority of Rust projects use Cargo, we will assume that -you’re using it for the rest of the book. Cargo comes installed with Rust -itself, if you used the official installers. If you installed Rust through some -other means, you can check if you have Cargo installed by typing:
-$ cargo --version
-
-Into a terminal. If you see a version number, great! If you see an error like
-‘command not found’, then you should look at the documentation for the system
-in which you installed Rust, to determine if Cargo is separate.
Let’s convert the Hello World program to Cargo. To Cargo-fy a project, you need -to do three things:
-main.exe on Windows, main everywhere
-else).Let's get started!
-First, go back to your terminal, move to your hello_world directory, and -enter the following commands:
-$ mkdir src
-$ mv main.rs src/main.rs # or 'move main.rs src/main.rs' on Windows
-$ rm main # or 'del main.exe' on Windows
-
-Cargo expects your source files to live inside a src directory, so do that -first. This leaves the top-level project directory (in this case, -hello_world) for READMEs, license information, and anything else not related -to your code. In this way, using Cargo helps you keep your projects nice and -tidy. There's a place for everything, and everything is in its place.
-Now, move main.rs into the src directory, and delete the compiled file you
-created with rustc. As usual, replace main with main.exe if you're on
-Windows.
This example retains main.rs as the source filename because it's creating an
-executable. If you wanted to make a library instead, you'd name the file
-lib.rs. This convention is used by Cargo to successfully compile your
-projects, but it can be overridden if you wish.
Next, create a new file inside your hello_world directory, and call it
-Cargo.toml.
Make sure to capitalize the C in Cargo.toml, or Cargo won't know what to do
-with the configuration file.
This file is in the TOML (Tom's Obvious, Minimal Language) format. TOML is -similar to INI, but has some extra goodies, and is used as Cargo’s -configuration format.
-Inside this file, type the following information:
-[package]
-
-name = "hello_world"
-version = "0.1.0"
-authors = [ "Your name <you@example.com>" ]
-
-The first line, [package], indicates that the following statements are
-configuring a package. As we add more information to this file, we’ll add other
-sections, but for now, we just have the package configuration.
The other three lines set the three bits of configuration that Cargo needs to -know to compile your program: its name, what version it is, and who wrote it.
-Once you've added this information to the Cargo.toml file, save it to finish -creating the configuration file.
-With your Cargo.toml file in place in your project's root directory, you -should be ready to build and run your Hello World program! To do so, enter the -following commands:
-$ cargo build
- Compiling hello_world v0.1.0 (file:///home/yourname/projects/hello_world)
-$ ./target/debug/hello_world
-Hello, world!
-
-Bam! If all goes well, Hello, world! should print to the terminal once more.
You just built a project with cargo build and ran it with
-./target/debug/hello_world, but you can actually do both in one step with
-cargo run as follows:
$ cargo run
- Running `target/debug/hello_world`
-Hello, world!
-
-Notice that this example didn’t re-build the project. Cargo figured out that -the file hasn’t changed, and so it just ran the binary. If you'd modified your -source code, Cargo would have rebuilt the project before running it, and you -would have seen something like this:
-$ cargo run
- Compiling hello_world v0.1.0 (file:///home/yourname/projects/hello_world)
- Running `target/debug/hello_world`
-Hello, world!
-
-Cargo checks to see if any of your project’s files have been modified, and only -rebuilds your project if they’ve changed since the last time you built it.
-With simple projects, Cargo doesn't bring a whole lot over just using rustc,
-but it will become useful in the future. With complex projects composed of multiple
-crates, it’s much easier to let Cargo coordinate the build. With Cargo, you can
-just run cargo build, and it should work the right way.
When your project is finally ready for release, you can use cargo build --release to compile your project with optimizations. These optimizations make
-your Rust code run faster, but turning them on makes your program take longer
-to compile. This is why there are two different profiles, one for development,
-and one for building the final program you’ll give to a user.
Running this command also causes Cargo to create a new file called -Cargo.lock, which looks like this:
-[root]
-name = "hello_world"
-version = "0.1.0"
-
-Cargo uses the Cargo.lock file to keep track of dependencies in your -application. This is the Hello World project's Cargo.lock file. This project -doesn't have dependencies, so the file is a bit sparse. Realistically, you -won't ever need to touch this file yourself; just let Cargo handle it.
-That’s it! If you've been following along, you should have successfully built
-hello_world with Cargo.
Even though the project is simple, it now uses much of the real tooling you’ll -use for the rest of your Rust career. In fact, you can expect to start -virtually all Rust projects with some variation on the following commands:
-$ git clone someurl.com/foo
-$ cd foo
-$ cargo build
-
-You don’t have to go through that previous process every time you want to start -a new project! Cargo can quickly make a bare-bones project directory that you -can start developing in right away.
-To start a new project with Cargo, enter cargo new at the command line:
$ cargo new hello_world --bin
-
-This command passes --bin because the goal is to get straight to making an
-executable application, as opposed to a library. Executables are often called
-binaries (as in /usr/bin, if you’re on a Unix system).
Cargo has generated two files and one directory for us: a Cargo.toml and a
-src directory with a main.rs file inside. These should look familiar,
-they’re exactly what we created by hand, above.
This output is all you need to get started. First, open Cargo.toml. It should
-look something like this:
[package]
-
-name = "hello_world"
-version = "0.1.0"
-authors = ["Your Name <you@example.com>"]
-
-Cargo has populated Cargo.toml with reasonable defaults based on the arguments
-you gave it and your git global configuration. You may notice that Cargo has
-also initialized the hello_world directory as a git repository.
Here’s what should be in src/main.rs:
fn main() {
- println!("Hello, world!");
-}
-
-Cargo has generated a "Hello World!" for you, and you’re ready to start coding!
--- -Note: If you want to look at Cargo in more detail, check out the official Cargo -guide, which covers all of its features.
-
Let's jump into Rust with a hands-on 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.
+Let’s set up a new project. Go to your projects directory, and create a new project using Cargo.
+$ cd ~/projects
+$ cargo new guessing_game --bin
+$ cd guessing_game
+
+We pass the name of our project to cargo new, then the --bin flag, since
+we’re going to be making another binary like in Chapter 1.
Take a look at the generated Cargo.toml:
[package]
+name = "guessing_game"
+version = "0.1.0"
+authors = ["Your Name <you@example.com>"]
+
+[dependencies]
+
+If the authors information that Cargo got from your environment is not correct, +go ahead and fix that.
+And as we saw in the last chapter, cargo new generates a ‘Hello, world!’ for
+us. Check out src/main.rs:
fn main() {
+ println!("Hello, world!");
+}
+
+Let’s try compiling what Cargo gave us and running it in the same step, using the cargo run command:
$ cargo run
+ Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
+ Running `target/debug/guessing_game`
+Hello, world!
+
+Great! The run command comes in handy when you need to rapidly iterate on a
+project. Our game is such a project: we want to quickly test each
+iteration before moving on to the next one.
Now open up your src/main.rs again. We’ll be writing all of our code in this
+file.
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:
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)
+ .expect("Failed to read line");
+
+ println!("You guessed: {}", guess);
+}
+
+There’s a lot here! Let’s go over it, bit by bit.
+use std::io;
+
+We’ll need to take user input and then print the result as output. As such, we
+need the io library from the standard library. Rust only imports a few things
+by default into every program, the ‘prelude’. If it’s not in the
+prelude, you’ll have to use it directly. Using the std::io library gets
+you a number of useful io-related things, so that's what we've done here.
fn main() {
+
+As you’ve seen in Chapter 1, the main() function is the entry point into the
+program. The fn syntax declares a new function, the ()s indicate that
+there are no arguments, and { starts the body of the function.
println!("Guess the number!");
+
+println!("Please input your guess.");
+
+We previously learned in Chapter 1 that 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 what are called ‘variable bindings’. Here's an example:
+let foo = bar;
+
+This will create a new binding named foo, and bind it to the value 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: it makes a binding mutable, rather than immutable.
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 will introduce a mutable binding named
+guess, but we have to look at the other side of the = for what it’s
+bound to: String::new().
String is a string type, provided by the standard library. A
+String is a growable, UTF-8 encoded bit of text.
The ::new() syntax uses :: because this is an ‘associated function’ of
+a particular type. That is to say, it’s associated with String itself,
+rather than a particular instance of a String. Some languages call this a
+‘static method’.
This function is named new(), because it creates a new, empty String.
+You’ll find a new() function on many types, as it’s a common name for making
+a new value of some kind.
Let’s move forward:
+io::stdin().read_line(&mut guess)
+ .expect("Failed to read line");
+
+Let’s go through this together bit-by-bit. The first line has two parts. Here’s +the first:
+io::stdin()
+
+Remember how we used std::io on the first line of the program? We’re now
+calling an associated function on it. If we didn’t use std::io, we could
+have written this line as 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:
+.read_line(&mut guess)
+
+Here, we call the read_line() method on our handle. We’re also
+passing one argument to read_line(): &mut guess.
Remember how we bound guess above? We said it was mutable. However,
+read_line doesn’t take a String as an argument: it takes a &mut String.
+The & is the feature of Rust called a ‘reference’, which allows you to have
+multiple ways to access one piece of data in order to 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; Chapter XX will cover them in
+more detail. For now, all we need to know is that like let bindings,
+references are immutable by default. Hence, we need to write &mut guess,
+rather than &guess.
Why does 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, that string 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. This is the second part of the line:
+.expect("Failed to read line");
+
+When you call a method with the .foo() syntax, you may introduce a newline
+and other whitespace. This helps you split up long lines. We could have
+written this code as:
io::stdin().read_line(&mut guess).expect("failed to read line");
+
+But that gets hard to read. So we’ve split it up, two lines for two method +calls.
+Result TypeWe already talked about read_line(), but what about expect()? Well,
+we already mentioned that read_line() puts what the user types into the &mut String we pass it. But it also returns a value: in this case, an
+io::Result. Rust has a number of types named Result in its
+standard library: a generic Result, and then specific versions for
+sub-libraries, like io::Result.
The purpose of these Result types is to encode error handling information.
+Values of the Result type, like any type, have methods defined on them. In
+this case, io::Result has an expect() method that takes a value
+it’s called on, and if it isn’t a successful result, will cause our program to
+crash and display the message that we passed as an argument to expect().
If we don't call this method, 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 value. This warning comes from
+a special annotation that 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 want to crash if there’s a
+problem, we can use expect(). If we can recover from the error somehow, we’d
+do something else, but we’ll save that for a future project.
println!() PlaceholdersThere’s only one line of this first example left, aside from the closing curly +brace:
+ println!("You guessed: {}", guess);
+}
+
+This prints out the string we saved our input in. The {}s are a placeholder:
+think of {} as little crab pincers, holding a value in place. The first {}
+holds the first value after the format string, the second set holds the second
+value, and so on. Printing out multiple values in one call to println!() would then look like this:
let x = 5;
+let y = 10;
+
+println!("x and y: {} and {}", x, y);
+
+Which would print out "x and y: 5 and 10".
+Anyway, back to our guessing game. We can run what we have with 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 crate. A ‘crate’ is a package of Rust code.
+We’ve been building a ‘binary crate’, which is an executable. 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, we need to modify our Cargo.toml. Open it up, and
+add this line at the bottom beneath the [dependencies] section header that
+Cargo created for you:
[dependencies]
+
+rand = "0.3.14"
+
+The [dependencies] section of Cargo.toml is like the [package] section:
+everything that follows the section heading is part of that section, until
+another section starts. Cargo uses the dependencies section to know what
+dependencies on external crates you have and what versions of those crates you
+require. In this case, we’ve specified the rand crate with the semantic
+version specifier 0.3.14. Cargo understands Semantic Versioning, a
+standard for writing version numbers. A bare number like above is actually
+shorthand for ^0.3.14, which means "any version that has a public API
+compatible with version 0.3.14".
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.14
+ Downloading libc v0.2.14
+ Compiling libc v0.2.14
+ Compiling rand v0.3.14
+ Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
+
+You may see different versions (but they will be compatible, thanks to semver!) +and the lines may be in a different order.
+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] and downloads
+any we don’t have yet. In this case, while we only said we wanted to depend on
+rand, we’ve also grabbed a copy of libc. This is because rand depends on
+libc to work. After downloading them, it compiles them and then compiles
+our project.
If we run cargo build again, we’ll get different output:
$ cargo build
+
+That’s right, no output! Cargo knows that our project has been built, that
+all of its dependencies are built, and that no changes have been made. There’s
+no reason to do all that stuff again. With nothing to do, it simply
+exits. If we open up src/main.rs, make a trivial change, then save it again,
+we’ll only see one line:
$ cargo build
+ Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
+
+What happens when next week version v0.3.15 of the rand crate comes out,
+with an important bugfix? While getting bugfixes is important, what if 0.3.15
+contains a regression that breaks our code?
The answer to this problem is the Cargo.lock file created the first time we
+ran cargo build that is now in your project directory. When you build your
+project for the first time, Cargo figures out all of the versions that fit your
+criteria then writes them to the Cargo.lock file. When you build your project
+in the future, Cargo will see that the Cargo.lock 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.14 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.15? Cargo has another command,
+update, which says ‘ignore the Cargo.lock file and figure out all the
+latest versions that fit what we’ve specified in Cargo.toml. 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 and smaller than 0.4.0. If we want to
+move to 0.4.x, we’d have to update what is in the Cargo.toml file. When we
+do, the next time we cargo build, Cargo will update the index and re-evaluate
+our rand requirements.
There’s a lot more to say about Cargo and its +ecosystem that we will get into in Chapter XX, but for now, +that’s all we need to know. Cargo makes it really easy to re-use libraries, so +Rustaceans are able to write smaller projects which are assembled out of a +number of sub-packages.
+Let’s get on to actually using 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)
+ .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. Because we declared rand in our [dependencies], we can now put
+extern crate in our code to let Rust know we’ll be making use of that
+dependency. This also does the equivalent of a use rand; as well, so we can
+call anything in the rand crate by prefixing it with rand::.
Next, we added another use line: use rand::Rng. We’re going to use a
+method in a moment, and it requires that 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 in Chapter XX.
There are two other lines we added, in the middle:
+let secret_number = rand::thread_rng().gen_range(1, 101);
+
+println!("The secret number is: {}", secret_number);
+
+We use the rand::thread_rng() function to get a copy of the random number
+generator, which is local to the particular thread of execution
+we’re in. Because we put use rand::Rng above, the random number generator has
+a gen_range() method available. This method takes two numbers as arguments
+and generates a random number between them. It’s inclusive on the lower bound
+but exclusive on the upper bound, so we need 1 and 101 to ask for a number
+ranging from one to a hundred.
The second line prints out the secret number. This is useful while +we’re developing our program to let us 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
+
+You should get different random numbers, and they should all be between 1 and
+Now that we’ve got user input, let’s compare our guess to the secret number. +Here’s part of our next step. It won't quite compile yet though:
+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)
+ .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. We bring a type called
+std::cmp::Ordering into scope. Then we add five new lines at the bottom that
+use that type:
match guess.cmp(&secret_number) {
+ Ordering::Less => println!("Too small!"),
+ Ordering::Greater => println!("Too big!"),
+ Ordering::Equal => println!("You win!"),
+}
+
+The 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
+Ordering type we used earlier. We use a match statement to
+determine exactly what kind of Ordering it is. Ordering is an
+enum, short for ‘enumeration’, which looks like this:
enum Foo {
+ Bar,
+ Baz,
+}
+
+With this definition, anything of type Foo can be either a
+Foo::Bar or a Foo::Baz. We use the :: to indicate the
+namespace for a particular enum variant.
The Ordering enum has three possible variants: Less, Equal,
+and Greater. The match statement takes a value of a type and lets you
+create an ‘arm’ for each possible value. An arm is made up of a pattern and the
+code that we should execute if the pattern matches the value of the type. Since
+we have three types of 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, we print Too small!, if it’s Greater, Too big!, and if
+Equal, You win!. match is really useful and is used often in Rust.
We did mention that this won’t quite compile yet, though. Let’s try it:
+$ cargo build
+ Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
+src/main.rs:23:21: 23:35 error: mismatched types [E0308]
+src/main.rs:23 match guess.cmp(&secret_number) {
+ ^~~~~~~~~~~~~~
+src/main.rs:23:21: 23:35 help: run `rustc --explain E0308` to see a detailed explanation
+src/main.rs:23:21: 23:35 note: expected type `&std::string::String`
+src/main.rs:23:21: 23:35 note: found type `&_`
+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(), Rust was able to infer that guess
+should be a String, so it doesn’t make us write out the type. With our
+secret_number, there are a number of types which can have a value between one
+and a hundred: i32, a thirty-two-bit number, or u32, an unsigned
+thirty-two-bit number, or i64, a sixty-four-bit number or others. So far,
+that hasn’t mattered, and so Rust defaults to an i32. However, here, Rust
+doesn’t know how to compare the guess and the secret_number. They need to
+be the same type.
Ultimately, we want to convert the String we read as input
+into a real number type so that we can compare it to the guess numerically. We
+can do that with two 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)
+ .expect("failed to read line");
+
+ let guess: u32 = guess.trim().parse()
+ .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 two lines:
+let guess: u32 = guess.trim().parse()
+ .expect("Please type a number!");
+
+Wait a minute, didn't we already have a guess? We do, but Rust allows us
+to ‘shadow’ the previous guess with a new one. This is often used in this
+exact situation, where guess starts as a String, but we want to convert it
+to a u32. Shadowing lets us re-use the guess name rather than forcing us
+to come up with two unique names like guess_str and guess or something
+else.
We bind guess to an expression that looks like something we wrote earlier:
guess.trim().parse()
+
+Here, guess refers to the old guess, the one that was a String with our
+input in it. The trim() method on 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 read_line(). If we type 5 and hit return, guess
+looks like this: 5\n. The \n represents ‘newline’, the enter key. trim()
+gets rid of this, leaving our string with only the 5.
The 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. The colon (:)
+after guess tells Rust we’re going to annotate its type. u32 is an
+unsigned, thirty-two bit integer. Rust has a number of built-in number
+types, but we’ve chosen u32. It’s a good default choice for a small
+positive number. You'll see the other number types in Chapter XX.
Just like read_line(), our call to parse() could cause an error. What if
+our string contained A👍%? There’d be no way to convert that to a number. As
+such, we’ll do the same thing we did with read_line(): use the expect()
+method 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 we even added spaces before our guess, and it still figured +out that we guessed 76. Run the program a few times. Verify that guessing +the secret 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 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)
+ .expect("failed to read line");
+
+ let guess: u32 = guess.trim().parse()
+ .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()? If we give a non-number answer, the program
+will crash and, therefore, 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!: ParseIntError { kind: InvalidDigit }', src/libcore/result.rs:785
+note: Run with `RUST_BACKTRACE=1` for a backtrace.
+error: Process didn't exit successfully: `target/debug/guess` (exit code: 101)
+
+Ha! 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)
+ .expect("failed to read line");
+
+ let guess: u32 = guess.trim().parse()
+ .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 line after the You win!, we’ll exit the loop when we
+win. Exiting the loop also means exiting the program, since the loop is the last
+thing in main(). We have another tweak to make: when someone inputs a
+non-number, we don’t want to quit, we 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)
+ .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:
+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 expect() to a match statement. A Result is the
+return type of parse(). Result is an enum like Ordering, but in this
+case, each variant has some data associated with it. Ok is a success, and
+Err is a failure. Each contains more information: in this case, the
+successfully parsed integer or an error type, respectively. When we match an
+Ok(num), that pattern sets the name num to the value inside the Ok (the
+integer), and the code we run just returns that integer. In the Err case, we
+don’t care what kind of error it is, so we just use the catch-all _ instead
+of a name. So for all errors, we run the code continue, which lets us move to
+the next iteration of the loop, effectively ignoring the errors.
Now we should be good! Let’s try it:
+$ 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 can finish 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)
+ .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;
+ }
+ }
+ }
+}
+
+This project showed you a lot: let, match, methods, associated
+functions, using external crates, and more.
At this point, you have successfully built the Guessing Game! Congratulations!
+ +Let's look at concepts that appear in almost every programming language and see +how they work in Rust. Many programming languages have much in common at their +core. None of the concepts presented in this chapter are unique to Rust, but +we’ll discuss Rust’s particular syntax and conventions concerning these common +concepts.
+Specifically, we’ll be talking about variable bindings, basic types, functions, +comments, and control flow. These foundations will be in every Rust +program, and learning them early will give you a strong core to start from.
+PROD: START BOX
+Keep in mind as we get into variables and functions that the Rust language has +a set of keywords that have been reserved for use by the language only, much +like other languages do. This means you cannot use these words as names of +variables or functions, for example. Most of these have special meaning and we +will be using them to do various things in our Rust programs; a few have no +current functionality associated but have been reserved for functionality that +might be in the Rust language in the future. You can find a list of the +keywords in Appendix XX.
+PROD: END BOX
+ +We’ll start our journey with Rust by talking about the absolute basics — -concepts that appear in almost every programming language. Many programming -languages have lots in common at their core. None of the concepts presented are -unique to Rust, but we’ll cover Rust’s particular syntax and conventions around -these common concepts.
-If you want to skip this section, you can, but you may end up coming back later -to find out small details. These foundations will be in every single useful -Rust program, and learning them gives us a strong core to start from.
- -We mentioned in Chapter XX that by default, variable bindings are immutable. +This is one of many nudges that Rust's design has to encourage us to write our +code to get the most of the safety and easy concurrency that Rust has to offer. +We still have the option to make our bindings mutable, though. Let's explore +how and why Rust encourages us to favor immutability, and why we might want to +opt out of that.
+Variable bindings being immutable means that once a value is bound, you can't +change that value. To illustrate this, let's generate a new project with Cargo. +Open a terminal, and navigate to the directory you want to store your projects +in. From there, run these commands:
+$ cargo new --bin bindings
+$ cd bindings
+
+Then open src/main.rs and replace its code with the following:
+fn main() {
+ let x = 5;
+ println!("The value of x is: {}", x);
+ x = 6;
+ println!("The value of x is: {}", x);
+}
+
+Save and run the program using cargo run, and you should receive an error
+message, as in this output:
$ cargo run
+ Compiling bindings v0.0.1 (file:///projects/bindings)
+error: re-assignment of immutable variable `x` [--explain E0384]
+ --> src/main.rs:4:5
+4 |> x = 6;
+ |> ^^^^^
+note: prior assignment occurs here
+ --> src/main.rs:2:9
+2 |> let x = 5;
+ |> ^
+
+This is our first example of the compiler helping us find an error in our +program! Compiler errors can be frustrating. Keep in mind that they only mean +your program isn't safely doing what you want it to do yet; they do not mean +that you're not a good programmer! Experienced Rustaceans still get compiler +errors. Try to keep in mind that the Rust compiler is trying to help your +program be the very best.
+PROD: START BOX +######Extended Error Explanations
+Now that you've seen an example of a Rust error, let's look at one particularly +useful aspect of errors. Rust encourages you to seek further information on the +kind of error you've received with output like this:
+error: re-assignment of immutable variable `x` [--explain E0384]
+
+This tells us that if we pass the --explain flag to rustc with the provided
+error code, we can see an extended explanation which will try to explain common
+causes of and solutions to that kind of error. Not every error has a longer
+explanation, but many do. Here’s the explanation for the E0384 error we
+received:
$ rustc --explain E0384
+This error occurs when an attempt is made to reassign an immutable variable.
+For example:
+
+```
+fn main(){
+ let x = 3;
+ x = 5; // error, reassignment of immutable variable
+}
+```
+
+By default, variables in Rust are immutable. To fix this error, add the keyword
+`mut` after the keyword `let` when declaring the variable. For example:
+
+```
+fn main(){
+ let mut x = 3;
+ x = 5;
+}
+```
+
+These explanations can really help if you’re stuck on an error, so don't +hesitate to look up the error code. The compiler is your friend, and it's there +to help.
+PROD: END BOX
+The error includes the message re-assigment of immutable variable because the
+program tried to assign a second value to the x variable.
Getting compile-time errors when your code attempts to change a value that it +previously said was immutable is important because this very situation can lead +to bugs. If one part of your code operates on an assumption that a value it's +operating on will never change, and another part of your code changes that +value, it's possible that the first code won't do what it was designed to do. +Especially when the second piece of code only changes the value sometimes, +this cause of bugs can be difficult to track down after the fact.
+In Rust, our code can know that a value our code assumes won't change really +won't change, because the compiler is enforcing that guarantee for us. When +reading and writing code, we don't have to keep track in our head how and where +a value might change. This can make code easier to reason about.
+Mutability is really useful, though! Bindings are immutable only by default;
+you can make them mutable by adding mut in front of the variable name. In
+addition to telling the compiler it should allow this value to be changed, it
+conveys intent to future readers of the code and says that other parts of the
+code will be changing this value.
For example, change the program you just wrote to the following:
+fn main() {
+ let mut x = 5;
+ println!("The value of x is: {}", x);
+ x = 6;
+ println!("The value of x is: {}", x);
+}
+
+Running this, we get:
+$ cargo run
+ Compiling bindings v0.1.0 (file:///projects/bindings)
+ Running `target/debug/bindings`
+The value of x is: 5
+The value of x is: 6
+
+Using mut, we are allowed to change the value that x binds to from 5 to
+6. You might want to make a binding mutable because it makes the code easier
+to understand than an implementation that only uses immutable bindings. In
+cases where you're using large data structures, mutating an instance in place
+may be faster than copying and returning newly allocated instances. It all
+depends on the tradeoffs you want to make in your situation.
As we saw in the guessing game tutorial, we can declare new bindings with the +same name as a previous binding, and the new binding shadows the previous +binding. We say that the first binding is ‘shadowed’ by the second, which means +that the second binding's value is what you will see when you use the variable +after the second binding. This can be useful if you’d like to perform a few +transformations on a value, but have the binding be immutable after those +transformations have been completed. For example:
+fn main() {
+ let x = 5;
+
+ let x = x + 1;
+
+ let x = x * 2;
+
+ println!("The value of x is: {}", x);
+}
+
+This program first binds x to a value of 5. Then, it shadows x by saying
+let x = again, taking the original value and adding 1 so that the value of
+x is then 6. The third let statement also shadows x, taking the
+previous value and multiplying it by 2 to give x a final value of 12. If
+you run this, it will output:
$ cargo run
+ Compiling bindings v0.1.0 (file:///projects/bindings)
+ Running `target/debug/bindings`
+The value of x is: 12
+
+Shadowing is useful because it lets us modify x without having to make the
+binding mutable. This means the compiler will still keep us from accidentally
+trying to mutate x directly later.
Now let's look at some of the types of values that we can bind variables to.
+ +Every value in Rust is of a certain type, which tells Rust what kind of data +is being given so it knows how to work with that data. In this section, we'll +look at a number of types built into the language itself split into two subsets +of Rust data types: scalar and compound.
+Something to keep in mind throughout this section: Rust is a statically typed
+language, which means that it must know the types of all bindings at compile
+time. The compiler can usually infer what type we want to use based on the
+value and how we use it. When many types are possible, such as when we
+converted a String to a numeric type using parse() in the guessing game
+tutorial, we can add a type annotation, like this:
let x: i32 = 5;
+
+You will see some type annotations as we discuss the various data types.
+A scalar type is one that represents a single value. There are four key +scalar types in Rust: integers, floating point numbers, booleans, and +characters. You'll likely recognize these from other programming languages, but +let's jump into how they work in Rust.
+An integer is a number without a fractional component. We've used one integer
+type already in this chapter, the i32 type. This type declaration indicates
+that the value it's associated with should be a signed integer (hence the i,
+as opposed to a u for unsigned) for a 32-bit system. There are a number of
+built-in integer types in Rust, shown in Table 3-1.
| Length | signed | unsigned |
| 8-bit | i8 | u8 |
| 16-bit | i16 | u16 |
| 32-bit | i32 | u32 |
| 64-bit | i64 | u64 |
| arch | isize | usize |
Table 4-1: Integer types in Rust. Each code (for example, i32) can be used to +declare the type of a value.
+Each variant can be either signed or unsigned and has an explicit size. Signed +and unsigned merely refers to whether it is possible for the number to be +either negative or positive, meaning the number needs to have a sign with it +("signed"), or whether it will only ever be positive and can therefore be +represented without a sign ("unsigned"). It's like writing numbers on paper: +when the sign matters, a number is shown with a plus sign or minus sign, but +when it's safe to assume the number is positive, it's shown with no sign. +Signed numbers are stored using two’s complement representation (if you're +unsure what this is you can search for it online; an explanation is outside the +scope of this text).
+Finally, the isize and usize types depend on the kind of computer your
+program is running on: 64-bits if you're on a 64-bit architecture, and 32-bits
+if you’re on a 32-bit architecture.
So how do you know which type of integer to use? If you're unsure, Rust's
+defaults are generally good choices, and integer types default to i32: it’s
+generally the fastest, even on 64-bit systems. The primary situation in which
+you'd need to specify isize or usize is when indexing some sort of
+collection, which we'll talk about in the "Arrays" section.
Rust also has two primitive types for floating-point numbers, which are
+numbers with decimal points. Rust's floating-point types are f32 and f64,
+which are 32 bits and 64 bits in size, respectively. The default type is f64,
+as it’s roughly the same speed as f32, but has a larger precision. It is
+possible to use an f64 on 32 bit systems, but it will be slower than using an
+f32 on those systems. Most of the time, trading potential worse performance
+for better precision is a reasonable initial choice, and you should benchmark
+your code if you suspect floating-point size is a problem in your case.
Here's an example showing floating-point numbers in action:
+fn main() {
+ let x = 2.0; // f64
+
+ let y: f32 = 3.0; // f32
+}
+
+Floating-point numbers are represented according to the IEEE-754 standard. The
+f32 type is a single-precision float, while f64 has double-precision.
Rust supports the usual basic mathematic operations you’d expect for all of
+these number types: addition, subtraction, multiplication, division, and
+modulo. This code shows how you'd use each one in a let statement:
fn main() {
+ // addition
+ let sum = 5 + 10;
+
+ // subtraction
+ let difference = 95.5 - 4.3;
+
+ // multiplication
+ let product = 4 * 30;
+
+ // division
+ let quotient = 56.7 / 32.2;
+
+ // modulo
+ let remainder = 43 % 5;
+}
+
+Each expression in these statements uses a mathematical operator and evaluates +to a single value, which is then bound to a variable.
+As in most other programming languages, a boolean type in Rust has two possible
+values: true and false. The boolean type in Rust is specified with bool.
+For example:
fn main() {
+ let t = true;
+
+ let f: bool = false; // with explicit type annotation
+}
+
+The main way to consume boolean values is through conditionals like an if
+statement. We’ll cover how if statements work in Rust in the "Control Flow"
+section of this chapter.
So far we’ve only worked with numbers, but Rust supports letters too. Rust’s
+char type is the language's most primitive alphabetic type, and this code
+shows one way to use it:
fn main() {
+ let c = 'z';
+ let z = 'ℤ';
+ let heart_eyed_cat = '😻';
+}
+
+Rust’s char represents a Unicode Scalar Value, which means that it can
+represent a lot more than just ASCII. Accented letters, Chinese/Japanese/Korean
+ideographs, emoji, and zero width spaces are all valid chars in Rust. Unicode
+Scalar Values range from U+0000 to U+D7FF and U+E000 to U+10FFFF
+inclusive. A "character" isn’t really a concept in Unicode, however, so your
+human intuition for what a "character" is may not match up with what a char
+is in Rust. It also means that chars are four bytes each. You can learn more
+about Unicode Scalar Values at
+http://www.unicode.org/glossary/#unicode_scalar_value and find a chart for
+all unicode code points at http://www.unicode.org/charts/.
Compound types can group multiple values of other types into one type. Rust +has two primitive compound types: tuples and arrays.
+We’ve seen tuples already, when binding multiple values at once. A tuple is a +general way of grouping together some number of other values with distinct +types into one compound type.
+We create a tuple by writing a comma-separated list of values inside +parentheses. Each position in the tuple has a distinct type, as in this example:
+fn main() {
+ let tup: (i32, f64, u8) = (500, 6.4, 1);
+}
+
+Note that, unlike the examples of multiple bindings, here we bind the single
+name tup to the entire tuple, emphasizing the fact that a tuple is considered
+a single compound element. We could then use pattern matching to destructure
+this tuple value, like this:
fn main() {
+ let tup: (i32, f64, u8) = (500, 6.4, 1);
+
+ let (x, y, z) = tup;
+
+ println!("The value of y is: {}", y);
+}
+
+In this program, we first create a tuple and bind it to the name tup. We then
+use a pattern with let to take tup and turn it into three separate
+bindings, x, y, and z. This is called ‘destructuring’, because it breaks
+the single tuple into three parts.
Finally, we print the value of y, which is 6.4.
In addition to destructuring through pattern matching, we can also access a
+tuple element directly by using a period (.) followed by the index of the
+value we want to access. For example:
fn main() {
+ let x: (i32, f64, u8) = (500, 6.4, 1);
+
+ let five_hundred = x.0;
+
+ let six_point_four = x.1;
+
+ let one = x.2;
+}
+
+This program creates a tuple, x, and then makes new bindings to each element
+by using their index. As with most programming languages, the first index in a
+tuple is 0.
Another way to bind a name to a collection of multiple values is with an +array. Unlike a tuple, every element of an array must have the same type. +Arrays in Rust are different than arrays in some other languages because arrays +in Rust have a fixed length-- once declared, they cannot grow or shrink in size.
+In Rust, the values going into an array are written as a comma separated list +inside square brackets:
+fn main() {
+ let a = [1, 2, 3, 4, 5];
+}
+
+While arrays can be useful since they are a primitive type, they aren't as
+flexible as the Vec (short for "vector"), a similar collection type provided
+by the standard library that is allowed to grow or shrink in size. If you're
+unsure whether to use an array or a Vec, you should probably go with a Vec,
+and we'll discuss them in more detail in chapter XX.
An array is a single chunk of memory, allocated on the stack. We can access +elements of an array using indexing, like this:
+fn main() {
+ let a = [1, 2, 3, 4, 5];
+
+ let first = a[0];
+ let second = a[1];
+}
+
+In this example, the first variable will bind to 1 at index [0] in the
+array, and second will bind to 2 at index [1] in the array. Note that
+these values are copied out of the array and into first and second when the
+let statement is called. That means if the array changes after the let
+statements, these bindings will not, and the two variables should retain their
+values.
What happens if you try to access an element of an array past the end of the +array? Say we changed our program to:
+fn main() {
+ let a = [1, 2, 3, 4, 5];
+
+ let element = a[10];
+
+ println!("The value of element is: {}", element);
+}
+
+Running this code with cargo run produces:
$ cargo run
+ Compiling arrays v0.1.0 (file:///projects/arrays)
+ Running `target/debug/arrays`
+thread '<main>' panicked at 'index out of bounds: the len is 5 but the index is 10', src/main.rs:4
+note: Run with `RUST_BACKTRACE=1` for a backtrace.
+error: Process didn't exit successfully: `target/debug/arrays` (exit code: 101)
+
+We can see that compiling did not give us any errors, but we got a runtime +error and our program didn't exit successfully. When we attempt to access an +element using indexing, Rust will check that the index we've specified is less +than the array length. If the index is greater than the length, it will +"panic", which is what it's called when a Rust program exits with an error.
+This is our first example of Rust’s safety principles in action. In many +low-level languages, this kind of check is not done, and when you provide an +incorrect index, invalid memory can be accessed. Rust protects us against this +kind of error by immediately exiting instead of allowing the memory access and +continuing. We'll discuss more of Rust’s error handling in Chapter XX.
+ +The foundation of virtually every program is the ability to store and modify -data. Rust programs are no different. Let’s start with a short example.
-First, we’ll generate a new project with Cargo. Open a terminal, and navigate -to the directory where you’d like to keep your projects. From there, let’s -generate a new project:
-$ cargo new --bin bindings
-$ cd bindings
-
-This creates a new project, ‘bindings’, and sets up our Cargo.toml and
-src/main.rs files. As we saw in “Hello, World!”, Cargo will generate these
-files and create a little ‘hello world’ program for us:
fn main() {
- println!("Hello, world!");
-}
-
-Let’s replace that program with this one:
-fn main() {
- let x = 5;
-
- println!("The value of x is: {}", x);
-}
-
-And finally, run it:
-$ cargo run
- Compiling bindings v0.1.0 (file:///projects/bindings)
- Running `target/debug/bindings`
-The value of x is: 5
-
-If you see an error instead, double check that you have copied the program -exactly as written. Let’s break this down, line by line.
-fn main() {
-
-The main() function is the entry point of every Rust program. We’ll talk more
-about functions in the next section, but for now, all we need to know is that
-this is where our program begins. The opening curly brace, {, indicates the
-start of the function’s body.
let x = 5;
-
-This is our first ‘variable binding’, which we create with a ‘let statement’.
Before we do that, though, let’s finish investigating this example. Here’s the -next line:
- println!("The value of x is: {}", x);
-
-The println! macro prints text to the screen. We can tell that it’s a macro
-due to the !. We won’t learn how to write macros until much later in the
-book, but we’ll use macros provided by the standard library throughout. Every
-time you see a !, remember that it signifies a macro. Macros can add new
-syntax to the language, and the ! is a reminder that things may look slightly
-unusual.
println!, specifically, has one required argument, a ‘format string’, and
-zero or more optional arguments. The format string can contain the special text
-{}. Each instance of {} corresponds to an additional argument. Here’s an
-example:
let x = 2 + 3;
-let y = x + 5;
-println!("The value of x is {}, and the value of y is {}", x, y);
-
-You can think of {} as little crab pincers, holding the value in place. This
-placeholder has a number of more advanced formatting options that we’ll discuss
-later.
}
-
-Finally, a closing curly brace matches up with the opening curly brace that
-declared the main() function, and declares its end.
This explains our output:
-The value of x is: 5
-
-We assign 5 to a binding, x, and then print it to the screen with
-println!.
We do not have to provide bindings with an initial value, and can assign it -later. Try this program:
-fn main() {
- let x;
-
- x = 5;
-
- println!("The value of x is: {}", x);
-}
-
-And run it with cargo run:
$ cargo run
- Compiling bindings v0.1.0 (file:///projects/bindings)
- Running `target/debug/bindings`
-The value of x is: 5
-
-It’s all good. This raises a question, though: what if we try to print out a -binding before we declare a value? Here’s a program that demonstrates this -question:
-fn main() {
- let x;
-
- println!("The value of x is: {}", x);
-
- x = 5;
-}
-
-We can find out the answer with cargo run:
Compiling bindings v0.1.0 (file:///projects/bindings)
-src/main.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x` [E0381]
-src/main.rs:4 println!(“The value of x is: {}”, x);
- ^
-<std macros>:2:25: 2:56 note: in this expansion of format_args!
-<std macros>:3:1: 3:54 note: in this expansion of print! (defined in <std macros>)
-src/main.rs:4:5: 4:42 note: in this expansion of println! (defined in <std macros>)
-src/main.rs:4:39: 4:40 help: run `rustc --explain E0381` to see a detailed explanation
-error: aborting due to previous error
-Could not compile `bindings`.
-
-To learn more, run the command again with --verbose.
-
-An error! The compiler won’t let us write a program like this. This is our
-first example of the compiler helping us find an error in our program.
-Different programming languages have different ways of approaching this
-problem. Some languages always initialize values with some sort of default.
-Other languages leave the value uninitialized, and make no promises about what
-happens if you try to use something before initialization. Rust chooses
-something else: error and force the programmer to explain what they want. We
-must do some sort of initialization before we can use x.
There’s one more interesting part of this error message:
-src/main.rs:4:39: 4:40 help: run `rustc --explain E0381` to see a detailed explanation
-
-We can see an extended explanation by passing the --explain flag to rustc.
-Not every error has a longer explanation, but many of them do. These extended
-explanations try to show off common ways that the error occurs, and common
-solutions to the issue. Here’s E0381:
$ rustc --explain E0381
-It is not allowed to use or capture an uninitialized variable. For example:
-
-fn main() {
- let x: i32;
- let y = x; // error, use of possibly uninitialized variable
-
-To fix this, ensure that any declared variables are initialized before being
-used.
-
-These explanations can really help if you’re stuck on an error. The compiler is -your friend, and is here to help.
-What about changing the value of a binding? Here’s another sample program that -asks this question:
-fn main() {
- let x = 5;
-
- x = 6;
-
- println!("The value of x is: {}", x);
-}
-
-cargo run has the answer for us:
$ cargo run
- Compiling bindings v0.1.0 (file:///projects/bindings)
-src/main.rs:4:5: 4:10 error: re-assignment of immutable variable `x` [E0384]
-src/main.rs:4 x = 6;
- ^~~~~
-src/main.rs:4:5: 4:10 help: run `rustc --explain E0384` to see a detailed explanation
-src/main.rs:2:9: 2:10 note: prior assignment occurs here
-src/main.rs:2 let x = 5;
- ^
-
-The error mentions re-assigment of immutable variable. That’s right: bindings
-are immutable. But they’re only immutable by default. In a pattern, when we’re
-creating a new name, we can add mut in front to make the binding a mutable
-one. Here’s an example:
fn main() {
- let mut x = 5;
-
- println!("The value of x is: {}", x);
-
- x = 6;
-
- println!("The value of x is: {}", x);
-}
-
-Running this, we get:
-$ cargo run
- Compiling bindings v0.1.0 (file:///projects/bindings)
- Running `target/debug/bindings`
-The value of x is: 5
-The value of x is: 6
-
-We can now change the value that x binds to. Note that the syntax is not let mut exactly; it’s using mut in a pattern. This becomes more obvious with our
-() pattern:
fn main() {
- let (mut x, y) = (5, 6);
-
- x = 7;
- y = 8;
-}
-
-The compiler will complain about this program:
-$ cargo build
- Compiling bindings v0.1.0 (file:///projects/bindings)
-src/main.rs:5:5: 5:10 error: re-assignment of immutable variable `y` [E0384]
-src/main.rs:5 y = 8;
- ^~~~~
-src/main.rs:5:5: 5:10 help: run `rustc --explain E0384` to see a detailed explanation
-src/main.rs:2:17: 2:18 note: prior assignment occurs here
-src/main.rs:2 let (mut x, y) = (5, 6);
- ^
-
-It’s fine with re-assigning x, but not y. The mut only applies to the
-name that follows it, not the whole pattern.
There is one subtlety we haven’t covered yet: mut allows you to mutate the
-binding, but not what the binding binds to. In other words:
fn main() {
- let mut x = 5;
-
- x = 6;
-}
-
-This is not changing the value that x is bound to, but creating a new value,
-6, and changing the binding to bind to it instead. It’s a subtle but
-important difference. Well, for now, it does not make a lot of difference, but
-when our programs get more complex, it will. Specifically, passing arguments to
-functions will illustrate the difference. We’ll talk about that in the next
-section, when we discuss functions.
Variable bindings have a ‘scope’ in which they’re valid. That scope begins from -the point at which the binding is declared, and ends at the end of the next -block of code. We can only access bindings which are ‘in scope’. We cannot -access them ‘before they come into scope’ or ‘after they go out of scope’. -Here’s an example:
-fn main() {
- println!("x is not yet in scope");
-
- let x = 5;
- println!("x is now in scope");
-
- println!("In real code, we’d now do a bunch of work.");
-
- println!("x will go out of scope now! The next curly brace is ending the main function.");
-}
-
-We can create arbitrary scopes through the use of { and }:
fn main() {
- println!("x is not yet in scope");
-
- let x = 5;
- println!("x is now in scope");
-
- println!("Let’s start a new scope!");
-
- {
- let y = 5;
- println!("y is now in scope");
- println!("x is also still in scope");
-
- println!("y will go out of scope now!");
- println!("The next curly brace is ending the scope we started.");
- }
-
- println!("x is still in scope, but y is now out of scope and is not usable");
-
- println!("x will go out of scope now! The next curly brace is ending the main function.");
-}
-
-What bindings are in and out of scope will become much more important later, -once we learn about ‘references’ and ‘traits’.
-A final thing about bindings: they can ‘shadow’ previous bindings with the same -name. Here’s a sample program:
-fn main() {
- let x = 5;
- let x = 6;
-
- println!("The value of x is: {}", x);
-}
-
-Running it, we can see the shadowing in action:
-src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variables)] on by default
-src/main.rs:2 let x = 5;
- ^
- Running `target/debug/bindings`
-The value of x is: 6
-
-There are two interesting things in this output. First, Rust will compile and
-run this program, no problem. And as we can see, the value of x is 6. But
-we didn’t declare x as mutable. Instead, we declared a new binding that is
-also named x, and gave it a new value. The older value that we bound x to
-is inaccessible as soon as the new x is declared. This can be useful if you’d
-like to perform a few transformations on a value, and leave it immutable. For
-example:
fn main() {
- let x = 5;
- let x = x + 1;
- let x = x * 2;
-
- println!("The value of x is: {}", x);
-}
-
-This will print:
- Compiling bindings v0.1.0 (file:///projects/bindings)
- Running `target/debug/bindings`
-The value of x is: 12
-
-This lets us modify x, but not deal with mutation. This is nice because we
-know that the compiler will let us know if we try to modify it later. Let’s
-assume that after we calculate 12, we don’t want to modify x again. If we
-had written this program in a mutable style, like this:
fn main() {
- let mut x = 5;
- x = x + 1;
- x = x * 2;
-
- println!("The value of x is: {}", x);
-
- x = 15;
-
- println!("The value of x is: {}", x);
-}
-
-Rust is happy to let us mutate it again, to 15. A similar program in our
-immutable style will let us know about that accidental mutation, however:
fn main() {
- let x = 5;
- let x = x + 1;
- let x = x * 2;
-
- println!("The value of x is: {}", x);
-
- x = 15;
-
- println!("The value of x is: {}", x);
-}
-
-If we try to compile, we get an error:
-$ cargo build
- Compiling bindings v0.1.0 (file:///projects/bindings)
-src/main.rs:8:5: 8:11 error: re-assignment of immutable variable `x` [E0384]
-src/main.rs:8 x = 15;
- ^~~~~~
-src/main.rs:8:5: 8:11 help: run `rustc --explain E0384` to see a detailed explanation
-src/main.rs:4:9: 4:10 note: prior assignment occurs here
-src/main.rs:4 let x = x * 2;
- ^
-error: aborting due to previous error
-Could not compile `bindings`.
-
-Exactly what we wanted.
-Shadowing can take some time to get used to, but it’s very powerful, and works -well with immutability.
-There was one more thing we should talk about in the output from compiling our -initial program. It’s this part:
-src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variables)] on by default
-
-Here’s the two lines of relevant code:
-let x = 5;
-let x = 6;
-
-Rust knows that we shadowed x, but we never ended up using the initial value.
-This isn’t wrong, exactly, it just may not have been what we wanted. In this
-case, the compiler issues a ‘warning’, but still compiles our program. The
-#[warn(unused_variables)] syntax is called an ‘attribute’, which we’ll
-discuss in a later section. More specifically, a warning like this is called a
-‘lint’, which is an old term for the bits of sheep’s wool that you wouldn’t
-want to put in cloth. Similarly, this lint is telling us that we may have an
-extra bit of code we don’t need. Our program would work just fine without it.
-It’s worth listening to these warnings, and fixing the problems they point out.
-They can be signs of a larger problem. In this case, we may not have realized
-that we were shadowing x.
Like any binding, a binding that shadows another binding will go away at the -end of a scope. Here’s an example program:
-fn main() {
- let x = 5;
-
- println!("Before shadowing, x is: {}", x);
-
- {
- let x = 6;
-
- println!("Now that x is shadowed, x is: {}", x);
- }
-
- println!("After shadowing, x is: {}", x);
-}
-
-If we run this example, we can see the shadow appear and disappear:
-$ cargo run
- Compiling bindings v0.1.0 (file:///projects/bindings)
- Running `target/debug/bindings`
-Before shadowing, x is: 5
-Now that x is shadowed, x is: 6
-After shadowing, x is: 5
-
-
- Functions are pervasive in Rust code. We’ve already seen the most important
-function, main(), in previous sections of the book:
fn main() {
- println!("Hello, world!");
-}
-
-We can declare new functions with the fn keyword:
fn another_function() {
- println!("Another function.");
-}
-
-Rust code uses snake_case as a style for function names: all lower case, with
-underscores separating words. (It also uses them for variable names, too.) We
-can call any function we’ve defined by using its name and some parentheses:
fn main() {
- println!("Hello, world!");
-
- another_function();
-}
-
-fn another_function() {
- println!("Another function.");
-}
-
-Let’s start a new project to explore functions. Open a terminal, and navigate -to the directory where you’d like to keep your projects. From there, use Cargo -to generate a new project:
-$ cargo new --bin functions
-$ cd functions
-
-Place the new example in src/main.rs, and run it:
$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
- Running `target/debug/functions`
-Hello, world!
-Another function.
-
-As we can see, the lines execute in order: first, we print out our “Hello,
-world!” message, and then another_function() is called. It then prints its
-message as well.
Functions can also take arguments:
-fn main() {
- another_function(5);
-}
-
-fn another_function(x: i32) {
- println!("The value of x is: {}", x);
-}
-
-Let’s try running it:
-$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
- Running `target/debug/functions`
-The value of x is: 5
-
-Let’s take a closer look at another_function()’s signature:
fn another_function(x: i32) {
-
-Declaring a function which takes a single argument looks like this:
-fn NAME(PATTERN: TYPE) {
-
-That’s right, patterns appear again. Consider how the parameter declaration
-here looks like the let bindings we used earlier:
let x: i32;
-fn another_function(x: i32) {
-
-There’s only one difference here: in function signatures, we must declare the -type. This is a deliberate decision; we find that requiring type annotations in -functions means that you almost never need them anywhere else.
-You can separate multiple arguments with a comma:
-fn NAME(PATTERN: TYPE, PATTERN: TYPE, PATTERN: TYPE, PATTERN: TYPE...) {
-
-Here’s a full example:
-fn main() {
- another_function(5, 6);
-}
-
-fn another_function(x: i32, y: i32) {
- println!("The value of x is: {}", x);
- println!("The value of y is: {}", y);
-}
-
-Let’s try it:
-$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
- Running `target/debug/functions`
-The value of x is: 5
-The value of y is: 6
-
-We could also create bindings, and pass them in as arguments:
-fn main() {
- let a = 5;
- let b = 6;
-
- another_function(a, b);
-}
-
-fn another_function(x: i32, y: i32) {
- println!("The value of x is: {}", x);
- println!("The value of y is: {}", y);
-}
-
-This has the same effect:
-$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
- Running `target/debug/functions`
-The value of x is: 5
-The value of y is: 6
-
-Note that our bindings are called a and b, yet inside of the function, we
-refer to them by the names in the signature, x and y. Inside a function,
-only its parameters are in scope, so we need to use those names. Bindings
-passed as parameters don’t need to have the same name as the arguments.
Functions can also return values back to the function that called them:
-fn NAME(PATTERN: TYPE, PATTERN: TYPE, PATTERN: TYPE, PATTERN: TYPE...) -> TYPE {
-
-We don’t name return values, but we do declare their type, after an arrow:
-->. Here’s a sample program:
fn main() {
- let x = five();
-
- println!("The value of x is: {}", x);
-}
-
-fn five() -> i32 {
- 5
-}
-
-Let’s try running it:
-$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
- Running `target/debug/functions`
-The value of x is: 5
-
-Let’s examine this in more detail. There are two important bits. First, we can -use the return value of a function to initialize a binding:
-let x = five();
-
-Because five() returns a 5, this is the same as:
let x = 5;
-
-The second interesting bit is five() itself:
fn five() -> i32 {
- 5
-}
-
-We have no arguments, and our return type, i32. However, the body of this
-function is a lonely 5. There’s a detail here that you may or may not have
-noticed: we’ve ended almost every line in our programs with a semicolon.
-There’s no semicolon here, though. Why not?
The answer to this question is:
---The return value of a function is the value of its final expression.
-
We haven’t talked about expressions yet, so this definition doesn’t help a lot. -Let’s go over that now.
-Expressions are bits of code that evaluate to a value. Consider some math -operations, like this:
-5 + 6
-
-We can evaluate this expression, and come up with a value: 11. In Rust, most
-bits of code are expressions. For example, calling a function is an expression:
foo(5)
-
-The value is equal to whatever the return value of foo() is.
So why does this matter? Well, not everything is an expression. Some things are
-‘statements’. Expressions compute something, but statements bind or do
-something. It’s a subtle difference. We’ve already seen two kinds of
-statements: let statements, and fn declarations.
Because let is a statement, not an expression, you can’t assign it to another
-binding. Here’s an example that doesn’t work:
fn main() {
- let x = (let y = 6);
-}
-
-If we try to run this program, we’ll get an error:
-$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
-src/main.rs:2:14: 2:17 error: expected identifier, found keyword `let`
-src/main.rs:2 let x = (let y = 6);
- ^~~
-src/main.rs:2:18: 2:19 error: expected one of `!`, `)`, `,`, `.`, `::`, `{`, or an operator, found `y`
-src/main.rs:2 let x = (let y = 6);
- ^
-Could not compile `functions`.
-
-We also cannot somehow assign a fn declaration to a binding, either.
So what’s this have to do with return values? Well, {}, a ‘block’ that we
-used earlier to create new scopes, is an expression. Let’s take a closer look
-at {}. It looks like this:
{
- STATEMENT*
- EXPRESSION
-}
-
-The * there means ‘zero or more’, so we can have any number of statements
-followed by an expression. Since blocks are expressions themselves, we can nest
-blocks inside of blocks. And since they return a value, we can use them in
-let statements:
fn main() {
- let x = 5;
-
- let y = {
- let z = 1;
-
- x + z + 5
- };
-
- println!("The value of y is: {}", y);
-}
-
-Let’s try running this program:
- Compiling functions v0.1.0 (file:///projects/functions)
- Running `target/debug/functions`
-The value of y is: 11
-
-We’re now using a block to give us a value for y:
let y = {
-
-};
-
-Since the block can contain statements, we create a new variable binding, z,
-and give it a value. We then do some math for the final expression of the
-block:
{
- let z = 1;
-
- x + z + 5
-}
-
-5 + 1 + 5 is 11, and so the value of the entire block is 11. This gets
-substituted into our let statement for y:
let y = 11;
-
-Hence our output saying y is 11.
Where else do we use blocks? As the body of functions! They’re very similar:
-fn main() {
- let x = 5;
-
- let y = {
- x + 1
- };
-
- println!("The value of y is: {}", y);
-
- let y = plus_one(x);
-
- println!("The value of y is: {}", y);
-}
-
-fn plus_one(x: i32) -> i32 {
- x + 1
-}
-
-Running this gives:
-$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
- Running `target/debug/functions`
-The value of y is: 6
-The value of y is: 6
-
-In both cases, we use a block to produce a value. In the first case, it’s
-assigning with let:
let y = {
-
-In the second, it’s the return value of the function:
-fn plus_one(x: i32) -> i32 {
-
-There’s one more detail about expressions and statements: a semicolon takes any
-expression, and turns it into a statement. Let’s accidentally cause an error
-with plus_one():
fn main() {
- let x = plus_one(5);
-
- println!("The value of x is: {}", x);
-}
-
-fn plus_one(x: i32) -> i32 {
- x + 1;
-}
-
-Instead of an expression, x + 1, we’ve now turned it into a statement,
-x + 1;.
Running this gives an error:
-$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
-src/main.rs:7:1: 9:2 error: not all control paths return a value [E0269]
-src/main.rs:7 fn plus_one(x: i32) -> i32 {
-src/main.rs:8 x + 1;
-src/main.rs:9 }
-src/main.rs:7:1: 9:2 help: run `rustc --explain E0269` to see a detailed explanation
-src/main.rs:8:10: 8:11 help: consider removing this semicolon:
-src/main.rs:8 x + 1;
- ^
-error: aborting due to previous error
-Could not compile `functions`.
-
-Rust has our back here: it even suggests removing the semicolon, which fixes
-the error. But the main error message is the core of the issue: statements
-don’t evaluate to a value, yet we want to return an i32.
In practice, Rust programmers don’t often think about these rules at this -level. Usually, you have a semicolon at the end of most lines, and maybe not at -the end of blocks.
-Functions cannot directly return multiple values. There’s a trick, however.
-Remember the ()s we used when showing off complex bindings?
fn main() {
- let (x, y) = (5, 6);
-}
-
-They form something called a ‘tuple’, one of Rust’s basic types. A tuple is an -anonymous collection of elements. But since a tuple is a singular thing, we can -use it as a way to return multiple values from functions:
-fn main() {
- let (x, y) = two_numbers();
-
- println!("The value of x is: {}", x);
- println!("The value of y is: {}", y);
-}
-
-fn two_numbers() -> (i32, i32) {
- (5, 6)
-}
-
-Running this will show us the values:
-$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
- Running `target/debug/functions`
-The value of x is: 5
-The value of y is: 6
-
-There are two interesting changes here: assigning the return value of
-two_numbers() to x and y, and the declaration of two_numbers() itself.
Let’s look at the declaration first:
-fn two_numbers() -> (i32, i32) {
- (5, 6)
-}
-
-The (i32, i32) should look familiar. We saw it in let bindings earlier:
let (x, y): (i32, i32) = (5, 6);
-
-The (i32, i32) syntax says “a tuple with two i32s in it.” The (5, 6)
-syntax creates a new one, with 5 and 6.
This tuple is then returned, and assigned to x and y:
let (x, y) = two_numbers();
-
-See how all these bits fit together?
-We call this behavior of let ‘destructuring’, because it takes the structure
-of the expression that comes after the = and takes it apart.
Functions are pervasive in Rust code. We’ve already seen one of the most
+important functions in the language: the main() function that’s the entry
+point of many programs. We've also seen the fn keyword, which allows us to
+declare new functions.
Rust code uses snake case as the conventional style for function names. In +snake case, all letters are lower case, and there are underscores separating +words. (Rust also uses snake case for the names of variable bindings; we just +haven't used any variable bindings with enough letters to need underscores +yet). Here's a program containing an example function definition:
+fn main() {
+ println!("Hello, world!");
+
+ another_function();
+}
+
+fn another_function() {
+ println!("Another function.");
+}
+
+Function definitions in Rust start with fn and have a set of parentheses
+after the function name. The curly braces tell the compiler where the function
+body begins and ends.
We can call any function we’ve defined by entering its name followed by a pair
+of parentheses. Since another_function() is defined in the program, it can be
+called from inside the main() function. Note that we defined
+another_function() after the main() function in our source code; we could
+have defined it before as well. Rust doesn’t care where you define your
+functions, only that they are defined somewhere.
Let’s start a new project to explore functions further. Open a terminal, and +navigate to the directory you're keeping your projects in. From there, use +Cargo to generate a new project, as follows:
+$ cargo new --bin functions
+$ cd functions
+
+Place the another_function() example in a file named src/main.rs and run
+it. You should see the following output:
$ cargo run
+ Compiling functions v0.1.0 (file:///projects/functions)
+ Running `target/debug/functions`
+Hello, world!
+Another function.
+
+The lines execute in the order they appear in the main() function. First, our
+“Hello, world!” message prints, and then another_function() is called and its
+message is printed.
Functions can also take arguments. The following rewritten version of
+another_function() shows what arguments look like in Rust:
fn main() {
+ another_function(5);
+}
+
+fn another_function(x: i32) {
+ println!("The value of x is: {}", x);
+}
+
+Try running this program, and you should get this output:
+$ cargo run
+ Compiling functions v0.1.0 (file:///projects/functions)
+ Running `target/debug/functions`
+The value of x is: 5
+
+Since we passed 5 to another_function(), the println! macro put 5 where
+the pair of curly braces were in the format string. The declaration of
+another_function() shows that it takes one argument named x, and the type
+of x is i32.
In function signatures, we must declare the type. This is a deliberate +decision in the design of Rust; requiring type annotations in function +definitions means the compiler almost never needs you to use them elsewhere in +the code in order to figure out what you mean.
+When you want a function to have multiple arguments, just separate them inside +the function signature with commas, like this:
+fn main() {
+ another_function(5, 6);
+}
+
+fn another_function(x: i32, y: i32) {
+ println!("The value of x is: {}", x);
+ println!("The value of y is: {}", y);
+}
+
+In this example, we make a function with two arguments, both of which are
+i32s. If your function has multiple arguments, they don’t need to be the same
+type, but they just happen to be in this example. Our function then prints out
+the values of both of its arguments.
Let’s try out this code. Replace the program currently in your function
+project's main.rs file with the example above, and run it as follows:
$ cargo run
+ Compiling functions v0.1.0 (file:///projects/functions)
+ Running `target/debug/functions`
+The value of x is: 5
+The value of y is: 6
+
+Since 5 is passed as the x argument and 6 is passed as the y argument,
+the two strings are printed with these values.
Function bodies are made up of a series of statements ending in an optional +expression. So far, we've only seen functions without an ending expression, but +we have seen expressions as parts of statements. Since Rust is an +expression-based language, this is an important distinction to understand. +Other languages don't have the same distinctions, so let's look at what +statements and expressions are and how their differences affect the bodies of +functions.
+We've already been using both statements and expressions. Statements are +instructions that perform some action and do not return a value. Expressions +evaluate to a resulting value. Let's look at some examples.
+Let bindings are statements. They instruct the program to create a binding
+name and assign a value to it. let y = 6; in this example is a statement:
fn main() {
+ let y = 6;
+}
+
+Function definitions are also statements-- so the entire previous example is a +statement as well.
+Statements do not return values themselves. Therefore, you can’t assign a let
+binding to another binding, as this code tries to do:
fn main() {
+ let x = (let y = 6);
+}
+
+If we were to run this program, we’d get an error like this:
+$ cargo run
+ Compiling functions v0.1.0 (file:///projects/functions)
+error: expected expression, found statement (`let`)
+ --> src/main.rs:2:14
+2 |> let x = (let y = 6);
+ |> ^^^
+note: variable declaration using `let` is a statement
+
+error: aborting due to previous error
+error: Could not compile `functions`.
+
+The let y = 6 statement does not return a value, so there isn't anything for
+x to bind to. This is different than in other languages like C and Ruby where
+the assignment returns the value of the assignment. In those languages, you
+could write x = y = 6 and have both x and y have the value 6, but that
+is not the case in Rust.
Expressions are most of the rest of the code that you will write in Rust. +Consider a simple math operation, like this:
+5 + 6
+
+This is an expression, and evaluating it results in the value 11. Expressions
+can be part of statements-- in the previous example that had the statement let y = 6;, 6 is an expression that evaluates to the value 6. Calling a
+function is an expression. Calling a macro is an expression. The block that we
+use to create new scopes, {}, is an expression, for example:
fn main() {
+ let x = 5;
+
+ let y = {
+ let x = 3;
+ x + 1
+ };
+
+ println!("The value of y is: {}", y);
+}
+
+The expression:
+{
+ let x = 3;
+ x + 1
+}
+
+is a block that, in this case, gets evaluated to 4, which then gets bound to
+y as part of the let statement.
Note that the line containing x + 1 does not have a semicolon at the end like
+most of the lines we've seen up until now have had. This is the most important
+distinction between expressions and statements to remember: statements end in
+semicolons while expressions do not. If you add a semicolon to the end of an
+expression, that will turn it into a statement, which will then not return a
+value. Keep this in mind as we explore function return values and expressions.
Functions can return values back to the code that calls them. We don’t name
+return values, but we do declare their type, after an arrow (->). In Rust,
+the "return value of the function” is synonymous with “the value of the final
+expression in the block of the body of a function.” Here's an example of a
+function that returns a value:
fn five() -> i32 {
+ 5
+}
+
+fn main() {
+ let x = five();
+
+ println!("The value of x is: {}", x);
+}
+
+There are no function calls, macros, or even let statements in the five()
+function-- just the number 5 by itself. That's a perfectly valid function in
+Rust. Note the function's return type, too. Try running this code, and the
+output should look like this:
$ cargo run
+ Compiling functions v0.1.0 (file:///projects/functions)
+ Running `target/debug/functions`
+The value of x is: 5
+
+The 5 in five() is actually the function's return value, which is why the
+return type is i32. Let’s examine this in more detail. There are two
+important bits. First, the line let x = five(); in main() shows that we can
+use the return value of a function to initialize a binding.
Because the function five() returns a 5, that line is the same as saying:
let x = 5;
+
+The second interesting bit is the five() function itself. It requires no
+arguments and defines the type of the return value, but the body of the
+function is a lonely 5 with no semicolon because it is an expression whose
+value we want to return. Let's look at another example:
fn main() {
+ let x = plus_one(5);
+
+ println!("The value of x is: {}", x);
+}
+
+fn plus_one(x: i32) -> i32 {
+ x + 1
+}
+
+Running this code will print The value of x is: 6. What happens if we put a
+semicolon at the end of the line containing x + 1, changing it from an
+expression to a statement?
fn main() {
+ let x = plus_one(5);
+
+ println!("The value of x is: {}", x);
+}
+
+fn plus_one(x: i32) -> i32 {
+ x + 1;
+}
+
+Running this code gives an error, as follows:
+$ cargo run
+ Compiling functions v0.1.0 (file:///projects/functions)
+error: not all control paths return a value [--explain E0269]
+ --> src/main.rs:7:1
+7 |> fn plus_one(x: i32) -> i32 {
+ |> ^
+help: consider removing this semicolon:
+ --> src/main.rs:8:10
+8 |> x + 1;
+ |> ^
+
+error: aborting due to previous error
+error: Could not compile `functions`.
+
+The main error message, "not all control paths return a value", reveals the
+core of the issue with this code. The definition of the function plus_one
+says that it will return an i32, but statements don’t evaluate to a value.
+Therefore, nothing is returned, which contradicts the function definition and
+results in an error. In this output, Rust gives an option to rectify this: it
+suggests removing the semicolon, which would fix the error.
All programmers strive to make their code easy to understand, but sometimes +extra explanation is warranted. In these cases, we leave notes in our source +code that the compiler will ignore but people reading the source code may find +useful. These notes are called comments.
+Here’s a simple comment:
+// Hello, world.
+
+In Rust, comments must start with two slashes and will last until the end of
+the line. For comments that extend beyond a single line, you'll need to
+include // on each line, like this:
// So we’re doing something complicated here, long enough that we need
+// multiple lines of comments to do it! Whew! Hopefully, this comment will
+// explain what’s going on.
+
+Comments can also be placed at the end of lines of code:
+fn main() {
+ let lucky_number = 7; // I’m feeling lucky today.
+}
+
+But you’ll more often see them above, like so:
+fn main() {
+ // I’m feeling lucky today.
+ let lucky_number = 7;
+}
+
+That’s all there is to it. Comments are not particularly complicated.
+ +We’ve seen that every value in Rust has a type of some kind. There are a number -of types which are built into the language itself. First, we’ll take a look at -‘scalar’ types, that is, types which represent a single value.
-Remember, you can rely on type inference to figure out the type of a binding, -or you can annotate it explicitly:
-fn main() {
- let x: i32 = 5;
-}
-
-You’ve already seen one primitive type: i32. There are a number of built-in
-number types in Rust.
Here’s a chart of Rust’s integer types:
-| signed | unsigned | |
| 8-bit | i8 | u8 |
| 16-bit | i16 | u16 |
| 32-bit | i32 | u32 |
| 64-bit | i64 | u64 |
| arch | isize | usize |
We have both signed and unsigned variants of numbers, and each variant has an -explicit size. Unsigned numbers are never negative, and signed numbers can be -positive or negative. (Think ‘plus sign’ or ‘minus sign’: that’s a signed -number.) Signed numbers are stored using ‘two’s complement’ representation.
-Finally, isize and usize are different sizes based on the kind of computer
-your program is running on. If you are on a 64-bit architecture, they are 64
-bits, and if you’re on a 32-bit one, they’re 32 bits.
So how do you choose from all these options? Well, if you really don’t know,
-the defaults are a good choice: integer types default to i32. The primary use
-case for isize/usize is when indexing some sort of collection. We’ll talk
-more about our first collection, arrays, in just a moment.
Rust also has two primitive floating-point numbers: f32 and f64. They are
-32 bits and 64 bits in size, respectively. The default is f64.
fn main() {
- let x = 2.0; // f64
-
- let y: f32 = 3.0; // f32
-}
-
-Floating-point numbers are represented according to the IEEE-754 standard.
-f32 is a single-precision float, f64 is double-precision.
Rust supports the usual operations you’d expect on all of these number types:
-fn main() {
- // addition
- let sum = 5 + 10;
-
- // subtraction
- let difference = 95.5 - 4.3;
-
- // multiplication
- let product = 4 * 30;
-
- // division
- let quotient = 56.7 / 32.2;
-
- // modulus
- let remainder = 43 % 5;
-}
-
-Somewhat fundamental to all computing, Rust has a boolean type, bool, with
-two possible values:
fn main() {
- let t = true;
- let f: bool = false; // with explicit type annotation
-}
-
-The main way to consume boolean values is through conditionals like if, which
-we’ll see later in the chapter.
We’ve only worked with numbers so far, but what about letters? Rust’s most
-primitive alphabetic type is the char:
fn main() {
- let c = 'z';
- let z = 'ℤ';
-}
-
-Rust’s char represents a Unicode Scalar Value, which means that it can
-represent a lot more than just ASCII. ‘Character’ isn’t really a concept in
-Unicode, however: your human intuition for what a ‘character’ is may not match
-up with a char. It also means that chars are four bytes each.
Now that we’ve discussed scalar types, let’s talk about compound types. -These types can group multiple values of scalar types into another type.
-We’ve seen tuples before, in the guise of binding or returning multiple values -at once. It turns out that there’s no magic here: tuples are a general way of -making a compound value that groups some number of other values with distinct -types. The number of values grouped is the ‘arity’ of the tuple.
-We create a tuple by writing a comma-separated list of values inside -parentheses; each position in the tuple has a distinct type:
-fn main() {
- let tup: (i32, f64, u8) = (500, 6.4, 1);
-}
-
-Note that, unlike the examples of multiple bindings, here we bound the
-single name tup to the entire tuple. We can then use pattern
-matching to destructure this tuple value:
fn main() {
- let tup: (i32, f64, u8) = (500, 6.4, 1);
- let (x, y, z) = tup;
-
- println!("The value of y is: {}", y);
-}
-
-Tuples are used sparingly in Rust code. This is because the elements of a tuple -are anonymous, which can make code hard to read.
-In addition to destructuring through pattern matching, we can also access a
-tuple element directly using ., followed by the index we want to access:
fn main() {
- let x: (i32, f64, u8) = (500, 6.4, 1);
-
- let five_hundred = x.0;
- let six_point_four = x.1;
- let one = x.2;
-}
-
-As you can see, the first index is 0.
There’s one last trick with tuples: (5) is actually ambiguous: is it a tuple,
-or is it a 5 in parenthesis? If you need to disambiguate, use a comma:
fn main() {
- let x = (5); // x is an i32, no tuple. Think of it like (5 + 1) without the + 1, they’re for grouping.
-
- let x = (5,); // x is a (i32), a tuple with one element.
-}
-
-So far, we’ve only represented single values in a binding. Sometimes, though, -it’s useful to have more than one value. These kinds of data structures are -called ‘collections’, and arrays are the ones we’ll learn about first. Arrays -look like this:
-fn main() {
- let a = [1, 2, 3, 4, 5];
-}
-
-An array’s type consists of the type of the elements it contains, as well as -the length:
-fn main() {
- let a: [i32; 5] = [1, 2, 3, 4, 5];
-}
-
-An array is a single chunk of memory, allocated on the stack.
-We can access elements of an array using indexing:
-fn main() {
- let a = [1, 2, 3, 4, 5];
-
- let first = a[0];
- let second = a[1];
-}
-
-In this example, first will hold the value 1, and second will be bound to
-2. Note that these values are copied out of the array; if the array changes,
-these bindings will not. Here’s an example, which also shows us how we can
-modify elements of the array:
fn main() {
- let mut a = [1, 2, 3, 4, 5];
-
- let first = a[0];
-
- a[0] = 7;
-
- println!("The value of first is: {}", first);
-}
-
-Running this example will show that first is still 1. If we didn’t want a
-copy, but instead wanted to refer to the first element, whatever its value was,
-we need a new concept. We’ll talk about ‘references’ in Section 4.
One last thing: now that we are modifying the array, a needs to be declared
-mut.
Arrays are our first real data structure, and so there’s a few other concepts
-that we haven’t covered in full yet. There are two: the panic! macro, and a
-new way of printing things: Debug.
We showed what happens when you access elements of an array, but what if we -give an invalid index?
-fn main() {
- let a = [1, 2, 3, 4, 5];
-
- let invalid = a[10];
-
- println!("The value of invalid is: {}", invalid);
-}
-
-If we run this example, we will get an error. Let’s re-use our functions
-project from before. Change your src/main.rs to look like the example, and
-run it:
$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
- Running `target/debug/functions`
-thread ‘<main>’ panicked at ‘index out of bounds: the len is 5 but the index is 10’, src/main.rs:4
-Process didn’t exit successfully: `target/debug/functions` (exit code: 101)
-
-It says that our thread panicked, and that our program didn’t exit -successfully. There’s also a reason: we had a length of five, but an index of
-For now, all you need to know is that a panic will crash your program. Rust’s -error handling story is described in full in a later chapter.
-So why did this code panic? Well, arrays know how many elements they hold. When -we access an element via indexing, Rust will check that the index is less than -the length. If it’s greater, it will panic, as something is very wrong. This is -our first example of Rust’s safety principles in action. In many low-level -languages, this kind of check is not done. If you have an incorrect index, -invalid memory can be accessed. Rust protects us against this kind of error.
-So far, we’ve been printing values using {}. If we try that with an array,
-though...
fn main() {
- let a = [1, 2, 3, 4, 5];
-
- println!("a is: {}", a);
-}
-
-... we will get an error:
-$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
-src/main.rs:4:25: 4:26 error: the trait `core::fmt::Display` is not implemented for the type `[_; 5]` [E0277]
-src/main.rs:4 println!(“a is {}”, a);
- ^
-<std macros>:2:25: 2:56 note: in this expansion of format_args!
-<std macros>:3:1: 3:54 note: in this expansion of print! (defined in <std macros>)
-src/main.rs:4:5: 4:28 note: in this expansion of println! (defined in <std macros>)
-src/main.rs:4:25: 4:26 help: run `rustc --explain E0277` to see a detailed explanation
-src/main.rs:4:25: 4:26 note: `[_; 5]` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string
-src/main.rs:4:25: 4:26 note: required by `core::fmt::Display::fmt`
-error: aborting due to previous error
-
-Whew! The core of the error is this part: the trait core::fmt::Display is not
-implemented. We haven’t discussed traits yet, so this is bound to be confusing!
-Here’s all we need to know for now: println! can do many kinds of formatting.
-By default, {} implements a kind of formatting known as Display: output
-intended for direct end-user consumption. The primitive types we’ve seen so far
-implement Display, as there’s only one way you’d show a 1 to a user. But
-with arrays, the output is less clear. Do you want commas or not? What about
-the []s?
Due to these questions, more complex types in the standard library do not
-implement Display formatting. There is another kind of formatting, Debug,
-which is a bit different: intended for programmer consumption. We can ask
-println! to use Debug formatting with :?:
fn main() {
- let a = [1, 2, 3, 4, 5];
-
- println!("a is {:?}", a);
-}
-
-This will work:
-$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
- Running `target/debug/functions`
-a is [1, 2, 3, 4, 5]
-
-You’ll see this repeated later, with other types. And we’ll cover traits fully -later in the book, Section 9.
- -Deciding whether or not to run some code depending on if a condition is true,
+or deciding to run some code repeatedly while a condition is true, are basic
+building blocks in most programming languages. The most common constructs that
+let us control the flow of execution of our Rust code are if expressions and
+loops.
if ExpressionsAn if expression allows us to branch our code depending on conditions. We
+provide a condition and then say, "If this condition is met, then run this
+block of code. If the condition is not met, do not run this block of code."
Let’s make a new project to explore if. Navigate to your projects directory,
+and use Cargo to make a new project called branches:
$ cargo new --bin branches
+$ cd branches
+
+Write this sample program using if and save it in the branches directory in
+src/main.rs:
fn main() {
+ let number = 3;
+
+ if number < 5 {
+ println!("condition was true");
+ } else {
+ println!("condition was false");
+ }
+}
+
+All if expressions start with if, which is followed by a condition. In this
+case, our condition is checking if our variable binding number has a value
+that is less than 5. The block of code we want to execute if the condition is
+true goes immediately after the condition, inside curly braces. These blocks
+are sometimes called ‘arms’. We can optionally also include an else
+statement, which we have chosen to do here. else gives the program a block of
+code to execute should condition evaluate to false.
Try running this code, and you should see output like this:
+$ cargo run
+ Compiling branches v0.1.0 (file:///projects/branches)
+ Running `target/debug/branches`
+condition was true
+
+Let’s try changing the value of number to a value that makes the condition
+false to see what happens:
let number = 7;
+
+Run the program again, and look at the output:
+$ cargo run
+ Compiling branches v0.1.0 (file:///projects/branches)
+ Running `target/debug/branches`
+condition was false
+
+It’s also worth noting that condition here must be a bool. To see what
+happens if the condition isn't a bool, try running this code:
fn main() {
+ let number = 3;
+
+ if number {
+ println!("number was three");
+ }
+}
+
+The if condition evaluates to a value of 3 this time, and Rust will
+complain about it:
Compiling branches v0.1.0 (file:///projects/branches)
+error: mismatched types [--explain E0308]
+ --> src/main.rs:4:8
+4 |> if number {
+ |> ^^^^^^ expected bool, found integral variable
+note: expected type `bool`
+note: found type `_`
+
+error: aborting due to previous error
+Could not compile `branches`.
+
+The error tells us that Rust expected a bool, but got an integer. Rust will
+not automatically try to convert non-boolean types to a boolean here, unlike
+languages like Ruby or JavaScript. We must be explicit and always give if a
+boolean as its condition. If your intention is for the if code block to be run if a number is not equal to 0, for example, we would change the if expression to read:
fn main() {
+ let number = 3;
+
+ if number != 0 {
+ println!("number was something other than zero");
+ }
+}
+
+Running this will print "number was something other than zero".
+else ifWe can have multiple coniditions by combining if and else in an else if
+expression. For example:
fn main() {
+ let number = 5;
+
+ if number == 3 {
+ println!("condition was 3");
+ } else if number == 4 {
+ println!("condition was 4");
+ } else if number == 5 {
+ println!("condition was 5");
+ } else {
+ println!("condition was something else");
+ }
+}
+
+This program has four possible paths it can take. If you try running it, you +should see output like this:
+$ cargo run
+ Compiling branches v0.1.0 (file:///projects/branches)
+ Running `target/debug/branches`
+condition was 5
+
+When this program executes, it will check each if expression in turn and
+execute the first body for which the condition holds true.
Using too many else if expressions can clutter your code, so if you find
+yourself with more than one, you may want to look at refactoring your code. In
+Chapter XX, we'll talk about a powerful Rust branching construct called match
+for these cases.
if in a BindingThe last detail you need to learn about if is that it’s an expression. That
+means that we can use it on the right hand side of a let binding, for
+instance:
fn main() {
+ let condition = true;
+ let number = if condition {
+ 5
+ } else {
+ 6
+ };
+
+ println!("The value of number is: {}", number);
+}
+
+The number variable will be bound to a value based on the outcome of the if
+expression. Let’s run this to see what happens:
$ cargo run
+ Compiling branches v0.1.0 (file:///projects/branches)
+ Running `target/debug/branches`
+The value of number is: 5
+
+Remember, blocks of code evaluate to the last expression in them, and numbers
+by themselves are also expressions. In this case, the value of the whole if
+expression depends on which block of code executes. This means that the value
+that results from both arms of the if must be the same type; in the previous
+example, they were both i32 integers. But what happens if the types are
+mismatched, as in the following example?
fn main() {
+ let condition = true;
+
+ let number = if condition {
+ 5
+ } else {
+ "six"
+ };
+
+ println!("The value of number is: {}", number);
+}
+
+The expression in the if block is an integer and the expresion in the else
+block is a string. This can’t work, because variable bindings must have a
+single type. If we try to run this, we’ll get an error:
Compiling branches v0.1.0 (file:///projects/branches)
+src/main.rs:4:18: 8:6 error: if and else have incompatible types:
+ expected `_`,
+ found `&‘static str`
+(expected integral variable,
+ found &-ptr) [E0308]
+src/main.rs:4 let number = if condition {
+src/main.rs:5 5
+src/main.rs:6 } else {
+src/main.rs:7 "six"
+src/main.rs:8 };
+src/main.rs:4:18: 8:6 help: run `rustc --explain E0308` to see a detailed explanation
+error: aborting due to previous error
+Could not compile `branches`.
+
+The if and else arms have value types that are incompatible, and Rust tells
+us exactly where to find the problem in our program.
It’s often useful to be able to execute a block of code more than one time. For +this, Rust has several constructs called loops. A loop runs through the code +inside it to the end and then starts immediately back at the beginning. To try +out loops, let’s make a new project. Navigate to your projects folder and use +Cargo to make a new project:
+$ cargo new --bin loops
+$ cd loops
+
+There are three kinds of loops in Rust: loop, while, and for. Let’s dig
+in.
loopThe loop keyword tells Rust to execute a block of code over and over again
+forever or until we explicitly tell it to stop.
For an example, change the src/main.rs file in your loops directory to look +like this:
+fn main() {
+ loop {
+ println!("again!");
+ }
+}
+
+If we run this program, we’ll see again! printed over and over continuously
+until we stop the program manually. Most terminals support a keyboard shortcut,
+control-c, to halt a program stuck in a continual loop. Give it a try:
$ cargo run
+ Compiling loops v0.1.0 (file:///projects/loops)
+ Running `target/debug/loops`
+again!
+again!
+again!
+again!
+^Cagain!
+
+That ^C there is where we hit control-c. You may or may not see "again!"
+printed after the ^C, depending on where the code was in the loop when it
+received the signal to halt.
Fortunately, Rust provides another, more reliable way to break out of a loop.
+We can place the break keyword within the loop to tell the program when to
+stop executing the loop. Recall that we did this in the guessing game to exit
+the program when the user won the game by guessing the number correctly.
whileA useful thing that many programs do is have a condition that can be evaluated
+within a loop. While the condition is true, the loop runs. When the condition
+ceases to be true, we call break, stopping the loop. This could be
+implemented with a combination of loop, if, else, and break; try to do
+that now if you'd like!
But this pattern is so common that Rust has a more efficient language construct
+for it, called a while loop. Here's an example using while: this program
+loops three times, counting down each time. Finally, after the loop, it prints
+another message, then exits:
fn main() {
+ let mut number = 3;
+
+ while number != 0 {
+ println!("{}!", number);
+
+ number = number - 1;
+ }
+
+ println!("LIFTOFF!!!");
+}
+
+This gets rid of a lot of nesting that would be necessary if we used loop,
+if, else, and break, and it's more clear. While a condition holds, run
+this code; otherwise, exit the loop.
forWe could use this while construct to loop over the elements of a collection,
+like an array. For example:
fn main() {
+ let a = [10, 20, 30, 40, 50];
+ let mut index = 0;
+
+ while index < 5 {
+ println!("the value is: {}", a[index]);
+
+ index = index + 1;
+ }
+}
+
+Here, we're counting up through the elements in the array. We start at index 0,
+then loop until we hit the final index of our array (that is, when index < 5
+is no longer true). Running this will print out every element of the array:
$ cargo run
+ Compiling loops v0.1.0 (file:///projects/loops)
+ Running `target/debug/loops`
+the value is: 10
+the value is: 20
+the value is: 30
+the value is: 40
+the value is: 50
+
+All five array values appear in the terminal, as expected. Even though index
+will reach a value of 6 at some point, the loop stops executing before trying
+to fetch a sixth value from the array.
This approach is error-prone, though; we could cause our program to panic by +getting the index length incorrect. It's also slow, as the compiler needs to +perform the conditional check on every element on every iteration through the +loop.
+As a more efficient alternative, we can use a for loop and execute some code
+for each item in a collection. A for loop looks like this:
fn main() {
+ let a = [10, 20, 30, 40, 50];
+
+ for element in a.iter() {
+ println!("the value is: {}", element);
+ }
+}
+
+If we run this, we'll see the same output as the previous example. Importantly, +though, we've now increased the safety of our code and eliminated the chance of +bugs resulting from going beyond the end of the array or not going far enough +and missing some items.
+For example, in the previous code that uses the while loop, if we removed an
+item from the a array but forgot to update the condition to be while index < 4, our code would panic. Using the for loop means we would not need to
+remember to change any other code if we changed the the number of values in the
+array.
If you're wondering about the .iter() code in this example, keep reading! We
+will cover method syntax generally in Chapter XX and iterators specifically in
+Chapter XX.
The safety and conciseness of for loops make them the most commonly used loop
+construct in Rust. Even in situations where you want to run some code a certain
+number of times, like our countdown example that used a while loop, most
+Rustaceans would use a for loop. The way to do that is using a Range, which
+is a type provided by the standard library that generates numbers starting from
+one number and ending before another number. Here's what the countdown would
+look like with a for loop, and using another method we haven't yet talked
+about, .rev(), to reverse the range:
fn main() {
+ for number in (1..4).rev() {
+ println!("{}!", number);
+ }
+ println!("LIFTOFF!!!");
+}
+
+That's a bit nicer, isn't it?
+Now that you know how Rust does things that most other languages can do, let's +talk about a concept that doesn't commonly exist: ownership.
+ +We strive to make our programs easy to understand, but sometimes, some extra -explanation is warranted. We can leave notes in our source code that the -compiler will ignore. These notes are called ‘comments’.
-Here’s a comment:
-// Hello, world.
-
-Comments start with two slashes, and last until the end of the line. Larger -comments will need more lines:
-// So we’re doing something complicated here, long enough that we need
-// multiple lines of comments to do it! Whew! Hopefully, this comment will
-// explain what’s going on.
-
-Comments can also go at the end of lines:
-fn main() {
- let lucky_number = 7; // I’m feeling lucky today.
-}
-
-But you’ll more often see them above:
-fn main() {
- // I’m feeling lucky today.
- let lucky_number = 7;
-}
-
-That’s all there is to it. Comments are not particularly complicated.
- -if--Two roads diverged in a yellow wood,
-
-And sorry I could not travel both
-And be one traveler, long I stood
-And looked down one as far as I could
-To where it bent in the undergrowth;-
-- Robert Frost, “The Road Not Taken”
-
In Rust, there are a few ways to cause our code to branch. The most fundamental
-way is by using if. An if expression gives us two paths forward, and asks
-the question, “Which one should I take?”
Let’s make a new project to explore if. Navigate to your projects directory,
-and use Cargo to make a new project called branches:
$ cargo new --bin branches
-$ cd branches
-
-Here’s a sample program using if:
fn main() {
- let condition = true;
-
- if condition {
- println!("condition was true");
- } else {
- println!("condition was false");
- }
-}
-
-Let's try running it:
-$ cargo run
- Compiling branches v0.1.0 (file:///projects/branches)
- Running `target/debug/branches`
-condition was true
-
-We can change the value of condition:
let condition = false;
-
-And then run it again:
-$ cargo run
- Compiling branches v0.1.0 (file:///projects/branches)
- Running `target/debug/branches`
-condition was false
-
-This is the very basic structure of if: if the condition is true, then
-execute some code. If it’s not true, then execute some other code, after
-else.
An else is not required:
fn main() {
- let condition = false;
-
- if condition {
- println!("condition was true");
- }
-}
-
-In this case, nothing is printed.
-It’s also worth noting that condition here must be a bool. Let’s try an
-example with something else:
fn main() {
- let condition = 5;
-
- if condition {
- println!("condition was five");
- }
-}
-
-If we try to run this program, Rust will complain:
- Compiling branches v0.1.0 (file:///projects/branches)
-src/main.rs:4:8: 4:17 error: mismatched types:
- expected `bool`,
- found `_`
-(expected bool,
- found integral variable) [E0308]
-src/main.rs:4 if condition {
- ^~~~~~~~~
-src/main.rs:4:8: 4:17 help: run `rustc --explain E0308` to see a detailed explanation
-error: aborting due to previous error
-Could not compile `branches`.
-
-We expected a bool, but got an integer. Rust will not automatically try to convert non-boolean types to a boolean here. We must be explicit.
else ifWe can make multiple decisions by combining if and else in another way:
fn main() {
- let number = 5;
-
- if number == 3 {
- println!("condition was 3");
- } else if number == 4 {
- println!("condition was 4");
- } else if number == 5 {
- println!("condition was 5");
- } else {
- println!("condition was something else");
- }
-}
-
-Let's try running it:
-$ cargo run
- Compiling branches v0.1.0 (file:///projects/branches)
- Running `target/debug/branches`
-condition was 5
-
-When this program executes, it will check each if in turn, and execute the
-first body for which the condition holds true.
Using a single else if can be okay, but if you find yourself with more than one,
-you may want to refactor your code. Rust has a more powerful branching construct
-called match for these cases. We'll cover it later, when we talk about enums.
if as an expressionThere’s one last detail we need to learn about if: it’s an expression. That means
-that we can use it on the right hand side of a let binding, for instance:
fn main() {
- let condition = true;
-
- let number = if condition {
- 5
- } else {
- 6
- };
-
- println!("The value of number is: {}", number);
-}
-
-Let’s run this:
-$ cargo run
- Compiling branches v0.1.0 (file:///projects/branches)
- Running `target/debug/branches`
-The value of number is: 5
-
-Remember, blocks of code evaluate to the last expression in them. And numbers
-by themselves are also expressions. So in this case, the value of the whole
-if expression depends on which block of code executes.
There’s another small detail involved here: this means that if you use if
-in this way, both arms of the if must be the same type. This doesn’t work:
fn main() {
- let condition = true;
-
- let number = if condition {
- 5
- } else {
- "six"
- };
-
- println!("The value of number is: {}", number);
-}
-
-If we try to run this, we’ll get an error:
- Compiling branches v0.1.0 (file:///projects/branches)
-src/main.rs:4:18: 8:6 error: if and else have incompatible types:
- expected `_`,
- found `&‘static str`
-(expected integral variable,
- found &-ptr) [E0308]
-src/main.rs:4 let number = if condition {
-src/main.rs:5 5
-src/main.rs:6 } else {
-src/main.rs:7 "six"
-src/main.rs:8 };
-src/main.rs:4:18: 8:6 help: run `rustc --explain E0308` to see a detailed explanation
-error: aborting due to previous error
-Could not compile `branches`.
-
-if and else have incompatible types. This can’t work.
It’s often quite useful to be able to execute a block of code more than one -time. For this, we have several constructs, called ‘loops’.
-To try out loops, let’s make a new project. Navigate to your projects folder -and use Cargo to make a new one:
-$ cargo new --bin loops
-$ cd loops
-
-There are three kinds of loops in Rust: loop, while, and for. Let’s dig
-in.
loopThe loop keyword is very straightforward: it executes a block of code over
-and over and over and over and over and over forever. Change your src/main.rs
-file to look like this:
fn main() {
- loop {
- println!("again!");
- }
-}
-
-If we run this program, we’ll see ‘again!’ printed over and over again. So
-how does our program end? It doesn’t, until we kill it. Most terminals support
-a keyboard shortcut, ‘control-c’, to stop a runaway program. Give it a try:
$ cargo run
- Compiling loops v0.1.0 (file:///projects/loops)
- Running `target/debug/loops`
-again!
-again!
-again!
-again!
-^Cagain!
-
-That ^C there is where I hit control-c.
That’s a lot of trouble though! Luckily, there’s a way to break an infinite loop.
The break keyword will allow us to quit looping. Try this version out:
fn main() {
- loop {
- println!("once!");
- break;
- }
-}
-
-If you run this program with cargo run, you’ll see that it only executes one
-time:
$ cargo run
- Compiling loops v0.1.0 (file:///projects/loops)
- Running `target/debug/loops`
-once!
-
-When a Rust program hits a break statement, it will exit the current loop.
whileWhat if we took loop, break, and if, and put them together? Something
-like this:
fn main() {
- let mut number = 3;
-
- loop {
- if number != 0 {
- println!("{}!", number);
-
- number = number - 1;
- } else {
- break;
- }
-
- }
-
- println!("LIFTOFF!!!");
-}
-
-If we run this, we’ll get some output:
- Compiling loops v0.1.0 (file:///projects/loops)
- Running `target/debug/loops`
-3!
-2!
-1!
-LIFTOFF!!!
-
-The core of this example is in the combination of these three constructs:
- loop {
- if number != 0 {
- // do stuff
- } else {
- break;
- }
-
-We want to loop, but only while some sort of condition is true. As soon as it
-isn't, we want to break out of the loop.
This pattern is so common that we have a language construct for it: while.
-Here's the same example, but using while instead:
fn main() {
- let mut number = 3;
- while number != 0 {
- println!("{}!", number);
-
- number = number - 1;
- }
-
- println!("LIFTOFF!!!");
-}
-
-This lets us get rid of a lot of nesting, and is more clear: while a condition holds, -run this code.
-forWe can use this while construct to loop over the elements of a collection, like an
-array:
fn main() {
- let a = [1, 2, 3, 4, 5];
- let mut index = 0;
-
- while index < 5 {
- println!("the value is: {}", a[index]);
-
- index = index + 1;
- }
-}
-
-Running this will print out every element of the array:
-$ cargo run
- Compiling loops v0.1.0 (file:///projects/loops)
- Running `target/debug/loops`
-the value is: 1
-the value is: 2
-the value is: 3
-the value is: 4
-the value is: 5
-
-Here, we're counting up instead of down: we start at zero, then loop until we -hit the final index of our array.
-This approach is error-prone, though. If we get the index length incorrect, we
-will end up causing a panic!. This is also slow, as the compiler needs to do
-that check on every element on every iteration through the loop.
Instead, we can use our last kind of loop: the for loop. It looks like this:
fn main() {
- let a = [1, 2, 3, 4, 5];
-
- for element in a.iter() {
- println!("the value is: {}", element);
- }
-}
-
-** NOTE: see https://github.com/rust-lang/rust/issues/25725#issuecomment-166365658, we may want to change this **
-If we run this, we'll see the same output as the previous example.
-** I'm going to leave it at this for now until we decide how we want to do it**
- -Ownership is important to understand: it's Rust's most unique feature, and +enables Rust to make memory safety guarantees without needing a garbage +collector. We’ll also talk about several related features: borrowing, slices, +and how Rust lays things out in memory.
+ +Rust’s central feature is called ‘ownership’. It is a feature that is straightforward to explain, but has deep implications for the rest of the language.
-Rust is committed to both safety and speed. One of the key tools for balancing -between them is “zero-cost abstractions”: the various abstractions in Rust do -not pose a global performance penalty. The ownership system is a prime example -of a zero-cost abstraction. All of the analysis we’ll talk about in this guide -is done at compile time. You do not pay any run-time cost for any of these +
All programs have to manage the way they use a computer's memory while running. +Some languages have garbage collection, while in others, the programmer has to +explicitly allocate and free the memory. Rust takes a third approach: memory is +managed through a system of ownership with a set of rules that the compiler +checks at compile-time. You do not pay any run-time cost for any of these features.
-However, this system does have a certain cost: learning curve. Many new -Rustaceans experience something we like to call ‘fighting with the borrow -checker’, where the Rust compiler refuses to compile a program that the author -thinks is valid. This can happen because the programmer isn’t used to thinking -carefully about ownership, or is thinking about it differently from the way -that Rust does. You probably will experience something similar at first. There is -good news, however: more experienced Rust developers report that once they work -with the rules of the ownership system for a period of time, they fight the -borrow checker less and less. Keep at it!
-This chapter will give you a foundation for understanding the rest of the -language. To do so, we’re going to learn through examples, focusing on a very -common data structure: strings.
-Let’s take a step back and look at the very basics again. Now that we’re past
-basic syntax, we won’t include all of the fn main() { stuff in examples, so
-if you’re following along, you will have to put them inside of a main()
-function. This lets our examples be a bit more concise, letting us focus on the
-actual details, rather than boilerplate.
Anyway, here it is:
+However, because ownership is a new concept for many programmers, it does take +some time to get used to. There is good news, though: the more experienced you +become with Rust and the rules of the ownership system, the more you'll be +able to naturally develop code that is both safe and efficient. Keep at it!
+Once you understand ownership, you have a good foundation for understanding the +features that make Rust unique. In this chapter, we'll learn ownership by going +through some examples, focusing on a very common data structure: strings.
+We've walked through an example of a Rust program already in the tutorial
+chapter. Now that we’re past basic syntax, we won’t include all of the fn main() { stuff in examples, so if you’re following along, you will have to put
+them inside of a main() function. This lets our examples be a bit more
+concise, letting us focus on the actual details rather than boilerplate.
Anyway, here is our first example:
let s = "hello";
-This variable binding refers to a string literal. It’s valid from the point at -which it’s declared, until the end of the current scope. That is:
-{ // s is not valid here, it’s not yet in scope
+This variable binding refers to a string literal, where the value of the string
+is hard coded into the text of our program. The binding is valid from the point
+at which it’s declared until the end of the current scope. That is:
+{ // s is not valid here, it’s not yet declared
let s = "hello"; // s is valid from this point forward
// do stuff with s
@@ -111,35 +106,39 @@ which it’s declared, until the end of the current scope. That is:
When s comes ‘into scope’, it is valid.
It remains so until it ‘goes out of scope’.
-At this point, things are similar to other programming languages. Let’s build
-on top of this understanding by introducing a new type: String.
-Strings
-String literals are convenient, but they aren’t the only way that you use strings.
-For one thing, they’re immutable. For another, not every string is literal:
-what about taking user input and storing it in a string?
-For this, Rust has a second string type, String. You can create a String from
-a string literal using the from function:
+At this point, things are similar to other programming languages. Now let’s
+build on top of this understanding by introducing the String type.
+Strings
+String literals are convenient, but they aren’t the only way that you use
+strings. For one thing, they’re immutable. For another, not every string is
+literal: what about taking user input and storing it in a string?
+For this, Rust has a second string type, String. You can create a String
+from a string literal using the from function:
let s = String::from("hello");
-We haven’t seen the double colon (::) syntax yet. It is a kind of scope
-operator, allowing us to namespace this particular from() function under the
-String type itself, rather than using some sort of name like string_from().
-We’ll discuss this syntax more in the “Method Syntax” and “Modules” chapters.
+We haven’t seen the double colon (::) syntax yet. It is an operator that
+allows us to namespace this particular from() function under the String
+type itself, rather than using some sort of name like string_from(). We’ll
+discuss this syntax more in the “Method Syntax” and “Modules” chapters.
This kind of string can be mutated:
let mut s = String::from("hello");
-s.push_str(", world!");
+s.push_str(", world!"); // push_str() appends a literal to a String
+
+println!("{}", s); // This will print `hello, world!`
-Memory and allocation
+Memory and allocation
So, what’s the difference here? Why can String be mutated, but literals
cannot? The difference comes down to how these two types deal with memory.
In the case of a string literal, because we know the contents of the string at
compile time, we can hard-code the text of the string directly into the final
executable. This means that string literals are quite fast and efficient. But
-these properties only come from its immutability; we can’t put an
-arbitrary-sized blob of memory into the binary for each string!
-With String, to support a mutable, growable string, we need to allocate an
-unknown amount of memory to hold the contents. This means two things:
+these properties only come from its immutability. Unfortunately, we can’t put a
+blob of memory into the binary for each string whose size is unknown at compile
+time and whose size might change over the course of running the program.
+With String, in order to support a mutable, growable string, we need to
+allocate an unknown amount of memory to hold the contents. This means two
+things:
- The memory must be requested from the operating system at runtime.
- We need a way of giving this memory back to the operating system when we’re
@@ -149,13 +148,14 @@ done with our
String.
implementation requests the memory it needs. This is pretty much universal in
programming languages.
The second case, however, is different. In languages with a garbage collector
-(‘GC’), the GC handles that second case, and we, as the programmer, don’t need
-to think about it. Without GC, it’s the programmer’s responsibility to identify
-when memory is no longer being used, and explicitly return it, just as it was
-requested. Doing this correctly has historically been a difficult problem. If
-we forget, we will waste memory. If we do it too early, we will have an invalid
-variable. If we do it twice, that’s a bug too. We need to pair exactly one
-allocate() with exactly one free().
+(‘GC’), the GC will keep track and clean up memory that isn't being used
+anymore, and we, as the programmer, don’t need to think about it. Without GC,
+it’s our responsibility to identify when memory is no longer being used and
+call code to explicitly return it, just as we did to request it. Doing this
+correctly has historically been a difficult problem. If we forget, we will
+waste memory. If we do it too early, we will have an invalid variable. If we do
+it twice, that’s a bug too. We need to pair exactly one allocate() with
+exactly one free().
Rust takes a different path. Remember our example? Here’s a version with
String:
{
@@ -164,10 +164,11 @@ variable. If we do it twice, that’s a bug too. We need to pair exactly one
// do stuff with s
} // this scope is now over, and s is no longer valid
-We have a natural point at which we can return the memory our String needs back
-to the operating system: when it goes out of scope! When a variable goes out of
-scope, a special function is called. This function is called drop(), and it
-is where the author of String can put the code to return the memory.
+We have a natural point at which we can return the memory our String needs
+back to the operating system: when it goes out of scope. When a variable goes
+out of scope, Rust calls a special function for us. This function is called
+drop(), and it is where the author of String can put the code to return the
+memory.
Aside: This pattern is sometimes called “Resource Acquisition Is
Initialization” in C++, or “RAII” for short. While they are very similar,
@@ -176,14 +177,14 @@ to use the same term. If you’re familiar with this idea, keep in mind that it
is roughly similar in Rust, but not identical.
This pattern has a profound impact on the way that Rust code is written. It may
-seem obvious right now, but things can get tricky in more advanced situations!
+seem obvious right now, but things can get tricky in more advanced situations.
Let’s go over the first one of those right now.
-Move
+Move
What would you expect this code to do?
let x = 5;
let y = x;
-You might say “Make a copy of 5.” That’d be correct! We now have two
+
You might say “Make a copy of 5”, and that would be correct. We now have two
bindings, x and y, and both equal 5.
Now let’s look at String. What would you expect this code to do?
let s1 = String::from("hello");
@@ -197,51 +198,45 @@ let’s take a look at what String looks like under the covers:
contents of the string, a length, and a capacity. The length is how much memory
the String is currently using. The capacity is the total amount of memory the
String has gotten from the operating system. The difference between length
-and capacity matters, but not in this context, so don’t worry about it too much
-if it doesn’t make sense, and just ignore the capacity.
-
-We’ve talked about two kinds of composite types: arrays and tuples. String
-is a third type: a struct, which we will cover the details of in the next
-chapter of the book. For now, thinking about String as a tuple is close
-enough.
-
-When we assign s1 to s2, the String itself is copied. But not all kinds
-of copying are the same. Many people draw distinctions between ‘shallow
-copying’ and ‘deep copying’. We don’t use these terms in Rust. We instead say
-that something is ‘moved’ or ‘cloned’. Assignment in Rust causes a ‘move’. In
-other words, it looks like this:
+and capacity matters but not in this context, so don’t worry about it too much.
+For right now, it's fine to ignore the capacity.
+When we assign s1 to s2, the String itself is copied, meaning we copy the
+pointer, the length, and the capacity. We do not copy the data that the
+String's pointer refers to. In other words, it looks like this:

Not this:

-When moving, Rust makes a copy of the data structure itself, the contents of
-s1 are copied, but if s1 contains a reference, like it does in this case,
-Rust will not copy the things that those references refer to.
-There’s a problem here! Both data pointers are pointing to the same place.
-Why is this a problem? Well, when s2 goes out of scope, it will free the
-memory that data points to. And then s1 goes out of scope, and it will
-also try to free the memory that data points to! That’s bad.
-So what’s the solution? Here, we stand at a crossroads. There are a few
-options. One would be to declare that assignment will also copy out any data.
-This works, but is inefficient: what if our String contained a novel? Also,
-it only works for memory. What if, instead of a String, we had a
-TcpConnection? Opening and closing a network connection is very similar to
-allocating and freeing memory. The solution that we could use there is to allow
-the programmer to hook into the assignment, similar to drop(), and write code
-to fix things up. That would work, but now, an = can run arbitrary code. That’s
-also not good, and it doesn’t solve our efficiency concerns either.
+There’s a problem here. Both data pointers are pointing to the same place. Why
+is this a problem? Well, when s2 goes out of scope, it will free the memory
+that the pointer points to. And then s1 goes out of scope, and it will also
+try to free the memory that the pointer points to. That’s bad, and is known as
+a "double free" error.
+So what’s the solution? Here, we stand at a crossroads with a few options.
+One way would be to change assignment so that it will also copy out any data.
+This works, but is inefficient: what if our String contained a novel?
+Also, that solution would only work for memory. What if, instead of a String,
+we had a TcpConnection? Opening and closing a network connection is very
+similar to allocating and freeing memory, so it would be nice to be able to use
+the same mechanism. We wouldn't be able to, though, because creating a new
+connection requires more than just copying memory: we have to request a new
+connection from the operating system. We could then extend our solution to
+allow the programmer to hook into the assignment, similar to drop(), and
+write code to fix things up. That would work, but if we did that, an = could
+run arbitrary code. That’s also not good, and it doesn’t solve our efficiency
+concerns either.
Let’s take a step back: the root of the problem is that s1 and s2 both
-think that they have control of the memory, and therefore needs to free it.
+think that they have control of the memory and therefore need to free it.
Instead of trying to copy the allocated memory, we could say that s1 is no
-longer valid, and therefore, doesn’t need to free anything. This is in fact the
-choice that Rust makes. Check it out what happens when you try to use s1
-after s2 is created:
+longer valid and, therefore, doesn’t need to free anything. This is in fact the
+choice that Rust makes. Check out what happens when you try to use s1 after
+s2 is created:
let s1 = String::from("hello");
let s2 = s1;
println!("{}", s1);
You’ll get an error like this:
-5:22 error: use of moved value: `s1` [E0382]
+5:22 error: use of moved value: `s1` [E0382]
println!("{}", s1);
^~
5:24 note: in this expansion of println! (defined in <std macros>)
@@ -249,26 +244,31 @@ println!("{}", s1);
let s2 = s1;
^~
-We say that s1 was moved into s2. When a value moves, its data is copied,
-but the original variable binding is no longer usable. That solves our problem:
+If you have heard the terms "shallow copy" and "deep copy" while working with
+other languages, the concept of copying the pointer, length, and capacity
+without copying the data probably sounded like a shallow copy. Because Rust
+also invalidates the first binding, instead of calling this a shallow copy,
+it's called a move. Here we would read this by saying that s1 was moved
+into s2. So what actually happens looks like this:

-With only s2 valid, when it goes out of scope, it will free the memory, and we’re done!
-Ownership Rules
+That solves our problem! With only s2 valid, when it goes out of scope, it
+alone will free the memory, and we’re done.
+Ownership Rules
This leads us to the Ownership Rules:
-- Each value in Rust has a variable binding that’s called it’s ‘owner’.
+- Each value in Rust has a variable binding that’s called its ‘owner’.
- There can only be one owner at a time.
- When the owner goes out of scope, the value will be
drop()ped.
Furthermore, there’s a design choice that’s implied by this: Rust will never
-automatically create ‘deep’ copies of your data. Any automatic copying must be
-inexpensive.
-Clone
-But what if we do want to deeply copy the String’s data, and not just the
+automatically create ‘deep’ copies of your data. Therefore, any automatic
+copying can be assumed to be inexpensive.
+Clone
+But what if we do want to deeply copy the String’s data and not just the
String itself? There’s a common method for that: clone(). We will discuss
-methods in the next section on structs, but they’re a common enough feature
+methods in the section on structs, but they’re a common enough feature
in many programming languages that you have probably seen them before.
Here’s an example of the clone() method in action:
let s1 = String::from("hello");
@@ -280,9 +280,9 @@ println!("{}", s1);
it is doing this:

When you see a call to clone(), you know that some arbitrary code is being
-executed, which may be expensive. It’s a visual indicator that something
+executed, and that code may be expensive. It’s a visual indicator that something
different is going on here.
-Copy
+Copy
There’s one last wrinkle that we haven’t talked about yet. This code works:
let x = 5;
let y = x;
@@ -290,34 +290,30 @@ let y = x;
println!("{}", x);
But why? We don’t have a call to clone(). Why didn’t x get moved into y?
-For types that do not have any kind of complex storage requirements, like
-integers, typing clone() is busy work. There’s no reason we would ever want
-to prevent x from being valid here, as there’s no situation in which it’s
-incorrect. In other words, there’s no difference between deep and shallow
-copying here, so calling clone() wouldn’t do anything differently from the
-usual shallow copying.
-Rust has a special annotation that you can place on types, called Copy. If
-a type is Copy, an older binding is still usable after assignment. Integers
-are an example of such a type; most of the primitive types are Copy.
-While we haven’t talked about how to mark a type as Copy yet, you might ask
-yourself “what happens if we made String Copy?” The answer is, you cannot.
-Remember drop()? Rust will not let you make something Copy if it has
+
Types like integers that have a known size at compile time do not ask for
+memory from the operating system and therefore do not need to be drop()ped
+when they go out of scope. That means there's no reason we would want to
+prevent x from being valid after we create the binding y. In other words,
+there’s no difference between deep and shallow copying here, so calling
+clone() wouldn’t do anything differently from the usual shallow copying and
+we can leave it out.
+Rust has a special annotation that you can place on types like these, and that
+annotation is the Copy trait. We'll talk more about traits in Chapter XX. If
+a type has the Copy trait, an older binding is still usable after assignment.
+Rust will not let you make something have the Copy trait if it has
implemented drop(). If you need to do something special when the value goes
out of scope, being Copy will be an error.
So what types are Copy? You can check the documentation for the given type to
-be sure, but as a rule of thumb, any group of simple scalar values can be
-Copy, but nothing that requires allocation or is some form of resource is Copy.
-And you can’t get it wrong: the compiler will throw an error if you try to use
-a type that moves incorrectly, as we saw above.
-Here’s some types that you’ve seen so far that are Copy:
+be sure, but as a rule of thumb, any group of simple scalar values can be Copy,
+but nothing that requires allocation or is some form of resource is Copy. Here’s some of the types that are Copy:
- All of the integer types, like
u32.
- The booleans,
true and false.
- All of the floating point types, like
f64.
- Tuples, but only if they contain types which are also
Copy. (i32, i32)
-is Copy, but (i32, String) is not!
+is Copy, but (i32, String) is not.
-Ownership and functions
+Ownership and functions
Passing a value to a function has similar semantics as assigning it:
fn main() {
let s = String::from("hello");
@@ -364,7 +360,9 @@ fn makes_copy(some_integer: i32) { // some_integer comes into scope.
} // Here, some_integer goes out of scope. Nothing special happens.
Remember: If we tried to use s after the call to takes_ownership(), Rust
-would throw a compile-time error! These static checks protect us from mistakes.
+would throw a compile-time error. These static checks protect us from mistakes.
+Try adding code to main that uses s and x to see where you can use them
+and where the ownership rules prevent you from doing so.
Returning values can also transfer ownership:
fn main() {
let s1 = gives_ownership();
@@ -417,9 +415,11 @@ fn takes_and_gives_back(a_string: String) -> String { // a_string comes into
It’s the same pattern, every time: assigning something moves it, and when an
owner goes out of scope, if it hasn’t been moved, it will drop().
-This might seem a bit tedious, and it is. What if I want to let a function use
-a value, but not take ownership? It’s quite annoying that anything I pass in
-also needs to be passed back. Look at this function:
+This might seem a bit tedious, and it is. What if we want to let a function use
+a value but not take ownership? It’s quite annoying that anything we pass in
+also needs to be passed back if we want to use it again, in addition to any
+data resulting from the body of the function that we might want to return as
+well. It's possible to return multiple values, using a tuple, like this:
fn main() {
let s1 = String::from("hello");
@@ -434,21 +434,21 @@ fn calculate_length(s: String) -> (String, usize) {
(s, length)
}
-This is too much ceremony: we have to use a tuple to give back the String as
-well as the length. It’s a lot of work for a pattern that should be common.
-Luckily for us, Rust has such a feature, and it’s what the next section is about.
+But this is too much ceremony and a lot of work for a concept that should be
+common. Luckily for us, Rust has a feature for this concept, and it’s what the
+next section is about.
Now that we’ve got some basic syntax under our belt, it’s time to take a look -at Rust’s most unique feature: ownership. We’ll also talk about several related -features: borrowing, slices, and lifetimes, as well as how Rust lays things out -in memory.
- -At the end of the last section, we had some example Rust that wasn’t very good. Here it is again:
fn main() {
@@ -85,7 +85,8 @@ fn calculate_length(s: String) -> (String, usize) {
}
The issue here is that we have to return the String back to the calling
-function so that it could still use it.
calculate_length().
There is a better way. It looks like this:
fn main() {
let s1 = String::from("hello");
@@ -101,10 +102,11 @@ fn calculate_length(s: &String) -> usize {
length
}
-First, you’ll notice all of the tuple stuff is gone. Next, that we pass &s1
-into calculate_lengths(). And in its definition, we take &String rather
-than String.
These &s are called ‘references’, and they allow you to refer to some value
+
First, you’ll notice all of the tuple stuff in the binding declaration and the
+function return value is gone. Next, note that we pass &s1 into
+calculate_length(), and in its definition, we take &String rather than
+String.
These &s are called ‘references’, and they allow you to refer to some value
without taking ownership of it. Here’s a diagram:
DIAGRAM GOES HERE of a &String pointing at a String, with (ptr, len, capacity)
Let’s take a closer look at the function call here:
@@ -117,12 +119,11 @@ let s1 = String::from("hello"); let len = calculate_length(&s1); -The &s1 syntax lets us create a reference from s1. This reference refers
-to the value of s1, but does not own it. Because it does not own it, the
+
The &s1 syntax lets us create a reference with s1. This reference refers
+to the value of s1 but does not own it. Because it does not own it, the
value it points to will not be dropped when the reference goes out of scope.
Likewise, the signature of the function uses & to indicate that it takes
-a reference as an argument:
Let’s add some explanatory annotations:
+a reference as an argument. Let’s add some explanatory annotations:fn calculate_length(s: &String) -> usize { // s is a reference to a String
let length = s.len();
@@ -135,10 +136,10 @@ we don’t drop what a reference points to when the reference goes out of scope.
This lets us write functions which take references as arguments instead of the
values themselves, so that we won’t need to return them to give back ownership.
There’s another word for what references do, and that’s ‘borrowing’. Just like
-with real life, if I own something, you can borrow it from me. When you’re done,
-you have to give it back.
+with real life, if a person owns something, you can borrow it from them. When
+you’re done, you have to give it back.
Speaking of which, what if you try to modify something you borrow from me? Try
-this code out. Spoiler alert: it doesn’t work:
+this code out. Spoiler alert: it doesn’t work!
fn main() {
let s = String::from("hello");
@@ -146,17 +147,19 @@ this code out. Spoiler alert: it doesn’t work:
}
fn change(some_string: &String) {
- some_string.push_str(", world"); // push_str() appends a literal to a String
+ some_string.push_str(", world");
}
Here’s the error:
-8:16 error: cannot borrow immutable borrowed content `*some_string` as mutable
- some_string.push_str(", world"); // push_str() appends a literal to a String
- ^~~~~~~~~~~
+error: cannot borrow immutable borrowed content `*some_string` as mutable
+ --> error.rs:8:5
+ |
+8 | some_string.push_str(", world");
+ | ^^^^^^^^^^^
-Just like bindings are immutable by default, so are references. We’re not allowed
-to modify something we have a reference to.
-Mutable references
+Just like bindings are immutable by default, so are references. We’re not
+allowed to modify something we have a reference to.
+Mutable references
We can fix this bug! Just a small tweak:
fn main() {
let mut s = String::from("hello");
@@ -165,11 +168,11 @@ to modify something we have a reference to.
}
fn change(some_string: &mut String) {
- some_string.push_str(", world"); // push_str() appends a literal to a String
+ some_string.push_str(", world");
}
-First, we had to change s to be mut. Then, we had to create a mutable reference
-with &mut s and accept a mutable reference with some_string: &mut String.
+First, we had to change s to be mut. Then we had to create a mutable
+reference with &mut s and accept a mutable reference with some_string: &mut String.
Mutable references have one big restriction, though. This code fails:
let mut s = String::from("hello");
@@ -177,26 +180,22 @@ let r1 = &mut s;
let r2 = &mut s;
Here’s the error:
-5:20 error: cannot borrow `s` as mutable more than once at a time [E0499]
- let r2 = &mut s;
- ^
-4:20 note: previous borrow of `s` occurs here; the mutable borrow prevents
- subsequent moves, borrows, or modification of `s` until the borrow
- ends
- let r1 = &mut s;
- ^
-7:2 note: previous borrow ends here
-fn main() {
-
-}
-^
+error[E0499]: cannot borrow `s` as mutable more than once at a time
+ --> borrow_twice.rs:5:19
+ |
+4 | let r1 = &mut s;
+ | - first mutable borrow occurs here
+5 | let r2 = &mut s;
+ | ^ second mutable borrow occurs here
+6 | }
+ | - first borrow ends here
-The error is what it says on the tin: you cannot borrow something more than
-once at a time in a mutable fashion. This restriction allows for mutation, but
-in a very controlled fashion. It is something that new Rustaceans struggle
-with, because most languages let you mutate whenever you’d like.
+The error is what it says: you cannot borrow something mutably more than once
+at a time. This restriction allows for mutation but in a very controlled
+fashion. It is something that new Rustaceans struggle with, because most
+languages let you mutate whenever you’d like.
As always, we can use {}s to create a new scope, allowing for multiple mutable
-references. Just not simultaneous ones:
+references, just not simultaneous ones:
let mut s = String::from("hello");
{
@@ -206,7 +205,8 @@ references. Just not simultaneous ones:
let r2 = &mut s;
-There is a similar rule for combining the two kinds of references. This code errors:
+There is a similar rule for combining mutable and immutable references. This
+code errors:
let mut s = String::from("hello");
let r1 = &s; // no problem
@@ -214,25 +214,21 @@ let r2 = &s; // no problem
let r3 = &mut s; // BIG PROBLEM
Here’s the error:
-19: 6:20 error: cannot borrow `s` as mutable because it is also borrowed as
- immutable [E0502]
- let r3 = &mut s; // BIG PROBLEM
- ^
-15: 4:16 note: previous borrow of `s` occurs here; the immutable borrow
- prevents subsequent moves or mutable borrows of `s` until the
- borrow ends
- let r1 = &s; // no problem
- ^
-8:2 note: previous borrow ends here
-fn main() {
-
-}
-^
+error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
+ --> borrow_thrice.rs:6:19
+ |
+4 | let r1 = &s; // no problem
+ | - immutable borrow occurs here
+5 | let r2 = &s; // no problem
+6 | let r3 = &mut s; // BIG PROBLEM
+ | ^ mutable borrow occurs here
+7 | }
+ | - immutable borrow ends here
Whew! We also cannot have a mutable reference while we have an immutable one.
Users of an immutable reference don’t expect the values to suddenly change out
from under them! Multiple immutable references are okay, however.
-Dangling references
+Dangling references
In languages with pointers, it’s easy to create a “dangling pointer” by freeing
some memory while keeping around a pointer to that memory. In Rust, by
contrast, the compiler guarantees that references will never be dangling: if we
@@ -250,12 +246,17 @@ fn dangle() -> &String {
}
Here’s the error:
-error: missing lifetime specifier [E0106]
-fn dangle() -> &String {
- ^~~~~~~
-help: this function’s return type contains a borrowed value, but there is no
- value for it to be borrowed from
-help: consider giving it a ‘static lifetime
+error[E0106]: missing lifetime specifier
+ --> dangle.rs:5:16
+ |
+5 | fn dangle() -> &String {
+ | ^^^^^^^
+ |
+ = help: this function's return type contains a borrowed value, but there is no
+ value for it to be borrowed from
+ = help: consider giving it a 'static lifetime
+
+error: aborting due to previous error
This error message refers to a feature we haven’t learned about yet,
‘lifetimes’. The message does contain the key to why this code is a problem,
@@ -284,34 +285,30 @@ no good. Rust won’t let us do this.
}
This works, no problem. Ownership is moved out, nothing is deallocated.
-The Rules of References
+The Rules of References
Here’s a recap of what we’ve talked about:
- At any given time, you may have either, but not both of:
- One mutable reference.
-- Any number of immutable references .
+- Any number of immutable references.
- References must always be valid.
-While these rules are not complicated on their own, they can be tricky when
-applied to real code. Let’s work through a number of examples to help build
-our understanding.
-More Examples
-COMING SOON
+Next, let's look at a different kind of reference: slices.
So far, we’ve talked about types that have ownership, like String, and ones
-that don’t, like &String. There is a second kind of type which does not have
+that don’t, like &String. There is another kind of type which does not have
ownership: slices. Slices let you reference a contiguous sequence of elements
-in a collection, rather than the whole collection itself.
Here’s a small programming problem: write a function which takes a string, +in a collection rather than the whole collection itself.
+Here’s a small programming problem: write a function which takes a string and returns the first word you find. If we don’t find a space in the string, then the whole string is a word, so the whole thing should be returned.
Let’s think about the signature of this function:
@@ -85,8 +85,8 @@ the word, though. Let’s try that:fn first_word(s: &String) -> usize {
let bytes = s.as_bytes();
- for (i, &byte) in bytes.iter().enumerate() {
- if byte == 32 {
+ for (i, &item) in bytes.iter().enumerate() {
+ if item == 32 {
return i;
}
}
@@ -95,47 +95,40 @@ the word, though. Let’s try that:
}
Let’s break that down a bit:
-fn first_word(s: &String) -> usize {
-
- // Since we need to go through the String element by element, and
- // check if a value is a space, we will convert our String to an
- // array of bytes, using the `.as_bytes()` method.
- let bytes = s.as_bytes();
-
- // We discussed using the iter() method with for in Chapter 3.7. Here,
- // we’re adding another method: enumerate(). While iter() returns each
- // element, enumerate() modifies the result of iter(), and returns a
- // tuple instead. The first element of the tuple is the index, and the
- // second element is a reference to the element itself. This is a bit
- // nicer than calculating the index ourselves.
- //
- // Since it’s a tuple, we can use patterns, just like elsewhere in Rust.
- // So we match against the tuple with i for the index, and &byte for
- // the byte itself.
- for (i, &byte) in bytes.iter().enumerate() {
-
- // 32 is the value of a space in UTF-8
- if byte == 32 {
-
- // We found a space! Return this position.
- return i;
- }
- }
-
- // If we got here, we didn’t find a space, so this whole thing must be a
- // word. So return the length.
- s.len()
-}
+let bytes = s.as_bytes();
+Since we need to go through the String element by element and
+check if a value is a space, we will convert our String to an
+array of bytes using the .as_bytes() method.
+for (i, &item) in bytes.iter().enumerate() {
+
+We will be discussing iterators in more detail in Chapter XX, but for
+now, know that iter() is a method that returns each element in a
+collection, and enumerate() modifies the result of iter() and returns
+a tuple instead. The first element of the tuple is the index, and the
+second element is a reference to the element itself. This is a bit
+nicer than calculating the index ourselves.
+Since it’s a tuple, we can use patterns, just like elsewhere in Rust. So we
+match against the tuple with i for the index and &item for a single byte. Since
+we get a reference from .iter().enumerate(), we use & in the pattern.
+ if item == 32 {
+ return i;
+ }
+}
+s.len()
+
+We search for the value 32, which represents a space in UTF-8. If we find one,
+we return the position. Otherwise, we return the length of the string, using
+s.len().
This works, but there’s a problem. We’re returning a usize on its own, but
-it’s only a meaningful number in the context of the &String itself. In other
+it’s only a meaningful number in the context of the &String. In other
words, because it’s a separate value from the String, there’s no guarantee
that it will still be valid in the future. Consider this:
# fn first_word(s: &String) -> usize {
# let bytes = s.as_bytes();
#
-# for (i, &byte) in bytes.iter().enumerate() {
-# if byte == 32 {
+# for (i, &item) in bytes.iter().enumerate() {
+# if item == 32 {
# return i;
# }
# }
@@ -146,22 +139,23 @@ that it will still be valid in the future. Consider this:
fn main() {
let mut s = String::from("hello world");
- let word = first_word(&s);
+ let word = first_word(&s); // word will get the value 5.
s.clear(); // This empties the String, making it equal to "".
- // word is now totally invalid! There’s no more word here.
+ // word still has the value 5 here, but there's no more string that
+ // we could meaningfully use the value 5 with. word is now totally invalid!
}
This is bad! It’s even worse if we wanted to write a second_word()
function. Its signature would have to look like this:
fn second_word(s: &String) -> (usize, usize) {
-Now we’re tracking both a start and and ending index. Even more chances for
+
Now we’re tracking both a start and an ending index. Even more chances for
things to go wrong. We now have three unrelated variable bindings floating
around which need to be kept in sync.
Luckily, Rust has a solution to this problem: string slices.
-String slices
+String slices
A string slice looks like this:
let s = String::from("hello world");
@@ -169,38 +163,47 @@ let hello = &s[0..5];
let world = &s[6..11];
This looks just like taking a reference to the whole String, but with the
-extra [0..5] bit. Instead of being a reference to the entire String,
-it’s a reference to an internal position in the String, but it also keeps
-track of the number of elements that it refers to as well. In other words,
-it looks like this:
+extra [0..5] bit. Instead of being a reference to the entire String, it’s a
+reference to an internal position in the String and the number of elements
+that it refers to.
+We can create slices with a range of [starting_index..ending_index], but the
+slice data structure actually stores the starting position and the length of the
+slice. So in the case of let world = &s[6..11];, world would be a slice that
+contains a pointer to the 6th byte of s and a length value of 5.
+In other words, it looks like this:
DIAGRAM GOES HERE of s, hello, and world
-Note that the internal position is specified through byte-offsets, not
-characters. The offset to the first byte of a String is 0 and the
-trailing number should point to the first byte that is not included
-in the slice.
-With Rust’s .. syntax, if you want to start at zero, you can drop the zero.
-In other words, these are equal:
+With Rust’s .. range syntax, if you want to start at the first index (zero),
+you can drop the value before the ... In other words, these are equal:
let s = String::from("hello");
let slice = &s[0..2];
let slice = &s[..2];
By the same token, if your slice should include the last byte of the
-String, you can drop the trailing number. In other words, these are
+String, you can drop the trailing number. That means these are
equal:
let s = String::from("hello");
let len = s.len();
+let slice = &s[3..len];
+let slice = &s[3..];
+
+You can also drop both values to take a slice of the entire string. So these
+are equal:
+let s = String::from("hello");
+
+let len = s.len();
+
let slice = &s[0..len];
-let slice = &s[0..];
+let slice = &s[..];
With this in mind, let’s re-write first_word() to return a slice:
fn first_word(s: &String) -> &str {
let bytes = s.as_bytes();
- for (i, &byte) in bytes.iter().enumerate() {
- if byte == 32 {
+ for (i, &item) in bytes.iter().enumerate() {
+ if item == 32 {
return &s[0..i];
}
}
@@ -208,26 +211,16 @@ let slice = &s[0..];
&s[..]
}
-Now, we have a single value, the &str. It contains both elements that we care
-about: a reference to the starting point, and the number of elements.
-This would also work for a second_word():
+Now we have a single value, the &str, pronounced "string slice". It stores
+both elements that we care about: a reference to the starting point of the
+slice and the number of elements in the slice.
+This would also work for a second_word():
fn second_word(s: &String) -> &str {
-Same deal. We now have a straightforward API, that’s much harder to mess up.
+We now have a straightforward API that’s much harder to mess up.
But what about our error condition from before? Slices also fix that. Using
the slice version of first_word() will throw an error:
-# fn first_word(s: &String) -> &str {
-# let bytes = s.as_bytes();
-#
-# for (i, &byte) in bytes.iter().enumerate() {
-# if byte == 32 {
-# return &s[0..i];
-# }
-# }
-#
-# &s[..]
-# }
-fn main() {
+fn main() {
let mut s = String::from("hello world");
let word = first_word(&s);
@@ -236,7 +229,7 @@ fn main() {
}
Here’s the error:
-17:6 error: cannot borrow `s` as mutable because it is also borrowed as
+17:6 error: cannot borrow `s` as mutable because it is also borrowed as
immutable [E0502]
s.clear(); // Error!
^
@@ -264,7 +257,7 @@ literals.
The type of s here is &str: It’s a slice, pointing to that specific point
of the binary. This is also why string literals are immutable; &str is an
immutable reference.
-String slices as arguments
+String slices as arguments
Knowing that you can take slices of both literals and Strings leads us to
one more improvement on first_word(), and that’s its signature:
fn first_word(s: &String) -> &str {
@@ -280,8 +273,8 @@ with no loss of functionality:
# fn first_word(s: &str) -> &str {
# let bytes = s.as_bytes();
#
-# for (i, &byte) in bytes.iter().enumerate() {
-# if byte == 32 {
+# for (i, &item) in bytes.iter().enumerate() {
+# if item == 32 {
# return &s[0..i];
# }
# }
@@ -289,16 +282,22 @@ with no loss of functionality:
# &s[..]
# }
fn main() {
- let s = String::from("hello world");
- let word = first_word(&s[..]);
+ let my_string = String::from("hello world");
- let s = "hello world";
- let word = first_word(&s[..]);
+ // first_word works on slices of `String`s
+ let word = first_word(&my_string[..]);
- let word = first_word(s); // since literals are &strs, this works too!
+ let my_string_literal = "hello world";
+
+ // first_word works on slices of string literals
+ let word = first_word(&my_string_literal[..]);
+
+ // since string literals *are* string slices already,
+ // this works too, without the slice syntax!
+ let word = first_word(my_string_literal);
}
-Other slices
+Other slices
String slices, as you might imagine, are specific to strings. But there’s a more
general slice type, too. Consider arrays:
let a = [1, 2, 3, 4, 5];
@@ -310,21 +309,21 @@ part of an array:
let slice = &a[1..3];
This slice has the type &[i32]. It works the exact same way as string slices
-do, with a reference to the first element, and a length. You’ll use this kind
-of slice for all sorts of other collections. We’ll discuss these other slices
-in detail when we talk about vectors, in Chapter 9.1.
+do, by storing a reference to the first element and a length. You’ll use this
+kind of slice for all sorts of other collections. We’ll discuss these in detail
+when we talk about vectors in Chapter XX.
A struct, short for "structure", gives us the ability to name and package
+together multiple related values that make up a meaningful group. If you come
+from an object-oriented language, a struct is like an object's data
+attributes. struct and enum (that we talked about in the last chapter) are
+the building blocks you can use in Rust to create new types in your program's
+domain in order to take full advantage of Rust's compile-time type checking.
Let’s write a program which calculates the distance between two points.
+We’ll start off with single variable bindings, and then refactor it to
+use structs instead.
Let’s make a new project with Cargo:
+$ cargo new --bin points
+$ cd points
+
+Here’s a short program which calculates the distance between two points. Put
+it into your src/main.rs:
fn main() {
+ let x1 = 0.0;
+ let y1 = 5.0;
+
+ let x2 = 12.0;
+ let y2 = 0.0;
+
+ let answer = distance(x1, y1, x2, y2);
+
+ println!("Point 1: ({}, {})", x1, y1);
+ println!("Point 2: ({}, {})", x2, y2);
+ println!("Distance: {}", answer);
+}
+
+fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
+ let x_squared = f64::powi(x2 - x1, 2);
+ let y_squared = f64::powi(y2 - y1, 2);
+
+ f64::sqrt(x_squared + y_squared)
+}
+
+Let's try running this program with cargo run:
$ cargo run
+ Compiling points v0.1.0 (file:///projects/points)
+ Running `target/debug/points`
+Point 1: (0, 5)
+Point 2: (12, 0)
+Distance: 13
+
+Let's take a quick look at distance() before we move forward. To find the
+distance between two points, we can use the Pythagorean Theorem. The theorem is
+named after Pythagoras, who was the first person to mathematically prove this
+formula. The details aren't that important; just know the theorem says that the
+formula for the distance between two points is equal to:
So that's what we're implementing here.
+f64::powi(2.0, 3)
+
+The double colon (::) here is a namespace operator. We haven’t talked about
+modules and namespaces in depth yet, but you can think of the powi() function
+as being scoped inside of another name. In this case, the name is f64, the
+same as the type. The powi() function takes two arguments: the first is a
+number, and the second is the power that it raises that number to. In this
+case, the second number is an integer, hence the ‘i’ in its name. Similarly,
+sqrt() is a function under the f64 module, which takes the square root of
+its argument.
structs?Our little program is okay, but we can do better. The key to seeing this is in
+the signature of distance():
fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
+
+The distance function is supposed to calculate the distance between two points.
+But our distance function calculates some distance between four numbers. The
+first two and last two arguments are related, but that’s not expressed anywhere
+in our program itself. It would be nicer if we had a way to group (x1, y1)
+and (x2, y2) together.
We’ve already discussed one way to do that: tuples. Here’s a version of our +program which uses tuples:
+fn main() {
+ let p1 = (0.0, 5.0);
+
+ let p2 = (12.0, 0.0);
+
+ let answer = distance(p1, p2);
+
+ println!("Point 1: {:?}", p1);
+ println!("Point 2: {:?}", p2);
+ println!("Distance: {}", answer);
+}
+
+fn distance(p1: (f64, f64), p2: (f64, f64)) -> f64 {
+ let x_squared = f64::powi(p2.0 - p1.0, 2);
+ let y_squared = f64::powi(p2.1 - p1.1, 2);
+
+ f64::sqrt(x_squared + y_squared)
+}
+
+This is a little better, for sure. Tuples let us add a little bit of structure. +We’re now passing two arguments, so that’s more clear. But it’s also worse: +tuples don’t give names to their elements, so our calculation has gotten more +confusing:
+p2.0 - p1.0
+p2.1 - p1.1
+
+When writing this example, your authors almost got it wrong themselves! Distance
+is all about x and y points, but our code is talking about 0 and 1.
+This isn’t great.
Enter structs. We can transform our tuples into something with a name for the
+whole as well as names for the parts:
let p1 = (0.0, 5.0);
+
+struct Point {
+ x: f64,
+ y: f64,
+}
+
+let p1 = Point { x: 0.0, y: 5.0 };
+
+Here we've defined a struct and given it the name Point. The parts inside
+{} are defining the fields of the struct. We can have as many or as few of
+them as we'd like, and we give them a name and specify their type. Here we have
+two fields named x and y, and they both hold f64s.
We can access the field of a struct in the same way we access an element of +a tuple, except we use its name:
+let p1 = (0.0, 5.0);
+let x = p1.0;
+
+struct Point {
+ x: f64,
+ y: f64,
+}
+
+let p1 = Point { x: 0.0, y: 5.0 };
+let x = p1.x;
+
+Let’s convert our program to use our Point struct. Here’s what it looks
+like now:
#[derive(Debug,Copy,Clone)]
+struct Point {
+ x: f64,
+ y: f64,
+}
+
+fn main() {
+ let p1 = Point { x: 0.0, y: 5.0};
+
+ let p2 = Point { x: 12.0, y: 0.0};
+
+ let answer = distance(p1, p2);
+
+ println!("Point 1: {:?}", p1);
+ println!("Point 2: {:?}", p2);
+ println!("Distance: {}", answer);
+}
+
+fn distance(p1: Point, p2: Point) -> f64 {
+ let x_squared = f64::powi(p2.x - p1.x, 2);
+ let y_squared = f64::powi(p2.y - p1.y, 2);
+
+ f64::sqrt(x_squared + y_squared)
+}
+
+Our function signature for distance() now says exactly what we mean: it
+calculates the distance between two Points. And rather than 0 and 1,
+we’ve got back our x and y. This is a win for clarity.
There’s one other thing that’s a bit strange here, this stuff above the
+struct declaration:
#[derive(Debug,Copy,Clone)]
+struct Point {
+
+This is an annotation that tells the compiler our struct should get some
+default behavior for the Debug, Copy, and Clone traits. We talked about
+marking that types can be Copy and Clone-able in Chapter XX when we
+discussed ownership. Debug is the trait that enables us to print out our
+struct so that we can see its value while we are debugging our code.
So far, we’ve been printing values using {} in a println! macro. If we try
+that with a struct, however, by default, we'll get an error. Say we have the
+following program:
struct Point {
+ x: f64,
+ y: f64,
+}
+
+fn main() {
+ let p1 = Point { x: 0.0, y: 5.0};
+ println!("Point 1: {}", p1);
+}
+
+This code tries to print the p1 point directly, which may seem innocuous. But
+running it produces the following output:
$ cargo run
+ Compiling points v0.1.0 (file:///projects/points)
+error: the trait bound `Point: std::fmt::Display` is not satisfied [--explain E0277]
+ --> src/main.rs:8:29
+8 |> println!("Point 1: {}", p1);
+ |> ^^
+<std macros>:2:27: 2:58: note: in this expansion of format_args!
+<std macros>:3:1: 3:54: note: in this expansion of print! (defined in <std macros>)
+src/main.rs:8:5: 8:33: note: in this expansion of println! (defined in <std macros>)
+note: `Point` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string
+note: required by `std::fmt::Display::fmt`
+
+Whew! The core of the error is this part: the trait bound Point: std::fmt::Display is not satisfied. println! can do many kinds of
+formatting. By default, {} implements a kind of formatting known as
+Display: output intended for direct end-user consumption. The primitive types
+we’ve seen implement Display, as there’s only one way you’d show a 1 to a
+user. But with structs, the output is less clear. Do you want commas or not?
+What about the {}s? Should all the fields be shown?
More complex types in the standard library and that are defined by the
+programmer do not automatically implement Display formatting. Standard
+library types implement Debug formatting, which is intended for the
+programmer to see. The #[derive(Debug)] annotation lets us use a default
+implementation of Debug formatting to easily get this ability for types we've
+defined. To ask println! to use Debug formatting with our Point, we add
+the annotation to derive the trait and include :? in the print string, like
+this:
#[derive(Debug)]
+struct Point {
+ x: f64,
+ y: f64,
+}
+
+fn main() {
+ let p1 = Point { x: 0.0, y: 5.0};
+ println!("Point 1: {:?}", p1);
+}
+
+If you run this, it should print the values of each field in the Point struct
+as desired:
$ cargo run
+ Compiling points v0.1.0 (file:///projects/points)
+ Running `target/debug/points`
+Point 1: Point { x: 0, y: 5 }
+
+You’ll see this repeated later with other types. We’ll cover traits fully in +Chapter XX.
+ +In the last section on ownership, we made several references to ‘methods’. +Methods look like this:
+let s1 = "hello";
+
+// call a method on s1
+let s2 = s1.clone();
+
+println!("{}", s1);
+
+The call to clone() is attached to s1 with a dot. This is called ‘method
+syntax’, and it’s a way to call certain functions with a different style.
Why have two ways to call functions? We’ll talk about some deeper reasons +related to ownership in a moment, but one big reason is that methods look nicer +when chained together:
+// with functions
+h(g(f(x)));
+
+// with methods
+x.f().g().h();
+
+The nested-functions version reads in reverse: the program executes f(), then
+g(), then h(), but we read it left-to-right as h(), then g(), then
+f(). The method syntax is executed in the same order as we would read it.
Before we get into the details, let’s talk about how to define your own +methods.
+We can define methods with the impl keyword. impl is short for
+‘implementation’. Doing so looks like this:
#[derive(Debug,Copy,Clone)]
+struct Point {
+ x: f64,
+ y: f64,
+}
+
+impl Point {
+ fn distance(&self, other: &Point) -> f64 {
+ let x_squared = f64::powi(other.x - self.x, 2);
+ let y_squared = f64::powi(other.y - self.y, 2);
+
+ f64::sqrt(x_squared + y_squared)
+ }
+}
+
+let p1 = Point { x: 0.0, y: 0.0 };
+let p2 = Point { x: 5.0, y: 6.5 };
+
+assert_eq!(8.200609733428363, p1.distance(&p2));
+
+Let’s break this down. First, we have our Point struct from earlier in the
+chapter. Next comes our first use of the impl keyword:
impl Point {
+ // ...
+}
+
+Everything we put inside of the curly braces will be methods implemented on
+Point. Next is our definition:
fn distance(&self, other: &Point) -> f64 {
+ // ...
+}
+
+Other than this, the rest of the example is familiar: an implementation of
+distance() and using the method to find an answer.
Our definition of distance() here as a method looks very similar to our
+previous definition of distance() as a function, but with two differences.
+Here's the distance() function again:
fn distance(p1: Point, p2: Point) -> f64 {
+ // ...
+}
+
+The first difference is in the first argument. Instead of a name and a type, we
+have written &self. This is what distinguishes a method from a function:
+using self inside of an impl block means we have a method. Because we
+already know that we are implementing this method on Point because of the
+surrounding impl Point block, we don’t need to write the type of self out.
Note that we have written &self, not just self. This is because we want to
+take a reference to our argument's value rather than taking ownership of it. In
+other words, these two forms are the same:
fn foo(self: &Point)
+fn foo(&self)
+
+Just like any other parameter, you can take self in three forms. Here’s the
+list, with the most common form first:
fn foo(&self) // take self by reference
+fn foo(&mut self) // take self by mutable reference
+fn foo(self) // take self by ownership
+
+In this case, we only need a reference. We don’t need to mutate either Point
+to get the distance between them, so we won't take a mutable reference to the
+Point that we call the method on. Methods that take ownership of self are
+rarely used. An example of a time to do that would be if we wanted to have a
+method that would transform self into something else and prevent other code
+from using the value of self after the transformation happens.
We’ve left out an important detail. It’s in this line of the example:
+assert_eq!(8.200609733428363, p1.distance(&p2));
+
+When we defined distance(), we took both self and the other argument by
+reference. Yet, we needed a & for p2 but not p1. What gives?
This feature is called ‘automatic referencing’, and calling methods is one
+of the few places in Rust that has behavior like this. Here’s how it works:
+when you call a method with self.(, Rust will automatically add in &s
+or &muts to match the signature. In other words, these are the same:
# #[derive(Debug,Copy,Clone)]
+# struct Point {
+# x: f64,
+# y: f64,
+# }
+#
+# impl Point {
+# fn distance(&self, other: &Point) -> f64 {
+# let x_squared = f64::powi(other.x - self.x, 2);
+# let y_squared = f64::powi(other.y - self.y, 2);
+#
+# f64::sqrt(x_squared + y_squared)
+# }
+# }
+# let p1 = Point { x: 0.0, y: 0.0 };
+# let p2 = Point { x: 5.0, y: 6.5 };
+p1.distance(&p2);
+(&p1).distance(&p2);
+
+The first one looks much, much cleaner. Here’s another example:
+let mut s = String::from("Hello,");
+
+s.push_str(" world!");
+
+// The above is the same as:
+// (&mut s).push_str(" world!");
+
+assert_eq!("Hello, world!", s);
+
+Because push_str() has the following signature:
fn push_str(&mut self, string: &str) {
+
+This automatic referencing behavior works because methods have a clear receiver
+— the type of self — and in most cases it’s clear given the receiver and name
+of a method whether the method is just reading (so needs &self), mutating (so
+&mut self), or consuming (so self). The fact that Rust makes borrowing
+implicit for method receivers is a big part of making ownership ergonomic in
+practice.
So far, all of the data types we’ve seen allow us to have a single value
-at a time. structs give us the ability to package up multiple values and
-keep them in one related structure.
Let’s write a program which calculates the distance between two points.
-We’ll start off with single variable bindings, and then refactor it to
-use structs instead.
Let’s make a new project with Cargo:
-$ cargo new --bin points
-$ cd points
-
-Here’s a short program which calculates the distance between two points. Put
-it into your src/main.rs:
fn main() {
- let x1 = 0.0;
- let y1 = 5.0;
-
- let x2 = 12.0;
- let y2 = 0.0;
-
- let answer = distance(x1, y1, x2, y2);
-
- println!("Point 1: ({}, {})", x1, y1);
- println!("Point 2: ({}, {})", x2, y2);
- println!("Distance: {}", answer);
-}
-
-fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
- let x_squared = f64::powi(x2 - x1, 2);
- let y_squared = f64::powi(y2 - y1, 2);
-
- f64::sqrt(x_squared + y_squared)
-}
-
-Let's try running this program with cargo run:
$ cargo run
- Compiling points v0.1.0 (file:///projects/points)
- Running `target/debug/points`
-Point 1: (0, 5)
-Point 2: (12, 0)
-Distance: 13
-
-Let's take a quick look at distance() before we move forward:
fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
- let x_squared = f64::powi(x2 - x1, 2);
- let y_squared = f64::powi(y2 - y1, 2);
-
- f64::sqrt(x_squared + y_squared)
-}
-
-To find the distance between two points, we can use the Pythagorean Theorem. -The theorem is named after Pythagoras, who was the first person to mathematically -prove this formula. The details aren't that important, to be honest. There's a few -things that we haven't discussed yet, though.
-f64::powi(2.0, 3)
-
-The double colon (::) here is a namespace operator. We haven’t talked about
-modules yet, but you can think of the powi() function as being scoped inside
-of another name. In this case, the name is f64, the same as the type. The
-powi() function takes two arguments: the first is a number, and the second is
-the power that it raises that number to. In this case, the second number is an
-integer, hence the ‘i’ in its name. Similarly, sqrt() is a function under the
-f64 module, which takes the square root of its argument.
structs?Our little program is okay, but we can do better. The key is in the signature
-of distance():
fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
-
-The distance function is supposed to calculate the distance between two points.
-But our distance function calculates some distance between four numbers. The
-first two and last two arguments are related, but that’s not expressed anywhere
-in our program itself. We need a way to group (x1, y1) and (x2, y2)
-together.
We’ve already discussed one way to do that: tuples. Here’s a version of our program -which uses tuples:
-fn main() {
- let p1 = (0.0, 5.0);
-
- let p2 = (12.0, 0.0);
-
- let answer = distance(p1, p2);
-
- println!("Point 1: {:?}", p1);
- println!("Point 2: {:?}", p2);
- println!("Distance: {}", answer);
-}
-
-fn distance(p1: (f64, f64), p2: (f64, f64)) -> f64 {
- let x_squared = f64::powi(p2.0 - p1.0, 2);
- let y_squared = f64::powi(p2.1 - p1.1, 2);
-
- f64::sqrt(x_squared + y_squared)
-}
-
-This is a little better, for sure. Tuples let us add a little bit of structure. -We’re now passing two arguments, so that’s more clear. But it’s also worse. -Tuples don’t give names to their elements, and so our calculation has gotten -much more confusing:
-p2.0 - p1.0
-p2.1 - p1.1
-
-When writing this example, your authors almost got it wrong themselves! Distance
-is all about x and y points, but now it’s all about 0 and 1. This isn’t
-great.
Enter structs. We can transform our tuples into something with a name:
let p1 = (0.0, 5.0);
-
-struct Point {
- x: f64,
- y: f64,
-}
-
-let p1 = Point { x: 0.0, y: 5.0 };
-
-Here’s what declaring a struct looks like:
struct NAME {
- NAME: TYPE,
-}
-
-The NAME: TYPE bit is called a ‘field’, and we can have as many or as few of
-them as you’d like. If you have none of them, drop the {}s:
struct Foo;
-
-structs with no fields are called ‘unit structs’, and are used in certain
-advanced situations. We will just ignore them for now.
You can access the field of a struct in the same way you access an element of -a tuple, except you use its name:
-let p1 = (0.0, 5.0);
-let x = p1.0;
-
-struct Point {
- x: f64,
- y: f64,
-}
-
-let p1 = Point { x: 0.0, y: 5.0 };
-let x = p1.x;
-
-Let’s convert our program to use our Point struct. Here’s what it looks
-like now:
#[derive(Debug,Copy,Clone)]
-struct Point {
- x: f64,
- y: f64,
-}
-
-fn main() {
- let p1 = Point { x: 0.0, y: 5.0};
-
- let p2 = Point { x: 12.0, y: 0.0};
-
- let answer = distance(p1, p2);
-
- println!("Point 1: {:?}", p1);
- println!("Point 2: {:?}", p2);
- println!("Distance: {}", answer);
-}
-
-fn distance(p1: Point, p2: Point) -> f64 {
- let x_squared = f64::powi(p2.x - p1.x, 2);
- let y_squared = f64::powi(p2.y - p1.y, 2);
-
- f64::sqrt(x_squared + y_squared)
-}
-
-Our function signature for distance() now says exactly what we mean: it
-calculates the distance between two Points. And rather than 0 and 1,
-we’ve got back our x and y. This is a win for clarity.
There’s one other thing that’s a bit strange here, this annotation on our
-struct declaration:
#[derive(Debug,Copy,Clone)]
-struct Point {
-
-We haven’t yet talked about traits, but we did talk about Debug when we
-discussed arrays. This derive attribute allows us to tweak the behavior of
-our Point. In this case, we are opting into copy semantics, and everything
-that implements Copy must implement Clone.
In the last section on ownership, we made several references to ‘methods’. -Methods look like this:
-let s1 = String::from("hello");
-
-// call a method on our String
-let s2 = s1.clone();
-
-println!("{}", s1);
-
-The call to clone() is attached to s1 with a dot. This is called ‘method
-syntax’, and it’s a way to call certain functions with a different style.
Why have two ways to call functions? We’ll talk about some deeper reasons -related to ownership in a moment, but one big reason is that methods look nicer -when chained together:
-// with functions
-h(g(f(x)));
-
-// with methods
-x.f().g().h();
-
-The nested-functions version reads in reverse: we call f(), then g(), then
-h(), but it reads as h(), then g(), then f().
Before we get into the details, let’s talk about how to define your own -methods.
-We can define methods with the impl keyword. impl is short for
-‘implementation’. Doing so looks like this:
#[derive(Debug,Copy,Clone)]
-struct Point {
- x: f64,
- y: f64,
-}
-
-impl Point {
- fn distance(&self, other: &Point) -> f64 {
- let x_squared = f64::powi(other.x - self.x, 2);
- let y_squared = f64::powi(other.y - self.y, 2);
-
- f64::sqrt(x_squared + y_squared)
- }
-}
-
-let p1 = Point { x: 0.0, y: 0.0 };
-let p2 = Point { x: 5.0, y: 6.5 };
-
-assert_eq!(8.200609733428363, p1.distance(&p2));
-
-Let’s break this down. First, we have our Point struct from earlier in the
-chapter. Next comes our first use of the impl keyword:
# #[derive(Debug,Copy,Clone)]
-# struct Point {
-# x: f64,
-# y: f64,
-# }
-#
-impl Point {
-# fn distance(&self, other: &Point) -> f64 {
-# let x_squared = f64::powi(other.x - self.x, 2);
-# let y_squared = f64::powi(other.y - self.y, 2);
-#
-# f64::sqrt(x_squared + y_squared)
-# }
-}
-#
-# let p1 = Point { x: 0.0, y: 0.0 };
-# let p2 = Point { x: 5.0, y: 6.5 };
-#
-# assert_eq!(8.200609733428363, p1.distance(&p2));
-
-Everything we put inside of the curly braces will be methods implemented on
-Point.
# #[derive(Debug,Copy,Clone)]
-# struct Point {
-# x: f64,
-# y: f64,
-# }
-#
-# impl Point {
- fn distance(&self, other: &Point) -> f64 {
-# let x_squared = f64::powi(other.x - self.x, 2);
-# let y_squared = f64::powi(other.y - self.y, 2);
-#
-# f64::sqrt(x_squared + y_squared)
- }
-# }
-#
-# let p1 = Point { x: 0.0, y: 0.0 };
-# let p2 = Point { x: 5.0, y: 6.5 };
-#
-# assert_eq!(8.200609733428363, p1.distance(&p2));
-
-Next is our definition. This looks very similar to our previous definition of
-distance() as a function:
# #[derive(Debug,Copy,Clone)]
-# struct Point {
-# x: f64,
-# y: f64,
-# }
-fn distance(p1: Point, p2: Point) -> f64 {
-# let x_squared = f64::powi(p2.x - p1.x, 2);
-# let y_squared = f64::powi(p2.y - p1.y, 2);
-#
-# f64::sqrt(x_squared + y_squared)
-# }
-
-Other than this, the rest of the example is familiar: an implementation of
-distance(), and using the method to find an answer.
There are two differences. The first is in the first argument. Instead of a name
-and a type, we have written &self. This is what distinguishes a method from a
-function: using self inside of an impl block. Because we already know that
-we are implementing this method on Point, we don’t need to write the type of
-self out. However, we have written &self, not only self. This is because
-we want to take our argument by reference rather than by ownership. In other
-words, these two forms are the same:
fn foo(self: &Point)
-fn foo(&self)
-
-Just like any other parameter, you can take self in three forms. Here’s the
-list, with the most common form first:
fn foo(&self) // take self by reference
-fn foo(&mut self) // take self by mutable reference
-fn foo(self) // take self by ownership
-
-In this case, we only need a reference. We don’t plan on taking ownership, and -we don’t need to mutate either point. Taking by reference is by far the most -common form of method, followed by a mutable reference, and then occasionally -by ownership.
-We’ve left out an important detail. It’s in this line of the example:
-# #[derive(Debug,Copy,Clone)]
-# struct Point {
-# x: f64,
-# y: f64,
-# }
-#
-# impl Point {
-# fn distance(&self, other: &Point) -> f64 {
-# let x_squared = f64::powi(other.x - self.x, 2);
-# let y_squared = f64::powi(other.y - self.y, 2);
-#
-# f64::sqrt(x_squared + y_squared)
-# }
-# }
-#
-# let p1 = Point { x: 0.0, y: 0.0 };
-# let p2 = Point { x: 5.0, y: 6.5 };
-#
-assert_eq!(8.200609733428363, p1.distance(&p2));
-
-When we defined distance(), we took both self and the other argument by
-reference. Yet, we needed a & for p2 but not p1. What gives?
This feature is called ‘automatic referencing’, and calling methods is one
-of the few places in Rust that has behavior like this. Here’s how it works:
-when you call a method with self.(, Rust will automatically add in &s
-or &muts to match the signature. In other words, these are the same:
# #[derive(Debug,Copy,Clone)]
-# struct Point {
-# x: f64,
-# y: f64,
-# }
-#
-# impl Point {
-# fn distance(&self, other: &Point) -> f64 {
-# let x_squared = f64::powi(other.x - self.x, 2);
-# let y_squared = f64::powi(other.y - self.y, 2);
-#
-# f64::sqrt(x_squared + y_squared)
-# }
-# }
-# let p1 = Point { x: 0.0, y: 0.0 };
-# let p2 = Point { x: 5.0, y: 6.5 };
-p1.distance(&p2);
-(&p1).distance(&p2);
-
-The first one looks much, much cleaner. Here’s another example:
-let mut s = String::from("Hello,");
-
-s.push_str(" world!");
-
-// The above is the same as:
-// (&mut s).push_str(" world!");
-
-assert_eq!("Hello, world!", s);
-
-Because push_str() has the following signature:
fn push_str(&mut self, string: &str) {
-
-This automatic referencing behavior works because methods have a clear receiver
-— the type of self — and in most cases it’s clear given the receiver and name
-of a method whether the method is just reading (so needs &self), mutating (so
-&mut self), or consuming (so self). The fact that Rust makes borrowing
-implicit for method receivers is a big part of making ownership ergonomic in
-practice.
Furthermore, if we have a method, we can also call it like a function:
-# #[derive(Debug,Copy,Clone)]
-# struct Point {
-# x: f64,
-# y: f64,
-# }
-#
-# impl Point {
-# fn distance(&self, other: &Point) -> f64 {
-# let x_squared = f64::powi(other.x - self.x, 2);
-# let y_squared = f64::powi(other.y - self.y, 2);
-#
-# f64::sqrt(x_squared + y_squared)
-# }
-# }
-# let p1 = Point { x: 0.0, y: 0.0 };
-# let p2 = Point { x: 5.0, y: 6.5 };
-let d1 = p1.distance(&p2);
-let d2 = Point::distance(&p1, &p2);
-
-assert_eq!(d1, d2);
-
-Instead of using self.(, we use Point and the namespace operator to call it
-like a function instead. Because functions do not do the automatic referencing,
-we must pass in &p1 explicitly.
While methods can be called like functions, functions cannot be called like
-methods. If the first argument isn’t named self, it cannot be called like a
-method.
Next, let’s look at a feature of Rust that’s similar to structs, but also -different. Enumerations, or ‘enums’ as they’re more commonly referred to, -are an extremely powerful feature of Rust. Enums are a feature that are in many -languages, but what they can do is different per-language. Rust’s enums are -most similar to enums in functional languages.
-Here’s an example of an enum:
+Next, let’s look at enumerations, which allow you to define a type by +enumerating its possible values. Commonly called "enums", these unlock a lot of +power in Rust when combined with pattern matching. Enums are a feature that are +in many languages, but what they can do is different per-language. Rust’s enums +are most similar to "algebraic data types" in functional languages like F#, +OCaml, or Haskell.
+Here’s an example of an enum definition:
enum IpAddrKind {
V4,
V6,
}
This enum represents the kind of an IP address. There are two major standards -used for IP addresses: version four, and version six. Any IP address can be either -a version four address, or a version six address. But it cannot be both kinds at -the same time. This is where enums get their name: they allow us to enumerate all -of the possible kinds that our value can have.
+used for IP addresses: version four and version six. Any IP address can be +either a version four address or a version six address, but it cannot be both +kinds at the same time. This is where enums get their name: they allow us to +enumerate all of the possible kinds that our value can have.We can create values of IpAddrKind like this:
# enum IpAddrKind {
# V4,
# V6,
# }
-
+#
let four = IpAddrKind::V4;
let six = IpAddrKind::V6;
Note that the variants of the enum are namespaced under its name, and we use the double colon to separate the two.
Enums have more tricks up their sleeves, however. Thinking more about our IP -address type, we don’t have a way to store the actual data of the IP address, +address type, we don’t have a way to store the actual data of the IP address; we only know what kind it is. Given that you just learned about structs, you might tackle this problem like this:
enum IpAddrKind {
@@ -120,8 +121,8 @@ let loopback = IpAddr {
};
We’ve used a struct to bundle the two values together: now we keep the kind -with the value itself. This design isn’t bad, exactly, but it wouldn’t be -considered idiomatic Rust. We can represent the same thing with just an enum:
+with the value itself. We can represent the same thing in a different way with +just an enum:enum IpAddr {
V4(String),
V6(String),
@@ -135,10 +136,10 @@ let loopback = IpAddr::V6(String::from("::1"));
struct. But beyond that, this approach is better than using a struct alongside
our enum because we can attach different kinds of data to each variant.
Imagine that instead of a String, we would prefer to store a V4 as its four
-individual components, while leaving the V6 variant as a String. With our
+individual components while leaving the V6 variant as a String. With our
struct, we’d be stuck. But enums deal with this case with ease:
enum IpAddr {
- V4(u32, u32, u32, u32),
+ V4(u8, u8, u8, u8),
V6(String),
}
@@ -147,8 +148,8 @@ let home = IpAddr::V4(127, 0, 0, 1);
let loopback = IpAddr::V6(String::from("::1"));
You can put any kind of data inside of an enum variant, including another enum!
-The IpAddr enum is in the standard library, but it embeds two different
-structs inside of its variants:
+The IpAddr enum is in the standard library, but it embeds two
+different structs inside of its variants:
struct Ipv4Addr {
// details elided
}
@@ -176,21 +177,33 @@ enum IpAddr {
Write includes a single String.
ChangeColor includes three i32s.
-We haven’t talked a lot about how to access the data inside an enum variant,
-however. To do that, let’s move on to some new Rust syntax that’s especially
-useful with enums: match.
+This might seem overwhelming, but another way to look at the different enum
+possibilities is that they are just like different kinds of struct definitions
+that you already know, except without the struct keyword and they are grouped
+together under the Message type. These structs could hold the same data that
+these enum variants hold:
+struct QuitMessage; // unit struct
+struct MoveMessage {
+ x: i32,
+ y: i32,
+}
+struct WriteMessage(String); // tuple struct
+struct ChangeColorMessage(i32, i32, i32); // tuple struct
+
+Let's look at another enum in the standard library that is very common and
+useful: Option.
match.
Now that we have a handle on enums, let's combine them with a feature that we -talked a little bit about in the previous chapter: generics.
-Programming language design is often though of as which features you include, +
Now that we have had an introduction to enums, let's combine them with a +feature that we talked a little bit about in the previous chapter: generics.
+Programming language design is often thought of as which features you include, but it's also about which features you leave out. Rust does not have a feature that is in many other languages: 'null'. In languages with this feature, variables can have two states: null or not-null.
@@ -96,14 +96,14 @@ pervasive, it's extremely easy to make this kind of error. useful one: this is a value which is currently invalid or not present for some reason. The problem isn't with the concept itself, but with the particular implementation. As such, Rust does not have the concept of null, but we do have -a type which can encode the concept of a value being present. We call this type -Option<T>, and it looks like this:
+an enum which can encode the concept of a value being present or not present. We
+call this enum Option<T>, and it looks like this:
enum Option<T> {
Some(T),
None,
}
-This type is provided by the standard library, and is so useful that +
This enum is provided by the standard library, and is so useful that
it's even in the prelude; you don't need to import it explicitly. Furthermore,
so are its variants: you can say Some and None directly, without prefixing
them with Option::.
None means 'null', and Some means 'not null'. S
better than null?
In short, because Option<T> and T are different types. That's a bit too
short though. Here's an example:
let x = 5;
-let y = Some(5);
+let x: i8 = 5;
+let y: Option<i8> = Some(5);
let sum = x + y;
This will not compile. We get an error message like this:
-error: the trait `core::ops::Add<core::option::Option<_>>` is not implemented
-for the type `_` [E0277]
+error: the trait bound `i8: std::ops::Add<std::option::Option<i8>>` is not
+satisfied [E0277]
let sum = x + y;
^~~~~
Intense! What this error message is trying to say is that Rust does not
understand how to add an Option<T> and a T. They're different types! This
-shows one of the big advantages of an Option<T> type: if you have a type that
+shows one of the big advantages of an Option<T>: if you have a value that
may or may not exist, you have to deal with that fact before you can assume it
exists. In other words, you have to convert an Option<T> to a T before you
can do T stuff with it. This helps catch one of the most common issues with
-null, generally: assuming that something isn't null, when it actually is.
-So, how do you get a T from an Option<T>? The option type has a large
-number of methods that you can check out in its documentation, and becoming
-familiar with them will be extremely useful in your journey with Rust.
+null, generally: assuming that something isn't null when it actually is.
+This is pretty powerful: in order to have a value that can possibly be null,
+you have to explicitly opt in by making the type of that value an Option<T>.
+Then, when you use that value, you are required to explicitly handle the case
+when the value is null. Everywhere that a value has a type that isn't an
+Option<T>, you can safely assume that the value isn't null. This was a
+deliberate design decision for Rust to limit null's pervasiveness and increase
+the safety of Rust code.
+So, how do you get a T from an Option<T>? The Option<T> enum has a
+large number of methods that you can check out in its documentation, and
+becoming familiar with them will be extremely useful in your journey with Rust.
But we want a deeper understanding than that. If we didn't have those methods
-defined for us already, what would we do? For that, we need a new feature: match.
+defined for us already, what would we do? And more generally, how do we get
+the inner values out of any enum variant? We need a new feature: match.
-
+
-
+
diff --git a/ch06-02-match.html b/ch06-02-match.html
new file mode 100644
index 000000000..708b1a58e
--- /dev/null
+++ b/ch06-02-match.html
@@ -0,0 +1,331 @@
+
+
+
+
+ The Rust Programming Language
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Match
+Rust has an extremely powerful control-flow operator: match. It allows us to
+compare a value against a series of patterns and then execute code based on
+how they compare.
+Think of a match expression kind of like a coin sorting machine. Coins slide
+down a track that has variously sized holes along it, and each coin falls
+through the first hole it encounters that it fits into. In the same way, values
+go through each pattern in a match, and for the first pattern that the value
+"fits", the value will fall into the associated code block to be used during
+execution.
+Since we're already talking about coins, let's use them for an example using
+match! We can write a function that can take an unknown American coin and, in
+a similar way as the coin counting machine, determine which coin it is and
+return its value in cents:
+enum Coin {
+ Penny,
+ Nickel,
+ Dime,
+ Quarter,
+}
+
+fn value_in_cents(coin: Coin) -> i32 {
+ match coin {
+ Coin::Penny => 1,
+ Coin::Nickel => 5,
+ Coin::Dime => 10,
+ Coin::Quarter => 25,
+ }
+}
+
+Let's break down the match! At a high-level, using match looks like this:
+match expression {
+ pattern => code,
+}
+
+First, we have the match keyword. Next, we have an expression. This feels
+very similar to an expression used with if, but there's a big difference:
+with if, the condition needs to return a boolean value. Here, it can be any
+type.
+Next, we have a "match arm". That's the part that looks like pattern => code,. We can have as many arms as we need to: our match above has four
+arms. An arm has two parts: a pattern and some code. When the match
+expression executes, it compares the resulting value against the pattern of
+each arm, in order. If a pattern matches the value, the code associated
+with that pattern is executed. If that pattern doesn't match the value,
+execution continues to the next arm, much like a coin sorting machine.
+The code associated with each arm is an expression, and the resulting value of
+the code with the matching arm that gets executed is the value that gets
+returned for the entire match expression.
+Curly braces typically aren't used if the match arm code is short, as it is in
+the above example where each arm just returns a value. If we wanted to run
+multiple lines of code in a match arm, we can use curly braces. This code would
+print out "Lucky penny!" every time the method was called with a Coin::Penny,
+but would still return the last value of the block, 1:
+# enum Coin {
+# Penny,
+# Nickel,
+# Dime,
+# Quarter,
+# }
+#
+fn value_in_cents(coin: Coin) -> i32 {
+ match coin {
+ Coin::Penny => {
+ println!("Lucky penny!");
+ 1
+ },
+ Coin::Nickel => 5,
+ Coin::Dime => 10,
+ Coin::Quarter => 25,
+ }
+}
+
+Another useful feature of match arms is that they can create bindings to parts
+of the values that match the pattern. From 1999 through 2008, the U.S. printed
+quarters with different designs for each of the 50 states on one side. The other
+coins did not get state designs, so only quarters have this extra attribute. We
+can add this information to our enum by changing the Quarter variant to have
+a State value:
+enum UsState {
+ Alabama,
+ Alaska,
+ // ... etc
+}
+
+enum Coin {
+ Penny,
+ Nickel,
+ Dime,
+ Quarter(UsState),
+}
+
+Let's imagine that a friend of ours is trying to collect all 50 state quarters.
+While we sort our loose change by coin type in order to count it, we're going
+to call out the name of the state so that if it's one our friend doesn't have
+yet, they can add it to their collection.
+In the match statement to do this, the quarter case now has a binding, state,
+that contains the value of the state of that quarter. The binding will only get
+created if the coin matches the Quarter pattern. Then we can use the binding
+in the code for that arm:
+# #[derive(Debug)]
+# enum UsState {
+# Alabama,
+# Alaska,
+# }
+#
+# enum Coin {
+# Penny,
+# Nickel,
+# Dime,
+# Quarter(UsState),
+# }
+#
+fn value_in_cents(coin: Coin) -> i32 {
+ match coin {
+ Coin::Penny => 1,
+ Coin::Nickel => 5,
+ Coin::Dime => 10,
+ Coin::Quarter(state) => {
+ println!("State quarter from {:?}!", state);
+ 25
+ },
+ }
+}
+
+If we were to call value_in_cents(Coin::Quarter(UsState::Alaska)), coin will
+be Coin::Quarter(UsState::Alaska). When we compare that value with each of the
+match arms, none of them match until we reach Coin::Quarter(state). At that
+point, the binding for state will be the value UsState::Alaska. We can then
+use that binding in the println!, thus getting the inner state value out of
+the Coin enum variant for Quarter.
+Remember the Option<T> type from the previous section, and that we wanted to
+be able to get the inner T value out of the Some case? This will be very
+similar! Instead of coins, we will be comparing to other patterns, but the way
+that the match expression works remains the same as a coin sorting machine in
+the way that we look for the first pattern that fits the value.
+Let's say that we want to write a function that takes an Option<i32>, and
+if there's a value inside, add one to it. If there isn't a value inside, we
+want to return the None value and not attempt to add.
+This function is very easy to write, thanks to match. It looks like this:
+fn plus_one(x: Option<i32>) -> Option<i32> {
+ match x {
+ None => None,
+ Some(i) => Some(i + 1),
+ }
+}
+
+let five = Some(5);
+let six = plus_one(five);
+let none = plus_one(None);
+
+Let's examine the first execution of plus_one() in more detail. In the above
+example, x will be Some(5). Let's compare that against each arm:
+None => None,
+
+Does Some(5) match None? No, it's the wrong variant. So let's continue.
+Some(i) => Some(i + 1),
+
+Does Some(5) match Some(i)? Why yes it does! We have the same variant. The
+i binds to the value inside of the Some, so i has the value 5. Then we
+execute the code in that match arm: take i, which is 5, add one to it, and
+create a new Some value with our total inside.
+Now let's consider the second call of plus_one(). In this case, x is
+None. We enter the match, and compare to the first arm:
+None => None,
+
+Does None match None? Yup! There's no value to add to. So we stop and
+return the None value that is on the right side of the =>. We don't
+check any other arms since we found one that matched.
+Combining match and enums together is extremely powerful. You'll see this
+pattern a lot in Rust code: match against an enum, bind to the data
+inside, and then execute code based on it. It's a bit tricky at first, but
+once you get used to it, you'll wish you had it in languages that don't support
+it. It's consistently a user favorite.
+Matches are exhaustive
+There's one other aspect of match we didn't talk about. Consider this version
+of plus_one():
+fn plus_one(x: Option<i32>) -> Option<i32> {
+ match x {
+ Some(i) => Some(i + 1),
+ }
+}
+
+A bug! We didn't handle the None case. Luckily, it's a bug Rust knows how to
+catch. If we try to compile this code, we'll get an error:
+error: non-exhaustive patterns: `None` not covered [E0004]
+match x {
+ Some(i) => Some(i + 1),
+}
+
+Rust knows that we did not cover every possible option, and even knows which
+pattern we forgot! This is referred to as being "exhaustive": we must exhaust
+every last option possible in order to be valid. Especially in the case of
+Option<T>, when Rust prevents us from forgetting to explicitly handle the
+None case, it protects us from assuming that we have a value when we might
+have null and thus making the billion-dollar mistake we discussed in the
+previous section.
+The _ placeholder
+What if we don't care about all of the possible values, though? Especially when
+there are a lot of possible values for a type: a u8 can have valid values of
+zero through 255-- if we only care about 1, 3, 5, and 7, does this mean we must
+list out 0, 2, 4, 6, 8, 9, all the way up through 255? Thankfully, no! We can
+use a special pattern, _:
+let some_u8_value = 0u8;
+match some_u8_value {
+ 1 => println!("one"),
+ 3 => println!("three"),
+ 5 => println!("five"),
+ 7 => println!("seven"),
+ _ => (),
+}
+
+The _ pattern will match all the other cases, and () will do nothing, it's
+the unit value. This way, we don't have to list individual match arms for all
+the other possible values in order to say that we want to do nothing for all of
+those-- the _ is a placeholder for any value.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/ch06-04-if-let.html b/ch06-03-if-let.html
similarity index 52%
rename from ch06-04-if-let.html
rename to ch06-03-if-let.html
index 1ed59906d..4432c4966 100644
--- a/ch06-04-if-let.html
+++ b/ch06-03-if-let.html
@@ -47,7 +47,7 @@
@@ -67,7 +67,7 @@
- if let
+ if let
There's one more advanced control flow structure we haven't discussed: if let. Imagine we're in a situation like this:
# let some_option = Some(5);
match some_option {
@@ -80,9 +80,9 @@ match some_option {
We care about the Some case, but don't want to do anything with the None
case. With an Option, this isn't too bad, but with a more complex enum,
adding _ => {} after processing just one variant doesn't feel great. We have
-this boilerplate arm, and we have an extra level of indentation: the code that
-does something with x is indented twice, rather than just once. We really want
-a construct that says "Do something with this one case, I don't care about the
+this boilerplate arm and an extra level of indentation (the code that
+does something with x is indented twice, rather than just once). We really want
+a construct that says "Do something with this one case; I don't care about the
others."
Enter if let:
# let some_option = Some(5);
@@ -117,13 +117,13 @@ match expression {
}
In other words, it's the high-level construct we were originally looking for:
-do something with a single pattern.
+do something special with only one pattern.
-
+
@@ -137,7 +137,7 @@ do something with a single pattern.
-
+
diff --git a/ch06-03-match.html b/ch06-03-match.html
deleted file mode 100644
index 79f233c8e..000000000
--- a/ch06-03-match.html
+++ /dev/null
@@ -1,254 +0,0 @@
-
-
-
-
- The Rust Programming Language
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Match
-Rust has an extremely powerful control-flow operator: match. It allows us to
-compare a value against a series of patterns, and then execute code based on
-how they compare. Remember the Option<T> type from the previous section?
-Let's say that we want to write a function that takes an Option<i32>, and
-if there's a value inside, add one to it.
-This function is very easy to write, thanks to match. It looks like this:
-fn plus_one(x: Option<i32>) -> Option<i32> {
- match x {
- None => None,
- Some(i) => Some(i + 1),
- }
-}
-
-let five = Some(5);
-let six = plus_one(five);
-let none = plus_one(None);
-
-Let's break down the match! At a high-level, the match expression looks
-like this:
-match condition {
- pattern => code,
-}
-
-First, we have the match keyword. Next, we have a condition. This feels very
-similar to an if expression, but there's a big difference: with if, the
-condition needs to be a boolean. Here, it can be any type.
-Next, we have a "match arm". That's the part that looks like pattern => code,. We can have as many arms as we need to: our match above has two
-arms. An arm has two parts: a pattern, and some code. When the match
-expression executes, it compares the condition against the pattern of each arm,
-in turn. If the pattern matches the condition, the associated code is executed,
-and the rest of the patterns are not checked. If it doesn't match, execution
-continues to the next arm.
-Let's examine the first execution of plus_one() in more detail. In the above
-example, x will be Some(5). Let's compare that against each arm:
-None => None,
-
-Does Some(5) match None? No, it's the wrong variant. So let's continue.
-Some(i) => Some(i + 1),
-
-Does Some(5) match Some(i)? Why yes it does! We have the same variant. But
-what about i? In a pattern like this, we can declare new bindings, similarly
-to what we did with let. So in this case, the code part of the match arm will
-have a binding, i, which corresponds to the 5.
-With this arm, the code portion is Some(i + 1). So we do exactly that: we
-take i, which is 5, add one to it, and create a new Some value with our
-sum inside.
-Because match is an expression, the value of the overall expression becomes
-the value of the arm that executed. So the value of this match expression
-will be Some(6). And since our match is the only expression in the
-function, the value of the match will be the value of the function, and so
-Some(6) is our return value as well, which is exactly what we were shooting
-for.
-Now let's consider the second call. In this case, x is None. We enter the
-match, and compare to the first arm:
-None => None,
-
-Does None match None? Yup! And so we return None. There's no value to add
-to.
-Combining match and enums together is extremely powerful. You'll see this
-pattern a lot in Rust code: match against an enum, binding to the data
-inside, and then executing code based on it. It's a bit tricky at first, but
-once you get used to it, you'll wish you had it in languages that don't support
-it. It's consistently a user favorite.
-Matches are exhaustive
-There's one other aspect of match we didn't talk about. Consider this version
-of plus_one():
-fn plus_one(x: Option<i32>) -> Option<i32> {
- match x {
- Some(i) => Some(i + 1),
- }
-}
-
-A bug! We didn't handle the None case. Luckily, it's a bug Rust knows how to catch.
-If we try to compile this code, we'll get an error:
-error: non-exhaustive patterns: `None` not covered [E0004]
-match x {
- Some(i) => Some(i + 1),
-}
-
-Rust knows that we did not cover every possible option, and even knows which
-pattern we forgot! This is referred to as being "exhaustive", we must exhaust
-every last option possible in order to be valid!
-This analysis isn't perfect, however. This will also error:
-# let some_u8_value = 0u8;
-match some_u8_value {
- 0 => println!("zero"),
- 1 => println!("one"),
- 2 => println!("two"),
- 3 => println!("three"),
- 4 => println!("four"),
- 5 => println!("five"),
- 6 => println!("six"),
- 7 => println!("seven"),
- // We won't write out all of the arms here, but imagine that there are more
- // arms corresponding to the rest of the numbers.
- 254 => println!("two-hundred and fifty-four"),
- 255 => println!("two-hundred and fifty-five"),
-}
-
-Even though a u8 can only have valid values of zero through 255, Rust isn't
-quite smart enough to understand we've covered all the cases. In order to fix
-this, we can use a special pattern, _:
-# let some_u8_value = 0u8;
-match some_u8_value {
- 0 => println!("zero"),
- 1 => println!("one"),
- 2 => println!("two"),
- 3 => println!("three"),
- 4 => println!("four"),
- 5 => println!("five"),
- 6 => println!("six"),
- 7 => println!("seven"),
- // ...
- 254 => println!("two-hundred and fifty-four"),
- 255 => println!("two-hundred and fifty-five"),
- _ => panic!("can't ever happen"),
-}
-
-The _ pattern matches anything at all, and so with it as the final pattern,
-Rust can understand that we have all our bases covered. It's not only used for
-this sort of exhaustiveness issue, though. It's useful any time we don't want to
-deal with a number of cases. Consider this scenario: if we wanted to print out
-something one one, three, five, and seven:
-# let some_u8_value = 0u8;
-match some_u8_value {
- 1 => println!("one"),
- 3 => println!("three"),
- 5 => println!("five"),
- 7 => println!("seven"),
- _ => (),
-}
-
-The _ pattern will match all the other cases, and () will do nothing, it's
-the unit value.
-More about patterns
-As we've just seen, patterns are powerful, yet complex. Let's take a whole
-section to cover all of the things that they can do.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/chXX-patterns.html b/chXX-patterns.html
index 5e40d74bb..474d182ee 100644
--- a/chXX-patterns.html
+++ b/chXX-patterns.html
@@ -47,7 +47,7 @@
diff --git a/chYY-YY-documentation.html b/chYY-YY-documentation.html
index 90ab400e1..f77e9a7c6 100644
--- a/chYY-YY-documentation.html
+++ b/chYY-YY-documentation.html
@@ -47,7 +47,7 @@
@@ -109,6 +109,10 @@ src/main.rs:1 /// What am I documenting?
+
+
+
+
@@ -119,6 +123,10 @@ src/main.rs:1 /// What am I documenting?
+
+
+
+
diff --git a/chZZ-generics.html b/chZZ-generics.html
index ef1cbf5d8..6a217c4a3 100644
--- a/chZZ-generics.html
+++ b/chZZ-generics.html
@@ -47,7 +47,7 @@
@@ -215,7 +215,7 @@ instead of values.
-
+
@@ -229,7 +229,7 @@ instead of values.
-
+
diff --git a/index.html b/index.html
index 9dd68927f..cce4e150b 100644
--- a/index.html
+++ b/index.html
@@ -46,7 +46,7 @@
@@ -68,25 +68,25 @@
Introduction
Welcome to “The Rust Programming Language”, an introductory book about Rust.
-Rust is a programming language that’s focused on safety, concurrency, and
-speed. It maintains these goals without having a garbage collector, making it a
-useful language for a number of use cases other languages aren’t good at:
-embedding in other languages, programs with specific space and time
-requirements, and writing low-level code, like device drivers and operating
-systems. It improves on current languages targeting this space by having a
-number of compile-time safety checks that produce no runtime overhead, while
-eliminating all data races. Rust also aims to achieve ‘zero-cost abstractions’
-even though some of these abstractions feel like those of a high-level
-language. Even then, Rust still allows precise control like a low-level
-language would.
+Rust is a programming language that’s focused on safety, speed, and
+concurrency. Its design lets you create programs that have the performance and
+control of a low-level language, but with helpful abstractions that feel like a
+high-level language. The Rust community welcomes all programmers who have their
+experience in languages like C and are looking for a safer alternative, as well
+as programmers from languages like Python who are looking for ways to write more
+performant code without losing expressiveness.
+Rust provides the majority of its safety checks at compile time and without a
+garbage collector so that your program's runtime isn't impacted. This makes it
+useful in a number of use cases that other languages aren’t good at: embedding
+in other languages, programs with specific space and time requirements, and
+writing low-level code, like device drivers and operating systems. It's also
+great for web applications: it powers the Rust package registry site, crates.io!
+We're excited to see what you create with Rust.
This book is written for a reader who already knows how to program in at least
-one programming language. Which language that is does not matter very much,
-though you may have an easier time if you’ve programmed in a low-level language
-with manual memory allocation.
-After reading this book, you should be comfortable writing Rust programs. We’ll
-be learning Rust through small, focused examples that demonstrate each topic.
-The chapters build upon each other, so if you skip ahead, you may have to skip
-back to refer to a previous concept.
+one programming language. After reading this book, you should be comfortable
+writing Rust programs. We’ll be learning Rust through small, focused examples
+that build on each other to demonstrate how to use various features of Rust as
+well as how they work behind the scenes.
Contributing to the book
This book is open source. If you find an error, please don’t hesitate to file an
issue or send a pull request on GitHub.
@@ -97,7 +97,7 @@ issue or send a pull request on GitH
-
+
@@ -107,7 +107,7 @@ issue or send a pull request on GitH
-
+
diff --git a/print.html b/print.html
index ef2f774ed..e03ce0716 100644
--- a/print.html
+++ b/print.html
@@ -47,7 +47,7 @@
@@ -69,60 +69,66 @@
Introduction
Welcome to “The Rust Programming Language”, an introductory book about Rust.
-Rust is a programming language that’s focused on safety, concurrency, and
-speed. It maintains these goals without having a garbage collector, making it a
-useful language for a number of use cases other languages aren’t good at:
-embedding in other languages, programs with specific space and time
-requirements, and writing low-level code, like device drivers and operating
-systems. It improves on current languages targeting this space by having a
-number of compile-time safety checks that produce no runtime overhead, while
-eliminating all data races. Rust also aims to achieve ‘zero-cost abstractions’
-even though some of these abstractions feel like those of a high-level
-language. Even then, Rust still allows precise control like a low-level
-language would.
+Rust is a programming language that’s focused on safety, speed, and
+concurrency. Its design lets you create programs that have the performance and
+control of a low-level language, but with helpful abstractions that feel like a
+high-level language. The Rust community welcomes all programmers who have their
+experience in languages like C and are looking for a safer alternative, as well
+as programmers from languages like Python who are looking for ways to write more
+performant code without losing expressiveness.
+Rust provides the majority of its safety checks at compile time and without a
+garbage collector so that your program's runtime isn't impacted. This makes it
+useful in a number of use cases that other languages aren’t good at: embedding
+in other languages, programs with specific space and time requirements, and
+writing low-level code, like device drivers and operating systems. It's also
+great for web applications: it powers the Rust package registry site, crates.io!
+We're excited to see what you create with Rust.
This book is written for a reader who already knows how to program in at least
-one programming language. Which language that is does not matter very much,
-though you may have an easier time if you’ve programmed in a low-level language
-with manual memory allocation.
-After reading this book, you should be comfortable writing Rust programs. We’ll
-be learning Rust through small, focused examples that demonstrate each topic.
-The chapters build upon each other, so if you skip ahead, you may have to skip
-back to refer to a previous concept.
+one programming language. After reading this book, you should be comfortable
+writing Rust programs. We’ll be learning Rust through small, focused examples
+that build on each other to demonstrate how to use various features of Rust as
+well as how they work behind the scenes.
Contributing to the book
This book is open source. If you find an error, please don’t hesitate to file an
issue or send a pull request on GitHub.
-Installation
-The first step to using Rust is to install it. Generally speaking, you’ll need
-an internet connection to run the commands in this chapter, as we’ll be
-downloading Rust from the internet.
+Installation
+The first step to using Rust is to install it. You’ll need an internet
+connection to run the commands in this chapter, as we’ll be downloading Rust
+from the internet.
We’ll be showing off a number of commands using a terminal, and those lines all
-start with $. You don't need to type in the $s, they are there to indicate
+start with $. You don't need to type in the $s; they are there to indicate
the start of each command. You’ll see many tutorials and examples around the web
that follow this convention: $ for commands run as a regular user, and #
-for commands you should be running as an administrator.
-Installing on Linux or Mac
-If you're on Linux or a Mac, all you need to do is open a terminal and type this:
-$ curl -sSf https://static.rust-lang.org/rustup.sh | sh
+for commands you should be running as an administrator. Lines that don't start
+with $ are typically showing the output of the previous command.
+Installing on Linux or Mac
+If you're on Linux or a Mac, all you need to do is open a terminal and type
+this:
+$ curl https://sh.rustup.rs -sSf | sh
-This will download a script, and start the installation. You may be prompted for your password.
-If it all goes well, you’ll see this appear:
- Rust is ready to roll.
+This will download a script and start the installation. You may be prompted for
+your password. If it all goes well, you’ll see this appear:
+Rust is installed now. Great!
-Installing on Windows
+Installing on Windows
If you're on Windows, please download the appropriate installer.
-Uninstalling
+Uninstalling
Uninstalling Rust is as easy as installing it. On Linux or Mac, just run
the uninstall script:
-$ sudo /usr/local/lib/rustlib/uninstall.sh
+$ rustup self uninstall
-If you used the Windows installer, you can re-run the .msi and it will give you
-an uninstall option.
-Troubleshooting
+If you used the Windows installer, you can re-run the .msi and it will give
+you an uninstall option.
+Troubleshooting
If you've got Rust installed, you can open up a shell, and type this:
$ rustc --version
-You should see the version number, commit hash, and commit date.
-If you do, Rust has been installed successfully! Congrats!
+You should see the version number, commit hash, and commit date in a format
+similar to this for the latest stable version at the time you install:
+rustc x.y.z (abcabcabc yyyy-mm-dd)
+
+If you see this, Rust has been installed successfully!
+Congrats!
If you don't and you're on Windows, check that Rust is in your %PATH% system
variable. If it isn't, run the installer again, select "Change" on the "Change,
repair, or remove installation" page and ensure "Add to PATH" is checked.
@@ -130,44 +136,41 @@ repair, or remove installation" page and ensure "Add to PATH" is
the #rust IRC channel on irc.mozilla.org, which you can access through
Mibbit. Click that link, and you'll be chatting with other Rustaceans
(a silly nickname we call ourselves) who can help you out. Other great resources
-include the user’s forum, and Stack Overflow.
-Local documentation
-This installer also installs a copy of the documentation locally, so you can
-read it offline. On UNIX systems, /usr/local/share/doc/rust is the location.
-On Windows, it's in a share/doc directory, inside the directory to which Rust
-was installed.
-Hello, world!
+include the user’s forum and Stack Overflow.
+Local documentation
+The installer also includes a copy of the documentation locally, so you can
+read it offline. On Linux or Mac, run rustup doc to open the local
+documentation in your browser. On Windows, the documentation is in a
+share/doc directory inside the directory where Rust was installed.
+Hello, World!
Now that you have Rust installed, let’s write your first Rust program. It's
traditional when learning a new language to write a little program to print the
text “Hello, world!” to the screen, and in this section, we'll follow that
tradition.
-The nice thing about starting with such a simple program is that you can
-quickly verify that your compiler is installed, and that it's working properly.
-Printing information to the screen is also just a pretty common thing to do, so
-practicing it early on is good.
Note: This book assumes basic familiarity with the command line. Rust itself
makes no specific demands about your editing, tooling, or where your code
lives, so if you prefer an IDE to the command line, that's an option.
-Creating a Project File
+Creating a Project File
First, make a file to put your Rust code in. Rust doesn't care where your code
-lives, but for this book, I suggest making a projects directory in your home
-directory, and keeping all your projects there. Open a terminal and enter the
-following commands to make a directory for this particular project:
+lives, but for this book, we'd suggest making a projects directory in your
+home directory and keeping all your projects there. Open a terminal and enter
+the following commands to make a directory for this particular project:
$ mkdir ~/projects
$ cd ~/projects
$ mkdir hello_world
$ cd hello_world
-Note: If you’re on Windows and not using PowerShell, the ~ may not work.
+
Note: If you’re on Windows and not using PowerShell, the ~ that represents
+your home directory may not work.
Consult the documentation for your shell for more details.
-Writing and Running a Rust Program
-Next, make a new source file and call it main.rs. Rust files always end
-in a .rs extension. If you’re using more than one word in your filename, use
-an underscore to separate them; for example, you'd use hello_world.rs rather
+
Writing and Running a Rust Program
+Next, make a new source file and call it main.rs. Rust files always end with
+the .rs extension. If you’re using more than one word in your filename, use
+an underscore to separate them. For example, you'd use hello_world.rs rather
than helloworld.rs.
Now open the main.rs file you just created, and type the following code:
fn main() {
@@ -180,11 +183,11 @@ following commands:
$ ./main
Hello, world!
-In Windows, just replace main with main.exe. Regardless of your operating
+
On Windows, just replace main with main.exe. Regardless of your operating
system, you should see the string Hello, world! print to the terminal. If you
did, then congratulations! You've officially written a Rust program. That makes
you a Rust programmer! Welcome.
-Anatomy of a Rust Program
+Anatomy of a Rust Program
Now, let’s go over what just happened in your "Hello, world!" program in
detail. Here's the first piece of the puzzle:
fn main() {
@@ -192,11 +195,12 @@ detail. Here's the first piece of the puzzle:
}
These lines define a function in Rust. The main function is special: it's
-the beginning of every Rust program. The first line says, “I’m declaring a
-function named main that takes no arguments and returns nothing.” If there
-were arguments, they would go inside the parentheses (( and )), and because
-we aren’t returning anything from this function, we can omit the return type
-entirely.
+the first thing that is run for every executable Rust program. The first line
+says, “I’m declaring a function named main that takes no arguments and
+returns nothing.” If there were arguments, they would go inside the parentheses
+(( and )). We aren’t returning anything from this function, so we have
+omitted the return type entirely. If there was a return type, there would be a
+-> and the return type after the parentheses.
Also note that the function body is wrapped in curly braces ({ and }). Rust
requires these around all function bodies. It's considered good style to put
the opening curly brace on the same line as the function declaration, with one
@@ -207,19 +211,18 @@ space in between.
This line does all of the work in this little program: it prints text to the
screen. There are a number of details that are important here. The first is
that it’s indented with four spaces, not tabs.
-The second important part is the println!() line. This is calling a Rust
-macro, which is how metaprogramming is done in Rust. If it were calling a
-function instead, it would look like this: println() (without the !). We'll
-discuss Rust macros in more detail later, but for now you just need to
-know that when you see a ! that means that you’re calling a macro instead of
-a normal function.
+The second important part is println!(). This is calling a Rust macro,
+which is how metaprogramming is done in Rust. If it were calling a function
+instead, it would look like this: println() (without the !). We'll discuss
+Rust macros in more detail in Chapter XX, but for now you just need to know
+that when you see a ! that means that you’re calling a macro instead of a
+normal function.
Next is "Hello, world!" which is a string. We pass this string as an
-argument to println!, which prints the string to the screen. Easy enough!
-The line ends with a semicolon (;). Rust is an expression oriented
-language, which means that most things are expressions, rather than statements.
-The ; indicates that this expression is over, and the next one is ready to
-begin. Most lines of Rust code end with a ;.
-Compiling and Running Are Separate Steps
+argument to println!(), which prints the string to the screen. Easy enough!
+The line ends with a semicolon (;). The ; indicates that this expression is
+over, and the next one is ready to begin. Most lines of Rust code end with a
+;.
+Compiling and Running Are Separate Steps
In "Writing and Running a Rust Program", we showed you how to run a newly
created program. We'll break that process down and examine each step now.
Before running a Rust program, you have to compile it. You can use the Rust
@@ -238,7 +241,7 @@ main main.rs
$ dir
main.exe main.rs
-This shows we have two files: the source code, with an .rs extension, and the
+
This shows we have two files: the source code, with the .rs extension, and the
executable (main.exe on Windows, main everywhere else). All that's left to
do from here is run the main or main.exe file, like this:
$ ./main # or main.exe on Windows
@@ -247,360 +250,1042 @@ do from here is run the main or main.exe file, like th
If you come from a dynamic language like Ruby, Python, or JavaScript, you may
not be used to compiling and running a program being separate steps. Rust is an
ahead-of-time compiled language, which means that you can compile a program,
-give it to someone else, and they can run it even without Rust installed. If
-you give someone a .rb or .py or .js file, on the other hand, they need
-to have a Ruby, Python, or JavaScript implementation installed (respectively),
-but you only need one command to both compile and run your program. Everything
-is a tradeoff in language design.
+give it to someone else, and they can run it even without having Rust
+installed. If you give someone a .rb, .py, or .js file, on the other
+hand, they need to have a Ruby, Python, or JavaScript implementation installed
+(respectively), but you only need one command to both compile and run your
+program. Everything is a tradeoff in language design.
Just compiling with rustc is fine for simple programs, but as your project
-grows, you'll want to be able to manage all of the options your project has,
-and make it easy to share your code with other people and projects. Next, I'll
+grows, you'll want to be able to manage all of the options your project has
+and make it easy to share your code with other people and projects. Next, we'll
introduce you to a tool called Cargo, which will help you write real-world Rust
programs.
-Hello, Cargo!
+Hello, Cargo!
Cargo is Rust’s build system and package manager, and Rustaceans use Cargo to
-manage their Rust projects. Cargo manages three things: building your code,
-downloading the libraries your code depends on, and building those libraries.
-We call libraries your code needs ‘dependencies’ since your code depends on
-them.
-The simplest Rust programs don’t have any dependencies, so right now, you'd
-only use the first part of its functionality. As you write more complex Rust
-programs, you’ll want to add dependencies, and if you start off using Cargo,
-that will be a lot easier to do.
+manage their Rust projects because it makes a lot of tasks easier. For example,
+Cargo takes care of building your code, downloading the libraries your code
+depends on, and building those libraries. We call libraries your code needs
+‘dependencies’ since your code depends on them.
+The simplest Rust programs, like the one we've written so far, don’t have any
+dependencies, so right now, you'd only be using the part of Cargo that can take
+care of building your code. As you write more complex Rust programs, you’ll
+want to add dependencies, and if you start off using Cargo, that will be a lot
+easier to do.
As the vast, vast majority of Rust projects use Cargo, we will assume that
you’re using it for the rest of the book. Cargo comes installed with Rust
-itself, if you used the official installers. If you installed Rust through some
-other means, you can check if you have Cargo installed by typing:
+itself, if you used the official installers as covered in the Installation
+chapter. If you installed Rust through some other means, you can check if you
+have Cargo installed by typing the following into your terminal:
$ cargo --version
-Into a terminal. If you see a version number, great! If you see an error like
-‘command not found’, then you should look at the documentation for the system
-in which you installed Rust, to determine if Cargo is separate.
-Converting to Cargo
-Let’s convert the Hello World program to Cargo. To Cargo-fy a project, you need
-to do three things:
-
-- Put your source file in the right directory.
-- Get rid of the old executable (
main.exe on Windows, main everywhere
-else).
-- Make a Cargo configuration file.
-
-Let's get started!
-Creating a Source Directory and Removing the Old Executable
-First, go back to your terminal, move to your hello_world directory, and
-enter the following commands:
-$ mkdir src
-$ mv main.rs src/main.rs # or 'move main.rs src/main.rs' on Windows
-$ rm main # or 'del main.exe' on Windows
+If you see a version number, great! If you see an error like command not found, then you should look at the documentation for the way you installed
+Rust to determine how to install Cargo separately.
+Creating a Project with Cargo
+Let's create a new project using Cargo and look at how it differs from our
+project in hello_world. Go back to your projects directory (or wherever you
+decided to put your code):
+$ cd ~/projects
-Cargo expects your source files to live inside a src directory, so do that
-first. This leaves the top-level project directory (in this case,
-hello_world) for READMEs, license information, and anything else not related
-to your code. In this way, using Cargo helps you keep your projects nice and
-tidy. There's a place for everything, and everything is in its place.
-Now, move main.rs into the src directory, and delete the compiled file you
-created with rustc. As usual, replace main with main.exe if you're on
-Windows.
-This example retains main.rs as the source filename because it's creating an
-executable. If you wanted to make a library instead, you'd name the file
-lib.rs. This convention is used by Cargo to successfully compile your
-projects, but it can be overridden if you wish.
-Creating a Configuration File
-Next, create a new file inside your hello_world directory, and call it
-Cargo.toml.
-Make sure to capitalize the C in Cargo.toml, or Cargo won't know what to do
-with the configuration file.
-This file is in the TOML (Tom's Obvious, Minimal Language) format. TOML is
-similar to INI, but has some extra goodies, and is used as Cargo’s
-configuration format.
-Inside this file, type the following information:
+And then run:
+$ cargo new hello_cargo --bin
+$ cd hello_cargo
+
+We passed the --bin argument to cargo new because our goal is to make an
+executable application, as opposed to a library. Executables are often called
+binaries (as in /usr/bin, if you’re on a Unix system). hello_cargo is the
+name we've chosen for our project, and Cargo creates its files in a directory
+of the same name that we can then go into.
+If we list the files in the hello_cargo directory, we can see that Cargo has
+generated two files and one directory for us: a Cargo.toml and a src
+directory with a main.rs file inside. It has also initialized a new git
+repository in the hello_cargo directory for us; you can change this to use a
+different version control system, or no version control system, by using the
+--vcs flag.
+Open up Cargo.toml in your text editor of choice. It should look something
+like this:
[package]
-
-name = "hello_world"
+name = "hello_cargo"
version = "0.1.0"
-authors = [ "Your name <you@example.com>" ]
+authors = ["Your Name <you@example.com>"]
+
+[dependencies]
-The first line, [package], indicates that the following statements are
-configuring a package. As we add more information to this file, we’ll add other
-sections, but for now, we just have the package configuration.
-The other three lines set the three bits of configuration that Cargo needs to
-know to compile your program: its name, what version it is, and who wrote it.
-Once you've added this information to the Cargo.toml file, save it to finish
-creating the configuration file.
-Building and Running a Cargo Project
-With your Cargo.toml file in place in your project's root directory, you
-should be ready to build and run your Hello World program! To do so, enter the
-following commands:
+This file is in the TOML (Tom's Obvious, Minimal Language) format. TOML is
+similar to INI but has some extra goodies and is used as Cargo’s
+configuration format.
+The first line, [package], is a section heading that indicates that the
+following statements are configuring a package. As we add more information to
+this file, we’ll add other sections.
+The next three lines set the three bits of configuration that Cargo needs to
+see in order to know that it should compile your program: its name, what
+version it is, and who wrote it. Cargo gets your name and email information
+from your environment. If it’s not correct, go ahead and fix that and save the
+file.
+The last line, [dependencies], is the start of a section for you to list any
+crates that your project will depend on so that Cargo knows to download and
+compile those too. We won't need any other crates for this project, but we will
+in the guessing game tutorial in the next chapter.
+Now let's look at src/main.rs:
+fn main() {
+ println!("Hello, world!");
+}
+
+Cargo has generated a "Hello World!" for you, just like the one we wrote
+earlier! So that part is the same. The differences between our previous project
+and the project generated by Cargo that we've seen so far are:
+
+- Our code goes in the
src directory
+- The top level contains a
Cargo.toml configuration file
+
+Cargo expects your source files to live inside the src directory so that the
+top-level project directory is just for READMEs, license information,
+configuration files, and anything else not related to your code. In this way,
+using Cargo helps you keep your projects nice and tidy. There's a place for
+everything, and everything is in its place.
+If you started a project that doesn't use Cargo, as we did with our project in
+the hello_world directory, you can convert it to a project that does use
+Cargo by moving your code into the src directory and creating an appropriate
+Cargo.toml.
+Building and Running a Cargo Project
+Now let's look at what's different about building and running your Hello World
+program through Cargo! To do so, enter the following commands:
$ cargo build
- Compiling hello_world v0.1.0 (file:///home/yourname/projects/hello_world)
-$ ./target/debug/hello_world
+ Compiling hello_cargo v0.1.0 (file:///home/yourname/projects/hello_cargo)
+
+This should have created an executable file in target/debug/hello_cargo (or target/debug/hello_cargo.exe on Windows), which you can run with this command:
+$ ./target/debug/hello_cargo # or ./target/debug/hello_cargo.exe on Windows
Hello, world!
Bam! If all goes well, Hello, world! should print to the terminal once more.
-You just built a project with cargo build and ran it with
-./target/debug/hello_world, but you can actually do both in one step with
-cargo run as follows:
-$ cargo run
- Running `target/debug/hello_world`
-Hello, world!
-
-Notice that this example didn’t re-build the project. Cargo figured out that
-the file hasn’t changed, and so it just ran the binary. If you'd modified your
-source code, Cargo would have rebuilt the project before running it, and you
-would have seen something like this:
-$ cargo run
- Compiling hello_world v0.1.0 (file:///home/yourname/projects/hello_world)
- Running `target/debug/hello_world`
-Hello, world!
-
-Cargo checks to see if any of your project’s files have been modified, and only
-rebuilds your project if they’ve changed since the last time you built it.
-With simple projects, Cargo doesn't bring a whole lot over just using rustc,
-but it will become useful in the future. With complex projects composed of multiple
-crates, it’s much easier to let Cargo coordinate the build. With Cargo, you can
-just run cargo build, and it should work the right way.
-Building for Release
-When your project is finally ready for release, you can use cargo build --release to compile your project with optimizations. These optimizations make
-your Rust code run faster, but turning them on makes your program take longer
-to compile. This is why there are two different profiles, one for development,
-and one for building the final program you’ll give to a user.
-Running this command also causes Cargo to create a new file called
-Cargo.lock, which looks like this:
+Running cargo build for the first time also causes Cargo to create a new file
+at the top level called Cargo.lock, which looks like this:
[root]
-name = "hello_world"
+name = "hello_cargo"
version = "0.1.0"
Cargo uses the Cargo.lock file to keep track of dependencies in your
-application. This is the Hello World project's Cargo.lock file. This project
-doesn't have dependencies, so the file is a bit sparse. Realistically, you
-won't ever need to touch this file yourself; just let Cargo handle it.
-That’s it! If you've been following along, you should have successfully built
-hello_world with Cargo.
-Even though the project is simple, it now uses much of the real tooling you’ll
-use for the rest of your Rust career. In fact, you can expect to start
-virtually all Rust projects with some variation on the following commands:
-$ git clone someurl.com/foo
-$ cd foo
+application. This project doesn't have dependencies, so the file is a bit
+sparse. Realistically, you won't ever need to touch this file yourself; just
+let Cargo handle it.
+We just built a project with cargo build and ran it with
+./target/debug/hello_cargo, but we can actually do both in one step with
+cargo run as follows:
+$ cargo run
+ Running `target/debug/hello_cargo`
+Hello, world!
+
+Notice that this time, we didn't see the output that Cargo was compiling
+hello_cargo. Cargo figured out that the files haven’t changed, so it just ran
+the binary. If you had modified your source code, Cargo would have rebuilt the
+project before running it, and you would have seen something like this:
+$ cargo run
+ Compiling hello_cargo v0.1.0 (file:///home/yourname/projects/hello_cargo)
+ Running `target/debug/hello_cargo`
+Hello, world!
+
+So a few more differences we've now seen:
+
+- Instead of using
rustc, build a project using cargo build (or build and run it in one step with cargo run)
+- Instead of the result of the build being put in the same directory as our code, Cargo will put it in the
target/debug directory.
+
+Building for Release
+When your project is finally ready for release, you can use cargo build --release to compile your project with optimizations. This will create an
+executable in target/release instead of target/debug. These optimizations
+make your Rust code run faster, but turning them on makes your program take
+longer to compile. This is why there are two different profiles: one for
+development when you want to be able to rebuild quickly and often, and one for
+building the final program you’ll give to a user that won't be rebuilt and
+that we want to run as fast as possible. If you're benchmarking the running
+time of your code, be sure to run cargo build --release and benchmark with
+the executable in target/release.
+Cargo as Convention
+With simple projects, Cargo doesn't provide a whole lot of value over just
+using rustc, but it will prove its worth as you continue. With complex
+projects composed of multiple crates, it’s much easier to let Cargo coordinate
+the build. With Cargo, you can just run cargo build, and it should work the
+right way. Even though this project is simple, it now uses much of the real
+tooling you’ll use for the rest of your Rust career. In fact, you can get
+started with virtually all Rust projects you might find that you want to work
+on with the following commands:
+$ git clone someurl.com/someproject
+$ cd someproject
$ cargo build
-Making A New Cargo Project the Easy Way
-You don’t have to go through that previous process every time you want to start
-a new project! Cargo can quickly make a bare-bones project directory that you
-can start developing in right away.
-To start a new project with Cargo, enter cargo new at the command line:
-$ cargo new hello_world --bin
+
+Note: If you want to look at Cargo in more detail, check out the official
+Cargo guide, which covers all of its features.
+
+Guessing Game
+Let's jump into Rust with a hands-on 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.
+Set up
+Let’s set up a new project. Go to your projects directory, and create a new project using Cargo.
+$ cd ~/projects
+$ cargo new guessing_game --bin
+$ cd guessing_game
-This command passes --bin because the goal is to get straight to making an
-executable application, as opposed to a library. Executables are often called
-binaries (as in /usr/bin, if you’re on a Unix system).
-Cargo has generated two files and one directory for us: a Cargo.toml and a
-src directory with a main.rs file inside. These should look familiar,
-they’re exactly what we created by hand, above.
-This output is all you need to get started. First, open Cargo.toml. It should
-look something like this:
+We pass the name of our project to cargo new, then the --bin flag, since
+we’re going to be making another binary like in Chapter 1.
+Take a look at the generated Cargo.toml:
[package]
-
-name = "hello_world"
+name = "guessing_game"
version = "0.1.0"
authors = ["Your Name <you@example.com>"]
+
+[dependencies]
-Cargo has populated Cargo.toml with reasonable defaults based on the arguments
-you gave it and your git global configuration. You may notice that Cargo has
-also initialized the hello_world directory as a git repository.
-Here’s what should be in src/main.rs:
+If the authors information that Cargo got from your environment is not correct,
+go ahead and fix that.
+And as we saw in the last chapter, cargo new generates a ‘Hello, world!’ for
+us. Check out src/main.rs:
fn main() {
println!("Hello, world!");
}
-Cargo has generated a "Hello World!" for you, and you’re ready to start coding!
-
-Note: If you want to look at Cargo in more detail, check out the official Cargo
-guide, which covers all of its features.
-
-The Design of Rust
-Up and Running
-We’ll start our journey with Rust by talking about the absolute basics —
-concepts that appear in almost every programming language. Many programming
-languages have lots in common at their core. None of the concepts presented are
-unique to Rust, but we’ll cover Rust’s particular syntax and conventions around
-these common concepts.
-If you want to skip this section, you can, but you may end up coming back later
-to find out small details. These foundations will be in every single useful
-Rust program, and learning them gives us a strong core to start from.
-Variable Bindings
-The foundation of virtually every program is the ability to store and modify
-data. Rust programs are no different. Let’s start with a short example.
-The basics of bindings
-First, we’ll generate a new project with Cargo. Open a terminal, and navigate
-to the directory where you’d like to keep your projects. From there, let’s
-generate a new project:
+Let’s try compiling what Cargo gave us and running it in the same step, using the cargo run command:
+$ cargo run
+ Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
+ Running `target/debug/guessing_game`
+Hello, world!
+
+Great! The run command comes in handy when you need to rapidly iterate on a
+project. Our game is such a project: we want to quickly test each
+iteration before moving on to the next one.
+Now open up your src/main.rs again. We’ll be writing all of our code in this
+file.
+Processing a Guess
+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:
+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)
+ .expect("Failed to read line");
+
+ println!("You guessed: {}", guess);
+}
+
+There’s a lot here! Let’s go over it, bit by bit.
+use std::io;
+
+We’ll need to take user input and then print the result as output. As such, we
+need the io library from the standard library. Rust only imports a few things
+by default into every program, the ‘prelude’. If it’s not in the
+prelude, you’ll have to use it directly. Using the std::io library gets
+you a number of useful io-related things, so that's what we've done here.
+fn main() {
+
+As you’ve seen in Chapter 1, the main() function is the entry point into the
+program. The fn syntax declares a new function, the ()s indicate that
+there are no arguments, and { starts the body of the function.
+println!("Guess the number!");
+
+println!("Please input your guess.");
+
+We previously learned in Chapter 1 that println!() is a macro that
+prints a string to the screen.
+Variable Bindings
+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 what are called ‘variable bindings’. Here's an example:
+let foo = bar;
+
+This will create a new binding named foo, and bind it to the value 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: it makes a binding mutable, rather than immutable.
+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 will introduce a mutable binding named
+guess, but we have to look at the other side of the = for what it’s
+bound to: String::new().
+String is a string type, provided by the standard library. A
+String is a growable, UTF-8 encoded bit of text.
+The ::new() syntax uses :: because this is an ‘associated function’ of
+a particular type. That is to say, it’s associated with String itself,
+rather than a particular instance of a String. Some languages call this a
+‘static method’.
+This function is named new(), because it creates a new, empty String.
+You’ll find a new() function on many types, as it’s a common name for making
+a new value of some kind.
+Let’s move forward:
+io::stdin().read_line(&mut guess)
+ .expect("Failed to read line");
+
+Let’s go through this together bit-by-bit. The first line has two parts. Here’s
+the first:
+io::stdin()
+
+Remember how we used std::io on the first line of the program? We’re now
+calling an associated function on it. If we didn’t use std::io, we could
+have written this line as 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:
+.read_line(&mut guess)
+
+Here, we call the read_line() method on our handle. We’re also
+passing one argument to read_line(): &mut guess.
+Remember how we bound guess above? We said it was mutable. However,
+read_line doesn’t take a String as an argument: it takes a &mut String.
+The & is the feature of Rust called a ‘reference’, which allows you to have
+multiple ways to access one piece of data in order to 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; Chapter XX will cover them in
+more detail. For now, all we need to know is that like let bindings,
+references are immutable by default. Hence, we need to write &mut guess,
+rather than &guess.
+Why does 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, that string 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. This is the second part of the line:
+.expect("Failed to read line");
+
+When you call a method with the .foo() syntax, you may introduce a newline
+and other whitespace. This helps you split up long lines. We could have
+written this code as:
+io::stdin().read_line(&mut guess).expect("failed to read line");
+
+But that gets hard to read. So we’ve split it up, two lines for two method
+calls.
+The Result Type
+We already talked about read_line(), but what about expect()? Well,
+we already mentioned that read_line() puts what the user types into the &mut String we pass it. But it also returns a value: in this case, an
+io::Result. Rust has a number of types named Result in its
+standard library: a generic Result, and then specific versions for
+sub-libraries, like io::Result.
+The purpose of these Result types is to encode error handling information.
+Values of the Result type, like any type, have methods defined on them. In
+this case, io::Result has an expect() method that takes a value
+it’s called on, and if it isn’t a successful result, will cause our program to
+crash and display the message that we passed as an argument to expect().
+If we don't call this method, 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 value. This warning comes from
+a special annotation that 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 want to crash if there’s a
+problem, we can use expect(). If we can recover from the error somehow, we’d
+do something else, but we’ll save that for a future project.
+println!() Placeholders
+There’s only one line of this first example left, aside from the closing curly
+brace:
+ println!("You guessed: {}", guess);
+}
+
+This prints out the string we saved our input in. The {}s are a placeholder:
+think of {} as little crab pincers, holding a value in place. The first {}
+holds the first value after the format string, the second set holds the second
+value, and so on. Printing out multiple values in one call to println!() would then look like this:
+let x = 5;
+let y = 10;
+
+println!("x and y: {} and {}", x, y);
+
+Which would print out "x and y: 5 and 10".
+Anyway, back to our guessing game. We can run what we have with 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.
+Generating a secret number
+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 crate. A ‘crate’ is a package of Rust code.
+We’ve been building a ‘binary crate’, which is an executable. 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, we need to modify our Cargo.toml. Open it up, and
+add this line at the bottom beneath the [dependencies] section header that
+Cargo created for you:
+[dependencies]
+
+rand = "0.3.14"
+
+The [dependencies] section of Cargo.toml is like the [package] section:
+everything that follows the section heading is part of that section, until
+another section starts. Cargo uses the dependencies section to know what
+dependencies on external crates you have and what versions of those crates you
+require. In this case, we’ve specified the rand crate with the semantic
+version specifier 0.3.14. Cargo understands Semantic Versioning, a
+standard for writing version numbers. A bare number like above is actually
+shorthand for ^0.3.14, which means "any version that has a public API
+compatible with version 0.3.14".
+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.14
+ Downloading libc v0.2.14
+ Compiling libc v0.2.14
+ Compiling rand v0.3.14
+ Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
+
+You may see different versions (but they will be compatible, thanks to semver!)
+and the lines may be in a different order.
+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] and downloads
+any we don’t have yet. In this case, while we only said we wanted to depend on
+rand, we’ve also grabbed a copy of libc. This is because rand depends on
+libc to work. After downloading them, it compiles them and then compiles
+our project.
+If we run cargo build again, we’ll get different output:
+$ cargo build
+
+That’s right, no output! Cargo knows that our project has been built, that
+all of its dependencies are built, and that no changes have been made. There’s
+no reason to do all that stuff again. With nothing to do, it simply
+exits. If we open up src/main.rs, make a trivial change, then save it again,
+we’ll only see one line:
+$ cargo build
+ Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
+
+What happens when next week version v0.3.15 of the rand crate comes out,
+with an important bugfix? While getting bugfixes is important, what if 0.3.15
+contains a regression that breaks our code?
+The answer to this problem is the Cargo.lock file created the first time we
+ran cargo build that is now in your project directory. When you build your
+project for the first time, Cargo figures out all of the versions that fit your
+criteria then writes them to the Cargo.lock file. When you build your project
+in the future, Cargo will see that the Cargo.lock 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.14 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.15? Cargo has another command,
+update, which says ‘ignore the Cargo.lock file and figure out all the
+latest versions that fit what we’ve specified in Cargo.toml. 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 and smaller than 0.4.0. If we want to
+move to 0.4.x, we’d have to update what is in the Cargo.toml file. When we
+do, the next time we cargo build, Cargo will update the index and re-evaluate
+our rand requirements.
+There’s a lot more to say about Cargo and its
+ecosystem that we will get into in Chapter XX, but for now,
+that’s all we need to know. Cargo makes it really easy to re-use libraries, so
+Rustaceans are able to write smaller projects which are assembled out of a
+number of sub-packages.
+Let’s get on to actually using 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)
+ .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. Because we declared rand in our [dependencies], we can now put
+extern crate in our code to let Rust know we’ll be making use of that
+dependency. This also does the equivalent of a use rand; as well, so we can
+call anything in the rand crate by prefixing it with rand::.
+Next, we added another use line: use rand::Rng. We’re going to use a
+method in a moment, and it requires that 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 in Chapter XX.
+There are two other lines we added, in the middle:
+let secret_number = rand::thread_rng().gen_range(1, 101);
+
+println!("The secret number is: {}", secret_number);
+
+We use the rand::thread_rng() function to get a copy of the random number
+generator, which is local to the particular thread of execution
+we’re in. Because we put use rand::Rng above, the random number generator has
+a gen_range() method available. This method takes two numbers as arguments
+and generates a random number between them. It’s inclusive on the lower bound
+but exclusive on the upper bound, so we need 1 and 101 to ask for a number
+ranging from one to a hundred.
+The second line prints out the secret number. This is useful while
+we’re developing our program to let us 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
+
+You should get different random numbers, and they should all be between 1 and
+
+- Great job! Next up: comparing our guess to the secret number.
+
+Comparing guesses
+Now that we’ve got user input, let’s compare our guess to the secret number.
+Here’s part of our next step. It won't quite compile yet though:
+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)
+ .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. We bring a type called
+std::cmp::Ordering into scope. Then we add five new lines at the bottom that
+use that type:
+match guess.cmp(&secret_number) {
+ Ordering::Less => println!("Too small!"),
+ Ordering::Greater => println!("Too big!"),
+ Ordering::Equal => println!("You win!"),
+}
+
+The 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
+Ordering type we used earlier. We use a match statement to
+determine exactly what kind of Ordering it is. Ordering is an
+enum, short for ‘enumeration’, which looks like this:
+enum Foo {
+ Bar,
+ Baz,
+}
+
+With this definition, anything of type Foo can be either a
+Foo::Bar or a Foo::Baz. We use the :: to indicate the
+namespace for a particular enum variant.
+The Ordering enum has three possible variants: Less, Equal,
+and Greater. The match statement takes a value of a type and lets you
+create an ‘arm’ for each possible value. An arm is made up of a pattern and the
+code that we should execute if the pattern matches the value of the type. Since
+we have three types of 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, we print Too small!, if it’s Greater, Too big!, and if
+Equal, You win!. match is really useful and is used often in Rust.
+We did mention that this won’t quite compile yet, though. Let’s try it:
+$ cargo build
+ Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
+src/main.rs:23:21: 23:35 error: mismatched types [E0308]
+src/main.rs:23 match guess.cmp(&secret_number) {
+ ^~~~~~~~~~~~~~
+src/main.rs:23:21: 23:35 help: run `rustc --explain E0308` to see a detailed explanation
+src/main.rs:23:21: 23:35 note: expected type `&std::string::String`
+src/main.rs:23:21: 23:35 note: found type `&_`
+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(), Rust was able to infer that guess
+should be a String, so it doesn’t make us write out the type. With our
+secret_number, there are a number of types which can have a value between one
+and a hundred: i32, a thirty-two-bit number, or u32, an unsigned
+thirty-two-bit number, or i64, a sixty-four-bit number or others. So far,
+that hasn’t mattered, and so Rust defaults to an i32. However, here, Rust
+doesn’t know how to compare the guess and the secret_number. They need to
+be the same type.
+Ultimately, we want to convert the String we read as input
+into a real number type so that we can compare it to the guess numerically. We
+can do that with two 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)
+ .expect("failed to read line");
+
+ let guess: u32 = guess.trim().parse()
+ .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 two lines:
+let guess: u32 = guess.trim().parse()
+ .expect("Please type a number!");
+
+Wait a minute, didn't we already have a guess? We do, but Rust allows us
+to ‘shadow’ the previous guess with a new one. This is often used in this
+exact situation, where guess starts as a String, but we want to convert it
+to a u32. Shadowing lets us re-use the guess name rather than forcing us
+to come up with two unique names like guess_str and guess or something
+else.
+We bind guess to an expression that looks like something we wrote earlier:
+guess.trim().parse()
+
+Here, guess refers to the old guess, the one that was a String with our
+input in it. The trim() method on 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 read_line(). If we type 5 and hit return, guess
+looks like this: 5\n. The \n represents ‘newline’, the enter key. trim()
+gets rid of this, leaving our string with only the 5.
+The 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. The colon (:)
+after guess tells Rust we’re going to annotate its type. u32 is an
+unsigned, thirty-two bit integer. Rust has a number of built-in number
+types, but we’ve chosen u32. It’s a good default choice for a small
+positive number. You'll see the other number types in Chapter XX.
+Just like read_line(), our call to parse() could cause an error. What if
+our string contained A👍%? There’d be no way to convert that to a number. As
+such, we’ll do the same thing we did with read_line(): use the expect()
+method 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 we even added spaces before our guess, and it still figured
+out that we guessed 76. Run the program a few times. Verify that guessing
+the secret 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!
+Looping
+The 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)
+ .expect("failed to read line");
+
+ let guess: u32 = guess.trim().parse()
+ .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()? If we give a non-number answer, the program
+will crash and, therefore, 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!: ParseIntError { kind: InvalidDigit }', src/libcore/result.rs:785
+note: Run with `RUST_BACKTRACE=1` for a backtrace.
+error: Process didn't exit successfully: `target/debug/guess` (exit code: 101)
+
+Ha! 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)
+ .expect("failed to read line");
+
+ let guess: u32 = guess.trim().parse()
+ .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 line after the You win!, we’ll exit the loop when we
+win. Exiting the loop also means exiting the program, since the loop is the last
+thing in main(). We have another tweak to make: when someone inputs a
+non-number, we don’t want to quit, we 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)
+ .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:
+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 expect() to a match statement. A Result is the
+return type of parse(). Result is an enum like Ordering, but in this
+case, each variant has some data associated with it. Ok is a success, and
+Err is a failure. Each contains more information: in this case, the
+successfully parsed integer or an error type, respectively. When we match an
+Ok(num), that pattern sets the name num to the value inside the Ok (the
+integer), and the code we run just returns that integer. In the Err case, we
+don’t care what kind of error it is, so we just use the catch-all _ instead
+of a name. So for all errors, we run the code continue, which lets us move to
+the next iteration of the loop, effectively ignoring the errors.
+Now we should be good! Let’s try it:
+$ 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 can finish 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)
+ .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;
+ }
+ }
+ }
+}
+
+Complete!
+This project showed you a lot: let, match, methods, associated
+functions, using external crates, and more.
+At this point, you have successfully built the Guessing Game! Congratulations!
+Common Programming Concepts in Rust
+Let's look at concepts that appear in almost every programming language and see
+how they work in Rust. Many programming languages have much in common at their
+core. None of the concepts presented in this chapter are unique to Rust, but
+we’ll discuss Rust’s particular syntax and conventions concerning these common
+concepts.
+Specifically, we’ll be talking about variable bindings, basic types, functions,
+comments, and control flow. These foundations will be in every Rust
+program, and learning them early will give you a strong core to start from.
+PROD: START BOX
+Keep in mind as we get into variables and functions that the Rust language has
+a set of keywords that have been reserved for use by the language only, much
+like other languages do. This means you cannot use these words as names of
+variables or functions, for example. Most of these have special meaning and we
+will be using them to do various things in our Rust programs; a few have no
+current functionality associated but have been reserved for functionality that
+might be in the Rust language in the future. You can find a list of the
+keywords in Appendix XX.
+PROD: END BOX
+Variable Bindings and Mutability
+We mentioned in Chapter XX that by default, variable bindings are immutable.
+This is one of many nudges that Rust's design has to encourage us to write our
+code to get the most of the safety and easy concurrency that Rust has to offer.
+We still have the option to make our bindings mutable, though. Let's explore
+how and why Rust encourages us to favor immutability, and why we might want to
+opt out of that.
+Variable bindings being immutable means that once a value is bound, you can't
+change that value. To illustrate this, let's generate a new project with Cargo.
+Open a terminal, and navigate to the directory you want to store your projects
+in. From there, run these commands:
$ cargo new --bin bindings
$ cd bindings
-This creates a new project, ‘bindings’, and sets up our Cargo.toml and
-src/main.rs files. As we saw in “Hello, World!”, Cargo will generate these
-files and create a little ‘hello world’ program for us:
-fn main() {
- println!("Hello, world!");
-}
-
-Let’s replace that program with this one:
-fn main() {
- let x = 5;
-
- println!("The value of x is: {}", x);
-}
-
-And finally, run it:
-$ cargo run
- Compiling bindings v0.1.0 (file:///projects/bindings)
- Running `target/debug/bindings`
-The value of x is: 5
-
-If you see an error instead, double check that you have copied the program
-exactly as written. Let’s break this down, line by line.
-fn main() {
-
-The main() function is the entry point of every Rust program. We’ll talk more
-about functions in the next section, but for now, all we need to know is that
-this is where our program begins. The opening curly brace, {, indicates the
-start of the function’s body.
- let x = 5;
-
-This is our first ‘variable binding’, which we create with a ‘let statement’.
-Before we do that, though, let’s finish investigating this example. Here’s the
-next line:
- println!("The value of x is: {}", x);
-
-The println! macro prints text to the screen. We can tell that it’s a macro
-due to the !. We won’t learn how to write macros until much later in the
-book, but we’ll use macros provided by the standard library throughout. Every
-time you see a !, remember that it signifies a macro. Macros can add new
-syntax to the language, and the ! is a reminder that things may look slightly
-unusual.
-println!, specifically, has one required argument, a ‘format string’, and
-zero or more optional arguments. The format string can contain the special text
-{}. Each instance of {} corresponds to an additional argument. Here’s an
-example:
-let x = 2 + 3;
-let y = x + 5;
-println!("The value of x is {}, and the value of y is {}", x, y);
-
-You can think of {} as little crab pincers, holding the value in place. This
-placeholder has a number of more advanced formatting options that we’ll discuss
-later.
-}
-
-Finally, a closing curly brace matches up with the opening curly brace that
-declared the main() function, and declares its end.
-This explains our output:
-The value of x is: 5
-
-We assign 5 to a binding, x, and then print it to the screen with
-println!.
-Delayed Initialization
-We do not have to provide bindings with an initial value, and can assign it
-later. Try this program:
-fn main() {
- let x;
-
- x = 5;
-
- println!("The value of x is: {}", x);
-}
-
-And run it with cargo run:
-$ cargo run
- Compiling bindings v0.1.0 (file:///projects/bindings)
- Running `target/debug/bindings`
-The value of x is: 5
-
-It’s all good. This raises a question, though: what if we try to print out a
-binding before we declare a value? Here’s a program that demonstrates this
-question:
-fn main() {
- let x;
-
- println!("The value of x is: {}", x);
-
- x = 5;
-}
-
-We can find out the answer with cargo run:
- Compiling bindings v0.1.0 (file:///projects/bindings)
-src/main.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x` [E0381]
-src/main.rs:4 println!(“The value of x is: {}”, x);
- ^
-<std macros>:2:25: 2:56 note: in this expansion of format_args!
-<std macros>:3:1: 3:54 note: in this expansion of print! (defined in <std macros>)
-src/main.rs:4:5: 4:42 note: in this expansion of println! (defined in <std macros>)
-src/main.rs:4:39: 4:40 help: run `rustc --explain E0381` to see a detailed explanation
-error: aborting due to previous error
-Could not compile `bindings`.
-
-To learn more, run the command again with --verbose.
-
-An error! The compiler won’t let us write a program like this. This is our
-first example of the compiler helping us find an error in our program.
-Different programming languages have different ways of approaching this
-problem. Some languages always initialize values with some sort of default.
-Other languages leave the value uninitialized, and make no promises about what
-happens if you try to use something before initialization. Rust chooses
-something else: error and force the programmer to explain what they want. We
-must do some sort of initialization before we can use x.
-Extended error explanations
-There’s one more interesting part of this error message:
-src/main.rs:4:39: 4:40 help: run `rustc --explain E0381` to see a detailed explanation
-
-We can see an extended explanation by passing the --explain flag to rustc.
-Not every error has a longer explanation, but many of them do. These extended
-explanations try to show off common ways that the error occurs, and common
-solutions to the issue. Here’s E0381:
-$ rustc --explain E0381
-It is not allowed to use or capture an uninitialized variable. For example:
-
-fn main() {
- let x: i32;
- let y = x; // error, use of possibly uninitialized variable
-
-To fix this, ensure that any declared variables are initialized before being
-used.
-
-These explanations can really help if you’re stuck on an error. The compiler is
-your friend, and is here to help.
-Mutable bindings
-What about changing the value of a binding? Here’s another sample program that
-asks this question:
+Then open src/main.rs and replace its code with the following:
fn main() {
let x = 5;
-
+ println!("The value of x is: {}", x);
x = 6;
-
println!("The value of x is: {}", x);
}
-cargo run has the answer for us:
+Save and run the program using cargo run, and you should receive an error
+message, as in this output:
$ cargo run
- Compiling bindings v0.1.0 (file:///projects/bindings)
-src/main.rs:4:5: 4:10 error: re-assignment of immutable variable `x` [E0384]
-src/main.rs:4 x = 6;
- ^~~~~
-src/main.rs:4:5: 4:10 help: run `rustc --explain E0384` to see a detailed explanation
-src/main.rs:2:9: 2:10 note: prior assignment occurs here
-src/main.rs:2 let x = 5;
- ^
+ Compiling bindings v0.0.1 (file:///projects/bindings)
+error: re-assignment of immutable variable `x` [--explain E0384]
+ --> src/main.rs:4:5
+4 |> x = 6;
+ |> ^^^^^
+note: prior assignment occurs here
+ --> src/main.rs:2:9
+2 |> let x = 5;
+ |> ^
-The error mentions re-assigment of immutable variable. That’s right: bindings
-are immutable. But they’re only immutable by default. In a pattern, when we’re
-creating a new name, we can add mut in front to make the binding a mutable
-one. Here’s an example:
+This is our first example of the compiler helping us find an error in our
+program! Compiler errors can be frustrating. Keep in mind that they only mean
+your program isn't safely doing what you want it to do yet; they do not mean
+that you're not a good programmer! Experienced Rustaceans still get compiler
+errors. Try to keep in mind that the Rust compiler is trying to help your
+program be the very best.
+PROD: START BOX
+######Extended Error Explanations
+Now that you've seen an example of a Rust error, let's look at one particularly
+useful aspect of errors. Rust encourages you to seek further information on the
+kind of error you've received with output like this:
+error: re-assignment of immutable variable `x` [--explain E0384]
+
+This tells us that if we pass the --explain flag to rustc with the provided
+error code, we can see an extended explanation which will try to explain common
+causes of and solutions to that kind of error. Not every error has a longer
+explanation, but many do. Here’s the explanation for the E0384 error we
+received:
+$ rustc --explain E0384
+This error occurs when an attempt is made to reassign an immutable variable.
+For example:
+
+```
+fn main(){
+ let x = 3;
+ x = 5; // error, reassignment of immutable variable
+}
+```
+
+By default, variables in Rust are immutable. To fix this error, add the keyword
+`mut` after the keyword `let` when declaring the variable. For example:
+
+```
+fn main(){
+ let mut x = 3;
+ x = 5;
+}
+```
+
+These explanations can really help if you’re stuck on an error, so don't
+hesitate to look up the error code. The compiler is your friend, and it's there
+to help.
+PROD: END BOX
+The error includes the message re-assigment of immutable variable because the
+program tried to assign a second value to the x variable.
+Getting compile-time errors when your code attempts to change a value that it
+previously said was immutable is important because this very situation can lead
+to bugs. If one part of your code operates on an assumption that a value it's
+operating on will never change, and another part of your code changes that
+value, it's possible that the first code won't do what it was designed to do.
+Especially when the second piece of code only changes the value sometimes,
+this cause of bugs can be difficult to track down after the fact.
+In Rust, our code can know that a value our code assumes won't change really
+won't change, because the compiler is enforcing that guarantee for us. When
+reading and writing code, we don't have to keep track in our head how and where
+a value might change. This can make code easier to reason about.
+Mutability is really useful, though! Bindings are immutable only by default;
+you can make them mutable by adding mut in front of the variable name. In
+addition to telling the compiler it should allow this value to be changed, it
+conveys intent to future readers of the code and says that other parts of the
+code will be changing this value.
+For example, change the program you just wrote to the following:
fn main() {
let mut x = 5;
-
println!("The value of x is: {}", x);
-
x = 6;
-
println!("The value of x is: {}", x);
}
@@ -611,611 +1296,118 @@ one. Here’s an example:
The value of x is: 5
The value of x is: 6
-We can now change the value that x binds to. Note that the syntax is not let mut exactly; it’s using mut in a pattern. This becomes more obvious with our
-() pattern:
-fn main() {
- let (mut x, y) = (5, 6);
-
- x = 7;
- y = 8;
-}
-
-The compiler will complain about this program:
-$ cargo build
- Compiling bindings v0.1.0 (file:///projects/bindings)
-src/main.rs:5:5: 5:10 error: re-assignment of immutable variable `y` [E0384]
-src/main.rs:5 y = 8;
- ^~~~~
-src/main.rs:5:5: 5:10 help: run `rustc --explain E0384` to see a detailed explanation
-src/main.rs:2:17: 2:18 note: prior assignment occurs here
-src/main.rs:2 let (mut x, y) = (5, 6);
- ^
-
-It’s fine with re-assigning x, but not y. The mut only applies to the
-name that follows it, not the whole pattern.
-Reassignment, not mutation
-There is one subtlety we haven’t covered yet: mut allows you to mutate the
-binding, but not what the binding binds to. In other words:
-fn main() {
- let mut x = 5;
-
- x = 6;
-}
-
-This is not changing the value that x is bound to, but creating a new value,
-6, and changing the binding to bind to it instead. It’s a subtle but
-important difference. Well, for now, it does not make a lot of difference, but
-when our programs get more complex, it will. Specifically, passing arguments to
-functions will illustrate the difference. We’ll talk about that in the next
-section, when we discuss functions.
-Scope
-Variable bindings have a ‘scope’ in which they’re valid. That scope begins from
-the point at which the binding is declared, and ends at the end of the next
-block of code. We can only access bindings which are ‘in scope’. We cannot
-access them ‘before they come into scope’ or ‘after they go out of scope’.
-Here’s an example:
-fn main() {
- println!("x is not yet in scope");
-
- let x = 5;
- println!("x is now in scope");
-
- println!("In real code, we’d now do a bunch of work.");
-
- println!("x will go out of scope now! The next curly brace is ending the main function.");
-}
-
-We can create arbitrary scopes through the use of { and }:
-fn main() {
- println!("x is not yet in scope");
-
- let x = 5;
- println!("x is now in scope");
-
- println!("Let’s start a new scope!");
-
- {
- let y = 5;
- println!("y is now in scope");
- println!("x is also still in scope");
-
- println!("y will go out of scope now!");
- println!("The next curly brace is ending the scope we started.");
- }
-
- println!("x is still in scope, but y is now out of scope and is not usable");
-
- println!("x will go out of scope now! The next curly brace is ending the main function.");
-}
-
-What bindings are in and out of scope will become much more important later,
-once we learn about ‘references’ and ‘traits’.
-Shadowing
-A final thing about bindings: they can ‘shadow’ previous bindings with the same
-name. Here’s a sample program:
+Using mut, we are allowed to change the value that x binds to from 5 to
+6. You might want to make a binding mutable because it makes the code easier
+to understand than an implementation that only uses immutable bindings. In
+cases where you're using large data structures, mutating an instance in place
+may be faster than copying and returning newly allocated instances. It all
+depends on the tradeoffs you want to make in your situation.
+Shadowing
+As we saw in the guessing game tutorial, we can declare new bindings with the
+same name as a previous binding, and the new binding shadows the previous
+binding. We say that the first binding is ‘shadowed’ by the second, which means
+that the second binding's value is what you will see when you use the variable
+after the second binding. This can be useful if you’d like to perform a few
+transformations on a value, but have the binding be immutable after those
+transformations have been completed. For example:
fn main() {
let x = 5;
- let x = 6;
- println!("The value of x is: {}", x);
-}
-
-Running it, we can see the shadowing in action:
-src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variables)] on by default
-src/main.rs:2 let x = 5;
- ^
- Running `target/debug/bindings`
-The value of x is: 6
-
-There are two interesting things in this output. First, Rust will compile and
-run this program, no problem. And as we can see, the value of x is 6. But
-we didn’t declare x as mutable. Instead, we declared a new binding that is
-also named x, and gave it a new value. The older value that we bound x to
-is inaccessible as soon as the new x is declared. This can be useful if you’d
-like to perform a few transformations on a value, and leave it immutable. For
-example:
-fn main() {
- let x = 5;
let x = x + 1;
+
let x = x * 2;
println!("The value of x is: {}", x);
}
-This will print:
- Compiling bindings v0.1.0 (file:///projects/bindings)
+This program first binds x to a value of 5. Then, it shadows x by saying
+let x = again, taking the original value and adding 1 so that the value of
+x is then 6. The third let statement also shadows x, taking the
+previous value and multiplying it by 2 to give x a final value of 12. If
+you run this, it will output:
+$ cargo run
+ Compiling bindings v0.1.0 (file:///projects/bindings)
Running `target/debug/bindings`
The value of x is: 12
-This lets us modify x, but not deal with mutation. This is nice because we
-know that the compiler will let us know if we try to modify it later. Let’s
-assume that after we calculate 12, we don’t want to modify x again. If we
-had written this program in a mutable style, like this:
-fn main() {
- let mut x = 5;
- x = x + 1;
- x = x * 2;
-
- println!("The value of x is: {}", x);
-
- x = 15;
-
- println!("The value of x is: {}", x);
-}
+Shadowing is useful because it lets us modify x without having to make the
+binding mutable. This means the compiler will still keep us from accidentally
+trying to mutate x directly later.
+Now let's look at some of the types of values that we can bind variables to.
+Data Types
+Every value in Rust is of a certain type, which tells Rust what kind of data
+is being given so it knows how to work with that data. In this section, we'll
+look at a number of types built into the language itself split into two subsets
+of Rust data types: scalar and compound.
+Something to keep in mind throughout this section: Rust is a statically typed
+language, which means that it must know the types of all bindings at compile
+time. The compiler can usually infer what type we want to use based on the
+value and how we use it. When many types are possible, such as when we
+converted a String to a numeric type using parse() in the guessing game
+tutorial, we can add a type annotation, like this:
+let x: i32 = 5;
-Rust is happy to let us mutate it again, to 15. A similar program in our
-immutable style will let us know about that accidental mutation, however:
-fn main() {
- let x = 5;
- let x = x + 1;
- let x = x * 2;
-
- println!("The value of x is: {}", x);
-
- x = 15;
-
- println!("The value of x is: {}", x);
-}
-
-If we try to compile, we get an error:
-$ cargo build
- Compiling bindings v0.1.0 (file:///projects/bindings)
-src/main.rs:8:5: 8:11 error: re-assignment of immutable variable `x` [E0384]
-src/main.rs:8 x = 15;
- ^~~~~~
-src/main.rs:8:5: 8:11 help: run `rustc --explain E0384` to see a detailed explanation
-src/main.rs:4:9: 4:10 note: prior assignment occurs here
-src/main.rs:4 let x = x * 2;
- ^
-error: aborting due to previous error
-Could not compile `bindings`.
-
-Exactly what we wanted.
-Shadowing can take some time to get used to, but it’s very powerful, and works
-well with immutability.
-There was one more thing we should talk about in the output from compiling our
-initial program. It’s this part:
-src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variables)] on by default
-
-Here’s the two lines of relevant code:
-let x = 5;
-let x = 6;
-
-Rust knows that we shadowed x, but we never ended up using the initial value.
-This isn’t wrong, exactly, it just may not have been what we wanted. In this
-case, the compiler issues a ‘warning’, but still compiles our program. The
-#[warn(unused_variables)] syntax is called an ‘attribute’, which we’ll
-discuss in a later section. More specifically, a warning like this is called a
-‘lint’, which is an old term for the bits of sheep’s wool that you wouldn’t
-want to put in cloth. Similarly, this lint is telling us that we may have an
-extra bit of code we don’t need. Our program would work just fine without it.
-It’s worth listening to these warnings, and fixing the problems they point out.
-They can be signs of a larger problem. In this case, we may not have realized
-that we were shadowing x.
-Shadowing and scopes
-Like any binding, a binding that shadows another binding will go away at the
-end of a scope. Here’s an example program:
-fn main() {
- let x = 5;
-
- println!("Before shadowing, x is: {}", x);
-
- {
- let x = 6;
-
- println!("Now that x is shadowed, x is: {}", x);
- }
-
- println!("After shadowing, x is: {}", x);
-}
-
-If we run this example, we can see the shadow appear and disappear:
-$ cargo run
- Compiling bindings v0.1.0 (file:///projects/bindings)
- Running `target/debug/bindings`
-Before shadowing, x is: 5
-Now that x is shadowed, x is: 6
-After shadowing, x is: 5
-
-Functions
-Functions are pervasive in Rust code. We’ve already seen the most important
-function, main(), in previous sections of the book:
-fn main() {
- println!("Hello, world!");
-}
-
-We can declare new functions with the fn keyword:
-fn another_function() {
- println!("Another function.");
-}
-
-Rust code uses snake_case as a style for function names: all lower case, with
-underscores separating words. (It also uses them for variable names, too.) We
-can call any function we’ve defined by using its name and some parentheses:
-fn main() {
- println!("Hello, world!");
-
- another_function();
-}
-
-fn another_function() {
- println!("Another function.");
-}
-
-Let’s start a new project to explore functions. Open a terminal, and navigate
-to the directory where you’d like to keep your projects. From there, use Cargo
-to generate a new project:
-$ cargo new --bin functions
-$ cd functions
-
-Place the new example in src/main.rs, and run it:
-$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
- Running `target/debug/functions`
-Hello, world!
-Another function.
-
-As we can see, the lines execute in order: first, we print out our “Hello,
-world!” message, and then another_function() is called. It then prints its
-message as well.
-Function Arguments
-Functions can also take arguments:
-fn main() {
- another_function(5);
-}
-
-fn another_function(x: i32) {
- println!("The value of x is: {}", x);
-}
-
-Let’s try running it:
-$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
- Running `target/debug/functions`
-The value of x is: 5
-
-Let’s take a closer look at another_function()’s signature:
-fn another_function(x: i32) {
-
-Declaring a function which takes a single argument looks like this:
-fn NAME(PATTERN: TYPE) {
-
-That’s right, patterns appear again. Consider how the parameter declaration
-here looks like the let bindings we used earlier:
-let x: i32;
-fn another_function(x: i32) {
-
-There’s only one difference here: in function signatures, we must declare the
-type. This is a deliberate decision; we find that requiring type annotations in
-functions means that you almost never need them anywhere else.
-You can separate multiple arguments with a comma:
-fn NAME(PATTERN: TYPE, PATTERN: TYPE, PATTERN: TYPE, PATTERN: TYPE...) {
-
-Here’s a full example:
-fn main() {
- another_function(5, 6);
-}
-
-fn another_function(x: i32, y: i32) {
- println!("The value of x is: {}", x);
- println!("The value of y is: {}", y);
-}
-
-Let’s try it:
-$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
- Running `target/debug/functions`
-The value of x is: 5
-The value of y is: 6
-
-We could also create bindings, and pass them in as arguments:
-fn main() {
- let a = 5;
- let b = 6;
-
- another_function(a, b);
-}
-
-fn another_function(x: i32, y: i32) {
- println!("The value of x is: {}", x);
- println!("The value of y is: {}", y);
-}
-
-This has the same effect:
-$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
- Running `target/debug/functions`
-The value of x is: 5
-The value of y is: 6
-
-Note that our bindings are called a and b, yet inside of the function, we
-refer to them by the names in the signature, x and y. Inside a function,
-only its parameters are in scope, so we need to use those names. Bindings
-passed as parameters don’t need to have the same name as the arguments.
-Return values
-Functions can also return values back to the function that called them:
-fn NAME(PATTERN: TYPE, PATTERN: TYPE, PATTERN: TYPE, PATTERN: TYPE...) -> TYPE {
-
-We don’t name return values, but we do declare their type, after an arrow:
-->. Here’s a sample program:
-fn main() {
- let x = five();
-
- println!("The value of x is: {}", x);
-}
-
-fn five() -> i32 {
- 5
-}
-
-Let’s try running it:
-$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
- Running `target/debug/functions`
-The value of x is: 5
-
-Let’s examine this in more detail. There are two important bits. First, we can
-use the return value of a function to initialize a binding:
-let x = five();
-
-Because five() returns a 5, this is the same as:
-let x = 5;
-
-The second interesting bit is five() itself:
-fn five() -> i32 {
- 5
-}
-
-We have no arguments, and our return type, i32. However, the body of this
-function is a lonely 5. There’s a detail here that you may or may not have
-noticed: we’ve ended almost every line in our programs with a semicolon.
-There’s no semicolon here, though. Why not?
-The answer to this question is:
-
-The return value of a function is the value of its final expression.
-
-We haven’t talked about expressions yet, so this definition doesn’t help a lot.
-Let’s go over that now.
-Statements and Expressions
-Expressions are bits of code that evaluate to a value. Consider some math
-operations, like this:
-5 + 6
-
-We can evaluate this expression, and come up with a value: 11. In Rust, most
-bits of code are expressions. For example, calling a function is an expression:
-foo(5)
-
-The value is equal to whatever the return value of foo() is.
-So why does this matter? Well, not everything is an expression. Some things are
-‘statements’. Expressions compute something, but statements bind or do
-something. It’s a subtle difference. We’ve already seen two kinds of
-statements: let statements, and fn declarations.
-Because let is a statement, not an expression, you can’t assign it to another
-binding. Here’s an example that doesn’t work:
-fn main() {
- let x = (let y = 6);
-}
-
-If we try to run this program, we’ll get an error:
-$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
-src/main.rs:2:14: 2:17 error: expected identifier, found keyword `let`
-src/main.rs:2 let x = (let y = 6);
- ^~~
-src/main.rs:2:18: 2:19 error: expected one of `!`, `)`, `,`, `.`, `::`, `{`, or an operator, found `y`
-src/main.rs:2 let x = (let y = 6);
- ^
-Could not compile `functions`.
-
-We also cannot somehow assign a fn declaration to a binding, either.
-So what’s this have to do with return values? Well, {}, a ‘block’ that we
-used earlier to create new scopes, is an expression. Let’s take a closer look
-at {}. It looks like this:
-{
- STATEMENT*
- EXPRESSION
-}
-
-The * there means ‘zero or more’, so we can have any number of statements
-followed by an expression. Since blocks are expressions themselves, we can nest
-blocks inside of blocks. And since they return a value, we can use them in
-let statements:
-fn main() {
- let x = 5;
-
- let y = {
- let z = 1;
-
- x + z + 5
- };
-
- println!("The value of y is: {}", y);
-}
-
-Let’s try running this program:
- Compiling functions v0.1.0 (file:///projects/functions)
- Running `target/debug/functions`
-The value of y is: 11
-
-We’re now using a block to give us a value for y:
-let y = {
-
-};
-
-Since the block can contain statements, we create a new variable binding, z,
-and give it a value. We then do some math for the final expression of the
-block:
-{
- let z = 1;
-
- x + z + 5
-}
-
-5 + 1 + 5 is 11, and so the value of the entire block is 11. This gets
-substituted into our let statement for y:
-let y = 11;
-
-Hence our output saying y is 11.
-Where else do we use blocks? As the body of functions! They’re very similar:
-fn main() {
- let x = 5;
-
- let y = {
- x + 1
- };
-
- println!("The value of y is: {}", y);
-
- let y = plus_one(x);
-
- println!("The value of y is: {}", y);
-}
-
-fn plus_one(x: i32) -> i32 {
- x + 1
-}
-
-Running this gives:
-$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
- Running `target/debug/functions`
-The value of y is: 6
-The value of y is: 6
-
-In both cases, we use a block to produce a value. In the first case, it’s
-assigning with let:
-let y = {
-
-In the second, it’s the return value of the function:
-fn plus_one(x: i32) -> i32 {
-
-Expression statements
-There’s one more detail about expressions and statements: a semicolon takes any
-expression, and turns it into a statement. Let’s accidentally cause an error
-with plus_one():
-fn main() {
- let x = plus_one(5);
-
- println!("The value of x is: {}", x);
-}
-
-fn plus_one(x: i32) -> i32 {
- x + 1;
-}
-
-Instead of an expression, x + 1, we’ve now turned it into a statement,
-x + 1;.
-Running this gives an error:
-$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
-src/main.rs:7:1: 9:2 error: not all control paths return a value [E0269]
-src/main.rs:7 fn plus_one(x: i32) -> i32 {
-src/main.rs:8 x + 1;
-src/main.rs:9 }
-src/main.rs:7:1: 9:2 help: run `rustc --explain E0269` to see a detailed explanation
-src/main.rs:8:10: 8:11 help: consider removing this semicolon:
-src/main.rs:8 x + 1;
- ^
-error: aborting due to previous error
-Could not compile `functions`.
-
-Rust has our back here: it even suggests removing the semicolon, which fixes
-the error. But the main error message is the core of the issue: statements
-don’t evaluate to a value, yet we want to return an i32.
-In practice, Rust programmers don’t often think about these rules at this
-level. Usually, you have a semicolon at the end of most lines, and maybe not at
-the end of blocks.
-Multiple return values
-Functions cannot directly return multiple values. There’s a trick, however.
-Remember the ()s we used when showing off complex bindings?
-fn main() {
- let (x, y) = (5, 6);
-}
-
-They form something called a ‘tuple’, one of Rust’s basic types. A tuple is an
-anonymous collection of elements. But since a tuple is a singular thing, we can
-use it as a way to return multiple values from functions:
-fn main() {
- let (x, y) = two_numbers();
-
- println!("The value of x is: {}", x);
- println!("The value of y is: {}", y);
-}
-
-fn two_numbers() -> (i32, i32) {
- (5, 6)
-}
-
-Running this will show us the values:
-$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
- Running `target/debug/functions`
-The value of x is: 5
-The value of y is: 6
-
-There are two interesting changes here: assigning the return value of
-two_numbers() to x and y, and the declaration of two_numbers() itself.
-Let’s look at the declaration first:
-fn two_numbers() -> (i32, i32) {
- (5, 6)
-}
-
-The (i32, i32) should look familiar. We saw it in let bindings earlier:
-let (x, y): (i32, i32) = (5, 6);
-
-The (i32, i32) syntax says “a tuple with two i32s in it.” The (5, 6)
-syntax creates a new one, with 5 and 6.
-This tuple is then returned, and assigned to x and y:
-let (x, y) = two_numbers();
-
-See how all these bits fit together?
-We call this behavior of let ‘destructuring’, because it takes the structure
-of the expression that comes after the = and takes it apart.
-Scalar Types
-We’ve seen that every value in Rust has a type of some kind. There are a number
-of types which are built into the language itself. First, we’ll take a look at
-‘scalar’ types, that is, types which represent a single value.
-Remember, you can rely on type inference to figure out the type of a binding,
-or you can annotate it explicitly:
-fn main() {
- let x: i32 = 5;
-}
-
-Integers
-You’ve already seen one primitive type: i32. There are a number of built-in
-number types in Rust.
-Here’s a chart of Rust’s integer types:
- signed unsigned
- 8-bit i8 u8
+You will see some type annotations as we discuss the various data types.
+Scalar Types
+A scalar type is one that represents a single value. There are four key
+scalar types in Rust: integers, floating point numbers, booleans, and
+characters. You'll likely recognize these from other programming languages, but
+let's jump into how they work in Rust.
+Integer Types
+An integer is a number without a fractional component. We've used one integer
+type already in this chapter, the i32 type. This type declaration indicates
+that the value it's associated with should be a signed integer (hence the i,
+as opposed to a u for unsigned) for a 32-bit system. There are a number of
+built-in integer types in Rust, shown in Table 3-1.
+ Length signed unsigned
+ 8-bit i8 u8
16-bit i16 u16
32-bit i32 u32
64-bit i64 u64
arch isize usize
-We have both signed and unsigned variants of numbers, and each variant has an
-explicit size. Unsigned numbers are never negative, and signed numbers can be
-positive or negative. (Think ‘plus sign’ or ‘minus sign’: that’s a signed
-number.) Signed numbers are stored using ‘two’s complement’ representation.
-Finally, isize and usize are different sizes based on the kind of computer
-your program is running on. If you are on a 64-bit architecture, they are 64
-bits, and if you’re on a 32-bit one, they’re 32 bits.
-So how do you choose from all these options? Well, if you really don’t know,
-the defaults are a good choice: integer types default to i32. The primary use
-case for isize/usize is when indexing some sort of collection. We’ll talk
-more about our first collection, arrays, in just a moment.
-Floating-point numbers
-Rust also has two primitive floating-point numbers: f32 and f64. They are
-32 bits and 64 bits in size, respectively. The default is f64.
+Table 4-1: Integer types in Rust. Each code (for example, i32) can be used to
+declare the type of a value.
+Each variant can be either signed or unsigned and has an explicit size. Signed
+and unsigned merely refers to whether it is possible for the number to be
+either negative or positive, meaning the number needs to have a sign with it
+("signed"), or whether it will only ever be positive and can therefore be
+represented without a sign ("unsigned"). It's like writing numbers on paper:
+when the sign matters, a number is shown with a plus sign or minus sign, but
+when it's safe to assume the number is positive, it's shown with no sign.
+Signed numbers are stored using two’s complement representation (if you're
+unsure what this is you can search for it online; an explanation is outside the
+scope of this text).
+Finally, the isize and usize types depend on the kind of computer your
+program is running on: 64-bits if you're on a 64-bit architecture, and 32-bits
+if you’re on a 32-bit architecture.
+So how do you know which type of integer to use? If you're unsure, Rust's
+defaults are generally good choices, and integer types default to i32: it’s
+generally the fastest, even on 64-bit systems. The primary situation in which
+you'd need to specify isize or usize is when indexing some sort of
+collection, which we'll talk about in the "Arrays" section.
+Floating-Point Types
+Rust also has two primitive types for floating-point numbers, which are
+numbers with decimal points. Rust's floating-point types are f32 and f64,
+which are 32 bits and 64 bits in size, respectively. The default type is f64,
+as it’s roughly the same speed as f32, but has a larger precision. It is
+possible to use an f64 on 32 bit systems, but it will be slower than using an
+f32 on those systems. Most of the time, trading potential worse performance
+for better precision is a reasonable initial choice, and you should benchmark
+your code if you suspect floating-point size is a problem in your case.
+Here's an example showing floating-point numbers in action:
fn main() {
let x = 2.0; // f64
let y: f32 = 3.0; // f32
}
-Floating-point numbers are represented according to the IEEE-754 standard.
-f32 is a single-precision float, f64 is double-precision.
-Numeric operations
-Rust supports the usual operations you’d expect on all of these number types:
+Floating-point numbers are represented according to the IEEE-754 standard. The
+f32 type is a single-precision float, while f64 has double-precision.
+Numeric Operations
+Rust supports the usual basic mathematic operations you’d expect for all of
+these number types: addition, subtraction, multiplication, division, and
+modulo. This code shows how you'd use each one in a let statement:
fn main() {
// addition
let sum = 5 + 10;
@@ -1229,96 +1421,111 @@ more about our first collection, arrays, in just a moment.
// division
let quotient = 56.7 / 32.2;
- // modulus
+ // modulo
let remainder = 43 % 5;
}
-Booleans
-Somewhat fundamental to all computing, Rust has a boolean type, bool, with
-two possible values:
+Each expression in these statements uses a mathematical operator and evaluates
+to a single value, which is then bound to a variable.
+The Boolean Type
+As in most other programming languages, a boolean type in Rust has two possible
+values: true and false. The boolean type in Rust is specified with bool.
+For example:
fn main() {
let t = true;
+
let f: bool = false; // with explicit type annotation
}
-The main way to consume boolean values is through conditionals like if, which
-we’ll see later in the chapter.
-Characters
-We’ve only worked with numbers so far, but what about letters? Rust’s most
-primitive alphabetic type is the char:
+The main way to consume boolean values is through conditionals like an if
+statement. We’ll cover how if statements work in Rust in the "Control Flow"
+section of this chapter.
+The Character Type
+So far we’ve only worked with numbers, but Rust supports letters too. Rust’s
+char type is the language's most primitive alphabetic type, and this code
+shows one way to use it:
fn main() {
let c = 'z';
let z = 'ℤ';
+ let heart_eyed_cat = '😻';
}
-Rust’s char represents a Unicode Scalar Value, which means that it can
-represent a lot more than just ASCII. ‘Character’ isn’t really a concept in
-Unicode, however: your human intuition for what a ‘character’ is may not match
-up with a char. It also means that chars are four bytes each.
-Compound Types
-Now that we’ve discussed scalar types, let’s talk about compound types.
-These types can group multiple values of scalar types into another type.
-Tuples
-We’ve seen tuples before, in the guise of binding or returning multiple values
-at once. It turns out that there’s no magic here: tuples are a general way of
-making a compound value that groups some number of other values with distinct
-types. The number of values grouped is the ‘arity’ of the tuple.
+Rust’s char represents a Unicode Scalar Value, which means that it can
+represent a lot more than just ASCII. Accented letters, Chinese/Japanese/Korean
+ideographs, emoji, and zero width spaces are all valid chars in Rust. Unicode
+Scalar Values range from U+0000 to U+D7FF and U+E000 to U+10FFFF
+inclusive. A "character" isn’t really a concept in Unicode, however, so your
+human intuition for what a "character" is may not match up with what a char
+is in Rust. It also means that chars are four bytes each. You can learn more
+about Unicode Scalar Values at
+http://www.unicode.org/glossary/#unicode_scalar_value and find a chart for
+all unicode code points at http://www.unicode.org/charts/.
+Compound Types
+Compound types can group multiple values of other types into one type. Rust
+has two primitive compound types: tuples and arrays.
+Grouping Values into Tuples
+We’ve seen tuples already, when binding multiple values at once. A tuple is a
+general way of grouping together some number of other values with distinct
+types into one compound type.
We create a tuple by writing a comma-separated list of values inside
-parentheses; each position in the tuple has a distinct type:
+parentheses. Each position in the tuple has a distinct type, as in this example:
fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
}
-Note that, unlike the examples of multiple bindings, here we bound the
-single name tup to the entire tuple. We can then use pattern
-matching to destructure this tuple value:
+Note that, unlike the examples of multiple bindings, here we bind the single
+name tup to the entire tuple, emphasizing the fact that a tuple is considered
+a single compound element. We could then use pattern matching to destructure
+this tuple value, like this:
fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
+
let (x, y, z) = tup;
println!("The value of y is: {}", y);
}
-Tuples are used sparingly in Rust code. This is because the elements of a tuple
-are anonymous, which can make code hard to read.
-Tuple indexing
+In this program, we first create a tuple and bind it to the name tup. We then
+use a pattern with let to take tup and turn it into three separate
+bindings, x, y, and z. This is called ‘destructuring’, because it breaks
+the single tuple into three parts.
+Finally, we print the value of y, which is 6.4.
+Tuple Indexing
In addition to destructuring through pattern matching, we can also access a
-tuple element directly using ., followed by the index we want to access:
+tuple element directly by using a period (.) followed by the index of the
+value we want to access. For example:
fn main() {
let x: (i32, f64, u8) = (500, 6.4, 1);
let five_hundred = x.0;
+
let six_point_four = x.1;
+
let one = x.2;
}
-As you can see, the first index is 0.
-Single-element tuples
-There’s one last trick with tuples: (5) is actually ambiguous: is it a tuple,
-or is it a 5 in parenthesis? If you need to disambiguate, use a comma:
-fn main() {
- let x = (5); // x is an i32, no tuple. Think of it like (5 + 1) without the + 1, they’re for grouping.
-
- let x = (5,); // x is a (i32), a tuple with one element.
-}
-
-Arrays
-So far, we’ve only represented single values in a binding. Sometimes, though,
-it’s useful to have more than one value. These kinds of data structures are
-called ‘collections’, and arrays are the ones we’ll learn about first. Arrays
-look like this:
+This program creates a tuple, x, and then makes new bindings to each element
+by using their index. As with most programming languages, the first index in a
+tuple is 0.
+Arrays
+Another way to bind a name to a collection of multiple values is with an
+array. Unlike a tuple, every element of an array must have the same type.
+Arrays in Rust are different than arrays in some other languages because arrays
+in Rust have a fixed length-- once declared, they cannot grow or shrink in size.
+In Rust, the values going into an array are written as a comma separated list
+inside square brackets:
fn main() {
let a = [1, 2, 3, 4, 5];
}
-An array’s type consists of the type of the elements it contains, as well as
-the length:
-fn main() {
- let a: [i32; 5] = [1, 2, 3, 4, 5];
-}
-
-An array is a single chunk of memory, allocated on the stack.
-We can access elements of an array using indexing:
+While arrays can be useful since they are a primitive type, they aren't as
+flexible as the Vec (short for "vector"), a similar collection type provided
+by the standard library that is allowed to grow or shrink in size. If you're
+unsure whether to use an array or a Vec, you should probably go with a Vec,
+and we'll discuss them in more detail in chapter XX.
+Accessing Array Elements
+An array is a single chunk of memory, allocated on the stack. We can access
+elements of an array using indexing, like this:
fn main() {
let a = [1, 2, 3, 4, 5];
@@ -1326,219 +1533,409 @@ the length:
let second = a[1];
}
-In this example, first will hold the value 1, and second will be bound to
-2. Note that these values are copied out of the array; if the array changes,
-these bindings will not. Here’s an example, which also shows us how we can
-modify elements of the array:
-fn main() {
- let mut a = [1, 2, 3, 4, 5];
-
- let first = a[0];
-
- a[0] = 7;
-
- println!("The value of first is: {}", first);
-}
-
-Running this example will show that first is still 1. If we didn’t want a
-copy, but instead wanted to refer to the first element, whatever its value was,
-we need a new concept. We’ll talk about ‘references’ in Section 4.
-One last thing: now that we are modifying the array, a needs to be declared
-mut.
-Arrays are our first real data structure, and so there’s a few other concepts
-that we haven’t covered in full yet. There are two: the panic! macro, and a
-new way of printing things: Debug.
-Panic
-We showed what happens when you access elements of an array, but what if we
-give an invalid index?
-fn main() {
- let a = [1, 2, 3, 4, 5];
-
- let invalid = a[10];
-
- println!("The value of invalid is: {}", invalid);
-}
-
-If we run this example, we will get an error. Let’s re-use our functions
-project from before. Change your src/main.rs to look like the example, and
-run it:
-$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
- Running `target/debug/functions`
-thread ‘<main>’ panicked at ‘index out of bounds: the len is 5 but the index is 10’, src/main.rs:4
-Process didn’t exit successfully: `target/debug/functions` (exit code: 101)
-
-It says that our thread panicked, and that our program didn’t exit
-successfully. There’s also a reason: we had a length of five, but an index of
-
-
-
-For now, all you need to know is that a panic will crash your program. Rust’s
-error handling story is described in full in a later chapter.
-So why did this code panic? Well, arrays know how many elements they hold. When
-we access an element via indexing, Rust will check that the index is less than
-the length. If it’s greater, it will panic, as something is very wrong. This is
-our first example of Rust’s safety principles in action. In many low-level
-languages, this kind of check is not done. If you have an incorrect index,
-invalid memory can be accessed. Rust protects us against this kind of error.
-Debug
-So far, we’ve been printing values using {}. If we try that with an array,
-though...
+In this example, the first variable will bind to 1 at index [0] in the
+array, and second will bind to 2 at index [1] in the array. Note that
+these values are copied out of the array and into first and second when the
+let statement is called. That means if the array changes after the let
+statements, these bindings will not, and the two variables should retain their
+values.
+Invalid array element access
+What happens if you try to access an element of an array past the end of the
+array? Say we changed our program to:
fn main() {
let a = [1, 2, 3, 4, 5];
- println!("a is: {}", a);
-}
-
-... we will get an error:
-$ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
-src/main.rs:4:25: 4:26 error: the trait `core::fmt::Display` is not implemented for the type `[_; 5]` [E0277]
-src/main.rs:4 println!(“a is {}”, a);
- ^
-<std macros>:2:25: 2:56 note: in this expansion of format_args!
-<std macros>:3:1: 3:54 note: in this expansion of print! (defined in <std macros>)
-src/main.rs:4:5: 4:28 note: in this expansion of println! (defined in <std macros>)
-src/main.rs:4:25: 4:26 help: run `rustc --explain E0277` to see a detailed explanation
-src/main.rs:4:25: 4:26 note: `[_; 5]` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string
-src/main.rs:4:25: 4:26 note: required by `core::fmt::Display::fmt`
-error: aborting due to previous error
-
-Whew! The core of the error is this part: the trait core::fmt::Display is not
-implemented. We haven’t discussed traits yet, so this is bound to be confusing!
-Here’s all we need to know for now: println! can do many kinds of formatting.
-By default, {} implements a kind of formatting known as Display: output
-intended for direct end-user consumption. The primitive types we’ve seen so far
-implement Display, as there’s only one way you’d show a 1 to a user. But
-with arrays, the output is less clear. Do you want commas or not? What about
-the []s?
-Due to these questions, more complex types in the standard library do not
-implement Display formatting. There is another kind of formatting, Debug,
-which is a bit different: intended for programmer consumption. We can ask
-println! to use Debug formatting with :?:
-fn main() {
- let a = [1, 2, 3, 4, 5];
+ let element = a[10];
- println!("a is {:?}", a);
+ println!("The value of element is: {}", element);
}
-This will work:
+Running this code with cargo run produces:
+$ cargo run
+ Compiling arrays v0.1.0 (file:///projects/arrays)
+ Running `target/debug/arrays`
+thread '<main>' panicked at 'index out of bounds: the len is 5 but the index is 10', src/main.rs:4
+note: Run with `RUST_BACKTRACE=1` for a backtrace.
+error: Process didn't exit successfully: `target/debug/arrays` (exit code: 101)
+
+We can see that compiling did not give us any errors, but we got a runtime
+error and our program didn't exit successfully. When we attempt to access an
+element using indexing, Rust will check that the index we've specified is less
+than the array length. If the index is greater than the length, it will
+"panic", which is what it's called when a Rust program exits with an error.
+This is our first example of Rust’s safety principles in action. In many
+low-level languages, this kind of check is not done, and when you provide an
+incorrect index, invalid memory can be accessed. Rust protects us against this
+kind of error by immediately exiting instead of allowing the memory access and
+continuing. We'll discuss more of Rust’s error handling in Chapter XX.
+How Functions Work
+Functions are pervasive in Rust code. We’ve already seen one of the most
+important functions in the language: the main() function that’s the entry
+point of many programs. We've also seen the fn keyword, which allows us to
+declare new functions.
+Rust code uses snake case as the conventional style for function names. In
+snake case, all letters are lower case, and there are underscores separating
+words. (Rust also uses snake case for the names of variable bindings; we just
+haven't used any variable bindings with enough letters to need underscores
+yet). Here's a program containing an example function definition:
+fn main() {
+ println!("Hello, world!");
+
+ another_function();
+}
+
+fn another_function() {
+ println!("Another function.");
+}
+
+Function definitions in Rust start with fn and have a set of parentheses
+after the function name. The curly braces tell the compiler where the function
+body begins and ends.
+We can call any function we’ve defined by entering its name followed by a pair
+of parentheses. Since another_function() is defined in the program, it can be
+called from inside the main() function. Note that we defined
+another_function() after the main() function in our source code; we could
+have defined it before as well. Rust doesn’t care where you define your
+functions, only that they are defined somewhere.
+Let’s start a new project to explore functions further. Open a terminal, and
+navigate to the directory you're keeping your projects in. From there, use
+Cargo to generate a new project, as follows:
+$ cargo new --bin functions
+$ cd functions
+
+Place the another_function() example in a file named src/main.rs and run
+it. You should see the following output:
$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Running `target/debug/functions`
-a is [1, 2, 3, 4, 5]
+Hello, world!
+Another function.
-You’ll see this repeated later, with other types. And we’ll cover traits fully
-later in the book, Section 9.
-Comments
-We strive to make our programs easy to understand, but sometimes, some extra
-explanation is warranted. We can leave notes in our source code that the
-compiler will ignore. These notes are called ‘comments’.
-Here’s a comment:
+The lines execute in the order they appear in the main() function. First, our
+“Hello, world!” message prints, and then another_function() is called and its
+message is printed.
+Function Arguments
+Functions can also take arguments. The following rewritten version of
+another_function() shows what arguments look like in Rust:
+fn main() {
+ another_function(5);
+}
+
+fn another_function(x: i32) {
+ println!("The value of x is: {}", x);
+}
+
+Try running this program, and you should get this output:
+$ cargo run
+ Compiling functions v0.1.0 (file:///projects/functions)
+ Running `target/debug/functions`
+The value of x is: 5
+
+Since we passed 5 to another_function(), the println! macro put 5 where
+the pair of curly braces were in the format string. The declaration of
+another_function() shows that it takes one argument named x, and the type
+of x is i32.
+In function signatures, we must declare the type. This is a deliberate
+decision in the design of Rust; requiring type annotations in function
+definitions means the compiler almost never needs you to use them elsewhere in
+the code in order to figure out what you mean.
+When you want a function to have multiple arguments, just separate them inside
+the function signature with commas, like this:
+fn main() {
+ another_function(5, 6);
+}
+
+fn another_function(x: i32, y: i32) {
+ println!("The value of x is: {}", x);
+ println!("The value of y is: {}", y);
+}
+
+In this example, we make a function with two arguments, both of which are
+i32s. If your function has multiple arguments, they don’t need to be the same
+type, but they just happen to be in this example. Our function then prints out
+the values of both of its arguments.
+Let’s try out this code. Replace the program currently in your function
+project's main.rs file with the example above, and run it as follows:
+$ cargo run
+ Compiling functions v0.1.0 (file:///projects/functions)
+ Running `target/debug/functions`
+The value of x is: 5
+The value of y is: 6
+
+Since 5 is passed as the x argument and 6 is passed as the y argument,
+the two strings are printed with these values.
+Function Bodies
+Function bodies are made up of a series of statements ending in an optional
+expression. So far, we've only seen functions without an ending expression, but
+we have seen expressions as parts of statements. Since Rust is an
+expression-based language, this is an important distinction to understand.
+Other languages don't have the same distinctions, so let's look at what
+statements and expressions are and how their differences affect the bodies of
+functions.
+Statements and Expressions
+We've already been using both statements and expressions. Statements are
+instructions that perform some action and do not return a value. Expressions
+evaluate to a resulting value. Let's look at some examples.
+Let bindings are statements. They instruct the program to create a binding
+name and assign a value to it. let y = 6; in this example is a statement:
+fn main() {
+ let y = 6;
+}
+
+Function definitions are also statements-- so the entire previous example is a
+statement as well.
+Statements do not return values themselves. Therefore, you can’t assign a let
+binding to another binding, as this code tries to do:
+fn main() {
+ let x = (let y = 6);
+}
+
+If we were to run this program, we’d get an error like this:
+$ cargo run
+ Compiling functions v0.1.0 (file:///projects/functions)
+error: expected expression, found statement (`let`)
+ --> src/main.rs:2:14
+2 |> let x = (let y = 6);
+ |> ^^^
+note: variable declaration using `let` is a statement
+
+error: aborting due to previous error
+error: Could not compile `functions`.
+
+The let y = 6 statement does not return a value, so there isn't anything for
+x to bind to. This is different than in other languages like C and Ruby where
+the assignment returns the value of the assignment. In those languages, you
+could write x = y = 6 and have both x and y have the value 6, but that
+is not the case in Rust.
+Expressions are most of the rest of the code that you will write in Rust.
+Consider a simple math operation, like this:
+5 + 6
+
+This is an expression, and evaluating it results in the value 11. Expressions
+can be part of statements-- in the previous example that had the statement let y = 6;, 6 is an expression that evaluates to the value 6. Calling a
+function is an expression. Calling a macro is an expression. The block that we
+use to create new scopes, {}, is an expression, for example:
+fn main() {
+ let x = 5;
+
+ let y = {
+ let x = 3;
+ x + 1
+ };
+
+ println!("The value of y is: {}", y);
+}
+
+The expression:
+{
+ let x = 3;
+ x + 1
+}
+
+is a block that, in this case, gets evaluated to 4, which then gets bound to
+y as part of the let statement.
+Note that the line containing x + 1 does not have a semicolon at the end like
+most of the lines we've seen up until now have had. This is the most important
+distinction between expressions and statements to remember: statements end in
+semicolons while expressions do not. If you add a semicolon to the end of an
+expression, that will turn it into a statement, which will then not return a
+value. Keep this in mind as we explore function return values and expressions.
+Functions with Return Values
+Functions can return values back to the code that calls them. We don’t name
+return values, but we do declare their type, after an arrow (->). In Rust,
+the "return value of the function” is synonymous with “the value of the final
+expression in the block of the body of a function.” Here's an example of a
+function that returns a value:
+fn five() -> i32 {
+ 5
+}
+
+fn main() {
+ let x = five();
+
+ println!("The value of x is: {}", x);
+}
+
+There are no function calls, macros, or even let statements in the five()
+function-- just the number 5 by itself. That's a perfectly valid function in
+Rust. Note the function's return type, too. Try running this code, and the
+output should look like this:
+$ cargo run
+ Compiling functions v0.1.0 (file:///projects/functions)
+ Running `target/debug/functions`
+The value of x is: 5
+
+The 5 in five() is actually the function's return value, which is why the
+return type is i32. Let’s examine this in more detail. There are two
+important bits. First, the line let x = five(); in main() shows that we can
+use the return value of a function to initialize a binding.
+Because the function five() returns a 5, that line is the same as saying:
+let x = 5;
+
+The second interesting bit is the five() function itself. It requires no
+arguments and defines the type of the return value, but the body of the
+function is a lonely 5 with no semicolon because it is an expression whose
+value we want to return. Let's look at another example:
+fn main() {
+ let x = plus_one(5);
+
+ println!("The value of x is: {}", x);
+}
+
+fn plus_one(x: i32) -> i32 {
+ x + 1
+}
+
+Running this code will print The value of x is: 6. What happens if we put a
+semicolon at the end of the line containing x + 1, changing it from an
+expression to a statement?
+fn main() {
+ let x = plus_one(5);
+
+ println!("The value of x is: {}", x);
+}
+
+fn plus_one(x: i32) -> i32 {
+ x + 1;
+}
+
+Running this code gives an error, as follows:
+$ cargo run
+ Compiling functions v0.1.0 (file:///projects/functions)
+error: not all control paths return a value [--explain E0269]
+ --> src/main.rs:7:1
+7 |> fn plus_one(x: i32) -> i32 {
+ |> ^
+help: consider removing this semicolon:
+ --> src/main.rs:8:10
+8 |> x + 1;
+ |> ^
+
+error: aborting due to previous error
+error: Could not compile `functions`.
+
+The main error message, "not all control paths return a value", reveals the
+core of the issue with this code. The definition of the function plus_one
+says that it will return an i32, but statements don’t evaluate to a value.
+Therefore, nothing is returned, which contradicts the function definition and
+results in an error. In this output, Rust gives an option to rectify this: it
+suggests removing the semicolon, which would fix the error.
+Comments
+All programmers strive to make their code easy to understand, but sometimes
+extra explanation is warranted. In these cases, we leave notes in our source
+code that the compiler will ignore but people reading the source code may find
+useful. These notes are called comments.
+Here’s a simple comment:
// Hello, world.
-Comments start with two slashes, and last until the end of the line. Larger
-comments will need more lines:
+In Rust, comments must start with two slashes and will last until the end of
+the line. For comments that extend beyond a single line, you'll need to
+include // on each line, like this:
// So we’re doing something complicated here, long enough that we need
// multiple lines of comments to do it! Whew! Hopefully, this comment will
// explain what’s going on.
-Comments can also go at the end of lines:
+Comments can also be placed at the end of lines of code:
fn main() {
let lucky_number = 7; // I’m feeling lucky today.
}
-But you’ll more often see them above:
+But you’ll more often see them above, like so:
fn main() {
// I’m feeling lucky today.
let lucky_number = 7;
}
That’s all there is to it. Comments are not particularly complicated.
-Control flow with if
-
-Two roads diverged in a yellow wood,
-And sorry I could not travel both
-And be one traveler, long I stood
-And looked down one as far as I could
-To where it bent in the undergrowth;
-
-- Robert Frost, “The Road Not Taken”
-
-
-In Rust, there are a few ways to cause our code to branch. The most fundamental
-way is by using if. An if expression gives us two paths forward, and asks
-the question, “Which one should I take?”
+Control Flow
+Deciding whether or not to run some code depending on if a condition is true,
+or deciding to run some code repeatedly while a condition is true, are basic
+building blocks in most programming languages. The most common constructs that
+let us control the flow of execution of our Rust code are if expressions and
+loops.
+if Expressions
+An if expression allows us to branch our code depending on conditions. We
+provide a condition and then say, "If this condition is met, then run this
+block of code. If the condition is not met, do not run this block of code."
Let’s make a new project to explore if. Navigate to your projects directory,
and use Cargo to make a new project called branches:
$ cargo new --bin branches
$ cd branches
-Here’s a sample program using if:
+Write this sample program using if and save it in the branches directory in
+src/main.rs:
fn main() {
- let condition = true;
+ let number = 3;
- if condition {
+ if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
}
-Let's try running it:
+All if expressions start with if, which is followed by a condition. In this
+case, our condition is checking if our variable binding number has a value
+that is less than 5. The block of code we want to execute if the condition is
+true goes immediately after the condition, inside curly braces. These blocks
+are sometimes called ‘arms’. We can optionally also include an else
+statement, which we have chosen to do here. else gives the program a block of
+code to execute should condition evaluate to false.
+Try running this code, and you should see output like this:
$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Running `target/debug/branches`
condition was true
-We can change the value of condition:
- let condition = false;
+Let’s try changing the value of number to a value that makes the condition
+false to see what happens:
+let number = 7;
-And then run it again:
+Run the program again, and look at the output:
$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Running `target/debug/branches`
condition was false
-This is the very basic structure of if: if the condition is true, then
-execute some code. If it’s not true, then execute some other code, after
-else.
-An else is not required:
-fn main() {
- let condition = false;
-
- if condition {
- println!("condition was true");
- }
-}
-
-In this case, nothing is printed.
-It’s also worth noting that condition here must be a bool. Let’s try an
-example with something else:
+It’s also worth noting that condition here must be a bool. To see what
+happens if the condition isn't a bool, try running this code:
fn main() {
- let condition = 5;
+ let number = 3;
- if condition {
- println!("condition was five");
+ if number {
+ println!("number was three");
}
}
-If we try to run this program, Rust will complain:
+The if condition evaluates to a value of 3 this time, and Rust will
+complain about it:
Compiling branches v0.1.0 (file:///projects/branches)
-src/main.rs:4:8: 4:17 error: mismatched types:
- expected `bool`,
- found `_`
-(expected bool,
- found integral variable) [E0308]
-src/main.rs:4 if condition {
- ^~~~~~~~~
-src/main.rs:4:8: 4:17 help: run `rustc --explain E0308` to see a detailed explanation
+error: mismatched types [--explain E0308]
+ --> src/main.rs:4:8
+4 |> if number {
+ |> ^^^^^^ expected bool, found integral variable
+note: expected type `bool`
+note: found type `_`
+
error: aborting due to previous error
Could not compile `branches`.
-We expected a bool, but got an integer. Rust will not automatically try to convert non-boolean types to a boolean here. We must be explicit.
-else if
-We can make multiple decisions by combining if and else in another way:
+The error tells us that Rust expected a bool, but got an integer. Rust will
+not automatically try to convert non-boolean types to a boolean here, unlike
+languages like Ruby or JavaScript. We must be explicit and always give if a
+boolean as its condition. If your intention is for the if code block to be run if a number is not equal to 0, for example, we would change the if expression to read:
+fn main() {
+ let number = 3;
+
+ if number != 0 {
+ println!("number was something other than zero");
+ }
+}
+
+Running this will print "number was something other than zero".
+Multiple Conditions with else if
+We can have multiple coniditions by combining if and else in an else if
+expression. For example:
fn main() {
let number = 5;
@@ -1553,23 +1950,25 @@ Could not compile `branches`.
}
}
-Let's try running it:
+This program has four possible paths it can take. If you try running it, you
+should see output like this:
$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Running `target/debug/branches`
condition was 5
-When this program executes, it will check each if in turn, and execute the
-first body for which the condition holds true.
-Using a single else if can be okay, but if you find yourself with more than one,
-you may want to refactor your code. Rust has a more powerful branching construct
-called match for these cases. We'll cover it later, when we talk about enums.
-if as an expression
-There’s one last detail we need to learn about if: it’s an expression. That means
-that we can use it on the right hand side of a let binding, for instance:
+When this program executes, it will check each if expression in turn and
+execute the first body for which the condition holds true.
+Using too many else if expressions can clutter your code, so if you find
+yourself with more than one, you may want to look at refactoring your code. In
+Chapter XX, we'll talk about a powerful Rust branching construct called match
+for these cases.
+Using if in a Binding
+The last detail you need to learn about if is that it’s an expression. That
+means that we can use it on the right hand side of a let binding, for
+instance:
fn main() {
let condition = true;
-
let number = if condition {
5
} else {
@@ -1579,17 +1978,19 @@ that we can use it on the right hand side of a let binding, for ins
println!("The value of number is: {}", number);
}
-Let’s run this:
+The number variable will be bound to a value based on the outcome of the if
+expression. Let’s run this to see what happens:
$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Running `target/debug/branches`
The value of number is: 5
-Remember, blocks of code evaluate to the last expression in them. And numbers
-by themselves are also expressions. So in this case, the value of the whole
-if expression depends on which block of code executes.
-There’s another small detail involved here: this means that if you use if
-in this way, both arms of the if must be the same type. This doesn’t work:
+Remember, blocks of code evaluate to the last expression in them, and numbers
+by themselves are also expressions. In this case, the value of the whole if
+expression depends on which block of code executes. This means that the value
+that results from both arms of the if must be the same type; in the previous
+example, they were both i32 integers. But what happens if the types are
+mismatched, as in the following example?
fn main() {
let condition = true;
@@ -1602,7 +2003,9 @@ in this way, both arms of the if must be the same type. This doesn
println!("The value of number is: {}", number);
}
-If we try to run this, we’ll get an error:
+The expression in the if block is an integer and the expresion in the else
+block is a string. This can’t work, because variable bindings must have a
+single type. If we try to run this, we’ll get an error:
Compiling branches v0.1.0 (file:///projects/branches)
src/main.rs:4:18: 8:6 error: if and else have incompatible types:
expected `_`,
@@ -1618,30 +2021,33 @@ src/main.rs:4:18: 8:6 help: run `rustc --explain E0308` to see a detailed explan
error: aborting due to previous error
Could not compile `branches`.
-if and else have incompatible types. This can’t work.
-Loops
-It’s often quite useful to be able to execute a block of code more than one
-time. For this, we have several constructs, called ‘loops’.
-To try out loops, let’s make a new project. Navigate to your projects folder
-and use Cargo to make a new one:
+The if and else arms have value types that are incompatible, and Rust tells
+us exactly where to find the problem in our program.
+Repetition with Loops
+It’s often useful to be able to execute a block of code more than one time. For
+this, Rust has several constructs called loops. A loop runs through the code
+inside it to the end and then starts immediately back at the beginning. To try
+out loops, let’s make a new project. Navigate to your projects folder and use
+Cargo to make a new project:
$ cargo new --bin loops
$ cd loops
There are three kinds of loops in Rust: loop, while, and for. Let’s dig
in.
-loop
-The loop keyword is very straightforward: it executes a block of code over
-and over and over and over and over and over forever. Change your src/main.rs
-file to look like this:
+Repeating Code with loop
+The loop keyword tells Rust to execute a block of code over and over again
+forever or until we explicitly tell it to stop.
+For an example, change the src/main.rs file in your loops directory to look
+like this:
fn main() {
loop {
println!("again!");
}
}
-If we run this program, we’ll see ‘again!’ printed over and over again. So
-how does our program end? It doesn’t, until we kill it. Most terminals support
-a keyboard shortcut, ‘control-c’, to stop a runaway program. Give it a try:
+If we run this program, we’ll see again! printed over and over continuously
+until we stop the program manually. Most terminals support a keyboard shortcut,
+control-c, to halt a program stuck in a continual loop. Give it a try:
$ cargo run
Compiling loops v0.1.0 (file:///projects/loops)
Running `target/debug/loops`
@@ -1651,67 +2057,26 @@ again!
again!
^Cagain!
-That ^C there is where I hit control-c.
-That’s a lot of trouble though! Luckily, there’s a way to break an infinite loop.
-Breaking out of a loop
-The break keyword will allow us to quit looping. Try this version out:
-fn main() {
- loop {
- println!("once!");
- break;
- }
-}
-
-If you run this program with cargo run, you’ll see that it only executes one
-time:
-$ cargo run
- Compiling loops v0.1.0 (file:///projects/loops)
- Running `target/debug/loops`
-once!
-
-When a Rust program hits a break statement, it will exit the current loop.
-while
-What if we took loop, break, and if, and put them together? Something
-like this:
+That ^C there is where we hit control-c. You may or may not see "again!"
+printed after the ^C, depending on where the code was in the loop when it
+received the signal to halt.
+Fortunately, Rust provides another, more reliable way to break out of a loop.
+We can place the break keyword within the loop to tell the program when to
+stop executing the loop. Recall that we did this in the guessing game to exit
+the program when the user won the game by guessing the number correctly.
+Conditional Loops With while
+A useful thing that many programs do is have a condition that can be evaluated
+within a loop. While the condition is true, the loop runs. When the condition
+ceases to be true, we call break, stopping the loop. This could be
+implemented with a combination of loop, if, else, and break; try to do
+that now if you'd like!
+But this pattern is so common that Rust has a more efficient language construct
+for it, called a while loop. Here's an example using while: this program
+loops three times, counting down each time. Finally, after the loop, it prints
+another message, then exits:
fn main() {
let mut number = 3;
- loop {
- if number != 0 {
- println!("{}!", number);
-
- number = number - 1;
- } else {
- break;
- }
-
- }
-
- println!("LIFTOFF!!!");
-}
-
-If we run this, we’ll get some output:
- Compiling loops v0.1.0 (file:///projects/loops)
- Running `target/debug/loops`
-3!
-2!
-1!
-LIFTOFF!!!
-
-The core of this example is in the combination of these three constructs:
- loop {
- if number != 0 {
- // do stuff
- } else {
- break;
- }
-
-We want to loop, but only while some sort of condition is true. As soon as it
-isn't, we want to break out of the loop.
-This pattern is so common that we have a language construct for it: while.
-Here's the same example, but using while instead:
-fn main() {
- let mut number = 3;
while number != 0 {
println!("{}!", number);
@@ -1721,13 +2086,14 @@ Here's the same example, but using while instead:
println!("LIFTOFF!!!");
}
-This lets us get rid of a lot of nesting, and is more clear: while a condition holds,
-run this code.
-for
-We can use this while construct to loop over the elements of a collection, like an
-array:
+This gets rid of a lot of nesting that would be necessary if we used loop,
+if, else, and break, and it's more clear. While a condition holds, run
+this code; otherwise, exit the loop.
+Looping Though a Collection with for
+We could use this while construct to loop over the elements of a collection,
+like an array. For example:
fn main() {
- let a = [1, 2, 3, 4, 5];
+ let a = [10, 20, 30, 40, 50];
let mut index = 0;
while index < 5 {
@@ -1737,72 +2103,98 @@ array:
}
}
-Running this will print out every element of the array:
+Here, we're counting up through the elements in the array. We start at index 0,
+then loop until we hit the final index of our array (that is, when index < 5
+is no longer true). Running this will print out every element of the array:
$ cargo run
Compiling loops v0.1.0 (file:///projects/loops)
Running `target/debug/loops`
-the value is: 1
-the value is: 2
-the value is: 3
-the value is: 4
-the value is: 5
+the value is: 10
+the value is: 20
+the value is: 30
+the value is: 40
+the value is: 50
-Here, we're counting up instead of down: we start at zero, then loop until we
-hit the final index of our array.
-This approach is error-prone, though. If we get the index length incorrect, we
-will end up causing a panic!. This is also slow, as the compiler needs to do
-that check on every element on every iteration through the loop.
-Instead, we can use our last kind of loop: the for loop. It looks like this:
+All five array values appear in the terminal, as expected. Even though index
+will reach a value of 6 at some point, the loop stops executing before trying
+to fetch a sixth value from the array.
+This approach is error-prone, though; we could cause our program to panic by
+getting the index length incorrect. It's also slow, as the compiler needs to
+perform the conditional check on every element on every iteration through the
+loop.
+As a more efficient alternative, we can use a for loop and execute some code
+for each item in a collection. A for loop looks like this:
fn main() {
- let a = [1, 2, 3, 4, 5];
+ let a = [10, 20, 30, 40, 50];
for element in a.iter() {
println!("the value is: {}", element);
}
}
-** NOTE: see https://github.com/rust-lang/rust/issues/25725#issuecomment-166365658, we may want to change this **
-If we run this, we'll see the same output as the previous example.
-** I'm going to leave it at this for now until we decide how we want to do it**
+If we run this, we'll see the same output as the previous example. Importantly,
+though, we've now increased the safety of our code and eliminated the chance of
+bugs resulting from going beyond the end of the array or not going far enough
+and missing some items.
+For example, in the previous code that uses the while loop, if we removed an
+item from the a array but forgot to update the condition to be while index < 4, our code would panic. Using the for loop means we would not need to
+remember to change any other code if we changed the the number of values in the
+array.
+If you're wondering about the .iter() code in this example, keep reading! We
+will cover method syntax generally in Chapter XX and iterators specifically in
+Chapter XX.
+The safety and conciseness of for loops make them the most commonly used loop
+construct in Rust. Even in situations where you want to run some code a certain
+number of times, like our countdown example that used a while loop, most
+Rustaceans would use a for loop. The way to do that is using a Range, which
+is a type provided by the standard library that generates numbers starting from
+one number and ending before another number. Here's what the countdown would
+look like with a for loop, and using another method we haven't yet talked
+about, .rev(), to reverse the range:
+fn main() {
+ for number in (1..4).rev() {
+ println!("{}!", number);
+ }
+ println!("LIFTOFF!!!");
+}
+
+That's a bit nicer, isn't it?
+Now that you know how Rust does things that most other languages can do, let's
+talk about a concept that doesn't commonly exist: ownership.
Understanding Ownership
-Now that we’ve got some basic syntax under our belt, it’s time to take a look
-at Rust’s most unique feature: ownership. We’ll also talk about several related
-features: borrowing, slices, and lifetimes, as well as how Rust lays things out
-in memory.
-Ownership
+Ownership is important to understand: it's Rust's most unique feature, and
+enables Rust to make memory safety guarantees without needing a garbage
+collector. We’ll also talk about several related features: borrowing, slices,
+and how Rust lays things out in memory.
+Ownership
Rust’s central feature is called ‘ownership’. It is a feature that is
straightforward to explain, but has deep implications for the rest of the
language.
-Rust is committed to both safety and speed. One of the key tools for balancing
-between them is “zero-cost abstractions”: the various abstractions in Rust do
-not pose a global performance penalty. The ownership system is a prime example
-of a zero-cost abstraction. All of the analysis we’ll talk about in this guide
-is done at compile time. You do not pay any run-time cost for any of these
+
All programs have to manage the way they use a computer's memory while running.
+Some languages have garbage collection, while in others, the programmer has to
+explicitly allocate and free the memory. Rust takes a third approach: memory is
+managed through a system of ownership with a set of rules that the compiler
+checks at compile-time. You do not pay any run-time cost for any of these
features.
-However, this system does have a certain cost: learning curve. Many new
-Rustaceans experience something we like to call ‘fighting with the borrow
-checker’, where the Rust compiler refuses to compile a program that the author
-thinks is valid. This can happen because the programmer isn’t used to thinking
-carefully about ownership, or is thinking about it differently from the way
-that Rust does. You probably will experience something similar at first. There is
-good news, however: more experienced Rust developers report that once they work
-with the rules of the ownership system for a period of time, they fight the
-borrow checker less and less. Keep at it!
-This chapter will give you a foundation for understanding the rest of the
-language. To do so, we’re going to learn through examples, focusing on a very
-common data structure: strings.
-Variable binding scope
-Let’s take a step back and look at the very basics again. Now that we’re past
-basic syntax, we won’t include all of the fn main() { stuff in examples, so
-if you’re following along, you will have to put them inside of a main()
-function. This lets our examples be a bit more concise, letting us focus on the
-actual details, rather than boilerplate.
-Anyway, here it is:
+However, because ownership is a new concept for many programmers, it does take
+some time to get used to. There is good news, though: the more experienced you
+become with Rust and the rules of the ownership system, the more you'll be
+able to naturally develop code that is both safe and efficient. Keep at it!
+Once you understand ownership, you have a good foundation for understanding the
+features that make Rust unique. In this chapter, we'll learn ownership by going
+through some examples, focusing on a very common data structure: strings.
+Variable binding scope
+We've walked through an example of a Rust program already in the tutorial
+chapter. Now that we’re past basic syntax, we won’t include all of the fn main() { stuff in examples, so if you’re following along, you will have to put
+them inside of a main() function. This lets our examples be a bit more
+concise, letting us focus on the actual details rather than boilerplate.
+Anyway, here is our first example:
let s = "hello";
-This variable binding refers to a string literal. It’s valid from the point at
-which it’s declared, until the end of the current scope. That is:
-{ // s is not valid here, it’s not yet in scope
+This variable binding refers to a string literal, where the value of the string
+is hard coded into the text of our program. The binding is valid from the point
+at which it’s declared until the end of the current scope. That is:
+{ // s is not valid here, it’s not yet declared
let s = "hello"; // s is valid from this point forward
// do stuff with s
@@ -1813,35 +2205,39 @@ which it’s declared, until the end of the current scope. That is:
When s comes ‘into scope’, it is valid.
It remains so until it ‘goes out of scope’.
-At this point, things are similar to other programming languages. Let’s build
-on top of this understanding by introducing a new type: String.
-Strings
-String literals are convenient, but they aren’t the only way that you use strings.
-For one thing, they’re immutable. For another, not every string is literal:
-what about taking user input and storing it in a string?
-For this, Rust has a second string type, String. You can create a String from
-a string literal using the from function:
+At this point, things are similar to other programming languages. Now let’s
+build on top of this understanding by introducing the String type.
+Strings
+String literals are convenient, but they aren’t the only way that you use
+strings. For one thing, they’re immutable. For another, not every string is
+literal: what about taking user input and storing it in a string?
+For this, Rust has a second string type, String. You can create a String
+from a string literal using the from function:
let s = String::from("hello");
-We haven’t seen the double colon (::) syntax yet. It is a kind of scope
-operator, allowing us to namespace this particular from() function under the
-String type itself, rather than using some sort of name like string_from().
-We’ll discuss this syntax more in the “Method Syntax” and “Modules” chapters.
+We haven’t seen the double colon (::) syntax yet. It is an operator that
+allows us to namespace this particular from() function under the String
+type itself, rather than using some sort of name like string_from(). We’ll
+discuss this syntax more in the “Method Syntax” and “Modules” chapters.
This kind of string can be mutated:
let mut s = String::from("hello");
-s.push_str(", world!");
+s.push_str(", world!"); // push_str() appends a literal to a String
+
+println!("{}", s); // This will print `hello, world!`
-Memory and allocation
+Memory and allocation
So, what’s the difference here? Why can String be mutated, but literals
cannot? The difference comes down to how these two types deal with memory.
In the case of a string literal, because we know the contents of the string at
compile time, we can hard-code the text of the string directly into the final
executable. This means that string literals are quite fast and efficient. But
-these properties only come from its immutability; we can’t put an
-arbitrary-sized blob of memory into the binary for each string!
-With String, to support a mutable, growable string, we need to allocate an
-unknown amount of memory to hold the contents. This means two things:
+these properties only come from its immutability. Unfortunately, we can’t put a
+blob of memory into the binary for each string whose size is unknown at compile
+time and whose size might change over the course of running the program.
+With String, in order to support a mutable, growable string, we need to
+allocate an unknown amount of memory to hold the contents. This means two
+things:
- The memory must be requested from the operating system at runtime.
- We need a way of giving this memory back to the operating system when we’re
@@ -1851,13 +2247,14 @@ done with our
String.
implementation requests the memory it needs. This is pretty much universal in
programming languages.
The second case, however, is different. In languages with a garbage collector
-(‘GC’), the GC handles that second case, and we, as the programmer, don’t need
-to think about it. Without GC, it’s the programmer’s responsibility to identify
-when memory is no longer being used, and explicitly return it, just as it was
-requested. Doing this correctly has historically been a difficult problem. If
-we forget, we will waste memory. If we do it too early, we will have an invalid
-variable. If we do it twice, that’s a bug too. We need to pair exactly one
-allocate() with exactly one free().
+(‘GC’), the GC will keep track and clean up memory that isn't being used
+anymore, and we, as the programmer, don’t need to think about it. Without GC,
+it’s our responsibility to identify when memory is no longer being used and
+call code to explicitly return it, just as we did to request it. Doing this
+correctly has historically been a difficult problem. If we forget, we will
+waste memory. If we do it too early, we will have an invalid variable. If we do
+it twice, that’s a bug too. We need to pair exactly one allocate() with
+exactly one free().
Rust takes a different path. Remember our example? Here’s a version with
String:
{
@@ -1866,10 +2263,11 @@ variable. If we do it twice, that’s a bug too. We need to pair exactly one
// do stuff with s
} // this scope is now over, and s is no longer valid
-We have a natural point at which we can return the memory our String needs back
-to the operating system: when it goes out of scope! When a variable goes out of
-scope, a special function is called. This function is called drop(), and it
-is where the author of String can put the code to return the memory.
+We have a natural point at which we can return the memory our String needs
+back to the operating system: when it goes out of scope. When a variable goes
+out of scope, Rust calls a special function for us. This function is called
+drop(), and it is where the author of String can put the code to return the
+memory.
Aside: This pattern is sometimes called “Resource Acquisition Is
Initialization” in C++, or “RAII” for short. While they are very similar,
@@ -1878,14 +2276,14 @@ to use the same term. If you’re familiar with this idea, keep in mind that it
is roughly similar in Rust, but not identical.
This pattern has a profound impact on the way that Rust code is written. It may
-seem obvious right now, but things can get tricky in more advanced situations!
+seem obvious right now, but things can get tricky in more advanced situations.
Let’s go over the first one of those right now.
-Move
+Move
What would you expect this code to do?
let x = 5;
let y = x;
-You might say “Make a copy of 5.” That’d be correct! We now have two
+
You might say “Make a copy of 5”, and that would be correct. We now have two
bindings, x and y, and both equal 5.
Now let’s look at String. What would you expect this code to do?
let s1 = String::from("hello");
@@ -1899,51 +2297,45 @@ let’s take a look at what String looks like under the covers:
contents of the string, a length, and a capacity. The length is how much memory
the String is currently using. The capacity is the total amount of memory the
String has gotten from the operating system. The difference between length
-and capacity matters, but not in this context, so don’t worry about it too much
-if it doesn’t make sense, and just ignore the capacity.
-
-We’ve talked about two kinds of composite types: arrays and tuples. String
-is a third type: a struct, which we will cover the details of in the next
-chapter of the book. For now, thinking about String as a tuple is close
-enough.
-
-When we assign s1 to s2, the String itself is copied. But not all kinds
-of copying are the same. Many people draw distinctions between ‘shallow
-copying’ and ‘deep copying’. We don’t use these terms in Rust. We instead say
-that something is ‘moved’ or ‘cloned’. Assignment in Rust causes a ‘move’. In
-other words, it looks like this:
+and capacity matters but not in this context, so don’t worry about it too much.
+For right now, it's fine to ignore the capacity.
+When we assign s1 to s2, the String itself is copied, meaning we copy the
+pointer, the length, and the capacity. We do not copy the data that the
+String's pointer refers to. In other words, it looks like this:

Not this:

-When moving, Rust makes a copy of the data structure itself, the contents of
-s1 are copied, but if s1 contains a reference, like it does in this case,
-Rust will not copy the things that those references refer to.
-There’s a problem here! Both data pointers are pointing to the same place.
-Why is this a problem? Well, when s2 goes out of scope, it will free the
-memory that data points to. And then s1 goes out of scope, and it will
-also try to free the memory that data points to! That’s bad.
-So what’s the solution? Here, we stand at a crossroads. There are a few
-options. One would be to declare that assignment will also copy out any data.
-This works, but is inefficient: what if our String contained a novel? Also,
-it only works for memory. What if, instead of a String, we had a
-TcpConnection? Opening and closing a network connection is very similar to
-allocating and freeing memory. The solution that we could use there is to allow
-the programmer to hook into the assignment, similar to drop(), and write code
-to fix things up. That would work, but now, an = can run arbitrary code. That’s
-also not good, and it doesn’t solve our efficiency concerns either.
+There’s a problem here. Both data pointers are pointing to the same place. Why
+is this a problem? Well, when s2 goes out of scope, it will free the memory
+that the pointer points to. And then s1 goes out of scope, and it will also
+try to free the memory that the pointer points to. That’s bad, and is known as
+a "double free" error.
+So what’s the solution? Here, we stand at a crossroads with a few options.
+One way would be to change assignment so that it will also copy out any data.
+This works, but is inefficient: what if our String contained a novel?
+Also, that solution would only work for memory. What if, instead of a String,
+we had a TcpConnection? Opening and closing a network connection is very
+similar to allocating and freeing memory, so it would be nice to be able to use
+the same mechanism. We wouldn't be able to, though, because creating a new
+connection requires more than just copying memory: we have to request a new
+connection from the operating system. We could then extend our solution to
+allow the programmer to hook into the assignment, similar to drop(), and
+write code to fix things up. That would work, but if we did that, an = could
+run arbitrary code. That’s also not good, and it doesn’t solve our efficiency
+concerns either.
Let’s take a step back: the root of the problem is that s1 and s2 both
-think that they have control of the memory, and therefore needs to free it.
+think that they have control of the memory and therefore need to free it.
Instead of trying to copy the allocated memory, we could say that s1 is no
-longer valid, and therefore, doesn’t need to free anything. This is in fact the
-choice that Rust makes. Check it out what happens when you try to use s1
-after s2 is created:
+longer valid and, therefore, doesn’t need to free anything. This is in fact the
+choice that Rust makes. Check out what happens when you try to use s1 after
+s2 is created:
let s1 = String::from("hello");
let s2 = s1;
println!("{}", s1);
You’ll get an error like this:
-5:22 error: use of moved value: `s1` [E0382]
+5:22 error: use of moved value: `s1` [E0382]
println!("{}", s1);
^~
5:24 note: in this expansion of println! (defined in <std macros>)
@@ -1951,26 +2343,31 @@ println!("{}", s1);
let s2 = s1;
^~
-We say that s1 was moved into s2. When a value moves, its data is copied,
-but the original variable binding is no longer usable. That solves our problem:
+If you have heard the terms "shallow copy" and "deep copy" while working with
+other languages, the concept of copying the pointer, length, and capacity
+without copying the data probably sounded like a shallow copy. Because Rust
+also invalidates the first binding, instead of calling this a shallow copy,
+it's called a move. Here we would read this by saying that s1 was moved
+into s2. So what actually happens looks like this:

-With only s2 valid, when it goes out of scope, it will free the memory, and we’re done!
-Ownership Rules
+That solves our problem! With only s2 valid, when it goes out of scope, it
+alone will free the memory, and we’re done.
+Ownership Rules
This leads us to the Ownership Rules:
-- Each value in Rust has a variable binding that’s called it’s ‘owner’.
+- Each value in Rust has a variable binding that’s called its ‘owner’.
- There can only be one owner at a time.
- When the owner goes out of scope, the value will be
drop()ped.
Furthermore, there’s a design choice that’s implied by this: Rust will never
-automatically create ‘deep’ copies of your data. Any automatic copying must be
-inexpensive.
-Clone
-But what if we do want to deeply copy the String’s data, and not just the
+automatically create ‘deep’ copies of your data. Therefore, any automatic
+copying can be assumed to be inexpensive.
+Clone
+But what if we do want to deeply copy the String’s data and not just the
String itself? There’s a common method for that: clone(). We will discuss
-methods in the next section on structs, but they’re a common enough feature
+methods in the section on structs, but they’re a common enough feature
in many programming languages that you have probably seen them before.
Here’s an example of the clone() method in action:
let s1 = String::from("hello");
@@ -1982,9 +2379,9 @@ println!("{}", s1);
it is doing this:

When you see a call to clone(), you know that some arbitrary code is being
-executed, which may be expensive. It’s a visual indicator that something
+executed, and that code may be expensive. It’s a visual indicator that something
different is going on here.
-Copy
+Copy
There’s one last wrinkle that we haven’t talked about yet. This code works:
let x = 5;
let y = x;
@@ -1992,34 +2389,30 @@ let y = x;
println!("{}", x);
But why? We don’t have a call to clone(). Why didn’t x get moved into y?
-For types that do not have any kind of complex storage requirements, like
-integers, typing clone() is busy work. There’s no reason we would ever want
-to prevent x from being valid here, as there’s no situation in which it’s
-incorrect. In other words, there’s no difference between deep and shallow
-copying here, so calling clone() wouldn’t do anything differently from the
-usual shallow copying.
-Rust has a special annotation that you can place on types, called Copy. If
-a type is Copy, an older binding is still usable after assignment. Integers
-are an example of such a type; most of the primitive types are Copy.
-While we haven’t talked about how to mark a type as Copy yet, you might ask
-yourself “what happens if we made String Copy?” The answer is, you cannot.
-Remember drop()? Rust will not let you make something Copy if it has
+
Types like integers that have a known size at compile time do not ask for
+memory from the operating system and therefore do not need to be drop()ped
+when they go out of scope. That means there's no reason we would want to
+prevent x from being valid after we create the binding y. In other words,
+there’s no difference between deep and shallow copying here, so calling
+clone() wouldn’t do anything differently from the usual shallow copying and
+we can leave it out.
+Rust has a special annotation that you can place on types like these, and that
+annotation is the Copy trait. We'll talk more about traits in Chapter XX. If
+a type has the Copy trait, an older binding is still usable after assignment.
+Rust will not let you make something have the Copy trait if it has
implemented drop(). If you need to do something special when the value goes
out of scope, being Copy will be an error.
So what types are Copy? You can check the documentation for the given type to
-be sure, but as a rule of thumb, any group of simple scalar values can be
-Copy, but nothing that requires allocation or is some form of resource is Copy.
-And you can’t get it wrong: the compiler will throw an error if you try to use
-a type that moves incorrectly, as we saw above.
-Here’s some types that you’ve seen so far that are Copy:
+be sure, but as a rule of thumb, any group of simple scalar values can be Copy,
+but nothing that requires allocation or is some form of resource is Copy. Here’s some of the types that are Copy:
- All of the integer types, like
u32.
- The booleans,
true and false.
- All of the floating point types, like
f64.
- Tuples, but only if they contain types which are also
Copy. (i32, i32)
-is Copy, but (i32, String) is not!
+is Copy, but (i32, String) is not.
-Ownership and functions
+Ownership and functions
Passing a value to a function has similar semantics as assigning it:
fn main() {
let s = String::from("hello");
@@ -2066,7 +2459,9 @@ fn makes_copy(some_integer: i32) { // some_integer comes into scope.
} // Here, some_integer goes out of scope. Nothing special happens.
Remember: If we tried to use s after the call to takes_ownership(), Rust
-would throw a compile-time error! These static checks protect us from mistakes.
+would throw a compile-time error. These static checks protect us from mistakes.
+Try adding code to main that uses s and x to see where you can use them
+and where the ownership rules prevent you from doing so.
Returning values can also transfer ownership:
fn main() {
let s1 = gives_ownership();
@@ -2119,9 +2514,11 @@ fn takes_and_gives_back(a_string: String) -> String { // a_string comes into
It’s the same pattern, every time: assigning something moves it, and when an
owner goes out of scope, if it hasn’t been moved, it will drop().
-This might seem a bit tedious, and it is. What if I want to let a function use
-a value, but not take ownership? It’s quite annoying that anything I pass in
-also needs to be passed back. Look at this function:
+This might seem a bit tedious, and it is. What if we want to let a function use
+a value but not take ownership? It’s quite annoying that anything we pass in
+also needs to be passed back if we want to use it again, in addition to any
+data resulting from the body of the function that we might want to return as
+well. It's possible to return multiple values, using a tuple, like this:
fn main() {
let s1 = String::from("hello");
@@ -2136,10 +2533,10 @@ fn calculate_length(s: String) -> (String, usize) {
(s, length)
}
-This is too much ceremony: we have to use a tuple to give back the String as
-well as the length. It’s a lot of work for a pattern that should be common.
-Luckily for us, Rust has such a feature, and it’s what the next section is about.
-References and Borrowing
+But this is too much ceremony and a lot of work for a concept that should be
+common. Luckily for us, Rust has a feature for this concept, and it’s what the
+next section is about.
+References and Borrowing
At the end of the last section, we had some example Rust that wasn’t very
good. Here it is again:
fn main() {
@@ -2157,7 +2554,8 @@ fn calculate_length(s: String) -> (String, usize) {
}
The issue here is that we have to return the String back to the calling
-function so that it could still use it.
+function so that we can still use it there, since it was moved when we called
+calculate_length().
There is a better way. It looks like this:
fn main() {
let s1 = String::from("hello");
@@ -2173,10 +2571,11 @@ fn calculate_length(s: &String) -> usize {
length
}
-First, you’ll notice all of the tuple stuff is gone. Next, that we pass &s1
-into calculate_lengths(). And in its definition, we take &String rather
-than String.
-These &s are called ‘references’, and they allow you to refer to some value
+
First, you’ll notice all of the tuple stuff in the binding declaration and the
+function return value is gone. Next, note that we pass &s1 into
+calculate_length(), and in its definition, we take &String rather than
+String.
+These &s are called ‘references’, and they allow you to refer to some value
without taking ownership of it. Here’s a diagram:
DIAGRAM GOES HERE of a &String pointing at a String, with (ptr, len, capacity)
Let’s take a closer look at the function call here:
@@ -2189,12 +2588,11 @@ let s1 = String::from("hello");
let len = calculate_length(&s1);
-The &s1 syntax lets us create a reference from s1. This reference refers
-to the value of s1, but does not own it. Because it does not own it, the
+
The &s1 syntax lets us create a reference with s1. This reference refers
+to the value of s1 but does not own it. Because it does not own it, the
value it points to will not be dropped when the reference goes out of scope.
Likewise, the signature of the function uses & to indicate that it takes
-a reference as an argument:
-Let’s add some explanatory annotations:
+a reference as an argument. Let’s add some explanatory annotations:
fn calculate_length(s: &String) -> usize { // s is a reference to a String
let length = s.len();
@@ -2207,10 +2605,10 @@ we don’t drop what a reference points to when the reference goes out of scope.
This lets us write functions which take references as arguments instead of the
values themselves, so that we won’t need to return them to give back ownership.
There’s another word for what references do, and that’s ‘borrowing’. Just like
-with real life, if I own something, you can borrow it from me. When you’re done,
-you have to give it back.
+with real life, if a person owns something, you can borrow it from them. When
+you’re done, you have to give it back.
Speaking of which, what if you try to modify something you borrow from me? Try
-this code out. Spoiler alert: it doesn’t work:
+this code out. Spoiler alert: it doesn’t work!
fn main() {
let s = String::from("hello");
@@ -2218,17 +2616,19 @@ this code out. Spoiler alert: it doesn’t work:
}
fn change(some_string: &String) {
- some_string.push_str(", world"); // push_str() appends a literal to a String
+ some_string.push_str(", world");
}
Here’s the error:
-8:16 error: cannot borrow immutable borrowed content `*some_string` as mutable
- some_string.push_str(", world"); // push_str() appends a literal to a String
- ^~~~~~~~~~~
+error: cannot borrow immutable borrowed content `*some_string` as mutable
+ --> error.rs:8:5
+ |
+8 | some_string.push_str(", world");
+ | ^^^^^^^^^^^
-Just like bindings are immutable by default, so are references. We’re not allowed
-to modify something we have a reference to.
-Mutable references
+Just like bindings are immutable by default, so are references. We’re not
+allowed to modify something we have a reference to.
+Mutable references
We can fix this bug! Just a small tweak:
fn main() {
let mut s = String::from("hello");
@@ -2237,11 +2637,11 @@ to modify something we have a reference to.
}
fn change(some_string: &mut String) {
- some_string.push_str(", world"); // push_str() appends a literal to a String
+ some_string.push_str(", world");
}
-First, we had to change s to be mut. Then, we had to create a mutable reference
-with &mut s and accept a mutable reference with some_string: &mut String.
+First, we had to change s to be mut. Then we had to create a mutable
+reference with &mut s and accept a mutable reference with some_string: &mut String.
Mutable references have one big restriction, though. This code fails:
let mut s = String::from("hello");
@@ -2249,26 +2649,22 @@ let r1 = &mut s;
let r2 = &mut s;
Here’s the error:
-5:20 error: cannot borrow `s` as mutable more than once at a time [E0499]
- let r2 = &mut s;
- ^
-4:20 note: previous borrow of `s` occurs here; the mutable borrow prevents
- subsequent moves, borrows, or modification of `s` until the borrow
- ends
- let r1 = &mut s;
- ^
-7:2 note: previous borrow ends here
-fn main() {
-
-}
-^
+error[E0499]: cannot borrow `s` as mutable more than once at a time
+ --> borrow_twice.rs:5:19
+ |
+4 | let r1 = &mut s;
+ | - first mutable borrow occurs here
+5 | let r2 = &mut s;
+ | ^ second mutable borrow occurs here
+6 | }
+ | - first borrow ends here
-The error is what it says on the tin: you cannot borrow something more than
-once at a time in a mutable fashion. This restriction allows for mutation, but
-in a very controlled fashion. It is something that new Rustaceans struggle
-with, because most languages let you mutate whenever you’d like.
+The error is what it says: you cannot borrow something mutably more than once
+at a time. This restriction allows for mutation but in a very controlled
+fashion. It is something that new Rustaceans struggle with, because most
+languages let you mutate whenever you’d like.
As always, we can use {}s to create a new scope, allowing for multiple mutable
-references. Just not simultaneous ones:
+references, just not simultaneous ones:
let mut s = String::from("hello");
{
@@ -2278,7 +2674,8 @@ references. Just not simultaneous ones:
let r2 = &mut s;
-There is a similar rule for combining the two kinds of references. This code errors:
+There is a similar rule for combining mutable and immutable references. This
+code errors:
let mut s = String::from("hello");
let r1 = &s; // no problem
@@ -2286,25 +2683,21 @@ let r2 = &s; // no problem
let r3 = &mut s; // BIG PROBLEM
Here’s the error:
-19: 6:20 error: cannot borrow `s` as mutable because it is also borrowed as
- immutable [E0502]
- let r3 = &mut s; // BIG PROBLEM
- ^
-15: 4:16 note: previous borrow of `s` occurs here; the immutable borrow
- prevents subsequent moves or mutable borrows of `s` until the
- borrow ends
- let r1 = &s; // no problem
- ^
-8:2 note: previous borrow ends here
-fn main() {
-
-}
-^
+error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
+ --> borrow_thrice.rs:6:19
+ |
+4 | let r1 = &s; // no problem
+ | - immutable borrow occurs here
+5 | let r2 = &s; // no problem
+6 | let r3 = &mut s; // BIG PROBLEM
+ | ^ mutable borrow occurs here
+7 | }
+ | - immutable borrow ends here
Whew! We also cannot have a mutable reference while we have an immutable one.
Users of an immutable reference don’t expect the values to suddenly change out
from under them! Multiple immutable references are okay, however.
-Dangling references
+Dangling references
In languages with pointers, it’s easy to create a “dangling pointer” by freeing
some memory while keeping around a pointer to that memory. In Rust, by
contrast, the compiler guarantees that references will never be dangling: if we
@@ -2322,12 +2715,17 @@ fn dangle() -> &String {
}
Here’s the error:
-error: missing lifetime specifier [E0106]
-fn dangle() -> &String {
- ^~~~~~~
-help: this function’s return type contains a borrowed value, but there is no
- value for it to be borrowed from
-help: consider giving it a ‘static lifetime
+error[E0106]: missing lifetime specifier
+ --> dangle.rs:5:16
+ |
+5 | fn dangle() -> &String {
+ | ^^^^^^^
+ |
+ = help: this function's return type contains a borrowed value, but there is no
+ value for it to be borrowed from
+ = help: consider giving it a 'static lifetime
+
+error: aborting due to previous error
This error message refers to a feature we haven’t learned about yet,
‘lifetimes’. The message does contain the key to why this code is a problem,
@@ -2356,28 +2754,24 @@ no good. Rust won’t let us do this.
}
This works, no problem. Ownership is moved out, nothing is deallocated.
-The Rules of References
+The Rules of References
Here’s a recap of what we’ve talked about:
- At any given time, you may have either, but not both of:
- One mutable reference.
-- Any number of immutable references .
+- Any number of immutable references.
- References must always be valid.
-While these rules are not complicated on their own, they can be tricky when
-applied to real code. Let’s work through a number of examples to help build
-our understanding.
-More Examples
-COMING SOON
-Slices
+Next, let's look at a different kind of reference: slices.
+Slices
So far, we’ve talked about types that have ownership, like String, and ones
-that don’t, like &String. There is a second kind of type which does not have
+that don’t, like &String. There is another kind of type which does not have
ownership: slices. Slices let you reference a contiguous sequence of elements
-in a collection, rather than the whole collection itself.
-Here’s a small programming problem: write a function which takes a string,
+in a collection rather than the whole collection itself.
+Here’s a small programming problem: write a function which takes a string
and returns the first word you find. If we don’t find a space in the string,
then the whole string is a word, so the whole thing should be returned.
Let’s think about the signature of this function:
@@ -2390,8 +2784,8 @@ the word, though. Let’s try that:
fn first_word(s: &String) -> usize {
let bytes = s.as_bytes();
- for (i, &byte) in bytes.iter().enumerate() {
- if byte == 32 {
+ for (i, &item) in bytes.iter().enumerate() {
+ if item == 32 {
return i;
}
}
@@ -2400,47 +2794,40 @@ the word, though. Let’s try that:
}
Let’s break that down a bit:
-fn first_word(s: &String) -> usize {
-
- // Since we need to go through the String element by element, and
- // check if a value is a space, we will convert our String to an
- // array of bytes, using the `.as_bytes()` method.
- let bytes = s.as_bytes();
-
- // We discussed using the iter() method with for in Chapter 3.7. Here,
- // we’re adding another method: enumerate(). While iter() returns each
- // element, enumerate() modifies the result of iter(), and returns a
- // tuple instead. The first element of the tuple is the index, and the
- // second element is a reference to the element itself. This is a bit
- // nicer than calculating the index ourselves.
- //
- // Since it’s a tuple, we can use patterns, just like elsewhere in Rust.
- // So we match against the tuple with i for the index, and &byte for
- // the byte itself.
- for (i, &byte) in bytes.iter().enumerate() {
-
- // 32 is the value of a space in UTF-8
- if byte == 32 {
-
- // We found a space! Return this position.
- return i;
- }
- }
-
- // If we got here, we didn’t find a space, so this whole thing must be a
- // word. So return the length.
- s.len()
-}
+let bytes = s.as_bytes();
+Since we need to go through the String element by element and
+check if a value is a space, we will convert our String to an
+array of bytes using the .as_bytes() method.
+for (i, &item) in bytes.iter().enumerate() {
+
+We will be discussing iterators in more detail in Chapter XX, but for
+now, know that iter() is a method that returns each element in a
+collection, and enumerate() modifies the result of iter() and returns
+a tuple instead. The first element of the tuple is the index, and the
+second element is a reference to the element itself. This is a bit
+nicer than calculating the index ourselves.
+Since it’s a tuple, we can use patterns, just like elsewhere in Rust. So we
+match against the tuple with i for the index and &item for a single byte. Since
+we get a reference from .iter().enumerate(), we use & in the pattern.
+ if item == 32 {
+ return i;
+ }
+}
+s.len()
+
+We search for the value 32, which represents a space in UTF-8. If we find one,
+we return the position. Otherwise, we return the length of the string, using
+s.len().
This works, but there’s a problem. We’re returning a usize on its own, but
-it’s only a meaningful number in the context of the &String itself. In other
+it’s only a meaningful number in the context of the &String. In other
words, because it’s a separate value from the String, there’s no guarantee
that it will still be valid in the future. Consider this:
# fn first_word(s: &String) -> usize {
# let bytes = s.as_bytes();
#
-# for (i, &byte) in bytes.iter().enumerate() {
-# if byte == 32 {
+# for (i, &item) in bytes.iter().enumerate() {
+# if item == 32 {
# return i;
# }
# }
@@ -2451,22 +2838,23 @@ that it will still be valid in the future. Consider this:
fn main() {
let mut s = String::from("hello world");
- let word = first_word(&s);
+ let word = first_word(&s); // word will get the value 5.
s.clear(); // This empties the String, making it equal to "".
- // word is now totally invalid! There’s no more word here.
+ // word still has the value 5 here, but there's no more string that
+ // we could meaningfully use the value 5 with. word is now totally invalid!
}
This is bad! It’s even worse if we wanted to write a second_word()
function. Its signature would have to look like this:
fn second_word(s: &String) -> (usize, usize) {
-Now we’re tracking both a start and and ending index. Even more chances for
+
Now we’re tracking both a start and an ending index. Even more chances for
things to go wrong. We now have three unrelated variable bindings floating
around which need to be kept in sync.
Luckily, Rust has a solution to this problem: string slices.
-String slices
+String slices
A string slice looks like this:
let s = String::from("hello world");
@@ -2474,38 +2862,47 @@ let hello = &s[0..5];
let world = &s[6..11];
This looks just like taking a reference to the whole String, but with the
-extra [0..5] bit. Instead of being a reference to the entire String,
-it’s a reference to an internal position in the String, but it also keeps
-track of the number of elements that it refers to as well. In other words,
-it looks like this:
+extra [0..5] bit. Instead of being a reference to the entire String, it’s a
+reference to an internal position in the String and the number of elements
+that it refers to.
+We can create slices with a range of [starting_index..ending_index], but the
+slice data structure actually stores the starting position and the length of the
+slice. So in the case of let world = &s[6..11];, world would be a slice that
+contains a pointer to the 6th byte of s and a length value of 5.
+In other words, it looks like this:
DIAGRAM GOES HERE of s, hello, and world
-Note that the internal position is specified through byte-offsets, not
-characters. The offset to the first byte of a String is 0 and the
-trailing number should point to the first byte that is not included
-in the slice.
-With Rust’s .. syntax, if you want to start at zero, you can drop the zero.
-In other words, these are equal:
+With Rust’s .. range syntax, if you want to start at the first index (zero),
+you can drop the value before the ... In other words, these are equal:
let s = String::from("hello");
let slice = &s[0..2];
let slice = &s[..2];
By the same token, if your slice should include the last byte of the
-String, you can drop the trailing number. In other words, these are
+String, you can drop the trailing number. That means these are
equal:
let s = String::from("hello");
let len = s.len();
+let slice = &s[3..len];
+let slice = &s[3..];
+
+You can also drop both values to take a slice of the entire string. So these
+are equal:
+let s = String::from("hello");
+
+let len = s.len();
+
let slice = &s[0..len];
-let slice = &s[0..];
+let slice = &s[..];
With this in mind, let’s re-write first_word() to return a slice:
fn first_word(s: &String) -> &str {
let bytes = s.as_bytes();
- for (i, &byte) in bytes.iter().enumerate() {
- if byte == 32 {
+ for (i, &item) in bytes.iter().enumerate() {
+ if item == 32 {
return &s[0..i];
}
}
@@ -2513,26 +2910,16 @@ let slice = &s[0..];
&s[..]
}
-Now, we have a single value, the &str. It contains both elements that we care
-about: a reference to the starting point, and the number of elements.
-This would also work for a second_word():
+Now we have a single value, the &str, pronounced "string slice". It stores
+both elements that we care about: a reference to the starting point of the
+slice and the number of elements in the slice.
+This would also work for a second_word():
fn second_word(s: &String) -> &str {
-Same deal. We now have a straightforward API, that’s much harder to mess up.
+We now have a straightforward API that’s much harder to mess up.
But what about our error condition from before? Slices also fix that. Using
the slice version of first_word() will throw an error:
-# fn first_word(s: &String) -> &str {
-# let bytes = s.as_bytes();
-#
-# for (i, &byte) in bytes.iter().enumerate() {
-# if byte == 32 {
-# return &s[0..i];
-# }
-# }
-#
-# &s[..]
-# }
-fn main() {
+fn main() {
let mut s = String::from("hello world");
let word = first_word(&s);
@@ -2541,7 +2928,7 @@ fn main() {
}
Here’s the error:
-17:6 error: cannot borrow `s` as mutable because it is also borrowed as
+17:6 error: cannot borrow `s` as mutable because it is also borrowed as
immutable [E0502]
s.clear(); // Error!
^
@@ -2569,7 +2956,7 @@ literals.
The type of s here is &str: It’s a slice, pointing to that specific point
of the binary. This is also why string literals are immutable; &str is an
immutable reference.
-String slices as arguments
+String slices as arguments
Knowing that you can take slices of both literals and Strings leads us to
one more improvement on first_word(), and that’s its signature:
fn first_word(s: &String) -> &str {
@@ -2585,8 +2972,8 @@ with no loss of functionality:
# fn first_word(s: &str) -> &str {
# let bytes = s.as_bytes();
#
-# for (i, &byte) in bytes.iter().enumerate() {
-# if byte == 32 {
+# for (i, &item) in bytes.iter().enumerate() {
+# if item == 32 {
# return &s[0..i];
# }
# }
@@ -2594,16 +2981,22 @@ with no loss of functionality:
# &s[..]
# }
fn main() {
- let s = String::from("hello world");
- let word = first_word(&s[..]);
+ let my_string = String::from("hello world");
- let s = "hello world";
- let word = first_word(&s[..]);
+ // first_word works on slices of `String`s
+ let word = first_word(&my_string[..]);
- let word = first_word(s); // since literals are &strs, this works too!
+ let my_string_literal = "hello world";
+
+ // first_word works on slices of string literals
+ let word = first_word(&my_string_literal[..]);
+
+ // since string literals *are* string slices already,
+ // this works too, without the slice syntax!
+ let word = first_word(my_string_literal);
}
-Other slices
+Other slices
String slices, as you might imagine, are specific to strings. But there’s a more
general slice type, too. Consider arrays:
let a = [1, 2, 3, 4, 5];
@@ -2615,13 +3008,16 @@ part of an array:
let slice = &a[1..3];
This slice has the type &[i32]. It works the exact same way as string slices
-do, with a reference to the first element, and a length. You’ll use this kind
-of slice for all sorts of other collections. We’ll discuss these other slices
-in detail when we talk about vectors, in Chapter 9.1.
+do, by storing a reference to the first element and a length. You’ll use this
+kind of slice for all sorts of other collections. We’ll discuss these in detail
+when we talk about vectors in Chapter XX.
Structs
-So far, all of the data types we’ve seen allow us to have a single value
-at a time. structs give us the ability to package up multiple values and
-keep them in one related structure.
+A struct, short for "structure", gives us the ability to name and package
+together multiple related values that make up a meaningful group. If you come
+from an object-oriented language, a struct is like an object's data
+attributes. struct and enum (that we talked about in the last chapter) are
+the building blocks you can use in Rust to create new types in your program's
+domain in order to take full advantage of Rust's compile-time type checking.
Let’s write a program which calculates the distance between two points.
We’ll start off with single variable bindings, and then refactor it to
use structs instead.
@@ -2660,39 +3056,40 @@ Point 1: (0, 5)
Point 2: (12, 0)
Distance: 13
-Let's take a quick look at distance() before we move forward:
-fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
- let x_squared = f64::powi(x2 - x1, 2);
- let y_squared = f64::powi(y2 - y1, 2);
-
- f64::sqrt(x_squared + y_squared)
-}
-
-To find the distance between two points, we can use the Pythagorean Theorem.
-The theorem is named after Pythagoras, who was the first person to mathematically
-prove this formula. The details aren't that important, to be honest. There's a few
-things that we haven't discussed yet, though.
+Let's take a quick look at distance() before we move forward. To find the
+distance between two points, we can use the Pythagorean Theorem. The theorem is
+named after Pythagoras, who was the first person to mathematically prove this
+formula. The details aren't that important; just know the theorem says that the
+formula for the distance between two points is equal to:
+
+- squaring the distance between the points horizontally (the "x" direction)
+- squaring the distance between the points vertically (the "y" direction)
+- adding those together
+- and taking the square root of that.
+
+So that's what we're implementing here.
f64::powi(2.0, 3)
The double colon (::) here is a namespace operator. We haven’t talked about
-modules yet, but you can think of the powi() function as being scoped inside
-of another name. In this case, the name is f64, the same as the type. The
-powi() function takes two arguments: the first is a number, and the second is
-the power that it raises that number to. In this case, the second number is an
-integer, hence the ‘i’ in its name. Similarly, sqrt() is a function under the
-f64 module, which takes the square root of its argument.
+modules and namespaces in depth yet, but you can think of the powi() function
+as being scoped inside of another name. In this case, the name is f64, the
+same as the type. The powi() function takes two arguments: the first is a
+number, and the second is the power that it raises that number to. In this
+case, the second number is an integer, hence the ‘i’ in its name. Similarly,
+sqrt() is a function under the f64 module, which takes the square root of
+its argument.
Why structs?
-Our little program is okay, but we can do better. The key is in the signature
-of distance():
+Our little program is okay, but we can do better. The key to seeing this is in
+the signature of distance():
fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
The distance function is supposed to calculate the distance between two points.
But our distance function calculates some distance between four numbers. The
first two and last two arguments are related, but that’s not expressed anywhere
-in our program itself. We need a way to group (x1, y1) and (x2, y2)
-together.
-We’ve already discussed one way to do that: tuples. Here’s a version of our program
-which uses tuples:
+in our program itself. It would be nicer if we had a way to group (x1, y1)
+and (x2, y2) together.
+We’ve already discussed one way to do that: tuples. Here’s a version of our
+program which uses tuples:
fn main() {
let p1 = (0.0, 5.0);
@@ -2713,16 +3110,17 @@ fn distance(p1: (f64, f64), p2: (f64, f64)) -> f64 {
}
This is a little better, for sure. Tuples let us add a little bit of structure.
-We’re now passing two arguments, so that’s more clear. But it’s also worse.
-Tuples don’t give names to their elements, and so our calculation has gotten
-much more confusing:
+We’re now passing two arguments, so that’s more clear. But it’s also worse:
+tuples don’t give names to their elements, so our calculation has gotten more
+confusing:
p2.0 - p1.0
p2.1 - p1.1
When writing this example, your authors almost got it wrong themselves! Distance
-is all about x and y points, but now it’s all about 0 and 1. This isn’t
-great.
-Enter structs. We can transform our tuples into something with a name:
+is all about x and y points, but our code is talking about 0 and 1.
+This isn’t great.
+Enter structs. We can transform our tuples into something with a name for the
+whole as well as names for the parts:
let p1 = (0.0, 5.0);
struct Point {
@@ -2732,19 +3130,12 @@ struct Point {
let p1 = Point { x: 0.0, y: 5.0 };
-Here’s what declaring a struct looks like:
-struct NAME {
- NAME: TYPE,
-}
-
-The NAME: TYPE bit is called a ‘field’, and we can have as many or as few of
-them as you’d like. If you have none of them, drop the {}s:
-struct Foo;
-
-structs with no fields are called ‘unit structs’, and are used in certain
-advanced situations. We will just ignore them for now.
-You can access the field of a struct in the same way you access an element of
-a tuple, except you use its name:
+Here we've defined a struct and given it the name Point. The parts inside
+{} are defining the fields of the struct. We can have as many or as few of
+them as we'd like, and we give them a name and specify their type. Here we have
+two fields named x and y, and they both hold f64s.
+We can access the field of a struct in the same way we access an element of
+a tuple, except we use its name:
let p1 = (0.0, 5.0);
let x = p1.0;
@@ -2786,21 +3177,84 @@ fn distance(p1: Point, p2: Point) -> f64 {
Our function signature for distance() now says exactly what we mean: it
calculates the distance between two Points. And rather than 0 and 1,
we’ve got back our x and y. This is a win for clarity.
-There’s one other thing that’s a bit strange here, this annotation on our
+
Derived Traits
+There’s one other thing that’s a bit strange here, this stuff above the
struct declaration:
#[derive(Debug,Copy,Clone)]
struct Point {
-We haven’t yet talked about traits, but we did talk about Debug when we
-discussed arrays. This derive attribute allows us to tweak the behavior of
-our Point. In this case, we are opting into copy semantics, and everything
-that implements Copy must implement Clone.
-Method Syntax
+This is an annotation that tells the compiler our struct should get some
+default behavior for the Debug, Copy, and Clone traits. We talked about
+marking that types can be Copy and Clone-able in Chapter XX when we
+discussed ownership. Debug is the trait that enables us to print out our
+struct so that we can see its value while we are debugging our code.
+So far, we’ve been printing values using {} in a println! macro. If we try
+that with a struct, however, by default, we'll get an error. Say we have the
+following program:
+struct Point {
+ x: f64,
+ y: f64,
+}
+
+fn main() {
+ let p1 = Point { x: 0.0, y: 5.0};
+ println!("Point 1: {}", p1);
+}
+
+This code tries to print the p1 point directly, which may seem innocuous. But
+running it produces the following output:
+$ cargo run
+ Compiling points v0.1.0 (file:///projects/points)
+error: the trait bound `Point: std::fmt::Display` is not satisfied [--explain E0277]
+ --> src/main.rs:8:29
+8 |> println!("Point 1: {}", p1);
+ |> ^^
+<std macros>:2:27: 2:58: note: in this expansion of format_args!
+<std macros>:3:1: 3:54: note: in this expansion of print! (defined in <std macros>)
+src/main.rs:8:5: 8:33: note: in this expansion of println! (defined in <std macros>)
+note: `Point` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string
+note: required by `std::fmt::Display::fmt`
+
+Whew! The core of the error is this part: the trait bound Point: std::fmt::Display is not satisfied. println! can do many kinds of
+formatting. By default, {} implements a kind of formatting known as
+Display: output intended for direct end-user consumption. The primitive types
+we’ve seen implement Display, as there’s only one way you’d show a 1 to a
+user. But with structs, the output is less clear. Do you want commas or not?
+What about the {}s? Should all the fields be shown?
+More complex types in the standard library and that are defined by the
+programmer do not automatically implement Display formatting. Standard
+library types implement Debug formatting, which is intended for the
+programmer to see. The #[derive(Debug)] annotation lets us use a default
+implementation of Debug formatting to easily get this ability for types we've
+defined. To ask println! to use Debug formatting with our Point, we add
+the annotation to derive the trait and include :? in the print string, like
+this:
+#[derive(Debug)]
+struct Point {
+ x: f64,
+ y: f64,
+}
+
+fn main() {
+ let p1 = Point { x: 0.0, y: 5.0};
+ println!("Point 1: {:?}", p1);
+}
+
+If you run this, it should print the values of each field in the Point struct
+as desired:
+$ cargo run
+ Compiling points v0.1.0 (file:///projects/points)
+ Running `target/debug/points`
+Point 1: Point { x: 0, y: 5 }
+
+You’ll see this repeated later with other types. We’ll cover traits fully in
+Chapter XX.
+Method Syntax
In the last section on ownership, we made several references to ‘methods’.
Methods look like this:
-let s1 = String::from("hello");
+let s1 = "hello";
-// call a method on our String
+// call a method on s1
let s2 = s1.clone();
println!("{}", s1);
@@ -2816,11 +3270,12 @@ h(g(f(x)));
// with methods
x.f().g().h();
-The nested-functions version reads in reverse: we call f(), then g(), then
-h(), but it reads as h(), then g(), then f().
+The nested-functions version reads in reverse: the program executes f(), then
+g(), then h(), but we read it left-to-right as h(), then g(), then
+f(). The method syntax is executed in the same order as we would read it.
Before we get into the details, let’s talk about how to define your own
methods.
-Defining methods
+Defining methods
We can define methods with the impl keyword. impl is short for
‘implementation’. Doing so looks like this:
#[derive(Debug,Copy,Clone)]
@@ -2845,71 +3300,33 @@ assert_eq!(8.200609733428363, p1.distance(&p2));
Let’s break this down. First, we have our Point struct from earlier in the
chapter. Next comes our first use of the impl keyword:
-# #[derive(Debug,Copy,Clone)]
-# struct Point {
-# x: f64,
-# y: f64,
-# }
-#
-impl Point {
-# fn distance(&self, other: &Point) -> f64 {
-# let x_squared = f64::powi(other.x - self.x, 2);
-# let y_squared = f64::powi(other.y - self.y, 2);
-#
-# f64::sqrt(x_squared + y_squared)
-# }
+impl Point {
+ // ...
}
-#
-# let p1 = Point { x: 0.0, y: 0.0 };
-# let p2 = Point { x: 5.0, y: 6.5 };
-#
-# assert_eq!(8.200609733428363, p1.distance(&p2));
Everything we put inside of the curly braces will be methods implemented on
-Point.
-# #[derive(Debug,Copy,Clone)]
-# struct Point {
-# x: f64,
-# y: f64,
-# }
-#
-# impl Point {
- fn distance(&self, other: &Point) -> f64 {
-# let x_squared = f64::powi(other.x - self.x, 2);
-# let y_squared = f64::powi(other.y - self.y, 2);
-#
-# f64::sqrt(x_squared + y_squared)
- }
-# }
-#
-# let p1 = Point { x: 0.0, y: 0.0 };
-# let p2 = Point { x: 5.0, y: 6.5 };
-#
-# assert_eq!(8.200609733428363, p1.distance(&p2));
-
-Next is our definition. This looks very similar to our previous definition of
-distance() as a function:
-# #[derive(Debug,Copy,Clone)]
-# struct Point {
-# x: f64,
-# y: f64,
-# }
-fn distance(p1: Point, p2: Point) -> f64 {
-# let x_squared = f64::powi(p2.x - p1.x, 2);
-# let y_squared = f64::powi(p2.y - p1.y, 2);
-#
-# f64::sqrt(x_squared + y_squared)
-# }
+Point. Next is our definition:
+fn distance(&self, other: &Point) -> f64 {
+ // ...
+}
Other than this, the rest of the example is familiar: an implementation of
-distance(), and using the method to find an answer.
-There are two differences. The first is in the first argument. Instead of a name
-and a type, we have written &self. This is what distinguishes a method from a
-function: using self inside of an impl block. Because we already know that
-we are implementing this method on Point, we don’t need to write the type of
-self out. However, we have written &self, not only self. This is because
-we want to take our argument by reference rather than by ownership. In other
-words, these two forms are the same:
+distance() and using the method to find an answer.
+Our definition of distance() here as a method looks very similar to our
+previous definition of distance() as a function, but with two differences.
+Here's the distance() function again:
+fn distance(p1: Point, p2: Point) -> f64 {
+ // ...
+}
+
+The first difference is in the first argument. Instead of a name and a type, we
+have written &self. This is what distinguishes a method from a function:
+using self inside of an impl block means we have a method. Because we
+already know that we are implementing this method on Point because of the
+surrounding impl Point block, we don’t need to write the type of self out.
+Note that we have written &self, not just self. This is because we want to
+take a reference to our argument's value rather than taking ownership of it. In
+other words, these two forms are the same:
fn foo(self: &Point)
fn foo(&self)
@@ -2919,31 +3336,15 @@ list, with the most common form first:
fn foo(&mut self) // take self by mutable reference
fn foo(self) // take self by ownership
-In this case, we only need a reference. We don’t plan on taking ownership, and
-we don’t need to mutate either point. Taking by reference is by far the most
-common form of method, followed by a mutable reference, and then occasionally
-by ownership.
-Methods and automatic referencing
+In this case, we only need a reference. We don’t need to mutate either Point
+to get the distance between them, so we won't take a mutable reference to the
+Point that we call the method on. Methods that take ownership of self are
+rarely used. An example of a time to do that would be if we wanted to have a
+method that would transform self into something else and prevent other code
+from using the value of self after the transformation happens.
+Methods and automatic referencing
We’ve left out an important detail. It’s in this line of the example:
-# #[derive(Debug,Copy,Clone)]
-# struct Point {
-# x: f64,
-# y: f64,
-# }
-#
-# impl Point {
-# fn distance(&self, other: &Point) -> f64 {
-# let x_squared = f64::powi(other.x - self.x, 2);
-# let y_squared = f64::powi(other.y - self.y, 2);
-#
-# f64::sqrt(x_squared + y_squared)
-# }
-# }
-#
-# let p1 = Point { x: 0.0, y: 0.0 };
-# let p2 = Point { x: 5.0, y: 6.5 };
-#
-assert_eq!(8.200609733428363, p1.distance(&p2));
+assert_eq!(8.200609733428363, p1.distance(&p2));
When we defined distance(), we took both self and the other argument by
reference. Yet, we needed a & for p2 but not p1. What gives?
@@ -2956,12 +3357,12 @@ or &muts to match the signature. In other words, these are the
# x: f64,
# y: f64,
# }
-#
+#
# impl Point {
# fn distance(&self, other: &Point) -> f64 {
# let x_squared = f64::powi(other.x - self.x, 2);
# let y_squared = f64::powi(other.y - self.y, 2);
-#
+#
# f64::sqrt(x_squared + y_squared)
# }
# }
@@ -2989,65 +3390,37 @@ of a method whether the method is just reading (so needs &self)
&mut self), or consuming (so self). The fact that Rust makes borrowing
implicit for method receivers is a big part of making ownership ergonomic in
practice.
-Methods can be called like functions
-Furthermore, if we have a method, we can also call it like a function:
-# #[derive(Debug,Copy,Clone)]
-# struct Point {
-# x: f64,
-# y: f64,
-# }
-#
-# impl Point {
-# fn distance(&self, other: &Point) -> f64 {
-# let x_squared = f64::powi(other.x - self.x, 2);
-# let y_squared = f64::powi(other.y - self.y, 2);
-#
-# f64::sqrt(x_squared + y_squared)
-# }
-# }
-# let p1 = Point { x: 0.0, y: 0.0 };
-# let p2 = Point { x: 5.0, y: 6.5 };
-let d1 = p1.distance(&p2);
-let d2 = Point::distance(&p1, &p2);
-
-assert_eq!(d1, d2);
-
-Instead of using self.(, we use Point and the namespace operator to call it
-like a function instead. Because functions do not do the automatic referencing,
-we must pass in &p1 explicitly.
-While methods can be called like functions, functions cannot be called like
-methods. If the first argument isn’t named self, it cannot be called like a
-method.
Enums
-Next, let’s look at a feature of Rust that’s similar to structs, but also
-different. Enumerations, or ‘enums’ as they’re more commonly referred to,
-are an extremely powerful feature of Rust. Enums are a feature that are in many
-languages, but what they can do is different per-language. Rust’s enums are
-most similar to enums in functional languages.
-Here’s an example of an enum:
+Next, let’s look at enumerations, which allow you to define a type by
+enumerating its possible values. Commonly called "enums", these unlock a lot of
+power in Rust when combined with pattern matching. Enums are a feature that are
+in many languages, but what they can do is different per-language. Rust’s enums
+are most similar to "algebraic data types" in functional languages like F#,
+OCaml, or Haskell.
+Here’s an example of an enum definition:
enum IpAddrKind {
V4,
V6,
}
This enum represents the kind of an IP address. There are two major standards
-used for IP addresses: version four, and version six. Any IP address can be either
-a version four address, or a version six address. But it cannot be both kinds at
-the same time. This is where enums get their name: they allow us to enumerate all
-of the possible kinds that our value can have.
+used for IP addresses: version four and version six. Any IP address can be
+either a version four address or a version six address, but it cannot be both
+kinds at the same time. This is where enums get their name: they allow us to
+enumerate all of the possible kinds that our value can have.
We can create values of IpAddrKind like this:
# enum IpAddrKind {
# V4,
# V6,
# }
-
+#
let four = IpAddrKind::V4;
let six = IpAddrKind::V6;
Note that the variants of the enum are namespaced under its name, and we use
the double colon to separate the two.
Enums have more tricks up their sleeves, however. Thinking more about our IP
-address type, we don’t have a way to store the actual data of the IP address,
+address type, we don’t have a way to store the actual data of the IP address;
we only know what kind it is. Given that you just learned about structs, you
might tackle this problem like this:
enum IpAddrKind {
@@ -3071,8 +3444,8 @@ let loopback = IpAddr {
};
We’ve used a struct to bundle the two values together: now we keep the kind
-with the value itself. This design isn’t bad, exactly, but it wouldn’t be
-considered idiomatic Rust. We can represent the same thing with just an enum:
+with the value itself. We can represent the same thing in a different way with
+just an enum:
enum IpAddr {
V4(String),
V6(String),
@@ -3086,10 +3459,10 @@ let loopback = IpAddr::V6(String::from("::1"));
struct. But beyond that, this approach is better than using a struct alongside
our enum because we can attach different kinds of data to each variant.
Imagine that instead of a String, we would prefer to store a V4 as its four
-individual components, while leaving the V6 variant as a String. With our
+individual components while leaving the V6 variant as a String. With our
struct, we’d be stuck. But enums deal with this case with ease:
enum IpAddr {
- V4(u32, u32, u32, u32),
+ V4(u8, u8, u8, u8),
V6(String),
}
@@ -3098,8 +3471,8 @@ let home = IpAddr::V4(127, 0, 0, 1);
let loopback = IpAddr::V6(String::from("::1"));
You can put any kind of data inside of an enum variant, including another enum!
-The IpAddr enum is in the standard library, but it embeds two different
-structs inside of its variants:
+The IpAddr enum is in the standard library, but it embeds two
+different structs inside of its variants:
struct Ipv4Addr {
// details elided
}
@@ -3127,13 +3500,25 @@ enum IpAddr {
Write includes a single String.
ChangeColor includes three i32s.
-We haven’t talked a lot about how to access the data inside an enum variant,
-however. To do that, let’s move on to some new Rust syntax that’s especially
-useful with enums: match.
-Option
-Now that we have a handle on enums, let's combine them with a feature that we
-talked a little bit about in the previous chapter: generics.
-Programming language design is often though of as which features you include,
+
This might seem overwhelming, but another way to look at the different enum
+possibilities is that they are just like different kinds of struct definitions
+that you already know, except without the struct keyword and they are grouped
+together under the Message type. These structs could hold the same data that
+these enum variants hold:
+struct QuitMessage; // unit struct
+struct MoveMessage {
+ x: i32,
+ y: i32,
+}
+struct WriteMessage(String); // tuple struct
+struct ChangeColorMessage(i32, i32, i32); // tuple struct
+
+Let's look at another enum in the standard library that is very common and
+useful: Option.
+Option
+Now that we have had an introduction to enums, let's combine them with a
+feature that we talked a little bit about in the previous chapter: generics.
+Programming language design is often thought of as which features you include,
but it's also about which features you leave out. Rust does not have a feature
that is in many other languages: 'null'. In languages with this feature,
variables can have two states: null or not-null.
@@ -3159,14 +3544,14 @@ pervasive, it's extremely easy to make this kind of error.
useful one: this is a value which is currently invalid or not present for some
reason. The problem isn't with the concept itself, but with the particular
implementation. As such, Rust does not have the concept of null, but we do have
-a type which can encode the concept of a value being present. We call this type
-Option<T>, and it looks like this:
+an enum which can encode the concept of a value being present or not present. We
+call this enum Option<T>, and it looks like this:
enum Option<T> {
Some(T),
None,
}
-This type is provided by the standard library, and is so useful that
+
This enum is provided by the standard library, and is so useful that
it's even in the prelude; you don't need to import it explicitly. Furthermore,
so are its variants: you can say Some and None directly, without prefixing
them with Option::.
@@ -3184,36 +3569,176 @@ sense, None means 'null', and Some means 'not null'. S
better than null?
In short, because Option<T> and T are different types. That's a bit too
short though. Here's an example:
-let x = 5;
-let y = Some(5);
+let x: i8 = 5;
+let y: Option<i8> = Some(5);
let sum = x + y;
This will not compile. We get an error message like this:
-error: the trait `core::ops::Add<core::option::Option<_>>` is not implemented
-for the type `_` [E0277]
+error: the trait bound `i8: std::ops::Add<std::option::Option<i8>>` is not
+satisfied [E0277]
let sum = x + y;
^~~~~
Intense! What this error message is trying to say is that Rust does not
understand how to add an Option<T> and a T. They're different types! This
-shows one of the big advantages of an Option<T> type: if you have a type that
+shows one of the big advantages of an Option<T>: if you have a value that
may or may not exist, you have to deal with that fact before you can assume it
exists. In other words, you have to convert an Option<T> to a T before you
can do T stuff with it. This helps catch one of the most common issues with
-null, generally: assuming that something isn't null, when it actually is.
-So, how do you get a T from an Option<T>? The option type has a large
-number of methods that you can check out in its documentation, and becoming
-familiar with them will be extremely useful in your journey with Rust.
+null, generally: assuming that something isn't null when it actually is.
+This is pretty powerful: in order to have a value that can possibly be null,
+you have to explicitly opt in by making the type of that value an Option<T>.
+Then, when you use that value, you are required to explicitly handle the case
+when the value is null. Everywhere that a value has a type that isn't an
+Option<T>, you can safely assume that the value isn't null. This was a
+deliberate design decision for Rust to limit null's pervasiveness and increase
+the safety of Rust code.
+So, how do you get a T from an Option<T>? The Option<T> enum has a
+large number of methods that you can check out in its documentation, and
+becoming familiar with them will be extremely useful in your journey with Rust.
But we want a deeper understanding than that. If we didn't have those methods
-defined for us already, what would we do? For that, we need a new feature: match.
-Match
+defined for us already, what would we do? And more generally, how do we get
+the inner values out of any enum variant? We need a new feature: match.
+Match
Rust has an extremely powerful control-flow operator: match. It allows us to
-compare a value against a series of patterns, and then execute code based on
-how they compare. Remember the Option<T> type from the previous section?
-Let's say that we want to write a function that takes an Option<i32>, and
-if there's a value inside, add one to it.
+compare a value against a series of patterns and then execute code based on
+how they compare.
+Think of a match expression kind of like a coin sorting machine. Coins slide
+down a track that has variously sized holes along it, and each coin falls
+through the first hole it encounters that it fits into. In the same way, values
+go through each pattern in a match, and for the first pattern that the value
+"fits", the value will fall into the associated code block to be used during
+execution.
+Since we're already talking about coins, let's use them for an example using
+match! We can write a function that can take an unknown American coin and, in
+a similar way as the coin counting machine, determine which coin it is and
+return its value in cents:
+enum Coin {
+ Penny,
+ Nickel,
+ Dime,
+ Quarter,
+}
+
+fn value_in_cents(coin: Coin) -> i32 {
+ match coin {
+ Coin::Penny => 1,
+ Coin::Nickel => 5,
+ Coin::Dime => 10,
+ Coin::Quarter => 25,
+ }
+}
+
+Let's break down the match! At a high-level, using match looks like this:
+match expression {
+ pattern => code,
+}
+
+First, we have the match keyword. Next, we have an expression. This feels
+very similar to an expression used with if, but there's a big difference:
+with if, the condition needs to return a boolean value. Here, it can be any
+type.
+Next, we have a "match arm". That's the part that looks like pattern => code,. We can have as many arms as we need to: our match above has four
+arms. An arm has two parts: a pattern and some code. When the match
+expression executes, it compares the resulting value against the pattern of
+each arm, in order. If a pattern matches the value, the code associated
+with that pattern is executed. If that pattern doesn't match the value,
+execution continues to the next arm, much like a coin sorting machine.
+The code associated with each arm is an expression, and the resulting value of
+the code with the matching arm that gets executed is the value that gets
+returned for the entire match expression.
+Curly braces typically aren't used if the match arm code is short, as it is in
+the above example where each arm just returns a value. If we wanted to run
+multiple lines of code in a match arm, we can use curly braces. This code would
+print out "Lucky penny!" every time the method was called with a Coin::Penny,
+but would still return the last value of the block, 1:
+# enum Coin {
+# Penny,
+# Nickel,
+# Dime,
+# Quarter,
+# }
+#
+fn value_in_cents(coin: Coin) -> i32 {
+ match coin {
+ Coin::Penny => {
+ println!("Lucky penny!");
+ 1
+ },
+ Coin::Nickel => 5,
+ Coin::Dime => 10,
+ Coin::Quarter => 25,
+ }
+}
+
+Another useful feature of match arms is that they can create bindings to parts
+of the values that match the pattern. From 1999 through 2008, the U.S. printed
+quarters with different designs for each of the 50 states on one side. The other
+coins did not get state designs, so only quarters have this extra attribute. We
+can add this information to our enum by changing the Quarter variant to have
+a State value:
+enum UsState {
+ Alabama,
+ Alaska,
+ // ... etc
+}
+
+enum Coin {
+ Penny,
+ Nickel,
+ Dime,
+ Quarter(UsState),
+}
+
+Let's imagine that a friend of ours is trying to collect all 50 state quarters.
+While we sort our loose change by coin type in order to count it, we're going
+to call out the name of the state so that if it's one our friend doesn't have
+yet, they can add it to their collection.
+In the match statement to do this, the quarter case now has a binding, state,
+that contains the value of the state of that quarter. The binding will only get
+created if the coin matches the Quarter pattern. Then we can use the binding
+in the code for that arm:
+# #[derive(Debug)]
+# enum UsState {
+# Alabama,
+# Alaska,
+# }
+#
+# enum Coin {
+# Penny,
+# Nickel,
+# Dime,
+# Quarter(UsState),
+# }
+#
+fn value_in_cents(coin: Coin) -> i32 {
+ match coin {
+ Coin::Penny => 1,
+ Coin::Nickel => 5,
+ Coin::Dime => 10,
+ Coin::Quarter(state) => {
+ println!("State quarter from {:?}!", state);
+ 25
+ },
+ }
+}
+
+If we were to call value_in_cents(Coin::Quarter(UsState::Alaska)), coin will
+be Coin::Quarter(UsState::Alaska). When we compare that value with each of the
+match arms, none of them match until we reach Coin::Quarter(state). At that
+point, the binding for state will be the value UsState::Alaska. We can then
+use that binding in the println!, thus getting the inner state value out of
+the Coin enum variant for Quarter.
+Remember the Option<T> type from the previous section, and that we wanted to
+be able to get the inner T value out of the Some case? This will be very
+similar! Instead of coins, we will be comparing to other patterns, but the way
+that the match expression works remains the same as a coin sorting machine in
+the way that we look for the first pattern that fits the value.
+Let's say that we want to write a function that takes an Option<i32>, and
+if there's a value inside, add one to it. If there isn't a value inside, we
+want to return the None value and not attempt to add.
This function is very easy to write, thanks to match. It looks like this:
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
@@ -3226,21 +3751,6 @@ let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
-Let's break down the match! At a high-level, the match expression looks
-like this:
-match condition {
- pattern => code,
-}
-
-First, we have the match keyword. Next, we have a condition. This feels very
-similar to an if expression, but there's a big difference: with if, the
-condition needs to be a boolean. Here, it can be any type.
-Next, we have a "match arm". That's the part that looks like pattern => code,. We can have as many arms as we need to: our match above has two
-arms. An arm has two parts: a pattern, and some code. When the match
-expression executes, it compares the condition against the pattern of each arm,
-in turn. If the pattern matches the condition, the associated code is executed,
-and the rest of the patterns are not checked. If it doesn't match, execution
-continues to the next arm.
Let's examine the first execution of plus_one() in more detail. In the above
example, x will be Some(5). Let's compare that against each arm:
None => None,
@@ -3248,31 +3758,23 @@ example, x will be Some(5). Let's compare that against
Does Some(5) match None? No, it's the wrong variant. So let's continue.
Some(i) => Some(i + 1),
-Does Some(5) match Some(i)? Why yes it does! We have the same variant. But
-what about i? In a pattern like this, we can declare new bindings, similarly
-to what we did with let. So in this case, the code part of the match arm will
-have a binding, i, which corresponds to the 5.
-With this arm, the code portion is Some(i + 1). So we do exactly that: we
-take i, which is 5, add one to it, and create a new Some value with our
-sum inside.
-Because match is an expression, the value of the overall expression becomes
-the value of the arm that executed. So the value of this match expression
-will be Some(6). And since our match is the only expression in the
-function, the value of the match will be the value of the function, and so
-Some(6) is our return value as well, which is exactly what we were shooting
-for.
-Now let's consider the second call. In this case, x is None. We enter the
-match, and compare to the first arm:
+Does Some(5) match Some(i)? Why yes it does! We have the same variant. The
+i binds to the value inside of the Some, so i has the value 5. Then we
+execute the code in that match arm: take i, which is 5, add one to it, and
+create a new Some value with our total inside.
+Now let's consider the second call of plus_one(). In this case, x is
+None. We enter the match, and compare to the first arm:
None => None,
-Does None match None? Yup! And so we return None. There's no value to add
-to.
+Does None match None? Yup! There's no value to add to. So we stop and
+return the None value that is on the right side of the =>. We don't
+check any other arms since we found one that matched.
Combining match and enums together is extremely powerful. You'll see this
-pattern a lot in Rust code: match against an enum, binding to the data
-inside, and then executing code based on it. It's a bit tricky at first, but
+pattern a lot in Rust code: match against an enum, bind to the data
+inside, and then execute code based on it. It's a bit tricky at first, but
once you get used to it, you'll wish you had it in languages that don't support
it. It's consistently a user favorite.
-Matches are exhaustive
+Matches are exhaustive
There's one other aspect of match we didn't talk about. Consider this version
of plus_one():
fn plus_one(x: Option<i32>) -> Option<i32> {
@@ -3281,58 +3783,27 @@ of plus_one():
}
}
-A bug! We didn't handle the None case. Luckily, it's a bug Rust knows how to catch.
-If we try to compile this code, we'll get an error:
+A bug! We didn't handle the None case. Luckily, it's a bug Rust knows how to
+catch. If we try to compile this code, we'll get an error:
error: non-exhaustive patterns: `None` not covered [E0004]
match x {
Some(i) => Some(i + 1),
}
Rust knows that we did not cover every possible option, and even knows which
-pattern we forgot! This is referred to as being "exhaustive", we must exhaust
-every last option possible in order to be valid!
-This analysis isn't perfect, however. This will also error:
-# let some_u8_value = 0u8;
-match some_u8_value {
- 0 => println!("zero"),
- 1 => println!("one"),
- 2 => println!("two"),
- 3 => println!("three"),
- 4 => println!("four"),
- 5 => println!("five"),
- 6 => println!("six"),
- 7 => println!("seven"),
- // We won't write out all of the arms here, but imagine that there are more
- // arms corresponding to the rest of the numbers.
- 254 => println!("two-hundred and fifty-four"),
- 255 => println!("two-hundred and fifty-five"),
-}
-
-Even though a u8 can only have valid values of zero through 255, Rust isn't
-quite smart enough to understand we've covered all the cases. In order to fix
-this, we can use a special pattern, _:
-# let some_u8_value = 0u8;
-match some_u8_value {
- 0 => println!("zero"),
- 1 => println!("one"),
- 2 => println!("two"),
- 3 => println!("three"),
- 4 => println!("four"),
- 5 => println!("five"),
- 6 => println!("six"),
- 7 => println!("seven"),
- // ...
- 254 => println!("two-hundred and fifty-four"),
- 255 => println!("two-hundred and fifty-five"),
- _ => panic!("can't ever happen"),
-}
-
-The _ pattern matches anything at all, and so with it as the final pattern,
-Rust can understand that we have all our bases covered. It's not only used for
-this sort of exhaustiveness issue, though. It's useful any time we don't want to
-deal with a number of cases. Consider this scenario: if we wanted to print out
-something one one, three, five, and seven:
-# let some_u8_value = 0u8;
+pattern we forgot! This is referred to as being "exhaustive": we must exhaust
+every last option possible in order to be valid. Especially in the case of
+Option<T>, when Rust prevents us from forgetting to explicitly handle the
+None case, it protects us from assuming that we have a value when we might
+have null and thus making the billion-dollar mistake we discussed in the
+previous section.
+The _ placeholder
+What if we don't care about all of the possible values, though? Especially when
+there are a lot of possible values for a type: a u8 can have valid values of
+zero through 255-- if we only care about 1, 3, 5, and 7, does this mean we must
+list out 0, 2, 4, 6, 8, 9, all the way up through 255? Thankfully, no! We can
+use a special pattern, _:
+let some_u8_value = 0u8;
match some_u8_value {
1 => println!("one"),
3 => println!("three"),
@@ -3342,11 +3813,10 @@ match some_u8_value {
}
The _ pattern will match all the other cases, and () will do nothing, it's
-the unit value.
-More about patterns
-As we've just seen, patterns are powerful, yet complex. Let's take a whole
-section to cover all of the things that they can do.
-if let
+the unit value. This way, we don't have to list individual match arms for all
+the other possible values in order to say that we want to do nothing for all of
+those-- the _ is a placeholder for any value.
+if let
There's one more advanced control flow structure we haven't discussed: if let. Imagine we're in a situation like this:
# let some_option = Some(5);
match some_option {
@@ -3359,9 +3829,9 @@ match some_option {
We care about the Some case, but don't want to do anything with the None
case. With an Option, this isn't too bad, but with a more complex enum,
adding _ => {} after processing just one variant doesn't feel great. We have
-this boilerplate arm, and we have an extra level of indentation: the code that
-does something with x is indented twice, rather than just once. We really want
-a construct that says "Do something with this one case, I don't care about the
+this boilerplate arm and an extra level of indentation (the code that
+does something with x is indented twice, rather than just once). We really want
+a construct that says "Do something with this one case; I don't care about the
others."
Enter if let:
# let some_option = Some(5);
@@ -3396,7 +3866,7 @@ match expression {
}
In other words, it's the high-level construct we were originally looking for:
-do something with a single pattern.
+do something special with only one pattern.
Generics
We've been working with a Point struct that looks like this:
#[derive(Debug,Copy,Clone)]
@@ -3809,6 +4279,67 @@ src/main.rs:1 /// What am I documenting?
^~~~~~~~~~~~~~~~~~~~~~~~~~
Generating HTML documentation
+Appendix
+The following sections contain reference material you may find useful in your
+Rust journey.
+Keywords
+The following keywords are reserved by the Rust language and may not be used as
+names of functions, variables, macros, modules, crates, constants, static
+values, attributes, struct fields, or arguments.
+
+abstract
+alignof
+as
+become
+box
+break
+const
+continue
+crate
+do
+else
+enum
+extern
+false
+final
+fn
+for
+if
+impl
+in
+let
+loop
+macro
+match
+mod
+move
+mut
+offsetof
+override
+priv
+proc
+pub
+pure
+ref
+return
+Self
+self
+sizeof
+static
+struct
+super
+trait
+true
+type
+typeof
+unsafe
+unsized
+use
+virtual
+where
+while
+yield
+