Clean out section three

Let's see if we can't make this all more consistent.
This commit is contained in:
Steve Klabnik
2015-12-16 15:13:26 -05:00
parent da54953597
commit 7f0b63387f
5 changed files with 0 additions and 1134 deletions
-308
View File
@@ -1,310 +1,2 @@
# Functions
Every Rust program has at least one function, the `main` function:
```rust
fn main() {
}
```
This is the simplest possible function declaration. As we mentioned before,
`fn` says ‘this is a function’, followed by the name, some parentheses because
this function takes no arguments, and then some curly braces to indicate the
body. Here’s a function named `foo`:
```rust
fn foo() {
}
```
So, what about taking arguments? Here’s a function that prints a number:
```rust
fn print_number(x: i32) {
println!("x is: {}", x);
}
```
Here’s a complete program that uses `print_number`:
```rust
fn main() {
print_number(5);
}
fn print_number(x: i32) {
println!("x is: {}", x);
}
```
As you can see, function arguments work very similar to `let` declarations:
you add a type to the argument name, after a colon.
Here’s a complete program that adds two numbers together and prints them:
```rust
fn main() {
print_sum(5, 6);
}
fn print_sum(x: i32, y: i32) {
println!("sum is: {}", x + y);
}
```
You separate arguments with a comma, both when you call the function, as well
as when you declare it.
Unlike `let`, you _must_ declare the types of function arguments. This does
not work:
```rust,ignore
fn print_sum(x, y) {
println!("sum is: {}", x + y);
}
```
You get this error:
```text
expected one of `!`, `:`, or `@`, found `)`
fn print_number(x, y) {
```
This is a deliberate design decision. While full-program inference is possible,
languages which have it, like Haskell, often suggest that documenting your
types explicitly is a best-practice. We agree that forcing functions to declare
types while allowing for inference inside of function bodies is a wonderful
sweet spot between full inference and no inference.
What about returning a value? Here’s a function that adds one to an integer:
```rust
fn add_one(x: i32) -> i32 {
x + 1
}
```
Rust functions return exactly one value, and you declare the type after an
‘arrow’, which is a dash (`-`) followed by a greater-than sign (`>`). The last
line of a function determines what it returns. You’ll note the lack of a
semicolon here. If we added it in:
```rust,ignore
fn add_one(x: i32) -> i32 {
x + 1;
}
```
We would get an error:
```text
error: not all control paths return a value
fn add_one(x: i32) -> i32 {
x + 1;
}
help: consider removing this semicolon:
x + 1;
^
```
This reveals two interesting things about Rust: it is an expression-based
language, and semicolons are different from semicolons in other ‘curly brace
and semicolon’-based languages. These two things are related.
## Expressions vs. Statements
Rust is primarily an expression-based language. There are only two kinds of
statements, and everything else is an expression.
So what's the difference? Expressions return a value, and statements do not.
That’s why we end up with ‘not all control paths return a value’ here: the
statement `x + 1;` doesn’t return a value. There are two kinds of statements in
Rust: ‘declaration statements’ and ‘expression statements’. Everything else is
an expression. Let’s talk about declaration statements first.
In some languages, variable bindings can be written as expressions, not just
statements. Like Ruby:
```ruby
x = y = 5
```
In Rust, however, using `let` to introduce a binding is _not_ an expression. The
following will produce a compile-time error:
```ignore
let x = (let y = 5); // expected identifier, found keyword `let`
```
The compiler is telling us here that it was expecting to see the beginning of
an expression, and a `let` can only begin a statement, not an expression.
Note that assigning to an already-bound variable (e.g. `y = 5`) is still an
expression, although its value is not particularly useful. Unlike other
languages where an assignment evaluates to the assigned value (e.g. `5` in the
previous example), in Rust the value of an assignment is an empty tuple `()`
because the assigned value can have [just one owner](ownership.html), and any
other returned value would be too surprising:
```rust
let mut y = 5;
let x = (y = 6); // x has the value `()`, not `6`
```
The second kind of statement in Rust is the *expression statement*. Its
purpose is to turn any expression into a statement. In practical terms, Rust's
grammar expects statements to follow other statements. This means that you use
semicolons to separate expressions from each other. This means that Rust
looks a lot like most other languages that require you to use semicolons
at the end of every line, and you will see semicolons at the end of almost
every line of Rust code you see.
What is this exception that makes us say "almost"? You saw it already, in this
code:
```rust
fn add_one(x: i32) -> i32 {
x + 1
}
```
Our function claims to return an `i32`, but with a semicolon, it would return
`()` instead. Rust realizes this probably isn’t what we want, and suggests
removing the semicolon in the error we saw before.
## Early returns
But what about early returns? Rust does have a keyword for that, `return`:
```rust
fn foo(x: i32) -> i32 {
return x;
// we never run this code!
x + 1
}
```
Using a `return` as the last line of a function works, but is considered poor
style:
```rust
fn foo(x: i32) -> i32 {
return x + 1;
}
```
The previous definition without `return` may look a bit strange if you haven’t
worked in an expression-based language before, but it becomes intuitive over
time.
## Diverging functions
Rust has some special syntax for ‘diverging functions’, which are functions that
do not return:
```rust
fn diverges() -> ! {
panic!("This function never returns!");
}
```
`panic!` is a macro, similar to `println!()` that we’ve already seen. Unlike
`println!()`, `panic!()` causes the current thread of execution to crash with
the given message. Because this function will cause a crash, it will never
return, and so it has the type ‘`!`’, which is read ‘diverges’.
If you add a main function that calls `diverges()` and run it, you’ll get
some output that looks like this:
```text
thread ‘<main>’ panicked at ‘This function never returns!’, hello.rs:2
```
If you want more information, you can get a backtrace by setting the
`RUST_BACKTRACE` environment variable:
```text
$ RUST_BACKTRACE=1 ./diverges
thread '<main>' panicked at 'This function never returns!', hello.rs:2
stack backtrace:
1: 0x7f402773a829 - sys::backtrace::write::h0942de78b6c02817K8r
2: 0x7f402773d7fc - panicking::on_panic::h3f23f9d0b5f4c91bu9w
3: 0x7f402773960e - rt::unwind::begin_unwind_inner::h2844b8c5e81e79558Bw
4: 0x7f4027738893 - rt::unwind::begin_unwind::h4375279447423903650
5: 0x7f4027738809 - diverges::h2266b4c4b850236beaa
6: 0x7f40277389e5 - main::h19bb1149c2f00ecfBaa
7: 0x7f402773f514 - rt::unwind::try::try_fn::h13186883479104382231
8: 0x7f402773d1d8 - __rust_try
9: 0x7f402773f201 - rt::lang_start::ha172a3ce74bb453aK5w
10: 0x7f4027738a19 - main
11: 0x7f402694ab44 - __libc_start_main
12: 0x7f40277386c8 - <unknown>
13: 0x0 - <unknown>
```
`RUST_BACKTRACE` also works with Cargo’s `run` command:
```text
$ RUST_BACKTRACE=1 cargo run
Running `target/debug/diverges`
thread '<main>' panicked at 'This function never returns!', hello.rs:2
stack backtrace:
1: 0x7f402773a829 - sys::backtrace::write::h0942de78b6c02817K8r
2: 0x7f402773d7fc - panicking::on_panic::h3f23f9d0b5f4c91bu9w
3: 0x7f402773960e - rt::unwind::begin_unwind_inner::h2844b8c5e81e79558Bw
4: 0x7f4027738893 - rt::unwind::begin_unwind::h4375279447423903650
5: 0x7f4027738809 - diverges::h2266b4c4b850236beaa
6: 0x7f40277389e5 - main::h19bb1149c2f00ecfBaa
7: 0x7f402773f514 - rt::unwind::try::try_fn::h13186883479104382231
8: 0x7f402773d1d8 - __rust_try
9: 0x7f402773f201 - rt::lang_start::ha172a3ce74bb453aK5w
10: 0x7f4027738a19 - main
11: 0x7f402694ab44 - __libc_start_main
12: 0x7f40277386c8 - <unknown>
13: 0x0 - <unknown>
```
A diverging function can be used as any type:
```should_panic
# fn diverges() -> ! {
# panic!("This function never returns!");
# }
let x: i32 = diverges();
let x: String = diverges();
```
## Function pointers
We can also create variable bindings which point to functions:
```rust
let f: fn(i32) -> i32;
```
`f` is a variable binding which points to a function that takes an `i32` as
an argument and returns an `i32`. For example:
```rust
fn plus_one(i: i32) -> i32 {
i + 1
}
// without type inference
let f: fn(i32) -> i32 = plus_one;
// with type inference
let f = plus_one;
```
We can then use `f` to call the function:
```rust
# fn plus_one(i: i32) -> i32 { i + 1 }
# let f = plus_one;
let six = f(5);
```
-71
View File
@@ -1,73 +1,2 @@
# if
Rust’s take on `if` is not particularly complex, but it’s much more like the
`if` you’ll find in a dynamically typed language than in a more traditional
systems language. So let’s talk about it, to make sure you grasp the nuances.
`if` is a specific form of a more general concept, the ‘branch’. The name comes
from a branch in a tree: a decision point, where depending on a choice,
multiple paths can be taken.
In the case of `if`, there is one choice that leads down two paths:
```rust
let x = 5;
if x == 5 {
println!("x is five!");
}
```
If we changed the value of `x` to something else, this line would not print.
More specifically, if the expression after the `if` evaluates to `true`, then
the block is executed. If it’s `false`, then it is not.
If you want something to happen in the `false` case, use an `else`:
```rust
let x = 5;
if x == 5 {
println!("x is five!");
} else {
println!("x is not five :(");
}
```
If there is more than one case, use an `else if`:
```rust
let x = 5;
if x == 5 {
println!("x is five!");
} else if x == 6 {
println!("x is six!");
} else {
println!("x is not five or six :(");
}
```
This is all pretty standard. However, you can also do this:
```rust
let x = 5;
let y = if x == 5 {
10
} else {
15
}; // y: i32
```
Which we can (and probably should) write like this:
```rust
let x = 5;
let y = if x == 5 { 10 } else { 15 }; // y: i32
```
This works because `if` is an expression. The value of the expression is the
value of the last expression in whichever branch was chosen. An `if` without an
`else` always results in `()` as the value.
-209
View File
@@ -1,211 +1,2 @@
# Loops
Rust currently provides three approaches to performing some kind of iterative activity. They are: `loop`, `while` and `for`. Each approach has its own set of uses.
## loop
The infinite `loop` is the simplest form of loop available in Rust. Using the keyword `loop`, Rust provides a way to loop indefinitely until some terminating statement is reached. Rust's infinite `loop`s look like this:
```rust,ignore
loop {
println!("Loop forever!");
}
```
## while
Rust also has a `while` loop. It looks like this:
```rust
let mut x = 5; // mut x: i32
let mut done = false; // mut done: bool
while !done {
x += x - 3;
println!("{}", x);
if x % 5 == 0 {
done = true;
}
}
```
`while` loops are the correct choice when you’re not sure how many times
you need to loop.
If you need an infinite loop, you may be tempted to write this:
```rust,ignore
while true {
```
However, `loop` is far better suited to handle this case:
```rust,ignore
loop {
```
Rust’s control-flow analysis treats this construct differently than a `while
true`, since we know that it will always loop. In general, the more information
we can give to the compiler, the better it can do with safety and code
generation, so you should always prefer `loop` when you plan to loop
infinitely.
## for
The `for` loop is used to loop a particular number of times. Rust’s `for` loops
work a bit differently than in other systems languages, however. Rust’s `for`
loop doesn’t look like this “C-style” `for` loop:
```c
for (x = 0; x < 10; x++) {
printf( "%d\n", x );
}
```
Instead, it looks like this:
```rust
for x in 0..10 {
println!("{}", x); // x: i32
}
```
In slightly more abstract terms,
```ignore
for var in expression {
code
}
```
The expression is an item that can be converted into an [iterator] using
[`IntoIterator`]. The iterator gives back a series of elements. Each element is
one iteration of the loop. That value is then bound to the name `var`, which is
valid for the loop body. Once the body is over, the next value is fetched from
the iterator, and we loop another time. When there are no more values, the `for`
loop is over.
[iterator]: iterators.html
[`IntoIterator`]: ../std/iter/trait.IntoIterator.html
In our example, `0..10` is an expression that takes a start and an end position,
and gives an iterator over those values. The upper bound is exclusive, though,
so our loop will print `0` through `9`, not `10`.
Rust does not have the “C-style” `for` loop on purpose. Manually controlling
each element of the loop is complicated and error prone, even for experienced C
developers.
### Enumerate
When you need to keep track of how many times you already looped, you can use the `.enumerate()` function.
#### On ranges:
```rust
for (i,j) in (5..10).enumerate() {
println!("i = {} and j = {}", i, j);
}
```
Outputs:
```text
i = 0 and j = 5
i = 1 and j = 6
i = 2 and j = 7
i = 3 and j = 8
i = 4 and j = 9
```
Don't forget to add the parentheses around the range.
#### On iterators:
```rust
# let lines = "hello\nworld".lines();
for (linenumber, line) in lines.enumerate() {
println!("{}: {}", linenumber, line);
}
```
Outputs:
```text
0: Content of line one
1: Content of line two
2: Content of line three
3: Content of line four
```
## Ending iteration early
Let’s take a look at that `while` loop we had earlier:
```rust
let mut x = 5;
let mut done = false;
while !done {
x += x - 3;
println!("{}", x);
if x % 5 == 0 {
done = true;
}
}
```
We had to keep a dedicated `mut` boolean variable binding, `done`, to know
when we should exit out of the loop. Rust has two keywords to help us with
modifying iteration: `break` and `continue`.
In this case, we can write the loop in a better way with `break`:
```rust
let mut x = 5;
loop {
x += x - 3;
println!("{}", x);
if x % 5 == 0 { break; }
}
```
We now loop forever with `loop` and use `break` to break out early. Issuing an explicit `return` statement will also serve to terminate the loop early.
`continue` is similar, but instead of ending the loop, goes to the next
iteration. This will only print the odd numbers:
```rust
for x in 0..10 {
if x % 2 == 0 { continue; }
println!("{}", x);
}
```
## Loop labels
You may also encounter situations where you have nested loops and need to
specify which one your `break` or `continue` statement is for. Like most
other languages, by default a `break` or `continue` will apply to innermost
loop. In a situation where you would like to a `break` or `continue` for one
of the outer loops, you can use labels to specify which loop the `break` or
`continue` statement applies to. This will only print when both `x` and `y` are
odd:
```rust
'outer: for x in 0..10 {
'inner: for y in 0..10 {
if x % 2 == 0 { continue 'outer; } // continues the loop over x
if y % 2 == 0 { continue 'inner; } // continues the loop over y
println!("x: {}, y: {}", x, y);
}
}
```
-296
View File
@@ -1,298 +1,2 @@
# Primitive Types
The Rust language has a number of types that are considered ‘primitive’. This
means that they’re built-in to the language. Rust is structured in such a way
that the standard library also provides a number of useful types built on top
of these ones, as well, but these are the most primitive.
# Booleans
Rust has a built in boolean type, named `bool`. It has two values, `true` and `false`:
```rust
let x = true;
let y: bool = false;
```
A common use of booleans is in [`if` conditionals][if].
[if]: if.html
You can find more documentation for `bool`s [in the standard library
documentation][bool].
[bool]: ../std/primitive.bool.html
# `char`
The `char` type represents a single Unicode scalar value. You can create `char`s
with a single tick: (`'`)
```rust
let x = 'x';
let two_hearts = '💕';
```
Unlike some other languages, this means that Rust’s `char` is not a single byte,
but four.
You can find more documentation for `char`s [in the standard library
documentation][char].
[char]: ../std/primitive.char.html
# Numeric types
Rust has a variety of numeric types in a few categories: signed and unsigned,
fixed and variable, floating-point and integer.
These types consist of two parts: the category, and the size. For example,
`u16` is an unsigned type with sixteen bits of size. More bits lets you have
bigger numbers.
If a number literal has nothing to cause its type to be inferred, it defaults:
```rust
let x = 42; // x has type i32
let y = 1.0; // y has type f64
```
Here’s a list of the different numeric types, with links to their documentation
in the standard library:
* [i8](../std/primitive.i8.html)
* [i16](../std/primitive.i16.html)
* [i32](../std/primitive.i32.html)
* [i64](../std/primitive.i64.html)
* [u8](../std/primitive.u8.html)
* [u16](../std/primitive.u16.html)
* [u32](../std/primitive.u32.html)
* [u64](../std/primitive.u64.html)
* [isize](../std/primitive.isize.html)
* [usize](../std/primitive.usize.html)
* [f32](../std/primitive.f32.html)
* [f64](../std/primitive.f64.html)
Let’s go over them by category:
## Signed and Unsigned
Integer types come in two varieties: signed and unsigned. To understand the
difference, let’s consider a number with four bits of size. A signed, four-bit
number would let you store numbers from `-8` to `+7`. Signed numbers use
“two’s complement representation”. An unsigned four bit number, since it does
not need to store negatives, can store values from `0` to `+15`.
Unsigned types use a `u` for their category, and signed types use `i`. The `i`
is for ‘integer’. So `u8` is an eight-bit unsigned number, and `i8` is an
eight-bit signed number.
## Fixed size types
Fixed size types have a specific number of bits in their representation. Valid
bit sizes are `8`, `16`, `32`, and `64`. So, `u32` is an unsigned, 32-bit integer,
and `i64` is a signed, 64-bit integer.
## Variable sized types
Rust also provides types whose size depends on the size of a pointer of the
underlying machine. These types have ‘size’ as the category, and come in signed
and unsigned varieties. This makes for two types: `isize` and `usize`.
## Floating-point types
Rust also has two floating point types: `f32` and `f64`. These correspond to
IEEE-754 single and double precision numbers.
# Arrays
Like many programming languages, Rust has list types to represent a sequence of
things. The most basic is the *array*, a fixed-size list of elements of the
same type. By default, arrays are immutable.
```rust
let a = [1, 2, 3]; // a: [i32; 3]
let mut m = [1, 2, 3]; // m: [i32; 3]
```
Arrays have type `[T; N]`. We’ll talk about this `T` notation [in the generics
section][generics]. The `N` is a compile-time constant, for the length of the
array.
There’s a shorthand for initializing each element of an array to the same
value. In this example, each element of `a` will be initialized to `0`:
```rust
let a = [0; 20]; // a: [i32; 20]
```
You can get the number of elements in an array `a` with `a.len()`:
```rust
let a = [1, 2, 3];
println!("a has {} elements", a.len());
```
You can access a particular element of an array with *subscript notation*:
```rust
let names = ["Graydon", "Brian", "Niko"]; // names: [&str; 3]
println!("The second name is: {}", names[1]);
```
Subscripts start at zero, like in most programming languages, so the first name
is `names[0]` and the second name is `names[1]`. The above example prints
`The second name is: Brian`. If you try to use a subscript that is not in the
array, you will get an error: array access is bounds-checked at run-time. Such
errant access is the source of many bugs in other systems programming
languages.
You can find more documentation for `array`s [in the standard library
documentation][array].
[array]: ../std/primitive.array.html
# Slices
A ‘slice’ is a reference to (or “view” into) another data structure. They are
useful for allowing safe, efficient access to a portion of an array without
copying. For example, you might want to reference just one line of a file read
into memory. By nature, a slice is not created directly, but from an existing
variable binding. Slices have a defined length, can be mutable or immutable.
## Slicing syntax
You can use a combo of `&` and `[]` to create a slice from various things. The
`&` indicates that slices are similar to references, and the `[]`s, with a
range, let you define the length of the slice:
```rust
let a = [0, 1, 2, 3, 4];
let complete = &a[..]; // A slice containing all of the elements in a
let middle = &a[1..4]; // A slice of a: just the elements 1, 2, and 3
```
Slices have type `&[T]`. We’ll talk about that `T` when we cover
[generics][generics].
[generics]: generics.html
You can find more documentation for slices [in the standard library
documentation][slice].
[slice]: ../std/primitive.slice.html
# `str`
Rust’s `str` type is the most primitive string type. As an [unsized type][dst],
it’s not very useful by itself, but becomes useful when placed behind a reference,
like [`&str`][strings]. As such, we’ll just leave it at that.
[dst]: unsized-types.html
[strings]: strings.html
You can find more documentation for `str` [in the standard library
documentation][str].
[str]: ../std/primitive.str.html
# Tuples
A tuple is an ordered list of fixed size. Like this:
```rust
let x = (1, "hello");
```
The parentheses and commas form this two-length tuple. Here’s the same code, but
with the type annotated:
```rust
let x: (i32, &str) = (1, "hello");
```
As you can see, the type of a tuple looks just like the tuple, but with each
position having a type name rather than the value. Careful readers will also
note that tuples are heterogeneous: we have an `i32` and a `&str` in this tuple.
In systems programming languages, strings are a bit more complex than in other
languages. For now, just read `&str` as a *string slice*, and we’ll learn more
soon.
You can assign one tuple into another, if they have the same contained types
and [arity]. Tuples have the same arity when they have the same length.
[arity]: glossary.html#arity
```rust
let mut x = (1, 2); // x: (i32, i32)
let y = (2, 3); // y: (i32, i32)
x = y;
```
You can access the fields in a tuple through a *destructuring let*. Here’s
an example:
```rust
let (x, y, z) = (1, 2, 3);
println!("x is {}", x);
```
Remember [before][let] when I said the left-hand side of a `let` statement was more
powerful than just assigning a binding? Here we are. We can put a pattern on
the left-hand side of the `let`, and if it matches up to the right-hand side,
we can assign multiple bindings at once. In this case, `let` “destructures”
or “breaks up” the tuple, and assigns the bits to three bindings.
[let]: variable-bindings.html
This pattern is very powerful, and we’ll see it repeated more later.
You can disambiguate a single-element tuple from a value in parentheses with a
comma:
```rust
(0,); // single-element tuple
(0); // zero in parentheses
```
## Tuple Indexing
You can also access fields of a tuple with indexing syntax:
```rust
let tuple = (1, 2, 3);
let x = tuple.0;
let y = tuple.1;
let z = tuple.2;
println!("x is {}", x);
```
Like array indexing, it starts at zero, but unlike array indexing, it uses a
`.`, rather than `[]`s.
You can find more documentation for tuples [in the standard library
documentation][tuple].
[tuple]: ../std/primitive.tuple.html
# Functions
Functions also have a type! They look like this:
```rust
fn foo(x: i32) -> i32 { x }
let x: fn(i32) -> i32 = foo;
```
In this case, `x` is a ‘function pointer’ to a function that takes an `i32` and
returns an `i32`.
-250
View File
@@ -1,252 +1,2 @@
# Variable Bindings
Virtually every non-'Hello World’ Rust program uses *variable bindings*. They
bind some value to a name, so it can be used later. `let` is
used to introduce a binding, just like this:
```rust
fn main() {
let x = 5;
}
```
Putting `fn main() {` in each example is a bit tedious, so we’ll leave that out
in the future. If you’re following along, make sure to edit your `main()`
function, rather than leaving it off. Otherwise, you’ll get an error.
# Patterns
In many languages, a variable binding would be called a *variable*, but Rust’s
variable bindings have a few tricks up their sleeves. For example the
left-hand side of a `let` expression is a ‘[pattern][pattern]’, not just a
variable name. This means we can do things like:
```rust
let (x, y) = (1, 2);
```
After this expression is evaluated, `x` will be one, and `y` will be two.
Patterns are really powerful, and have [their own section][pattern] in the
book. We don’t need those features for now, so we’ll just keep this in the back
of our minds as we go forward.
[pattern]: patterns.html
# Type annotations
Rust is a statically typed language, which means that we specify our types up
front, and they’re checked at compile time. So why does our first example
compile? Well, Rust has this thing called ‘type inference’. If it can figure
out what the type of something is, Rust doesn’t require you to actually type it
out.
We can add the type if we want to, though. Types come after a colon (`:`):
```rust
let x: i32 = 5;
```
If I asked you to read this out loud to the rest of the class, you’d say “`x`
is a binding with the type `i32` and the value `five`.”
In this case we chose to represent `x` as a 32-bit signed integer. Rust has
many different primitive integer types. They begin with `i` for signed integers
and `u` for unsigned integers. The possible integer sizes are 8, 16, 32, and 64
bits.
In future examples, we may annotate the type in a comment. The examples will
look like this:
```rust
fn main() {
let x = 5; // x: i32
}
```
Note the similarities between this annotation and the syntax you use with
`let`. Including these kinds of comments is not idiomatic Rust, but we'll
occasionally include them to help you understand what the types that Rust
infers are.
# Mutability
By default, bindings are *immutable*. This code will not compile:
```rust,ignore
let x = 5;
x = 10;
```
It will give you this error:
```text
error: re-assignment of immutable variable `x`
x = 10;
^~~~~~~
```
If you want a binding to be mutable, you can use `mut`:
```rust
let mut x = 5; // mut x: i32
x = 10;
```
There is no single reason that bindings are immutable by default, but we can
think about it through one of Rust’s primary focuses: safety. If you forget to
say `mut`, the compiler will catch it, and let you know that you have mutated
something you may not have intended to mutate. If bindings were mutable by
default, the compiler would not be able to tell you this. If you _did_ intend
mutation, then the solution is quite easy: add `mut`.
There are other good reasons to avoid mutable state when possible, but they’re
out of the scope of this guide. In general, you can often avoid explicit
mutation, and so it is preferable in Rust. That said, sometimes, mutation is
what you need, so it’s not verboten.
# Initializing bindings
Rust variable bindings have one more aspect that differs from other languages:
bindings are required to be initialized with a value before you're allowed to
use them.
Let’s try it out. Change your `src/main.rs` file to look like this:
```rust
fn main() {
let x: i32;
println!("Hello world!");
}
```
You can use `cargo build` on the command line to build it. You’ll get a
warning, but it will still print "Hello, world!":
```text
Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world)
src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variable)]
on by default
src/main.rs:2 let x: i32;
^
```
Rust warns us that we never use the variable binding, but since we never use
it, no harm, no foul. Things change if we try to actually use this `x`,
however. Let’s do that. Change your program to look like this:
```rust,ignore
fn main() {
let x: i32;
println!("The value of x is: {}", x);
}
```
And try to build it. You’ll get an error:
```bash
$ cargo build
Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world)
src/main.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x`
src/main.rs:4 println!("The value of x is: {}", x);
^
note: in expansion of format_args!
<std macros>:2:23: 2:77 note: expansion site
<std macros>:1:1: 3:2 note: in expansion of println!
src/main.rs:4:5: 4:42 note: expansion site
error: aborting due to previous error
Could not compile `hello_world`.
```
Rust will not let us use a value that has not been initialized. Next, let’s
talk about this stuff we've added to `println!`.
If you include two curly braces (`{}`, some call them moustaches...) in your
string to print, Rust will interpret this as a request to interpolate some sort
of value. *String interpolation* is a computer science term that means "stick
in the middle of a string." We add a comma, and then `x`, to indicate that we
want `x` to be the value we’re interpolating. The comma is used to separate
arguments we pass to functions and macros, if you’re passing more than one.
When you just use the curly braces, Rust will attempt to display the value in a
meaningful way by checking out its type. If you want to specify the format in a
more detailed manner, there are a [wide number of options available][format].
For now, we'll just stick to the default: integers aren't very complicated to
print.
[format]: ../std/fmt/index.html
# Scope and shadowing
Let’s get back to bindings. Variable bindings have a scope - they are
constrained to live in a block they were defined in. A block is a collection
of statements enclosed by `{` and `}`. Function definitions are also blocks!
In the following example we define two variable bindings, `x` and `y`, which
live in different blocks. `x` can be accessed from inside the `fn main() {}`
block, while `y` can be accessed only from inside the inner block:
```rust,ignore
fn main() {
let x: i32 = 17;
{
let y: i32 = 3;
println!("The value of x is {} and value of y is {}", x, y);
}
println!("The value of x is {} and value of y is {}", x, y); // This won't work
}
```
The first `println!` would print "The value of x is 17 and the value of y is
3", but this example cannot be compiled successfully, because the second
`println!` cannot access the value of `y`, since it is not in scope anymore.
Instead we get this error:
```bash
$ cargo build
Compiling hello v0.1.0 (file:///home/you/projects/hello_world)
main.rs:7:62: 7:63 error: unresolved name `y`. Did you mean `x`? [E0425]
main.rs:7 println!("The value of x is {} and value of y is {}", x, y); // This won't work
^
note: in expansion of format_args!
<std macros>:2:25: 2:56 note: expansion site
<std macros>:1:1: 2:62 note: in expansion of print!
<std macros>:3:1: 3:54 note: expansion site
<std macros>:1:1: 3:58 note: in expansion of println!
main.rs:7:5: 7:65 note: expansion site
main.rs:7:62: 7:63 help: run `rustc --explain E0425` to see a detailed explanation
error: aborting due to previous error
Could not compile `hello`.
To learn more, run the command again with --verbose.
```
Additionally, variable bindings can be shadowed. This means that a later
variable binding with the same name as another binding, that's currently in
scope, will override the previous binding.
```rust
let x: i32 = 8;
{
println!("{}", x); // Prints "8"
let x = 12;
println!("{}", x); // Prints "12"
}
println!("{}", x); // Prints "8"
let x = 42;
println!("{}", x); // Prints "42"
```
Shadowing and mutable bindings may appear as two sides of the same coin, but
they are two distinct concepts that can't always be used interchangeably. For
one, shadowing enables us to rebind a name to a value of a different type. It
is also possible to change the mutability of a binding.
```rust
let mut x: i32 = 1;
x = 7;
let x = x; // x is now immutable and is bound to 7
let y = 4;
let y = "I can also be bound to text!"; // y is now of a different type
```