diff --git a/src/basics.md b/src/basics.md index 440d1a1fe..357bbb06f 100644 --- a/src/basics.md +++ b/src/basics.md @@ -1 +1,7 @@ # The Basics + +We’ll start our journey with Rust by talking about the absolute basics. +Many programming languages have lots in common at their core. +Much of this may feel similar to other languages you’ve used, but some parts are different. +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. diff --git a/src/functions.md b/src/functions.md index 6fb060081..c7c38a26d 100644 --- a/src/functions.md +++ b/src/functions.md @@ -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 ‘
’ 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 '
' 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 - - 13: 0x0 - -``` - -`RUST_BACKTRACE` also works with Cargo’s `run` command: - -```text -$ RUST_BACKTRACE=1 cargo run - Running `target/debug/diverges` -thread '
' 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 - - 13: 0x0 - -``` - -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); -``` diff --git a/src/if.md b/src/if.md index a59e7b051..f994a6495 100644 --- a/src/if.md +++ b/src/if.md @@ -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. diff --git a/src/loops.md b/src/loops.md index 784a6baee..07c9bbb7f 100644 --- a/src/loops.md +++ b/src/loops.md @@ -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); - } -} -``` diff --git a/src/primitive-types.md b/src/primitive-types.md index db1f522be..3ca75dec5 100644 --- a/src/primitive-types.md +++ b/src/primitive-types.md @@ -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`. diff --git a/src/variable-bindings.md b/src/variable-bindings.md index b1239e3bb..9bb56357e 100644 --- a/src/variable-bindings.md +++ b/src/variable-bindings.md @@ -1,252 +1,485 @@ # 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: +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: + +```bash +$ 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: + +```rust +fn main() { + println!("Hello, world!"); +} +``` + +Let’s replace that program with this one: ```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: +And finally, run it: ```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! -:2:23: 2:77 note: expansion site -: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`. +$ cargo run + Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings) + Running `target/debug/bindings` +The value of x is: 5 ``` -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: +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. ```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 `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. + +```rust,ignore + let x = 5; +``` + +This is our first ‘variable binding’. +This looks like many languages, but there are some subtleties. +We create variable bindings with a ‘`let` statement’, which looks like this: + +```text +let PATTERN = VALUE; +``` + +In our example, the `PATTERN` is a humble `x`, and the `VALUE` is a simple `5`. +The `let` statement takes the `VALUE`, and matches it to the `PATTERN`, creating new bindings. +Therefore, our example creates a new binding, `x`, and gives it an initial value of `5`. +Patterns are a big part of Rust, we will see them in many places. + +That seems like a lot of explanation for a basic assignment statement! +The trick is that these patterns can become more complex, and have a lot of power. +We’ll explore more complex patterns as we learn more. + +Before we do that, though, let’s finish investigating this example. +Here’s the next line: + +```rust,ignore + 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. +This is why it’s a macro; Rust does not support optional arguments for regular functions. +The format string can contain the special text `{}`. +If it does, it fills in that place in the string with the values of the other arguments. +In this case, we’ve passed `x`. +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. + +```rust,ignore } ``` -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: +Finally, a closing curly brace matches up with the opening curly brace that declared the `main()` function, and declares its end. -```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! -:2:25: 2:56 note: expansion site -:1:1: 2:62 note: in expansion of print! -:3:1: 3:54 note: expansion site -: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 +This explains our output: + +```text +The value of x is: 5 +``` + +We assign `5` to a binding, `x`, and then print it to the screen with `println!`. + +## Multiple assignment + +Let’s try a more complex pattern. +Change our example program to this: + +```rust +fn main() { + let (x, y) = (5, 6); + + println!("The value of x is: {}", x); + println!("The value of y is: {}", y); +} +``` + +And run it with `cargo run`: + +```text +$ cargo run + Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings) + Running `target/debug/bindings` +The value of x is: 5 +The value of y is: 6 +``` + +We’ve created two bindings with one `let`! +Here’s our pattern: + +```text +(x, y) +``` + +And here’s the value: + +```text +(5, 6) +``` + +As you can see, the two line up visually, and so `let` binds `5` to `x` and `6` to `y`. +We could have used two `let` statements as well: + +```rust +let x = 5; +let y = 6; +``` + +In simple cases like this, two `let`s may be clearer, but in others, creating multiple bindings at once is nice. +As we become more proficient in Rust, we’ll figure out which style is better, but it’s mostly a judgement call. + +## Initialization + +We do not have to provide bindings with an initial value, and can assign it later. Try this program: + +```rust +fn main() { + let x; + + x = 5; + + println!("The value of x is: {}", x); +} +``` + +And run it with `cargo run`: + +```text +$ cargo run + Compiling bindings v0.1.0 (file:///home/steve/tmp/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: + +```rust,ignore +fn main() { + let x; + + println!("The value of x is: {}", x); + + x = 5; +} +``` + +We can find out the answer with `cargo run`: + +```text + Compiling bindings v0.1.0 (file:///home/steve/tmp/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); + ^ +:2:25: 2:56 note: in this expansion of format_args! +:3:1: 3:54 note: in this expansion of print! (defined in ) +src/main.rs:4:5: 4:42 note: in this expansion of println! (defined in ) +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 `hello`. +Could not compile `bindings`. 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. +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`. -```rust -let x: i32 = 8; -{ - println!("{}", x); // Prints "8" - let x = 12; - println!("{}", x); // Prints "12" +### Extended error explanations + +There’s one more interesting part of this error message: + +```text +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`: + +```bash +$ 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: + +```rust,ignore +fn main() { + let x = 5; + + x = 6; + + println!("The value of x is: {}", x); } -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. +`cargo run` has the answer for us: + +```bash +$ cargo run + Compiling bindings v0.1.0 (file:///home/steve/tmp/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: ```rust -let mut x: i32 = 1; -x = 7; -let x = x; // x is now immutable and is bound to 7 +fn main() { + let mut x = 5; -let y = 4; -let y = "I can also be bound to text!"; // y is now of a different type + println!("The value of x is: {}", x); + + x = 6; + + println!("The value of x is: {}", x); +} ``` + +Running this, we get: + +```bash +$ cargo run + Compiling bindings v0.1.0 (file:///home/steve/tmp/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: + + +```rust,ignore +fn main() { + let (mut x, y) = (5, 6); + + x = 7; + y = 8; +} +``` + +The compiler will complain about this program: + +```bash +$ cargo build + Compiling bindings v0.1.0 (file:///home/steve/tmp/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: + +```rust +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. + +## Shadowing + +A final thing about bindings: they can ‘shadow’ previous bindings with the same name. +Here’s a sample program: + +```rust +fn main() { + let x = 5; + let x = 6; + + println!("The value of x is: {}", x); +} +``` + +Running it, we can see the shadowing in action: + +```text +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: + +```rust +fn main() { + let x = 5; + let x = x + 1; + let x = x * 2; + + println!("The value of x is: {}", x); +} +``` + +This will print: + +```bash + Compiling bindings v0.1.0 (file:///home/steve/tmp/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: + +```rust,ignore +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: + +```bash +$ cargo build + Compiling bindings v0.1.0 (file:///home/steve/tmp/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: + +```text +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: + +```rust +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`.