From 4e18be330e5e107dcb66bae5df190a48c15dced7 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Mon, 21 Dec 2015 17:39:44 +0000 Subject: [PATCH] rebuild pages at 26bc17b --- if.html | 172 ++++++++++++ loops.html | 145 ++++++++++ primitive-types.html | 154 ++++++++++- print.html | 488 +++++++++++++++++++++++++++++++++- references-and-borrowing.html | 17 ++ 5 files changed, 974 insertions(+), 2 deletions(-) diff --git a/if.html b/if.html index d16f3361a..8d6f9163f 100644 --- a/if.html +++ b/if.html @@ -66,6 +66,178 @@

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”
  • +
+
+

One of the most primitive operations in computer programming is the ability to +‘branch’ between two different code paths. A program can look at a value, and +then decide: should I follow this path, or should I take the other? There’s +actually two different metaphors here: a tree, whose branches come from the +same, single trunk. And a road, which splits off into two, each going in a +different direction.

+

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:///home/steve/tmp/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:///home/steve/tmp/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:///home/steve/tmp/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 if

+

We 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:///home/steve/tmp/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:

+
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:///home/steve/tmp/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:///home/steve/tmp/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. This also +means that you almost certainly need an else when using if in +this way. If you don’t, what would the value be if the condition was +false?

diff --git a/loops.html b/loops.html index ab0bbf893..aadf60a9e 100644 --- a/loops.html +++ b/loops.html @@ -66,6 +66,151 @@

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:

+
$ 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:

+
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:///home/steve/tmp/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.

+

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:///home/steve/tmp/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:

+
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:///home/steve/tmp/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.

+

for

+

We 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 is: {}", a[index]);
+
+        index = index + 1;
+    }
+}
+
+

Running this will print out every element of the array:

+
$ cargo run
+   Compiling loops v0.1.0 (file:///home/steve/tmp/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];
+    let mut index = 0;
+    
+    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**

diff --git a/primitive-types.html b/primitive-types.html index d57d563e7..7a0c373f0 100644 --- a/primitive-types.html +++ b/primitive-types.html @@ -236,9 +236,161 @@ The second time, we pass plus_two() instead.

That’s really all there is to say about that!

Arrays

-

Slices

+

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.

+

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:///home/steve/tmp/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 10.

+

A ‘panic’ can also be induced manually, with the panic! macro:

+
fn main() {
+    panic!("Oh no!");
+}
+
+

When the panic! macro runs, it will cause a panic. +When a Rust program panics, it starts a kind of controlled crash. +The current thread of execution will stop entirely. +As such, panics are reserved for serious, program-ending errors. +They’re not a general error-handling mechanism.

+

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.

+

Steve’s note: this next bit might be our first ‘advanced’ section, on get()?

+

Debug

+

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:///home/steve/tmp/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 for end-users. +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, Deubg, which is a bit different: output for programmers and debuggers. +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:///home/steve/tmp/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.

char

+

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 intutition for what a ‘character’ is may not match up with a char. +It also means that chars are four bytes each.

+

The single quotes are important: to define a literal single character, we use single quotes. +If we used double quotes, we’d be defining a &str. Let’s talk about that next!

str

+

We can declare literal strings with "s. We’ve seen them already, with println!:

+
fn main() {
+    println!("println! takes a literal string as an argument.");
+
+    let s = "We can also create bindings to string literals.";
+
+    let s: &str = "Here’s one with a type annotation.";
+}
+
+

String literals are immutable, and of a fixed length. +Rust has a second string type, String, that we’ll discuss in section 8.

+

&strs are UTF-8 encoded.

diff --git a/print.html b/print.html index 82c9b2d89..298b6e32e 100644 --- a/print.html +++ b/print.html @@ -1411,9 +1411,161 @@ The second time, we pass plus_two() instead.

That’s really all there is to say about that!

Arrays

-

Slices

+

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.

+

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:///home/steve/tmp/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 10.

+

A ‘panic’ can also be induced manually, with the panic! macro:

+
fn main() {
+    panic!("Oh no!");
+}
+
+

When the panic! macro runs, it will cause a panic. +When a Rust program panics, it starts a kind of controlled crash. +The current thread of execution will stop entirely. +As such, panics are reserved for serious, program-ending errors. +They’re not a general error-handling mechanism.

+

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.

+

Steve’s note: this next bit might be our first ‘advanced’ section, on get()?

+

Debug

+

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:///home/steve/tmp/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 for end-users. +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, Deubg, which is a bit different: output for programmers and debuggers. +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:///home/steve/tmp/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.

char

+

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 intutition for what a ‘character’ is may not match up with a char. +It also means that chars are four bytes each.

+

The single quotes are important: to define a literal single character, we use single quotes. +If we used double quotes, we’d be defining a &str. Let’s talk about that next!

str

+

We can declare literal strings with "s. We’ve seen them already, with println!:

+
fn main() {
+    println!("println! takes a literal string as an argument.");
+
+    let s = "We can also create bindings to string literals.";
+
+    let s: &str = "Here’s one with a type annotation.";
+}
+
+

String literals are immutable, and of a fixed length. +Rust has a second string type, String, that we’ll discuss in section 8.

+

&strs are UTF-8 encoded.

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. @@ -1470,7 +1622,324 @@ src/main.rs:1 /// What am I documenting? Inner documentation comments look like this: //!. They are only really used to document modules, however, and so we will talk about them in the modules section.

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;

+ +
+

One of the most primitive operations in computer programming is the ability to +‘branch’ between two different code paths. A program can look at a value, and +then decide: should I follow this path, or should I take the other? There’s +actually two different metaphors here: a tree, whose branches come from the +same, single trunk. And a road, which splits off into two, each going in a +different direction.

+

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:///home/steve/tmp/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:///home/steve/tmp/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:///home/steve/tmp/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 if

+

We 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:///home/steve/tmp/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:

+
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:///home/steve/tmp/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:///home/steve/tmp/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. This also +means that you almost certainly need an else when using if in +this way. If you don’t, what would the value be if the condition was +false?

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:

+
$ 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:

+
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:///home/steve/tmp/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.

+

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:///home/steve/tmp/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:

+
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:///home/steve/tmp/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.

+

for

+

We 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 is: {}", a[index]);
+
+        index = index + 1;
+    }
+}
+
+

Running this will print out every element of the array:

+
$ cargo run
+   Compiling loops v0.1.0 (file:///home/steve/tmp/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];
+    let mut index = 0;
+    
+    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 & borrowing

Ownership

This guide is one of three presenting Rust’s ownership system. This is one of @@ -1645,6 +2114,23 @@ complicated.

Luckily, Rust offers a feature, borrowing, which helps us solve this problem. It’s the topic of the next section!

References and Borrowing

+

Slices

+

We saw how to use indexing to get a single element out of an array. +But we can also use indexing to get a reference to multiple elements:

+
fn main() {
+    let a = [1, 2, 3, 4, 5];
+
+    let s = &a[0..2];
+
+    println!("The value of s is: {:?}", s);
+}
+
+

Let’s try running it:

+
$ cargo run
+   Compiling functions v0.1.0 (file:///home/steve/tmp/functions)
+     Running `target/debug/functions`
+The value of s is: [1, 2]
+

This guide is two of three presenting Rust’s ownership system. This is one of Rust’s most unique and compelling features, with which Rust developers should become quite acquainted. Ownership is how Rust achieves its largest goal, diff --git a/references-and-borrowing.html b/references-and-borrowing.html index f9e087a48..a5628e71f 100644 --- a/references-and-borrowing.html +++ b/references-and-borrowing.html @@ -66,6 +66,23 @@

References and Borrowing

+

Slices

+

We saw how to use indexing to get a single element out of an array. +But we can also use indexing to get a reference to multiple elements:

+
fn main() {
+    let a = [1, 2, 3, 4, 5];
+
+    let s = &a[0..2];
+
+    println!("The value of s is: {:?}", s);
+}
+
+

Let’s try running it:

+
$ cargo run
+   Compiling functions v0.1.0 (file:///home/steve/tmp/functions)
+     Running `target/debug/functions`
+The value of s is: [1, 2]
+

This guide is two of three presenting Rust’s ownership system. This is one of Rust’s most unique and compelling features, with which Rust developers should become quite acquainted. Ownership is how Rust achieves its largest goal,