diff --git a/src/advanced-type-system-features.md b/src/advanced-type-system-features.md deleted file mode 100644 index c2a0aeb77..000000000 --- a/src/advanced-type-system-features.md +++ /dev/null @@ -1 +0,0 @@ -# Advanced Type System Features diff --git a/src/arc.md b/src/arc.md deleted file mode 100644 index 5186ad709..000000000 --- a/src/arc.md +++ /dev/null @@ -1 +0,0 @@ -# `Arc` diff --git a/src/associated-types.md b/src/associated-types.md deleted file mode 100644 index 8f692c38d..000000000 --- a/src/associated-types.md +++ /dev/null @@ -1,202 +0,0 @@ -# Associated Types - -Associated types are a powerful part of Rust’s type system. They’re related to -the idea of a ‘type family’, in other words, grouping multiple types together. That -description is a bit abstract, so let’s dive right into an example. If you want -to write a `Graph` trait, you have two types to be generic over: the node type -and the edge type. So you might write a trait, `Graph`, that looks like -this: - -```rust -trait Graph { - fn has_edge(&self, &N, &N) -> bool; - fn edges(&self, &N) -> Vec; - // etc -} -``` - -While this sort of works, it ends up being awkward. For example, any function -that wants to take a `Graph` as a parameter now _also_ needs to be generic over -the `N`ode and `E`dge types too: - -```rust,ignore -fn distance>(graph: &G, start: &N, end: &N) -> u32 { ... } -``` - -Our distance calculation works regardless of our `Edge` type, so the `E` stuff in -this signature is just a distraction. - -What we really want to say is that a certain `E`dge and `N`ode type come together -to form each kind of `Graph`. We can do that with associated types: - -```rust -trait Graph { - type N; - type E; - - fn has_edge(&self, &Self::N, &Self::N) -> bool; - fn edges(&self, &Self::N) -> Vec; - // etc -} -``` - -Now, our clients can be abstract over a given `Graph`: - -```rust,ignore -fn distance(graph: &G, start: &G::N, end: &G::N) -> u32 { ... } -``` - -No need to deal with the `E`dge type here! - -Let’s go over all this in more detail. - -## Defining associated types - -Let’s build that `Graph` trait. Here’s the definition: - -```rust -trait Graph { - type N; - type E; - - fn has_edge(&self, &Self::N, &Self::N) -> bool; - fn edges(&self, &Self::N) -> Vec; -} -``` - -Simple enough. Associated types use the `type` keyword, and go inside the body -of the trait, with the functions. - -These `type` declarations can have all the same thing as functions do. For example, -if we wanted our `N` type to implement `Display`, so we can print the nodes out, -we could do this: - -```rust -use std::fmt; - -trait Graph { - type N: fmt::Display; - type E; - - fn has_edge(&self, &Self::N, &Self::N) -> bool; - fn edges(&self, &Self::N) -> Vec; -} -``` - -## Implementing associated types - -Just like any trait, traits that use associated types use the `impl` keyword to -provide implementations. Here’s a simple implementation of Graph: - -```rust -# trait Graph { -# type N; -# type E; -# fn has_edge(&self, &Self::N, &Self::N) -> bool; -# fn edges(&self, &Self::N) -> Vec; -# } -struct Node; - -struct Edge; - -struct MyGraph; - -impl Graph for MyGraph { - type N = Node; - type E = Edge; - - fn has_edge(&self, n1: &Node, n2: &Node) -> bool { - true - } - - fn edges(&self, n: &Node) -> Vec { - Vec::new() - } -} -``` - -This silly implementation always returns `true` and an empty `Vec`, but it -gives you an idea of how to implement this kind of thing. We first need three -`struct`s, one for the graph, one for the node, and one for the edge. If it made -more sense to use a different type, that would work as well, we’re just going to -use `struct`s for all three here. - -Next is the `impl` line, which is just like implementing any other trait. - -From here, we use `=` to define our associated types. The name the trait uses -goes on the left of the `=`, and the concrete type we’re `impl`ementing this -for goes on the right. Finally, we use the concrete types in our function -declarations. - -## Trait objects with associated types - -There’s one more bit of syntax we should talk about: trait objects. If you -try to create a trait object from an associated type, like this: - -```rust,ignore -# trait Graph { -# type N; -# type E; -# fn has_edge(&self, &Self::N, &Self::N) -> bool; -# fn edges(&self, &Self::N) -> Vec; -# } -# struct Node; -# struct Edge; -# struct MyGraph; -# impl Graph for MyGraph { -# type N = Node; -# type E = Edge; -# fn has_edge(&self, n1: &Node, n2: &Node) -> bool { -# true -# } -# fn edges(&self, n: &Node) -> Vec { -# Vec::new() -# } -# } -let graph = MyGraph; -let obj = Box::new(graph) as Box; -``` - -You’ll get two errors: - -```text -error: the value of the associated type `E` (from the trait `main::Graph`) must -be specified [E0191] -let obj = Box::new(graph) as Box; - ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -24:44 error: the value of the associated type `N` (from the trait -`main::Graph`) must be specified [E0191] -let obj = Box::new(graph) as Box; - ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -``` - -We can’t create a trait object like this, because we don’t know the associated -types. Instead, we can write this: - -```rust -# trait Graph { -# type N; -# type E; -# fn has_edge(&self, &Self::N, &Self::N) -> bool; -# fn edges(&self, &Self::N) -> Vec; -# } -# struct Node; -# struct Edge; -# struct MyGraph; -# impl Graph for MyGraph { -# type N = Node; -# type E = Edge; -# fn has_edge(&self, n1: &Node, n2: &Node) -> bool { -# true -# } -# fn edges(&self, n: &Node) -> Vec { -# Vec::new() -# } -# } -let graph = MyGraph; -let obj = Box::new(graph) as Box>; -``` - -The `N=Node` syntax allows us to provide a concrete type, `Node`, for the `N` -type parameter. Same with `E=Edge`. If we didn’t provide this constraint, we -couldn’t be sure which `impl` to match this trait object to. diff --git a/src/basic-collections.md b/src/basic-collections.md deleted file mode 100644 index 406d41688..000000000 --- a/src/basic-collections.md +++ /dev/null @@ -1 +0,0 @@ -# Basic Collections diff --git a/src/bindings-to-c.md b/src/bindings-to-c.md deleted file mode 100644 index b3c82d8b5..000000000 --- a/src/bindings-to-c.md +++ /dev/null @@ -1 +0,0 @@ -# Bindings to C diff --git a/src/box.md b/src/box.md deleted file mode 100644 index d341edce8..000000000 --- a/src/box.md +++ /dev/null @@ -1 +0,0 @@ -# `Box` diff --git a/src/cargo.md b/src/cargo.md deleted file mode 100644 index 079555759..000000000 --- a/src/cargo.md +++ /dev/null @@ -1 +0,0 @@ -# Cargo diff --git a/src/cell.md b/src/cell.md deleted file mode 100644 index 0acaf74f0..000000000 --- a/src/cell.md +++ /dev/null @@ -1 +0,0 @@ -# `Cell` diff --git a/src/channels.md b/src/channels.md deleted file mode 100644 index bc5edc347..000000000 --- a/src/channels.md +++ /dev/null @@ -1 +0,0 @@ -# `Channels` diff --git a/src/closures.md b/src/closures.md deleted file mode 100644 index ec78cb635..000000000 --- a/src/closures.md +++ /dev/null @@ -1,506 +0,0 @@ -# Closures - -Sometimes it is useful to wrap up a function and _free variables_ for better -clarity and reuse. The free variables that can be used come from the -enclosing scope and are ‘closed over’ when used in the function. From this, we -get the name ‘closures’ and Rust provides a really great implementation of -them, as we’ll see. - -# Syntax - -Closures look like this: - -```rust -let plus_one = |x: i32| x + 1; - -assert_eq!(2, plus_one(1)); -``` - -We create a binding, `plus_one`, and assign it to a closure. The closure’s -arguments go between the pipes (`|`), and the body is an expression, in this -case, `x + 1`. Remember that `{ }` is an expression, so we can have multi-line -closures too: - -```rust -let plus_two = |x| { - let mut result: i32 = x; - - result += 1; - result += 1; - - result -}; - -assert_eq!(4, plus_two(2)); -``` - -You’ll notice a few things about closures that are a bit different from regular -named functions defined with `fn`. The first is that we did not need to -annotate the types of arguments the closure takes or the values it returns. We -can: - -```rust -let plus_one = |x: i32| -> i32 { x + 1 }; - -assert_eq!(2, plus_one(1)); -``` - -But we don’t have to. Why is this? Basically, it was chosen for ergonomic -reasons. While specifying the full type for named functions is helpful with -things like documentation and type inference, the full type signatures of -closures are rarely documented since they’re anonymous, and they don’t cause -the kinds of error-at-a-distance problems that inferring named function types -can. - -The second is that the syntax is similar, but a bit different. I’ve added -spaces here for easier comparison: - -```rust -fn plus_one_v1 (x: i32) -> i32 { x + 1 } -let plus_one_v2 = |x: i32| -> i32 { x + 1 }; -let plus_one_v3 = |x: i32| x + 1 ; -``` - -Small differences, but they’re similar. - -# Closures and their environment - -The environment for a closure can include bindings from its enclosing scope in -addition to parameters and local bindings. It looks like this: - -```rust -let num = 5; -let plus_num = |x: i32| x + num; - -assert_eq!(10, plus_num(5)); -``` - -This closure, `plus_num`, refers to a `let` binding in its scope: `num`. More -specifically, it borrows the binding. If we do something that would conflict -with that binding, we get an error. Like this one: - -```rust,ignore -let mut num = 5; -let plus_num = |x: i32| x + num; - -let y = &mut num; -``` - -Which errors with: - -```text -error: cannot borrow `num` as mutable because it is also borrowed as immutable - let y = &mut num; - ^~~ -note: previous borrow of `num` occurs here due to use in closure; the immutable - borrow prevents subsequent moves or mutable borrows of `num` until the borrow - ends - let plus_num = |x| x + num; - ^~~~~~~~~~~ -note: previous borrow ends here -fn main() { - let mut num = 5; - let plus_num = |x| x + num; - - let y = &mut num; -} -^ -``` - -A verbose yet helpful error message! As it says, we can’t take a mutable borrow -on `num` because the closure is already borrowing it. If we let the closure go -out of scope, we can: - -```rust -let mut num = 5; -{ - let plus_num = |x: i32| x + num; - -} // plus_num goes out of scope, borrow of num ends - -let y = &mut num; -``` - -If your closure requires it, however, Rust will take ownership and move -the environment instead. This doesn’t work: - -```rust,ignore -let nums = vec![1, 2, 3]; - -let takes_nums = || nums; - -println!("{:?}", nums); -``` - -We get this error: - -```text -note: `nums` moved into closure environment here because it has type - `[closure(()) -> collections::vec::Vec]`, which is non-copyable -let takes_nums = || nums; - ^~~~~~~ -``` - -`Vec` has ownership over its contents, and therefore, when we refer to it -in our closure, we have to take ownership of `nums`. It’s the same as if we’d -passed `nums` to a function that took ownership of it. - -## `move` closures - -We can force our closure to take ownership of its environment with the `move` -keyword: - -```rust -let num = 5; - -let owns_num = move |x: i32| x + num; -``` - -Now, even though the keyword is `move`, the variables follow normal move semantics. -In this case, `5` implements `Copy`, and so `owns_num` takes ownership of a copy -of `num`. So what’s the difference? - -```rust -let mut num = 5; - -{ - let mut add_num = |x: i32| num += x; - - add_num(5); -} - -assert_eq!(10, num); -``` - -So in this case, our closure took a mutable reference to `num`, and then when -we called `add_num`, it mutated the underlying value, as we’d expect. We also -needed to declare `add_num` as `mut` too, because we’re mutating its -environment. - -If we change to a `move` closure, it’s different: - -```rust -let mut num = 5; - -{ - let mut add_num = move |x: i32| num += x; - - add_num(5); -} - -assert_eq!(5, num); -``` - -We only get `5`. Rather than taking a mutable borrow out on our `num`, we took -ownership of a copy. - -Another way to think about `move` closures: they give a closure its own stack -frame. Without `move`, a closure may be tied to the stack frame that created -it, while a `move` closure is self-contained. This means that you cannot -generally return a non-`move` closure from a function, for example. - -But before we talk about taking and returning closures, we should talk some -more about the way that closures are implemented. As a systems language, Rust -gives you tons of control over what your code does, and closures are no -different. - -# Closure implementation - -Rust’s implementation of closures is a bit different than other languages. They -are effectively syntax sugar for traits. You’ll want to make sure to have read -the [traits chapter][traits] before this one, as well as the chapter on [trait -objects][trait-objects]. - -[traits]: traits.html -[trait-objects]: trait-objects.html - -Got all that? Good. - -The key to understanding how closures work under the hood is something a bit -strange: Using `()` to call a function, like `foo()`, is an overloadable -operator. From this, everything else clicks into place. In Rust, we use the -trait system to overload operators. Calling functions is no different. We have -three separate traits to overload with: - -```rust -# mod foo { -pub trait Fn : FnMut { - extern "rust-call" fn call(&self, args: Args) -> Self::Output; -} - -pub trait FnMut : FnOnce { - extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output; -} - -pub trait FnOnce { - type Output; - - extern "rust-call" fn call_once(self, args: Args) -> Self::Output; -} -# } -``` - -You’ll notice a few differences between these traits, but a big one is `self`: -`Fn` takes `&self`, `FnMut` takes `&mut self`, and `FnOnce` takes `self`. This -covers all three kinds of `self` via the usual method call syntax. But we’ve -split them up into three traits, rather than having a single one. This gives us -a large amount of control over what kind of closures we can take. - -The `|| {}` syntax for closures is sugar for these three traits. Rust will -generate a struct for the environment, `impl` the appropriate trait, and then -use it. - -# Taking closures as arguments - -Now that we know that closures are traits, we already know how to accept and -return closures: just like any other trait! - -This also means that we can choose static vs dynamic dispatch as well. First, -let’s write a function which takes something callable, calls it, and returns -the result: - -```rust -fn call_with_one(some_closure: F) -> i32 - where F : Fn(i32) -> i32 { - - some_closure(1) -} - -let answer = call_with_one(|x| x + 2); - -assert_eq!(3, answer); -``` - -We pass our closure, `|x| x + 2`, to `call_with_one`. It just does what it -suggests: it calls the closure, giving it `1` as an argument. - -Let’s examine the signature of `call_with_one` in more depth: - -```rust -fn call_with_one(some_closure: F) -> i32 -# where F : Fn(i32) -> i32 { -# some_closure(1) } -``` - -We take one parameter, and it has the type `F`. We also return a `i32`. This part -isn’t interesting. The next part is: - -```rust -# fn call_with_one(some_closure: F) -> i32 - where F : Fn(i32) -> i32 { -# some_closure(1) } -``` - -Because `Fn` is a trait, we can bound our generic with it. In this case, our -closure takes a `i32` as an argument and returns an `i32`, and so the generic -bound we use is `Fn(i32) -> i32`. - -There’s one other key point here: because we’re bounding a generic with a -trait, this will get monomorphized, and therefore, we’ll be doing static -dispatch into the closure. That’s pretty neat. In many languages, closures are -inherently heap allocated, and will always involve dynamic dispatch. In Rust, -we can stack allocate our closure environment, and statically dispatch the -call. This happens quite often with iterators and their adapters, which often -take closures as arguments. - -Of course, if we want dynamic dispatch, we can get that too. A trait object -handles this case, as usual: - -```rust -fn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 { - some_closure(1) -} - -let answer = call_with_one(&|x| x + 2); - -assert_eq!(3, answer); -``` - -Now we take a trait object, a `&Fn`. And we have to make a reference -to our closure when we pass it to `call_with_one`, so we use `&||`. - -# Function pointers and closures - -A function pointer is kind of like a closure that has no environment. As such, -you can pass a function pointer to any function expecting a closure argument, -and it will work: - -```rust -fn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 { - some_closure(1) -} - -fn add_one(i: i32) -> i32 { - i + 1 -} - -let f = add_one; - -let answer = call_with_one(&f); - -assert_eq!(2, answer); -``` - -In this example, we don’t strictly need the intermediate variable `f`, -the name of the function works just fine too: - -```ignore -let answer = call_with_one(&add_one); -``` - -# Returning closures - -It’s very common for functional-style code to return closures in various -situations. If you try to return a closure, you may run into an error. At -first, it may seem strange, but we’ll figure it out. Here’s how you’d probably -try to return a closure from a function: - -```rust,ignore -fn factory() -> (Fn(i32) -> i32) { - let num = 5; - - |x| x + num -} - -let f = factory(); - -let answer = f(1); -assert_eq!(6, answer); -``` - -This gives us these long, related errors: - -```text -error: the trait `core::marker::Sized` is not implemented for the type -`core::ops::Fn(i32) -> i32` [E0277] -fn factory() -> (Fn(i32) -> i32) { - ^~~~~~~~~~~~~~~~ -note: `core::ops::Fn(i32) -> i32` does not have a constant size known at compile-time -fn factory() -> (Fn(i32) -> i32) { - ^~~~~~~~~~~~~~~~ -error: the trait `core::marker::Sized` is not implemented for the type `core::ops::Fn(i32) -> i32` [E0277] -let f = factory(); - ^ -note: `core::ops::Fn(i32) -> i32` does not have a constant size known at compile-time -let f = factory(); - ^ -``` - -In order to return something from a function, Rust needs to know what -size the return type is. But since `Fn` is a trait, it could be various -things of various sizes: many different types can implement `Fn`. An easy -way to give something a size is to take a reference to it, as references -have a known size. So we’d write this: - -```rust,ignore -fn factory() -> &(Fn(i32) -> i32) { - let num = 5; - - |x| x + num -} - -let f = factory(); - -let answer = f(1); -assert_eq!(6, answer); -``` - -But we get another error: - -```text -error: missing lifetime specifier [E0106] -fn factory() -> &(Fn(i32) -> i32) { - ^~~~~~~~~~~~~~~~~ -``` - -Right. Because we have a reference, we need to give it a lifetime. But -our `factory()` function takes no arguments, so -[elision](lifetimes.html#lifetime-elision) doesn’t kick in here. Then what -choices do we have? Try `'static`: - -```rust,ignore -fn factory() -> &'static (Fn(i32) -> i32) { - let num = 5; - - |x| x + num -} - -let f = factory(); - -let answer = f(1); -assert_eq!(6, answer); -``` - -But we get another error: - -```text -error: mismatched types: - expected `&'static core::ops::Fn(i32) -> i32`, - found `[closure@:7:9: 7:20]` -(expected &-ptr, - found closure) [E0308] - |x| x + num - ^~~~~~~~~~~ - -``` - -This error is letting us know that we don’t have a `&'static Fn(i32) -> i32`, -we have a `[closure@:7:9: 7:20]`. Wait, what? - -Because each closure generates its own environment `struct` and implementation -of `Fn` and friends, these types are anonymous. They exist just solely for -this closure. So Rust shows them as `closure@`, rather than some -autogenerated name. - -The error also points out that the return type is expected to be a reference, -but what we are trying to return is not. Further, we cannot directly assign a -`'static` lifetime to an object. So we'll take a different approach and return -a ‘trait object’ by `Box`ing up the `Fn`. This _almost_ works: - -```rust,ignore -fn factory() -> Box i32> { - let num = 5; - - Box::new(|x| x + num) -} -# fn main() { -let f = factory(); - -let answer = f(1); -assert_eq!(6, answer); -# } -``` - -There’s just one last problem: - -```text -error: closure may outlive the current function, but it borrows `num`, -which is owned by the current function [E0373] -Box::new(|x| x + num) - ^~~~~~~~~~~ -``` - -Well, as we discussed before, closures borrow their environment. And in this -case, our environment is based on a stack-allocated `5`, the `num` variable -binding. So the borrow has a lifetime of the stack frame. So if we returned -this closure, the function call would be over, the stack frame would go away, -and our closure is capturing an environment of garbage memory! With one last -fix, we can make this work: - -```rust -fn factory() -> Box i32> { - let num = 5; - - Box::new(move |x| x + num) -} -# fn main() { -let f = factory(); - -let answer = f(1); -assert_eq!(6, answer); -# } -``` - -By making the inner closure a `move Fn`, we create a new stack frame for our -closure. By `Box`ing it up, we’ve given it a known size, and allowing it to -escape our stack frame. diff --git a/src/coherence.md b/src/coherence.md deleted file mode 100644 index 27c845bf9..000000000 --- a/src/coherence.md +++ /dev/null @@ -1 +0,0 @@ -# Coherence diff --git a/src/concurrency.md b/src/concurrency.md deleted file mode 100644 index 5cbbf4f4e..000000000 --- a/src/concurrency.md +++ /dev/null @@ -1 +0,0 @@ -# Concurrency diff --git a/src/conditional-compilation.md b/src/conditional-compilation.md deleted file mode 100644 index 55bea273c..000000000 --- a/src/conditional-compilation.md +++ /dev/null @@ -1,93 +0,0 @@ -# Conditional Compilation - -Rust has a special attribute, `#[cfg]`, which allows you to compile code -based on a flag passed to the compiler. It has two forms: - -```rust -#[cfg(foo)] -# fn foo() {} - -#[cfg(bar = "baz")] -# fn bar() {} -``` - -They also have some helpers: - -```rust -#[cfg(any(unix, windows))] -# fn foo() {} - -#[cfg(all(unix, target_pointer_width = "32"))] -# fn bar() {} - -#[cfg(not(foo))] -# fn not_foo() {} -``` - -These can nest arbitrarily: - -```rust -#[cfg(any(not(unix), all(target_os="macos", target_arch = "powerpc")))] -# fn foo() {} -``` - -As for how to enable or disable these switches, if you’re using Cargo, -they get set in the [`[features]` section][features] of your `Cargo.toml`: - -[features]: http://doc.crates.io/manifest.html#the-features-section - -```toml -[features] -# no features by default -default = [] - -# The “secure-password” feature depends on the bcrypt package. -secure-password = ["bcrypt"] -``` - -When you do this, Cargo passes along a flag to `rustc`: - -```text ---cfg feature="${feature_name}" -``` - -The sum of these `cfg` flags will determine which ones get activated, and -therefore, which code gets compiled. Let’s take this code: - -```rust -#[cfg(feature = "foo")] -mod foo { -} -``` - -If we compile it with `cargo build --features "foo"`, it will send the `--cfg -feature="foo"` flag to `rustc`, and the output will have the `mod foo` in it. -If we compile it with a regular `cargo build`, no extra flags get passed on, -and so, no `foo` module will exist. - -# cfg_attr - -You can also set another attribute based on a `cfg` variable with `cfg_attr`: - -```rust -#[cfg_attr(a, b)] -# fn foo() {} -``` - -Will be the same as `#[b]` if `a` is set by `cfg` attribute, and nothing otherwise. - -# cfg! - -The `cfg!` [syntax extension][compilerplugins] lets you use these kinds of flags -elsewhere in your code, too: - -```rust -if cfg!(target_os = "macos") || cfg!(target_os = "ios") { - println!("Think Different!"); -} -``` - -[compilerplugins]: compiler-plugins.html - -These will be replaced by a `true` or `false` at compile-time, depending on the -configuration settings. diff --git a/src/core-concepts.md b/src/core-concepts.md deleted file mode 100644 index e8a038cc3..000000000 --- a/src/core-concepts.md +++ /dev/null @@ -1,2 +0,0 @@ -# Core Concepts - diff --git a/src/crates-and-modules.md b/src/crates-and-modules.md deleted file mode 100644 index 6262066ef..000000000 --- a/src/crates-and-modules.md +++ /dev/null @@ -1,588 +0,0 @@ -# Crates and Modules - -When a project starts getting large, it’s considered good software -engineering practice to split it up into a bunch of smaller pieces, and then -fit them together. It’s also important to have a well-defined interface, so -that some of your functionality is private, and some is public. To facilitate -these kinds of things, Rust has a module system. - -# Basic terminology: Crates and Modules - -Rust has two distinct terms that relate to the module system: ‘crate’ and -‘module’. A crate is synonymous with a ‘library’ or ‘package’ in other -languages. Hence “Cargo” as the name of Rust’s package management tool: you -ship your crates to others with Cargo. Crates can produce an executable or a -library, depending on the project. - -Each crate has an implicit *root module* that contains the code for that crate. -You can then define a tree of sub-modules under that root module. Modules allow -you to partition your code within the crate itself. - -As an example, let’s make a *phrases* crate, which will give us various phrases -in different languages. To keep things simple, we’ll stick to ‘greetings’ and -‘farewells’ as two kinds of phrases, and use English and Japanese (日本語) as -two languages for those phrases to be in. We’ll use this module layout: - -```text - +-----------+ - +---| greetings | - | +-----------+ - +---------+ | - +---| english |---+ - | +---------+ | +-----------+ - | +---| farewells | -+---------+ | +-----------+ -| phrases |---+ -+---------+ | +-----------+ - | +---| greetings | - | +----------+ | +-----------+ - +---| japanese |--+ - +----------+ | - | +-----------+ - +---| farewells | - +-----------+ -``` - -In this example, `phrases` is the name of our crate. All of the rest are -modules. You can see that they form a tree, branching out from the crate -*root*, which is the root of the tree: `phrases` itself. - -Now that we have a plan, let’s define these modules in code. To start, -generate a new crate with Cargo: - -```bash -$ cargo new phrases -$ cd phrases -``` - -If you remember, this generates a simple project for us: - -```bash -$ tree . -. -├── Cargo.toml -└── src - └── lib.rs - -1 directory, 2 files -``` - -`src/lib.rs` is our crate root, corresponding to the `phrases` in our diagram -above. - -# Defining Modules - -To define each of our modules, we use the `mod` keyword. Let’s make our -`src/lib.rs` look like this: - -```rust -mod english { - mod greetings { - } - - mod farewells { - } -} - -mod japanese { - mod greetings { - } - - mod farewells { - } -} -``` - -After the `mod` keyword, you give the name of the module. Module names follow -the conventions for other Rust identifiers: `lower_snake_case`. The contents of -each module are within curly braces (`{}`). - -Within a given `mod`, you can declare sub-`mod`s. We can refer to sub-modules -with double-colon (`::`) notation: our four nested modules are -`english::greetings`, `english::farewells`, `japanese::greetings`, and -`japanese::farewells`. Because these sub-modules are namespaced under their -parent module, the names don’t conflict: `english::greetings` and -`japanese::greetings` are distinct, even though their names are both -`greetings`. - -Because this crate does not have a `main()` function, and is called `lib.rs`, -Cargo will build this crate as a library: - -```bash -$ cargo build - Compiling phrases v0.0.1 (file:///home/you/projects/phrases) -$ ls target/debug -build deps examples libphrases-a7448e02a0468eaa.rlib native -``` - -`libphrases-hash.rlib` is the compiled crate. Before we see how to use this -crate from another crate, let’s break it up into multiple files. - -# Multiple file crates - -If each crate were just one file, these files would get very large. It’s often -easier to split up crates into multiple files, and Rust supports this in two -ways. - -Instead of declaring a module like this: - -```rust,ignore -mod english { - // contents of our module go here -} -``` - -We can instead declare our module like this: - -```rust,ignore -mod english; -``` - -If we do that, Rust will expect to find either a `english.rs` file, or a -`english/mod.rs` file with the contents of our module. - -Note that in these files, you don’t need to re-declare the module: that’s -already been done with the initial `mod` declaration. - -Using these two techniques, we can break up our crate into two directories and -seven files: - -```bash -$ tree . -. -├── Cargo.lock -├── Cargo.toml -├── src -│   ├── english -│   │   ├── farewells.rs -│   │   ├── greetings.rs -│   │   └── mod.rs -│   ├── japanese -│   │   ├── farewells.rs -│   │   ├── greetings.rs -│   │   └── mod.rs -│   └── lib.rs -└── target - └── debug - ├── build - ├── deps - ├── examples - ├── libphrases-a7448e02a0468eaa.rlib - └── native -``` - -`src/lib.rs` is our crate root, and looks like this: - -```rust,ignore -mod english; -mod japanese; -``` - -These two declarations tell Rust to look for either `src/english.rs` and -`src/japanese.rs`, or `src/english/mod.rs` and `src/japanese/mod.rs`, depending -on our preference. In this case, because our modules have sub-modules, we’ve -chosen the second. Both `src/english/mod.rs` and `src/japanese/mod.rs` look -like this: - -```rust,ignore -mod greetings; -mod farewells; -``` - -Again, these declarations tell Rust to look for either -`src/english/greetings.rs` and `src/japanese/greetings.rs` or -`src/english/farewells/mod.rs` and `src/japanese/farewells/mod.rs`. Because -these sub-modules don’t have their own sub-modules, we’ve chosen to make them -`src/english/greetings.rs` and `src/japanese/farewells.rs`. Whew! - -The contents of `src/english/greetings.rs` and `src/japanese/farewells.rs` are -both empty at the moment. Let’s add some functions. - -Put this in `src/english/greetings.rs`: - -```rust -fn hello() -> String { - "Hello!".to_string() -} -``` - -Put this in `src/english/farewells.rs`: - -```rust -fn goodbye() -> String { - "Goodbye.".to_string() -} -``` - -Put this in `src/japanese/greetings.rs`: - -```rust -fn hello() -> String { - "こんにちは".to_string() -} -``` - -Of course, you can copy and paste this from this web page, or just type -something else. It’s not important that you actually put ‘konnichiwa’ to learn -about the module system. - -Put this in `src/japanese/farewells.rs`: - -```rust -fn goodbye() -> String { - "さようなら".to_string() -} -``` - -(This is ‘Sayōnara’, if you’re curious.) - -Now that we have some functionality in our crate, let’s try to use it from -another crate. - -# Importing External Crates - -We have a library crate. Let’s make an executable crate that imports and uses -our library. - -Make a `src/main.rs` and put this in it (it won’t quite compile yet): - -```rust,ignore -extern crate phrases; - -fn main() { - println!("Hello in English: {}", phrases::english::greetings::hello()); - println!("Goodbye in English: {}", phrases::english::farewells::goodbye()); - - println!("Hello in Japanese: {}", phrases::japanese::greetings::hello()); - println!("Goodbye in Japanese: {}", phrases::japanese::farewells::goodbye()); -} -``` - -The `extern crate` declaration tells Rust that we need to compile and link to -the `phrases` crate. We can then use `phrases`’ modules in this one. As we -mentioned earlier, you can use double colons to refer to sub-modules and the -functions inside of them. - -(Note: when importing a crate that has dashes in its name "like-this", which is -not a valid Rust identifier, it will be converted by changing the dashes to -underscores, so you would write `extern crate like_this;`.) - -Also, Cargo assumes that `src/main.rs` is the crate root of a binary crate, -rather than a library crate. Our package now has two crates: `src/lib.rs` and -`src/main.rs`. This pattern is quite common for executable crates: most -functionality is in a library crate, and the executable crate uses that -library. This way, other programs can also use the library crate, and it’s also -a nice separation of concerns. - -This doesn’t quite work yet, though. We get four errors that look similar to -this: - -```bash -$ cargo build - Compiling phrases v0.0.1 (file:///home/you/projects/phrases) -src/main.rs:4:38: 4:72 error: function `hello` is private -src/main.rs:4 println!("Hello in English: {}", phrases::english::greetings::hello()); - ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -note: in expansion of format_args! -:2:25: 2:58 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! -phrases/src/main.rs:4:5: 4:76 note: expansion site -``` - -By default, everything is private in Rust. Let’s talk about this in some more -depth. - -# Exporting a Public Interface - -Rust allows you to precisely control which aspects of your interface are -public, and so private is the default. To make things public, you use the `pub` -keyword. Let’s focus on the `english` module first, so let’s reduce our `src/main.rs` -to just this: - -```rust,ignore -extern crate phrases; - -fn main() { - println!("Hello in English: {}", phrases::english::greetings::hello()); - println!("Goodbye in English: {}", phrases::english::farewells::goodbye()); -} -``` - -In our `src/lib.rs`, let’s add `pub` to the `english` module declaration: - -```rust,ignore -pub mod english; -mod japanese; -``` - -And in our `src/english/mod.rs`, let’s make both `pub`: - -```rust,ignore -pub mod greetings; -pub mod farewells; -``` - -In our `src/english/greetings.rs`, let’s add `pub` to our `fn` declaration: - -```rust,ignore -pub fn hello() -> String { - "Hello!".to_string() -} -``` - -And also in `src/english/farewells.rs`: - -```rust,ignore -pub fn goodbye() -> String { - "Goodbye.".to_string() -} -``` - -Now, our crate compiles, albeit with warnings about not using the `japanese` -functions: - -```bash -$ cargo run - Compiling phrases v0.0.1 (file:///home/you/projects/phrases) -src/japanese/greetings.rs:1:1: 3:2 warning: function is never used: `hello`, #[warn(dead_code)] on by default -src/japanese/greetings.rs:1 fn hello() -> String { -src/japanese/greetings.rs:2 "こんにちは".to_string() -src/japanese/greetings.rs:3 } -src/japanese/farewells.rs:1:1: 3:2 warning: function is never used: `goodbye`, #[warn(dead_code)] on by default -src/japanese/farewells.rs:1 fn goodbye() -> String { -src/japanese/farewells.rs:2 "さようなら".to_string() -src/japanese/farewells.rs:3 } - Running `target/debug/phrases` -Hello in English: Hello! -Goodbye in English: Goodbye. -``` - -`pub` also applies to `struct`s and their member fields. In keeping with Rust’s -tendency toward safety, simply making a `struct` public won't automatically -make its members public: you must mark the fields individually with `pub`. - -Now that our functions are public, we can use them. Great! However, typing out -`phrases::english::greetings::hello()` is very long and repetitive. Rust has -another keyword for importing names into the current scope, so that you can -refer to them with shorter names. Let’s talk about `use`. - -# Importing Modules with `use` - -Rust has a `use` keyword, which allows us to import names into our local scope. -Let’s change our `src/main.rs` to look like this: - -```rust,ignore -extern crate phrases; - -use phrases::english::greetings; -use phrases::english::farewells; - -fn main() { - println!("Hello in English: {}", greetings::hello()); - println!("Goodbye in English: {}", farewells::goodbye()); -} -``` - -The two `use` lines import each module into the local scope, so we can refer to -the functions by a much shorter name. By convention, when importing functions, it’s -considered best practice to import the module, rather than the function directly. In -other words, you _can_ do this: - -```rust,ignore -extern crate phrases; - -use phrases::english::greetings::hello; -use phrases::english::farewells::goodbye; - -fn main() { - println!("Hello in English: {}", hello()); - println!("Goodbye in English: {}", goodbye()); -} -``` - -But it is not idiomatic. This is significantly more likely to introduce a -naming conflict. In our short program, it’s not a big deal, but as it grows, it -becomes a problem. If we have conflicting names, Rust will give a compilation -error. For example, if we made the `japanese` functions public, and tried to do -this: - -```rust,ignore -extern crate phrases; - -use phrases::english::greetings::hello; -use phrases::japanese::greetings::hello; - -fn main() { - println!("Hello in English: {}", hello()); - println!("Hello in Japanese: {}", hello()); -} -``` - -Rust will give us a compile-time error: - -```text - Compiling phrases v0.0.1 (file:///home/you/projects/phrases) -src/main.rs:4:5: 4:40 error: a value named `hello` has already been imported in this module [E0252] -src/main.rs:4 use phrases::japanese::greetings::hello; - ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -error: aborting due to previous error -Could not compile `phrases`. -``` - -If we’re importing multiple names from the same module, we don’t have to type it out -twice. Instead of this: - -```rust,ignore -use phrases::english::greetings; -use phrases::english::farewells; -``` - -We can use this shortcut: - -```rust,ignore -use phrases::english::{greetings, farewells}; -``` - -## Re-exporting with `pub use` - -You don’t just use `use` to shorten identifiers. You can also use it inside of your crate -to re-export a function inside another module. This allows you to present an external -interface that may not directly map to your internal code organization. - -Let’s look at an example. Modify your `src/main.rs` to read like this: - -```rust,ignore -extern crate phrases; - -use phrases::english::{greetings,farewells}; -use phrases::japanese; - -fn main() { - println!("Hello in English: {}", greetings::hello()); - println!("Goodbye in English: {}", farewells::goodbye()); - - println!("Hello in Japanese: {}", japanese::hello()); - println!("Goodbye in Japanese: {}", japanese::goodbye()); -} -``` - -Then, modify your `src/lib.rs` to make the `japanese` mod public: - -```rust,ignore -pub mod english; -pub mod japanese; -``` - -Next, make the two functions public, first in `src/japanese/greetings.rs`: - -```rust,ignore -pub fn hello() -> String { - "こんにちは".to_string() -} -``` - -And then in `src/japanese/farewells.rs`: - -```rust,ignore -pub fn goodbye() -> String { - "さようなら".to_string() -} -``` - -Finally, modify your `src/japanese/mod.rs` to read like this: - -```rust,ignore -pub use self::greetings::hello; -pub use self::farewells::goodbye; - -mod greetings; -mod farewells; -``` - -The `pub use` declaration brings the function into scope at this part of our -module hierarchy. Because we’ve `pub use`d this inside of our `japanese` -module, we now have a `phrases::japanese::hello()` function and a -`phrases::japanese::goodbye()` function, even though the code for them lives in -`phrases::japanese::greetings::hello()` and -`phrases::japanese::farewells::goodbye()`. Our internal organization doesn’t -define our external interface. - -Here we have a `pub use` for each function we want to bring into the -`japanese` scope. We could alternatively use the wildcard syntax to include -everything from `greetings` into the current scope: `pub use self::greetings::*`. - -What about the `self`? Well, by default, `use` declarations are absolute paths, -starting from your crate root. `self` makes that path relative to your current -place in the hierarchy instead. There’s one more special form of `use`: you can -`use super::` to reach one level up the tree from your current location. Some -people like to think of `self` as `.` and `super` as `..`, from many shells’ -display for the current directory and the parent directory. - -Outside of `use`, paths are relative: `foo::bar()` refers to a function inside -of `foo` relative to where we are. If that’s prefixed with `::`, as in -`::foo::bar()`, it refers to a different `foo`, an absolute path from your -crate root. - -This will build and run: - -```bash -$ cargo run - Compiling phrases v0.0.1 (file:///home/you/projects/phrases) - Running `target/debug/phrases` -Hello in English: Hello! -Goodbye in English: Goodbye. -Hello in Japanese: こんにちは -Goodbye in Japanese: さようなら -``` - -## Complex imports - -Rust offers several advanced options that can add compactness and -convenience to your `extern crate` and `use` statements. Here is an example: - -```rust,ignore -extern crate phrases as sayings; - -use sayings::japanese::greetings as ja_greetings; -use sayings::japanese::farewells::*; -use sayings::english::{self, greetings as en_greetings, farewells as en_farewells}; - -fn main() { - println!("Hello in English; {}", en_greetings::hello()); - println!("And in Japanese: {}", ja_greetings::hello()); - println!("Goodbye in English: {}", english::farewells::goodbye()); - println!("Again: {}", en_farewells::goodbye()); - println!("And in Japanese: {}", goodbye()); -} -``` - -What's going on here? - -First, both `extern crate` and `use` allow renaming the thing that is being -imported. So the crate is still called "phrases", but here we will refer -to it as "sayings". Similarly, the first `use` statement pulls in the -`japanese::greetings` module from the crate, but makes it available as -`ja_greetings` as opposed to simply `greetings`. This can help to avoid -ambiguity when importing similarly-named items from different places. - -The second `use` statement uses a star glob to bring in _all_ symbols from the -`sayings::japanese::farewells` module. As you can see we can later refer to -the Japanese `goodbye` function with no module qualifiers. This kind of glob -should be used sparingly. - -The third `use` statement bears more explanation. It's using "brace expansion" -globbing to compress three `use` statements into one (this sort of syntax -may be familiar if you've written Linux shell scripts before). The -uncompressed form of this statement would be: - -```rust,ignore -use sayings::english; -use sayings::english::greetings as en_greetings; -use sayings::english::farewells as en_farewells; -``` - -As you can see, the curly brackets compress `use` statements for several items -under the same path, and in this context `self` just refers back to that path. -Note: The curly brackets cannot be nested or mixed with star globbing. diff --git a/src/cratesio.md b/src/cratesio.md deleted file mode 100644 index 90df62bbc..000000000 --- a/src/cratesio.md +++ /dev/null @@ -1 +0,0 @@ -# Crates.io diff --git a/src/deref-coercions.md b/src/deref-coercions.md deleted file mode 100644 index c356a5f14..000000000 --- a/src/deref-coercions.md +++ /dev/null @@ -1 +0,0 @@ -# `Deref` coercions diff --git a/src/deref.md b/src/deref.md deleted file mode 100644 index e58fca161..000000000 --- a/src/deref.md +++ /dev/null @@ -1 +0,0 @@ -# `Deref` diff --git a/src/enums.md b/src/enums.md deleted file mode 100644 index ccd0392e9..000000000 --- a/src/enums.md +++ /dev/null @@ -1,108 +0,0 @@ -# Enums - -An `enum` in Rust is a type that represents data that is one of -several possible variants. Each variant in the `enum` can optionally -have data associated with it: - -```rust -enum Message { - Quit, - ChangeColor(i32, i32, i32), - Move { x: i32, y: i32 }, - Write(String), -} -``` - -The syntax for defining variants resembles the syntaxes used to define structs: -you can have variants with no data (like unit-like structs), variants with named -data, and variants with unnamed data (like tuple structs). Unlike -separate struct definitions, however, an `enum` is a single type. A -value of the enum can match any of the variants. For this reason, an -enum is sometimes called a ‘sum type’: the set of possible values of the -enum is the sum of the sets of possible values for each variant. - -We use the `::` syntax to use the name of each variant: they’re scoped by the name -of the `enum` itself. This allows both of these to work: - -```rust -# enum Message { -# Move { x: i32, y: i32 }, -# } -let x: Message = Message::Move { x: 3, y: 4 }; - -enum BoardGameTurn { - Move { squares: i32 }, - Pass, -} - -let y: BoardGameTurn = BoardGameTurn::Move { squares: 1 }; -``` - -Both variants are named `Move`, but since they’re scoped to the name of -the enum, they can both be used without conflict. - -A value of an `enum` type contains information about which variant it is, -in addition to any data associated with that variant. This is sometimes -referred to as a ‘tagged union’, since the data includes a ‘tag’ -indicating what type it is. The compiler uses this information to -enforce that you’re accessing the data in the enum safely. For instance, -you can’t simply try to destructure a value as if it were one of the -possible variants: - -```rust,ignore -fn process_color_change(msg: Message) { - let Message::ChangeColor(r, g, b) = msg; // compile-time error -} -``` - -Not supporting these operations may seem rather limiting, but it’s a limitation -which we can overcome. There are two ways: by implementing equality ourselves, -or by pattern matching variants with [`match`][match] expressions, which you’ll -learn in the next section. We don’t know enough about Rust to implement -equality yet, but we’ll find out in the [`traits`][traits] section. - -[match]: match.html -[if-let]: if-let.html -[traits]: traits.html - -# Constructors as functions - -An `enum` constructor can also be used like a function. For example: - -```rust -# enum Message { -# Write(String), -# } -let m = Message::Write("Hello, world".to_string()); -``` - -is the same as - -```rust -# enum Message { -# Write(String), -# } -fn foo(x: String) -> Message { - Message::Write(x) -} - -let x = foo("Hello, world".to_string()); -``` - -This is not immediately useful to us, but when we get to -[`closures`][closures], we’ll talk about passing functions as arguments to -other functions. For example, with [`iterators`][iterators], we can do this -to convert a vector of `String`s into a vector of `Message::Write`s: - -```rust -# enum Message { -# Write(String), -# } - -let v = vec!["Hello".to_string(), "World".to_string()]; - -let v1: Vec = v.into_iter().map(Message::Write).collect(); -``` - -[closures]: closures.html -[iterators]: iterators.html diff --git a/src/env.md b/src/env.md deleted file mode 100644 index 1cb0b936f..000000000 --- a/src/env.md +++ /dev/null @@ -1 +0,0 @@ -# `std::env` diff --git a/src/error-handling.md b/src/error-handling.md deleted file mode 100644 index 4f6c27f57..000000000 --- a/src/error-handling.md +++ /dev/null @@ -1 +0,0 @@ -# Error Handling diff --git a/src/ffi.md b/src/ffi.md deleted file mode 100644 index 34117bf57..000000000 --- a/src/ffi.md +++ /dev/null @@ -1 +0,0 @@ -# FFI diff --git a/src/fs.md b/src/fs.md deleted file mode 100644 index 79f3ef78d..000000000 --- a/src/fs.md +++ /dev/null @@ -1 +0,0 @@ -# `std::fs` diff --git a/src/hashmap.md b/src/hashmap.md deleted file mode 100644 index 0841475f2..000000000 --- a/src/hashmap.md +++ /dev/null @@ -1 +0,0 @@ -# `HashMap` diff --git a/src/if-let.md b/src/if-let.md deleted file mode 100644 index 72cfb74a1..000000000 --- a/src/if-let.md +++ /dev/null @@ -1 +0,0 @@ -# if let diff --git a/src/interior-mutability.md b/src/interior-mutability.md deleted file mode 100644 index da07cc991..000000000 --- a/src/interior-mutability.md +++ /dev/null @@ -1 +0,0 @@ -# Interior mutability diff --git a/src/io.md b/src/io.md deleted file mode 100644 index c879cabff..000000000 --- a/src/io.md +++ /dev/null @@ -1 +0,0 @@ -# I/O diff --git a/src/iterators.md b/src/iterators.md deleted file mode 100644 index 4a8779e93..000000000 --- a/src/iterators.md +++ /dev/null @@ -1,337 +0,0 @@ -# Iterators - -Let's talk about loops. - -Remember Rust's `for` loop? Here's an example: - -```rust -for x in 0..10 { - println!("{}", x); -} -``` - -Now that you know more Rust, we can talk in detail about how this works. -Ranges (the `0..10`) are 'iterators'. An iterator is something that we can -call the `.next()` method on repeatedly, and it gives us a sequence of things. - -Like this: - -```rust -let mut range = 0..10; - -loop { - match range.next() { - Some(x) => { - println!("{}", x); - }, - None => { break } - } -} -``` - -We make a mutable binding to the range, which is our iterator. We then `loop`, -with an inner `match`. This `match` is used on the result of `range.next()`, -which gives us a reference to the next value of the iterator. `next` returns an -`Option`, in this case, which will be `Some(i32)` when we have a value and -`None` once we run out. If we get `Some(i32)`, we print it out, and if we get -`None`, we `break` out of the loop. - -This code sample is basically the same as our `for` loop version. The `for` -loop is just a handy way to write this `loop`/`match`/`break` construct. - -`for` loops aren't the only thing that uses iterators, however. Writing your -own iterator involves implementing the `Iterator` trait. While doing that is -outside of the scope of this guide, Rust provides a number of useful iterators -to accomplish various tasks. But first, a few notes about limitations of ranges. - -Ranges are very primitive, and we often can use better alternatives. Consider the -following Rust anti-pattern: using ranges to emulate a C-style `for` loop. Let’s -suppose you needed to iterate over the contents of a vector. You may be tempted -to write this: - -```rust -let nums = vec![1, 2, 3]; - -for i in 0..nums.len() { - println!("{}", nums[i]); -} -``` - -This is strictly worse than using an actual iterator. You can iterate over vectors -directly, so write this: - -```rust -let nums = vec![1, 2, 3]; - -for num in &nums { - println!("{}", num); -} -``` - -There are two reasons for this. First, this more directly expresses what we -mean. We iterate through the entire vector, rather than iterating through -indexes, and then indexing the vector. Second, this version is more efficient: -the first version will have extra bounds checking because it used indexing, -`nums[i]`. But since we yield a reference to each element of the vector in turn -with the iterator, there's no bounds checking in the second example. This is -very common with iterators: we can ignore unnecessary bounds checks, but still -know that we're safe. - -There's another detail here that's not 100% clear because of how `println!` -works. `num` is actually of type `&i32`. That is, it's a reference to an `i32`, -not an `i32` itself. `println!` handles the dereferencing for us, so we don't -see it. This code works fine too: - -```rust -let nums = vec![1, 2, 3]; - -for num in &nums { - println!("{}", *num); -} -``` - -Now we're explicitly dereferencing `num`. Why does `&nums` give us -references? Firstly, because we explicitly asked it to with -`&`. Secondly, if it gave us the data itself, we would have to be its -owner, which would involve making a copy of the data and giving us the -copy. With references, we're just borrowing a reference to the data, -and so it's just passing a reference, without needing to do the move. - -So, now that we've established that ranges are often not what you want, let's -talk about what you do want instead. - -There are three broad classes of things that are relevant here: iterators, -*iterator adaptors*, and *consumers*. Here's some definitions: - -* *iterators* give you a sequence of values. -* *iterator adaptors* operate on an iterator, producing a new iterator with a - different output sequence. -* *consumers* operate on an iterator, producing some final set of values. - -Let's talk about consumers first, since you've already seen an iterator, ranges. - -## Consumers - -A *consumer* operates on an iterator, returning some kind of value or values. -The most common consumer is `collect()`. This code doesn't quite compile, -but it shows the intention: - -```rust,ignore -let one_to_one_hundred = (1..101).collect(); -``` - -As you can see, we call `collect()` on our iterator. `collect()` takes -as many values as the iterator will give it, and returns a collection -of the results. So why won't this compile? Rust can't determine what -type of things you want to collect, and so you need to let it know. -Here's the version that does compile: - -```rust -let one_to_one_hundred = (1..101).collect::>(); -``` - -If you remember, the `::<>` syntax allows us to give a type hint, -and so we tell it that we want a vector of integers. You don't always -need to use the whole type, though. Using a `_` will let you provide -a partial hint: - -```rust -let one_to_one_hundred = (1..101).collect::>(); -``` - -This says "Collect into a `Vec`, please, but infer what the `T` is for me." -`_` is sometimes called a "type placeholder" for this reason. - -`collect()` is the most common consumer, but there are others too. `find()` -is one: - -```rust -let greater_than_forty_two = (0..100) - .find(|x| *x > 42); - -match greater_than_forty_two { - Some(_) => println!("Found a match!"), - None => println!("No match found :("), -} -``` - -`find` takes a closure, and works on a reference to each element of an -iterator. This closure returns `true` if the element is the element we're -looking for, and `false` otherwise. `find` returns the first element satisfying -the specified predicate. Because we might not find a matching element, `find` -returns an `Option` rather than the element itself. - -Another important consumer is `fold`. Here's what it looks like: - -```rust -let sum = (1..4).fold(0, |sum, x| sum + x); -``` - -`fold()` is a consumer that looks like this: -`fold(base, |accumulator, element| ...)`. It takes two arguments: the first -is an element called the *base*. The second is a closure that itself takes two -arguments: the first is called the *accumulator*, and the second is an -*element*. Upon each iteration, the closure is called, and the result is the -value of the accumulator on the next iteration. On the first iteration, the -base is the value of the accumulator. - -Okay, that's a bit confusing. Let's examine the values of all of these things -in this iterator: - -| base | accumulator | element | closure result | -|------|-------------|---------|----------------| -| 0 | 0 | 1 | 1 | -| 0 | 1 | 2 | 3 | -| 0 | 3 | 3 | 6 | - -We called `fold()` with these arguments: - -```rust -# (1..4) -.fold(0, |sum, x| sum + x); -``` - -So, `0` is our base, `sum` is our accumulator, and `x` is our element. On the -first iteration, we set `sum` to `0`, and `x` is the first element of `nums`, -`1`. We then add `sum` and `x`, which gives us `0 + 1 = 1`. On the second -iteration, that value becomes our accumulator, `sum`, and the element is -the second element of the array, `2`. `1 + 2 = 3`, and so that becomes -the value of the accumulator for the last iteration. On that iteration, -`x` is the last element, `3`, and `3 + 3 = 6`, which is our final -result for our sum. `1 + 2 + 3 = 6`, and that's the result we got. - -Whew. `fold` can be a bit strange the first few times you see it, but once it -clicks, you can use it all over the place. Any time you have a list of things, -and you want a single result, `fold` is appropriate. - -Consumers are important due to one additional property of iterators we haven't -talked about yet: laziness. Let's talk some more about iterators, and you'll -see why consumers matter. - -## Iterators - -As we've said before, an iterator is something that we can call the -`.next()` method on repeatedly, and it gives us a sequence of things. -Because you need to call the method, this means that iterators -can be *lazy* and not generate all of the values upfront. This code, -for example, does not actually generate the numbers `1-99`, instead -creating a value that merely represents the sequence: - -```rust -let nums = 1..100; -``` - -Since we didn't do anything with the range, it didn't generate the sequence. -Let's add the consumer: - -```rust -let nums = (1..100).collect::>(); -``` - -Now, `collect()` will require that the range gives it some numbers, and so -it will do the work of generating the sequence. - -Ranges are one of two basic iterators that you'll see. The other is `iter()`. -`iter()` can turn a vector into a simple iterator that gives you each element -in turn: - -```rust -let nums = vec![1, 2, 3]; - -for num in nums.iter() { - println!("{}", num); -} -``` - -These two basic iterators should serve you well. There are some more -advanced iterators, including ones that are infinite. - -That's enough about iterators. Iterator adaptors are the last concept -we need to talk about with regards to iterators. Let's get to it! - -## Iterator adaptors - -*Iterator adaptors* take an iterator and modify it somehow, producing -a new iterator. The simplest one is called `map`: - -```rust,ignore -(1..100).map(|x| x + 1); -``` - -`map` is called upon another iterator, and produces a new iterator where each -element reference has the closure it's been given as an argument called on it. -So this would give us the numbers from `2-100`. Well, almost! If you -compile the example, you'll get a warning: - -```text -warning: unused result which must be used: iterator adaptors are lazy and - do nothing unless consumed, #[warn(unused_must_use)] on by default -(1..100).map(|x| x + 1); - ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -``` - -Laziness strikes again! That closure will never execute. This example -doesn't print any numbers: - -```rust,ignore -(1..100).map(|x| println!("{}", x)); -``` - -If you are trying to execute a closure on an iterator for its side effects, -just use `for` instead. - -There are tons of interesting iterator adaptors. `take(n)` will return an -iterator over the next `n` elements of the original iterator. Let's try it out -with an infinite iterator: - -```rust -for i in (1..).take(5) { - println!("{}", i); -} -``` - -This will print - -```text -1 -2 -3 -4 -5 -``` - -`filter()` is an adapter that takes a closure as an argument. This closure -returns `true` or `false`. The new iterator `filter()` produces -only the elements that the closure returns `true` for: - -```rust -for i in (1..100).filter(|&x| x % 2 == 0) { - println!("{}", i); -} -``` - -This will print all of the even numbers between one and a hundred. -(Note that because `filter` doesn't consume the elements that are -being iterated over, it is passed a reference to each element, and -thus the filter predicate uses the `&x` pattern to extract the integer -itself.) - -You can chain all three things together: start with an iterator, adapt it -a few times, and then consume the result. Check it out: - -```rust -(1..) - .filter(|&x| x % 2 == 0) - .filter(|&x| x % 3 == 0) - .take(5) - .collect::>(); -``` - -This will give you a vector containing `6`, `12`, `18`, `24`, and `30`. - -This is just a small taste of what iterators, iterator adaptors, and consumers -can help you with. There are a number of really useful iterators, and you can -write your own as well. Iterators provide a safe, efficient way to manipulate -all kinds of lists. They're a little unusual at first, but if you play with -them, you'll get hooked. For a full list of the different iterators and -consumers, check out the [iterator module documentation](../std/iter/index.html). diff --git a/src/lifetimes.md b/src/lifetimes.md deleted file mode 100644 index c9b6fc3ce..000000000 --- a/src/lifetimes.md +++ /dev/null @@ -1,361 +0,0 @@ -# Lifetimes - -This guide is three 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, -memory safety. There are a few distinct concepts, each with its own chapter: - -* [ownership][ownership], the key concept -* [borrowing][borrowing], and their associated feature ‘references’ -* lifetimes, which you’re reading now - -These three chapters are related, and in order. You’ll need all three to fully -understand the ownership system. - -[ownership]: ownership.html -[borrowing]: references-and-borrowing.html - -# Meta - -Before we get to the details, two important notes about the ownership system. - -Rust has a focus on safety and speed. It accomplishes these goals through many -‘zero-cost abstractions’, which means that in Rust, abstractions cost as little -as possible in order to make them work. The ownership system is a prime example -of a zero-cost abstraction. All of the analysis we’ll talk about in this guide -is _done at compile time_. You do not pay any run-time cost for any of these -features. - -However, this system does have a certain cost: learning curve. Many new users -to Rust experience something we like to call ‘fighting with the borrow -checker’, where the Rust compiler refuses to compile a program that the author -thinks is valid. This often happens because the programmer’s mental model of -how ownership should work doesn’t match the actual rules that Rust implements. -You probably will experience similar things at first. There is good news, -however: more experienced Rust developers report that once they work with the -rules of the ownership system for a period of time, they fight the borrow -checker less and less. - -With that in mind, let’s learn about lifetimes. - -# Lifetimes - -Lending out a reference to a resource that someone else owns can be -complicated. For example, imagine this set of operations: - -1. I acquire a handle to some kind of resource. -2. I lend you a reference to the resource. -3. I decide I’m done with the resource, and deallocate it, while you still have - your reference. -4. You decide to use the resource. - -Uh oh! Your reference is pointing to an invalid resource. This is called a -dangling pointer or ‘use after free’, when the resource is memory. - -To fix this, we have to make sure that step four never happens after step -three. The ownership system in Rust does this through a concept called -lifetimes, which describe the scope that a reference is valid for. - -When we have a function that takes a reference by argument, we can be implicit -or explicit about the lifetime of the reference: - -```rust -// implicit -fn foo(x: &i32) { -} - -// explicit -fn bar<'a>(x: &'a i32) { -} -``` - -The `'a` reads ‘the lifetime a’. Technically, every reference has some lifetime -associated with it, but the compiler lets you elide (i.e. omit, see -["Lifetime Elision"][lifetime-elision] below) them in common cases. -Before we get to that, though, let’s break the explicit example down: - -[lifetime-elision]: #lifetime-elision - -```rust,ignore -fn bar<'a>(...) -``` - -We previously talked a little about [function syntax][functions], but we didn’t -discuss the `<>`s after a function’s name. A function can have ‘generic -parameters’ between the `<>`s, of which lifetimes are one kind. We’ll discuss -other kinds of generics [later in the book][generics], but for now, let’s -just focus on the lifetimes aspect. - -[functions]: functions.html -[generics]: generics.html - -We use `<>` to declare our lifetimes. This says that `bar` has one lifetime, -`'a`. If we had two reference parameters, it would look like this: - - -```rust,ignore -fn bar<'a, 'b>(...) -``` - -Then in our parameter list, we use the lifetimes we’ve named: - -```rust,ignore -...(x: &'a i32) -``` - -If we wanted an `&mut` reference, we’d do this: - -```rust,ignore -...(x: &'a mut i32) -``` - -If you compare `&mut i32` to `&'a mut i32`, they’re the same, it’s just that -the lifetime `'a` has snuck in between the `&` and the `mut i32`. We read `&mut -i32` as ‘a mutable reference to an `i32`’ and `&'a mut i32` as ‘a mutable -reference to an `i32` with the lifetime `'a`’. - -# In `struct`s - -You’ll also need explicit lifetimes when working with [`struct`][structs]s that -contain references: - -```rust -struct Foo<'a> { - x: &'a i32, -} - -fn main() { - let y = &5; // this is the same as `let _y = 5; let y = &_y;` - let f = Foo { x: y }; - - println!("{}", f.x); -} -``` - -[structs]: structs.html - -As you can see, `struct`s can also have lifetimes. In a similar way to functions, - -```rust -struct Foo<'a> { -# x: &'a i32, -# } -``` - -declares a lifetime, and - -```rust -# struct Foo<'a> { -x: &'a i32, -# } -``` - -uses it. So why do we need a lifetime here? We need to ensure that any reference -to a `Foo` cannot outlive the reference to an `i32` it contains. - -## `impl` blocks - -Let’s implement a method on `Foo`: - -```rust -struct Foo<'a> { - x: &'a i32, -} - -impl<'a> Foo<'a> { - fn x(&self) -> &'a i32 { self.x } -} - -fn main() { - let y = &5; // this is the same as `let _y = 5; let y = &_y;` - let f = Foo { x: y }; - - println!("x is: {}", f.x()); -} -``` - -As you can see, we need to declare a lifetime for `Foo` in the `impl` line. We repeat -`'a` twice, just like on functions: `impl<'a>` defines a lifetime `'a`, and `Foo<'a>` -uses it. - -## Multiple lifetimes - -If you have multiple references, you can use the same lifetime multiple times: - -```rust -fn x_or_y<'a>(x: &'a str, y: &'a str) -> &'a str { -# x -# } -``` - -This says that `x` and `y` both are alive for the same scope, and that the -return value is also alive for that scope. If you wanted `x` and `y` to have -different lifetimes, you can use multiple lifetime parameters: - -```rust -fn x_or_y<'a, 'b>(x: &'a str, y: &'b str) -> &'a str { -# x -# } -``` - -In this example, `x` and `y` have different valid scopes, but the return value -has the same lifetime as `x`. - -## Thinking in scopes - -A way to think about lifetimes is to visualize the scope that a reference is -valid for. For example: - -```rust -fn main() { - let y = &5; // -+ y goes into scope - // | - // stuff // | - // | -} // -+ y goes out of scope -``` - -Adding in our `Foo`: - -```rust -struct Foo<'a> { - x: &'a i32, -} - -fn main() { - let y = &5; // -+ y goes into scope - let f = Foo { x: y }; // -+ f goes into scope - // stuff // | - // | -} // -+ f and y go out of scope -``` - -Our `f` lives within the scope of `y`, so everything works. What if it didn’t? -This code won’t work: - -```rust,ignore -struct Foo<'a> { - x: &'a i32, -} - -fn main() { - let x; // -+ x goes into scope - // | - { // | - let y = &5; // ---+ y goes into scope - let f = Foo { x: y }; // ---+ f goes into scope - x = &f.x; // | | error here - } // ---+ f and y go out of scope - // | - println!("{}", x); // | -} // -+ x goes out of scope -``` - -Whew! As you can see here, the scopes of `f` and `y` are smaller than the scope -of `x`. But when we do `x = &f.x`, we make `x` a reference to something that’s -about to go out of scope. - -Named lifetimes are a way of giving these scopes a name. Giving something a -name is the first step towards being able to talk about it. - -## 'static - -The lifetime named ‘static’ is a special lifetime. It signals that something -has the lifetime of the entire program. Most Rust programmers first come across -`'static` when dealing with strings: - -```rust -let x: &'static str = "Hello, world."; -``` - -String literals have the type `&'static str` because the reference is always -alive: they are baked into the data segment of the final binary. Another -example are globals: - -```rust -static FOO: i32 = 5; -let x: &'static i32 = &FOO; -``` - -This adds an `i32` to the data segment of the binary, and `x` is a reference -to it. - -## Lifetime Elision - -Rust supports powerful local type inference in function bodies, but it’s -forbidden in item signatures to allow reasoning about the types based on -the item signature alone. However, for ergonomic reasons a very restricted -secondary inference algorithm called “lifetime elision” applies in function -signatures. It infers only based on the signature components themselves and not -based on the body of the function, only infers lifetime parameters, and does -this with only three easily memorizable and unambiguous rules. This makes -lifetime elision a shorthand for writing an item signature, while not hiding -away the actual types involved as full local inference would if applied to it. - -When talking about lifetime elision, we use the term *input lifetime* and -*output lifetime*. An *input lifetime* is a lifetime associated with a parameter -of a function, and an *output lifetime* is a lifetime associated with the return -value of a function. For example, this function has an input lifetime: - -```rust,ignore -fn foo<'a>(bar: &'a str) -``` - -This one has an output lifetime: - -```rust,ignore -fn foo<'a>() -> &'a str -``` - -This one has a lifetime in both positions: - -```rust,ignore -fn foo<'a>(bar: &'a str) -> &'a str -``` - -Here are the three rules: - -* Each elided lifetime in a function’s arguments becomes a distinct lifetime - parameter. - -* If there is exactly one input lifetime, elided or not, that lifetime is - assigned to all elided lifetimes in the return values of that function. - -* If there are multiple input lifetimes, but one of them is `&self` or `&mut - self`, the lifetime of `self` is assigned to all elided output lifetimes. - -Otherwise, it is an error to elide an output lifetime. - -### Examples - -Here are some examples of functions with elided lifetimes. We’ve paired each -example of an elided lifetime with its expanded form. - -```rust,ignore -fn print(s: &str); // elided -fn print<'a>(s: &'a str); // expanded - -fn debug(lvl: u32, s: &str); // elided -fn debug<'a>(lvl: u32, s: &'a str); // expanded - -// In the preceding example, `lvl` doesn’t need a lifetime because it’s not a -// reference (`&`). Only things relating to references (such as a `struct` -// which contains a reference) need lifetimes. - -fn substr(s: &str, until: u32) -> &str; // elided -fn substr<'a>(s: &'a str, until: u32) -> &'a str; // expanded - -fn get_str() -> &str; // ILLEGAL, no inputs - -fn frob(s: &str, t: &str) -> &str; // ILLEGAL, two inputs -fn frob<'a, 'b>(s: &'a str, t: &'b str) -> &str; // Expanded: Output lifetime is ambiguous - -fn get_mut(&mut self) -> &mut T; // elided -fn get_mut<'a>(&'a mut self) -> &'a mut T; // expanded - -fn args(&mut self, args: &[T]) -> &mut Command; // elided -fn args<'a, 'b, T:ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command; // expanded - -fn new(buf: &mut [u8]) -> BufWriter; // elided -fn new<'a>(buf: &'a mut [u8]) -> BufWriter<'a>; // expanded -``` diff --git a/src/macros.md b/src/macros.md deleted file mode 100644 index 2b802aeff..000000000 --- a/src/macros.md +++ /dev/null @@ -1,773 +0,0 @@ -# Macros - -By now you’ve learned about many of the tools Rust provides for abstracting and -reusing code. These units of code reuse have a rich semantic structure. For -example, functions have a type signature, type parameters have trait bounds, -and overloaded functions must belong to a particular trait. - -This structure means that Rust’s core abstractions have powerful compile-time -correctness checking. But this comes at the price of reduced flexibility. If -you visually identify a pattern of repeated code, you may find it’s difficult -or cumbersome to express that pattern as a generic function, a trait, or -anything else within Rust’s semantics. - -Macros allow us to abstract at a syntactic level. A macro invocation is -shorthand for an "expanded" syntactic form. This expansion happens early in -compilation, before any static checking. As a result, macros can capture many -patterns of code reuse that Rust’s core abstractions cannot. - -The drawback is that macro-based code can be harder to understand, because -fewer of the built-in rules apply. Like an ordinary function, a well-behaved -macro can be used without understanding its implementation. However, it can be -difficult to design a well-behaved macro! Additionally, compiler errors in -macro code are harder to interpret, because they describe problems in the -expanded code, not the source-level form that developers use. - -These drawbacks make macros something of a "feature of last resort". That’s not -to say that macros are bad; they are part of Rust because sometimes they’re -needed for truly concise, well-abstracted code. Just keep this tradeoff in -mind. - -# Defining a macro - -You may have seen the `vec!` macro, used to initialize a [vector][vector] with -any number of elements. - -[vector]: vectors.html - -```rust -let x: Vec = vec![1, 2, 3]; -# assert_eq!(x, [1, 2, 3]); -``` - -This can’t be an ordinary function, because it takes any number of arguments. -But we can imagine it as syntactic shorthand for - -```rust -let x: Vec = { - let mut temp_vec = Vec::new(); - temp_vec.push(1); - temp_vec.push(2); - temp_vec.push(3); - temp_vec -}; -# assert_eq!(x, [1, 2, 3]); -``` - -We can implement this shorthand, using a macro: [^actual] - -[^actual]: The actual definition of `vec!` in libcollections differs from the - one presented here, for reasons of efficiency and reusability. - -```rust -macro_rules! vec { - ( $( $x:expr ),* ) => { - { - let mut temp_vec = Vec::new(); - $( - temp_vec.push($x); - )* - temp_vec - } - }; -} -# fn main() { -# assert_eq!(vec![1,2,3], [1, 2, 3]); -# } -``` - -Whoa, that’s a lot of new syntax! Let’s break it down. - -```ignore -macro_rules! vec { ... } -``` - -This says we’re defining a macro named `vec`, much as `fn vec` would define a -function named `vec`. In prose, we informally write a macro’s name with an -exclamation point, e.g. `vec!`. The exclamation point is part of the invocation -syntax and serves to distinguish a macro from an ordinary function. - -## Matching - -The macro is defined through a series of rules, which are pattern-matching -cases. Above, we had - -```ignore -( $( $x:expr ),* ) => { ... }; -``` - -This is like a `match` expression arm, but the matching happens on Rust syntax -trees, at compile time. The semicolon is optional on the last (here, only) -case. The "pattern" on the left-hand side of `=>` is known as a ‘matcher’. -These have [their own little grammar] within the language. - -[their own little grammar]: ../reference.html#macros - -The matcher `$x:expr` will match any Rust expression, binding that syntax tree -to the ‘metavariable’ `$x`. The identifier `expr` is a ‘fragment specifier’; -the full possibilities are enumerated later in this chapter. -Surrounding the matcher with `$(...),*` will match zero or more expressions, -separated by commas. - -Aside from the special matcher syntax, any Rust tokens that appear in a matcher -must match exactly. For example, - -```rust -macro_rules! foo { - (x => $e:expr) => (println!("mode X: {}", $e)); - (y => $e:expr) => (println!("mode Y: {}", $e)); -} - -fn main() { - foo!(y => 3); -} -``` - -will print - -```text -mode Y: 3 -``` - -With - -```rust,ignore -foo!(z => 3); -``` - -we get the compiler error - -```text -error: no rules expected the token `z` -``` - -## Expansion - -The right-hand side of a macro rule is ordinary Rust syntax, for the most part. -But we can splice in bits of syntax captured by the matcher. From the original -example: - -```ignore -$( - temp_vec.push($x); -)* -``` - -Each matched expression `$x` will produce a single `push` statement in the -macro expansion. The repetition in the expansion proceeds in "lockstep" with -repetition in the matcher (more on this in a moment). - -Because `$x` was already declared as matching an expression, we don’t repeat -`:expr` on the right-hand side. Also, we don’t include a separating comma as -part of the repetition operator. Instead, we have a terminating semicolon -within the repeated block. - -Another detail: the `vec!` macro has *two* pairs of braces on the right-hand -side. They are often combined like so: - -```ignore -macro_rules! foo { - () => {{ - ... - }} -} -``` - -The outer braces are part of the syntax of `macro_rules!`. In fact, you can use -`()` or `[]` instead. They simply delimit the right-hand side as a whole. - -The inner braces are part of the expanded syntax. Remember, the `vec!` macro is -used in an expression context. To write an expression with multiple statements, -including `let`-bindings, we use a block. If your macro expands to a single -expression, you don’t need this extra layer of braces. - -Note that we never *declared* that the macro produces an expression. In fact, -this is not determined until we use the macro as an expression. With care, you -can write a macro whose expansion works in several contexts. For example, -shorthand for a data type could be valid as either an expression or a pattern. - -## Repetition - -The repetition operator follows two principal rules: - -1. `$(...)*` walks through one "layer" of repetitions, for all of the `$name`s - it contains, in lockstep, and -2. each `$name` must be under at least as many `$(...)*`s as it was matched - against. If it is under more, it’ll be duplicated, as appropriate. - -This baroque macro illustrates the duplication of variables from outer -repetition levels. - -```rust -macro_rules! o_O { - ( - $( - $x:expr; [ $( $y:expr ),* ] - );* - ) => { - &[ $($( $x + $y ),*),* ] - } -} - -fn main() { - let a: &[i32] - = o_O!(10; [1, 2, 3]; - 20; [4, 5, 6]); - - assert_eq!(a, [11, 12, 13, 24, 25, 26]); -} -``` - -That’s most of the matcher syntax. These examples use `$(...)*`, which is a -"zero or more" match. Alternatively you can write `$(...)+` for a "one or -more" match. Both forms optionally include a separator, which can be any token -except `+` or `*`. - -This system is based on -"[Macro-by-Example](https://www.cs.indiana.edu/ftp/techreports/TR206.pdf)" -(PDF link). - -# Hygiene - -Some languages implement macros using simple text substitution, which leads to -various problems. For example, this C program prints `13` instead of the -expected `25`. - -```text -#define FIVE_TIMES(x) 5 * x - -int main() { - printf("%d\n", FIVE_TIMES(2 + 3)); - return 0; -} -``` - -After expansion we have `5 * 2 + 3`, and multiplication has greater precedence -than addition. If you’ve used C macros a lot, you probably know the standard -idioms for avoiding this problem, as well as five or six others. In Rust, we -don’t have to worry about it. - -```rust -macro_rules! five_times { - ($x:expr) => (5 * $x); -} - -fn main() { - assert_eq!(25, five_times!(2 + 3)); -} -``` - -The metavariable `$x` is parsed as a single expression node, and keeps its -place in the syntax tree even after substitution. - -Another common problem in macro systems is ‘variable capture’. Here’s a C -macro, using [a GNU C extension] to emulate Rust’s expression blocks. - -[a GNU C extension]: https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html - -```text -#define LOG(msg) ({ \ - int state = get_log_state(); \ - if (state > 0) { \ - printf("log(%d): %s\n", state, msg); \ - } \ -}) -``` - -Here’s a simple use case that goes terribly wrong: - -```text -const char *state = "reticulating splines"; -LOG(state) -``` - -This expands to - -```text -const char *state = "reticulating splines"; -int state = get_log_state(); -if (state > 0) { - printf("log(%d): %s\n", state, state); -} -``` - -The second variable named `state` shadows the first one. This is a problem -because the print statement should refer to both of them. - -The equivalent Rust macro has the desired behavior. - -```rust -# fn get_log_state() -> i32 { 3 } -macro_rules! log { - ($msg:expr) => {{ - let state: i32 = get_log_state(); - if state > 0 { - println!("log({}): {}", state, $msg); - } - }}; -} - -fn main() { - let state: &str = "reticulating splines"; - log!(state); -} -``` - -This works because Rust has a [hygienic macro system]. Each macro expansion -happens in a distinct ‘syntax context’, and each variable is tagged with the -syntax context where it was introduced. It’s as though the variable `state` -inside `main` is painted a different "color" from the variable `state` inside -the macro, and therefore they don’t conflict. - -[hygienic macro system]: https://en.wikipedia.org/wiki/Hygienic_macro - -This also restricts the ability of macros to introduce new bindings at the -invocation site. Code such as the following will not work: - -```rust,ignore -macro_rules! foo { - () => (let x = 3); -} - -fn main() { - foo!(); - println!("{}", x); -} -``` - -Instead you need to pass the variable name into the invocation, so it’s tagged -with the right syntax context. - -```rust -macro_rules! foo { - ($v:ident) => (let $v = 3); -} - -fn main() { - foo!(x); - println!("{}", x); -} -``` - -This holds for `let` bindings and loop labels, but not for [items][items]. -So the following code does compile: - -```rust -macro_rules! foo { - () => (fn x() { }); -} - -fn main() { - foo!(); - x(); -} -``` - -[items]: ../reference.html#items - -# Recursive macros - -A macro’s expansion can include more macro invocations, including invocations -of the very same macro being expanded. These recursive macros are useful for -processing tree-structured input, as illustrated by this (simplistic) HTML -shorthand: - -```rust -# #![allow(unused_must_use)] -macro_rules! write_html { - ($w:expr, ) => (()); - - ($w:expr, $e:tt) => (write!($w, "{}", $e)); - - ($w:expr, $tag:ident [ $($inner:tt)* ] $($rest:tt)*) => {{ - write!($w, "<{}>", stringify!($tag)); - write_html!($w, $($inner)*); - write!($w, "", stringify!($tag)); - write_html!($w, $($rest)*); - }}; -} - -fn main() { -# // FIXME(#21826) - use std::fmt::Write; - let mut out = String::new(); - - write_html!(&mut out, - html[ - head[title["Macros guide"]] - body[h1["Macros are the best!"]] - ]); - - assert_eq!(out, - "Macros guide\ -

Macros are the best!

"); -} -``` - -# Debugging macro code - -To see the results of expanding macros, run `rustc --pretty expanded`. The -output represents a whole crate, so you can also feed it back in to `rustc`, -which will sometimes produce better error messages than the original -compilation. Note that the `--pretty expanded` output may have a different -meaning if multiple variables of the same name (but different syntax contexts) -are in play in the same scope. In this case `--pretty expanded,hygiene` will -tell you about the syntax contexts. - -`rustc` provides two syntax extensions that help with macro debugging. For now, -they are unstable and require feature gates. - -* `log_syntax!(...)` will print its arguments to standard output, at compile - time, and "expand" to nothing. - -* `trace_macros!(true)` will enable a compiler message every time a macro is - expanded. Use `trace_macros!(false)` later in expansion to turn it off. - -# Syntactic requirements - -Even when Rust code contains un-expanded macros, it can be parsed as a full -[syntax tree][ast]. This property can be very useful for editors and other -tools that process code. It also has a few consequences for the design of -Rust’s macro system. - -[ast]: glossary.html#abstract-syntax-tree - -One consequence is that Rust must determine, when it parses a macro invocation, -whether the macro stands in for - -* zero or more items, -* zero or more methods, -* an expression, -* a statement, or -* a pattern. - -A macro invocation within a block could stand for some items, or for an -expression / statement. Rust uses a simple rule to resolve this ambiguity. A -macro invocation that stands for items must be either - -* delimited by curly braces, e.g. `foo! { ... }`, or -* terminated by a semicolon, e.g. `foo!(...);` - -Another consequence of pre-expansion parsing is that the macro invocation must -consist of valid Rust tokens. Furthermore, parentheses, brackets, and braces -must be balanced within a macro invocation. For example, `foo!([)` is -forbidden. This allows Rust to know where the macro invocation ends. - -More formally, the macro invocation body must be a sequence of ‘token trees’. -A token tree is defined recursively as either - -* a sequence of token trees surrounded by matching `()`, `[]`, or `{}`, or -* any other single token. - -Within a matcher, each metavariable has a ‘fragment specifier’, identifying -which syntactic form it matches. - -* `ident`: an identifier. Examples: `x`; `foo`. -* `path`: a qualified name. Example: `T::SpecialA`. -* `expr`: an expression. Examples: `2 + 2`; `if true { 1 } else { 2 }`; `f(42)`. -* `ty`: a type. Examples: `i32`; `Vec<(char, String)>`; `&T`. -* `pat`: a pattern. Examples: `Some(t)`; `(17, 'a')`; `_`. -* `stmt`: a single statement. Example: `let x = 3`. -* `block`: a brace-delimited sequence of statements. Example: - `{ log(error, "hi"); return 12; }`. -* `item`: an [item][item]. Examples: `fn foo() { }`; `struct Bar;`. -* `meta`: a "meta item", as found in attributes. Example: `cfg(target_os = "windows")`. -* `tt`: a single token tree. - -There are additional rules regarding the next token after a metavariable: - -* `expr` variables may only be followed by one of: `=> , ;` -* `ty` and `path` variables may only be followed by one of: `=> , : = > as` -* `pat` variables may only be followed by one of: `=> , = if in` -* Other variables may be followed by any token. - -These rules provide some flexibility for Rust’s syntax to evolve without -breaking existing macros. - -The macro system does not deal with parse ambiguity at all. For example, the -grammar `$($t:ty)* $e:expr` will always fail to parse, because the parser would -be forced to choose between parsing `$t` and parsing `$e`. Changing the -invocation syntax to put a distinctive token in front can solve the problem. In -this case, you can write `$(T $t:ty)* E $e:exp`. - -[item]: ../reference.html#items - -# Scoping and macro import/export - -Macros are expanded at an early stage in compilation, before name resolution. -One downside is that scoping works differently for macros, compared to other -constructs in the language. - -Definition and expansion of macros both happen in a single depth-first, -lexical-order traversal of a crate’s source. So a macro defined at module scope -is visible to any subsequent code in the same module, which includes the body -of any subsequent child `mod` items. - -A macro defined within the body of a single `fn`, or anywhere else not at -module scope, is visible only within that item. - -If a module has the `macro_use` attribute, its macros are also visible in its -parent module after the child’s `mod` item. If the parent also has `macro_use` -then the macros will be visible in the grandparent after the parent’s `mod` -item, and so forth. - -The `macro_use` attribute can also appear on `extern crate`. In this context -it controls which macros are loaded from the external crate, e.g. - -```rust,ignore -#[macro_use(foo, bar)] -extern crate baz; -``` - -If the attribute is given simply as `#[macro_use]`, all macros are loaded. If -there is no `#[macro_use]` attribute then no macros are loaded. Only macros -defined with the `#[macro_export]` attribute may be loaded. - -To load a crate’s macros without linking it into the output, use `#[no_link]` -as well. - -An example: - -```rust -macro_rules! m1 { () => (()) } - -// visible here: m1 - -mod foo { - // visible here: m1 - - #[macro_export] - macro_rules! m2 { () => (()) } - - // visible here: m1, m2 -} - -// visible here: m1 - -macro_rules! m3 { () => (()) } - -// visible here: m1, m3 - -#[macro_use] -mod bar { - // visible here: m1, m3 - - macro_rules! m4 { () => (()) } - - // visible here: m1, m3, m4 -} - -// visible here: m1, m3, m4 -# fn main() { } -``` - -When this library is loaded with `#[macro_use] extern crate`, only `m2` will -be imported. - -The Rust Reference has a [listing of macro-related -attributes](../reference.html#macro-related-attributes). - -# The variable `$crate` - -A further difficulty occurs when a macro is used in multiple crates. Say that -`mylib` defines - -```rust -pub fn increment(x: u32) -> u32 { - x + 1 -} - -#[macro_export] -macro_rules! inc_a { - ($x:expr) => ( ::increment($x) ) -} - -#[macro_export] -macro_rules! inc_b { - ($x:expr) => ( ::mylib::increment($x) ) -} -# fn main() { } -``` - -`inc_a` only works within `mylib`, while `inc_b` only works outside the -library. Furthermore, `inc_b` will break if the user imports `mylib` under -another name. - -Rust does not (yet) have a hygiene system for crate references, but it does -provide a simple workaround for this problem. Within a macro imported from a -crate named `foo`, the special macro variable `$crate` will expand to `::foo`. -By contrast, when a macro is defined and then used in the same crate, `$crate` -will expand to nothing. This means we can write - -```rust -#[macro_export] -macro_rules! inc { - ($x:expr) => ( $crate::increment($x) ) -} -# fn main() { } -``` - -to define a single macro that works both inside and outside our library. The -function name will expand to either `::increment` or `::mylib::increment`. - -To keep this system simple and correct, `#[macro_use] extern crate ...` may -only appear at the root of your crate, not inside `mod`. This ensures that -`$crate` is a single identifier. - -# The deep end - -The introductory chapter mentioned recursive macros, but it did not give the -full story. Recursive macros are useful for another reason: Each recursive -invocation gives you another opportunity to pattern-match the macro’s -arguments. - -As an extreme example, it is possible, though hardly advisable, to implement -the [Bitwise Cyclic Tag](https://esolangs.org/wiki/Bitwise_Cyclic_Tag) automaton -within Rust’s macro system. - -```rust -macro_rules! bct { - // cmd 0: d ... => ... - (0, $($ps:tt),* ; $_d:tt) - => (bct!($($ps),*, 0 ; )); - (0, $($ps:tt),* ; $_d:tt, $($ds:tt),*) - => (bct!($($ps),*, 0 ; $($ds),*)); - - // cmd 1p: 1 ... => 1 ... p - (1, $p:tt, $($ps:tt),* ; 1) - => (bct!($($ps),*, 1, $p ; 1, $p)); - (1, $p:tt, $($ps:tt),* ; 1, $($ds:tt),*) - => (bct!($($ps),*, 1, $p ; 1, $($ds),*, $p)); - - // cmd 1p: 0 ... => 0 ... - (1, $p:tt, $($ps:tt),* ; $($ds:tt),*) - => (bct!($($ps),*, 1, $p ; $($ds),*)); - - // halt on empty data string - ( $($ps:tt),* ; ) - => (()); -} -``` - -Exercise: use macros to reduce duplication in the above definition of the -`bct!` macro. - -# Common macros - -Here are some common macros you’ll see in Rust code. - -## panic! - -This macro causes the current thread to panic. You can give it a message -to panic with: - -```rust,no_run -panic!("oh no!"); -``` - -## vec! - -The `vec!` macro is used throughout the book, so you’ve probably seen it -already. It creates `Vec`s with ease: - -```rust -let v = vec![1, 2, 3, 4, 5]; -``` - -It also lets you make vectors with repeating values. For example, a hundred -zeroes: - -```rust -let v = vec![0; 100]; -``` - -## assert! and assert_eq! - -These two macros are used in tests. `assert!` takes a boolean. `assert_eq!` -takes two values and checks them for equality. `true` passes, `false` `panic!`s. -Like this: - -```rust,no_run -// A-ok! - -assert!(true); -assert_eq!(5, 3 + 2); - -// nope :( - -assert!(5 < 3); -assert_eq!(5, 3); -``` - -## try! - -`try!` is used for error handling. It takes something that can return a -`Result`, and gives `T` if it’s a `Ok`, and `return`s with the -`Err(E)` if it’s that. Like this: - -```rust,no_run -use std::fs::File; - -fn foo() -> std::io::Result<()> { - let f = try!(File::create("foo.txt")); - - Ok(()) -} -``` - -This is cleaner than doing this: - -```rust,no_run -use std::fs::File; - -fn foo() -> std::io::Result<()> { - let f = File::create("foo.txt"); - - let f = match f { - Ok(t) => t, - Err(e) => return Err(e), - }; - - Ok(()) -} -``` - -## unreachable! - -This macro is used when you think some code should never execute: - -```rust -if false { - unreachable!(); -} -``` - -Sometimes, the compiler may make you have a different branch that you know -will never, ever run. In these cases, use this macro, so that if you end -up wrong, you’ll get a `panic!` about it. - -```rust -let x: Option = None; - -match x { - Some(_) => unreachable!(), - None => println!("I know x is None!"), -} -``` - -## unimplemented! - -The `unimplemented!` macro can be used when you’re trying to get your functions -to typecheck, and don’t want to worry about writing out the body of the -function. One example of this situation is implementing a trait with multiple -required methods, where you want to tackle one at a time. Define the others -as `unimplemented!` until you’re ready to write them. - -# Procedural macros - -If Rust’s macro system can’t do what you need, you may want to write a -[compiler plugin](compiler-plugins.html) instead. Compared to `macro_rules!` -macros, this is significantly more work, the interfaces are much less stable, -and bugs can be much harder to track down. In exchange you get the -flexibility of running arbitrary Rust code within the compiler. Syntax -extension plugins are sometimes called ‘procedural macros’ for this reason. diff --git a/src/match.md b/src/match.md deleted file mode 100644 index 46acfb8a9..000000000 --- a/src/match.md +++ /dev/null @@ -1 +0,0 @@ -# Match diff --git a/src/method-syntax.md b/src/method-syntax.md deleted file mode 100644 index 5dfaae2c2..000000000 --- a/src/method-syntax.md +++ /dev/null @@ -1 +0,0 @@ -# Method Syntax diff --git a/src/mutex.md b/src/mutex.md deleted file mode 100644 index 1bbfc0113..000000000 --- a/src/mutex.md +++ /dev/null @@ -1 +0,0 @@ -# `Mutex` diff --git a/src/nightly-rust.md b/src/nightly-rust.md deleted file mode 100644 index f99a3f3b8..000000000 --- a/src/nightly-rust.md +++ /dev/null @@ -1 +0,0 @@ -# Nightly Rust diff --git a/src/option.md b/src/option.md deleted file mode 100644 index f33af4ff3..000000000 --- a/src/option.md +++ /dev/null @@ -1 +0,0 @@ -# Option diff --git a/src/ownership-and-borrowing.md b/src/ownership-and-borrowing.md deleted file mode 100644 index 45b2f9ca8..000000000 --- a/src/ownership-and-borrowing.md +++ /dev/null @@ -1 +0,0 @@ -# Ownership & borrowing diff --git a/src/path.md b/src/path.md deleted file mode 100644 index 5edc288d2..000000000 --- a/src/path.md +++ /dev/null @@ -1 +0,0 @@ -# `std::path` diff --git a/src/patterns.md b/src/patterns.md deleted file mode 100644 index 3c9daa330..000000000 --- a/src/patterns.md +++ /dev/null @@ -1 +0,0 @@ -# Patterns diff --git a/src/raw-pointers.md b/src/raw-pointers.md deleted file mode 100644 index fe32b8a11..000000000 --- a/src/raw-pointers.md +++ /dev/null @@ -1,121 +0,0 @@ -# Raw Pointers - -Rust has a number of different smart pointer types in its standard library, but -there are two types that are extra-special. Much of Rust’s safety comes from -compile-time checks, but raw pointers don’t have such guarantees, and are -[unsafe][unsafe] to use. - -`*const T` and `*mut T` are called ‘raw pointers’ in Rust. Sometimes, when -writing certain kinds of libraries, you’ll need to get around Rust’s safety -guarantees for some reason. In this case, you can use raw pointers to implement -your library, while exposing a safe interface for your users. For example, `*` -pointers are allowed to alias, allowing them to be used to write -shared-ownership types, and even thread-safe shared memory types (the `Rc` -and `Arc` types are both implemented entirely in Rust). - -Here are some things to remember about raw pointers that are different than -other pointer types. They: - -- are not guaranteed to point to valid memory and are not even - guaranteed to be non-null (unlike both `Box` and `&`); -- do not have any automatic clean-up, unlike `Box`, and so require - manual resource management; -- are plain-old-data, that is, they don't move ownership, again unlike - `Box`, hence the Rust compiler cannot protect against bugs like - use-after-free; -- lack any form of lifetimes, unlike `&`, and so the compiler cannot - reason about dangling pointers; and -- have no guarantees about aliasing or mutability other than mutation - not being allowed directly through a `*const T`. - -# Basics - -Creating a raw pointer is perfectly safe: - -```rust -let x = 5; -let raw = &x as *const i32; - -let mut y = 10; -let raw_mut = &mut y as *mut i32; -``` - -However, dereferencing one is not. This won’t work: - -```rust,ignore -let x = 5; -let raw = &x as *const i32; - -println!("raw points at {}", *raw); -``` - -It gives this error: - -```text -error: dereference of raw pointer requires unsafe function or block [E0133] - println!("raw points at {}", *raw); - ^~~~ -``` - -When you dereference a raw pointer, you’re taking responsibility that it’s not -pointing somewhere that would be incorrect. As such, you need `unsafe`: - -```rust -let x = 5; -let raw = &x as *const i32; - -let points_at = unsafe { *raw }; - -println!("raw points at {}", points_at); -``` - -For more operations on raw pointers, see [their API documentation][rawapi]. - -[unsafe]: unsafe.html -[rawapi]: ../std/primitive.pointer.html - -# FFI - -Raw pointers are useful for FFI: Rust’s `*const T` and `*mut T` are similar to -C’s `const T*` and `T*`, respectively. For more about this use, consult the -[FFI chapter][ffi]. - -[ffi]: ffi.html - -# References and raw pointers - -At runtime, a raw pointer `*` and a reference pointing to the same piece of -data have an identical representation. In fact, an `&T` reference will -implicitly coerce to an `*const T` raw pointer in safe code and similarly for -the `mut` variants (both coercions can be performed explicitly with, -respectively, `value as *const T` and `value as *mut T`). - -Going the opposite direction, from `*const` to a reference `&`, is not safe. A -`&T` is always valid, and so, at a minimum, the raw pointer `*const T` has to -point to a valid instance of type `T`. Furthermore, the resulting pointer must -satisfy the aliasing and mutability laws of references. The compiler assumes -these properties are true for any references, no matter how they are created, -and so any conversion from raw pointers is asserting that they hold. The -programmer *must* guarantee this. - -The recommended method for the conversion is: - -```rust -// explicit cast -let i: u32 = 1; -let p_imm: *const u32 = &i as *const u32; - -// implicit coercion -let mut m: u32 = 2; -let p_mut: *mut u32 = &mut m; - -unsafe { - let ref_imm: &u32 = &*p_imm; - let ref_mut: &mut u32 = &mut *p_mut; -} -``` - -The `&*x` dereferencing style is preferred to using a `transmute`. The latter -is far more powerful than necessary, and the more restricted operation is -harder to use incorrectly; for example, it requires that `x` is a pointer -(unlike `transmute`). diff --git a/src/rc.md b/src/rc.md deleted file mode 100644 index 3fed7f478..000000000 --- a/src/rc.md +++ /dev/null @@ -1 +0,0 @@ -# `Rc` diff --git a/src/read-and-write.md b/src/read-and-write.md deleted file mode 100644 index 2029f9c14..000000000 --- a/src/read-and-write.md +++ /dev/null @@ -1 +0,0 @@ -# `Read` & `Write` diff --git a/src/refcell.md b/src/refcell.md deleted file mode 100644 index b9995cfa0..000000000 --- a/src/refcell.md +++ /dev/null @@ -1 +0,0 @@ -# `RefCell` diff --git a/src/references-and-borrowing.md b/src/references-and-borrowing.md deleted file mode 100644 index c60a0e21a..000000000 --- a/src/references-and-borrowing.md +++ /dev/null @@ -1,407 +0,0 @@ -# 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: - -```rust -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: - -```bash -$ cargo run - Compiling functions v0.1.0 (file:///projects/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, -memory safety. There are a few distinct concepts, each with its own -chapter: - -* [ownership][ownership], the key concept -* borrowing, which you’re reading now -* [lifetimes][lifetimes], an advanced concept of borrowing - -These three chapters are related, and in order. You’ll need all three to fully -understand the ownership system. - -[ownership]: ownership.html -[lifetimes]: lifetimes.html - -# Meta - -Before we get to the details, two important notes about the ownership system. - -Rust has a focus on safety and speed. It accomplishes these goals through many -‘zero-cost abstractions’, which means that in Rust, abstractions cost as little -as possible in order to make them work. The ownership system is a prime example -of a zero cost abstraction. All of the analysis we’ll talk about in this guide -is _done at compile time_. You do not pay any run-time cost for any of these -features. - -However, this system does have a certain cost: learning curve. Many new users -to Rust experience something we like to call ‘fighting with the borrow -checker’, where the Rust compiler refuses to compile a program that the author -thinks is valid. This often happens because the programmer’s mental model of -how ownership should work doesn’t match the actual rules that Rust implements. -You probably will experience similar things at first. There is good news, -however: more experienced Rust developers report that once they work with the -rules of the ownership system for a period of time, they fight the borrow -checker less and less. - -With that in mind, let’s learn about borrowing. - -# Borrowing - -At the end of the [ownership][ownership] section, we had a nasty function that looked -like this: - -```rust -fn foo(v1: Vec, v2: Vec) -> (Vec, Vec, i32) { - // do stuff with v1 and v2 - - // hand back ownership, and the result of our function - (v1, v2, 42) -} - -let v1 = vec![1, 2, 3]; -let v2 = vec![1, 2, 3]; - -let (v1, v2, answer) = foo(v1, v2); -``` - -This is not idiomatic Rust, however, as it doesn’t take advantage of borrowing. Here’s -the first step: - -```rust -fn foo(v1: &Vec, v2: &Vec) -> i32 { - // do stuff with v1 and v2 - - // return the answer - 42 -} - -let v1 = vec![1, 2, 3]; -let v2 = vec![1, 2, 3]; - -let answer = foo(&v1, &v2); - -// we can use v1 and v2 here! -``` - -Instead of taking `Vec`s as our arguments, we take a reference: -`&Vec`. And instead of passing `v1` and `v2` directly, we pass `&v1` and -`&v2`. We call the `&T` type a ‘reference’, and rather than owning the resource, -it borrows ownership. A binding that borrows something does not deallocate the -resource when it goes out of scope. This means that after the call to `foo()`, -we can use our original bindings again. - -References are immutable, just like bindings. This means that inside of `foo()`, -the vectors can’t be changed at all: - -```rust,ignore -fn foo(v: &Vec) { - v.push(5); -} - -let v = vec![]; - -foo(&v); -``` - -errors with: - -```text -error: cannot borrow immutable borrowed content `*v` as mutable -v.push(5); -^ -``` - -Pushing a value mutates the vector, and so we aren’t allowed to do it. - -# &mut references - -There’s a second kind of reference: `&mut T`. A ‘mutable reference’ allows you -to mutate the resource you’re borrowing. For example: - -```rust -let mut x = 5; -{ - let y = &mut x; - *y += 1; -} -println!("{}", x); -``` - -This will print `6`. We make `y` a mutable reference to `x`, then add one to -the thing `y` points at. You’ll notice that `x` had to be marked `mut` as well. -If it wasn’t, we couldn’t take a mutable borrow to an immutable value. - -You'll also notice we added an asterisk (`*`) in front of `y`, making it `*y`, -this is because `y` is an `&mut` reference. You'll also need to use them for -accessing the contents of a reference as well. - -Otherwise, `&mut` references are just like references. There _is_ a large -difference between the two, and how they interact, though. You can tell -something is fishy in the above example, because we need that extra scope, with -the `{` and `}`. If we remove them, we get an error: - -```text -error: cannot borrow `x` as immutable because it is also borrowed as mutable - println!("{}", x); - ^ -note: previous borrow of `x` occurs here; the mutable borrow prevents -subsequent moves, borrows, or modification of `x` until the borrow ends - let y = &mut x; - ^ -note: previous borrow ends here -fn main() { - -} -^ -``` - -As it turns out, there are rules. - -# The Rules - -Here’s the rules about borrowing in Rust: - -First, any borrow must last for a scope no greater than that of the owner. -Second, you may have one or the other of these two kinds of borrows, but not -both at the same time: - -* one or more references (`&T`) to a resource, -* exactly one mutable reference (`&mut T`). - - -You may notice that this is very similar, though not exactly the same as, -to the definition of a data race: - -> There is a ‘data race’ when two or more pointers access the same memory -> location at the same time, where at least one of them is writing, and the -> operations are not synchronized. - -With references, you may have as many as you’d like, since none of them are -writing. However, as we can only have one `&mut` at a time, it is impossible to -have a data race. This is how Rust prevents data races at compile time: we’ll -get errors if we break the rules. - -With this in mind, let’s consider our example again. - -## Thinking in scopes - -Here’s the code: - -```rust,ignore -let mut x = 5; -let y = &mut x; - -*y += 1; - -println!("{}", x); -``` - -This code gives us this error: - -```text -error: cannot borrow `x` as immutable because it is also borrowed as mutable - println!("{}", x); - ^ -``` - -This is because we’ve violated the rules: we have a `&mut T` pointing to `x`, -and so we aren’t allowed to create any `&T`s. One or the other. The note -hints at how to think about this problem: - -```text -note: previous borrow ends here -fn main() { - -} -^ -``` - -In other words, the mutable borrow is held through the rest of our example. What -we want is for the mutable borrow to end _before_ we try to call `println!` and -make an immutable borrow. In Rust, borrowing is tied to the scope that the -borrow is valid for. And our scopes look like this: - -```rust,ignore -let mut x = 5; - -let y = &mut x; // -+ &mut borrow of x starts here - // | -*y += 1; // | - // | -println!("{}", x); // -+ - try to borrow x here - // -+ &mut borrow of x ends here -``` - -The scopes conflict: we can’t make an `&x` while `y` is in scope. - -So when we add the curly braces: - -```rust -let mut x = 5; - -{ - let y = &mut x; // -+ &mut borrow starts here - *y += 1; // | -} // -+ ... and ends here - -println!("{}", x); // <- try to borrow x here -``` - -There’s no problem. Our mutable borrow goes out of scope before we create an -immutable one. But scope is the key to seeing how long a borrow lasts for. - -## Issues borrowing prevents - -Why have these restrictive rules? Well, as we noted, these rules prevent data -races. What kinds of issues do data races cause? Here’s a few. - -### Iterator invalidation - -One example is ‘iterator invalidation’, which happens when you try to mutate a -collection that you’re iterating over. Rust’s borrow checker prevents this from -happening: - -```rust -let mut v = vec![1, 2, 3]; - -for i in &v { - println!("{}", i); -} -``` - -This prints out one through three. As we iterate through the vectors, we’re -only given references to the elements. And `v` is itself borrowed as immutable, -which means we can’t change it while we’re iterating: - -```rust,ignore -let mut v = vec![1, 2, 3]; - -for i in &v { - println!("{}", i); - v.push(34); -} -``` - -Here’s the error: - -```text -error: cannot borrow `v` as mutable because it is also borrowed as immutable - v.push(34); - ^ -note: previous borrow of `v` occurs here; the immutable borrow prevents -subsequent moves or mutable borrows of `v` until the borrow ends -for i in &v { - ^ -note: previous borrow ends here -for i in &v { - println!(“{}”, i); - v.push(34); -} -^ -``` - -We can’t modify `v` because it’s borrowed by the loop. - -### use after free - -References must not live longer than the resource they refer to. Rust will -check the scopes of your references to ensure that this is true. - -If Rust didn’t check this property, we could accidentally use a reference -which was invalid. For example: - -```rust,ignore -let y: &i32; -{ - let x = 5; - y = &x; -} - -println!("{}", y); -``` - -We get this error: - -```text -error: `x` does not live long enough - y = &x; - ^ -note: reference must be valid for the block suffix following statement 0 at -2:16... -let y: &i32; -{ - let x = 5; - y = &x; -} - -note: ...but borrowed value is only valid for the block suffix following -statement 0 at 4:18 - let x = 5; - y = &x; -} -``` - -In other words, `y` is only valid for the scope where `x` exists. As soon as -`x` goes away, it becomes invalid to refer to it. As such, the error says that -the borrow ‘doesn’t live long enough’ because it’s not valid for the right -amount of time. - -The same problem occurs when the reference is declared _before_ the variable it -refers to. This is because resources within the same scope are freed in the -opposite order they were declared: - -```rust,ignore -let y: &i32; -let x = 5; -y = &x; - -println!("{}", y); -``` - -We get this error: - -```text -error: `x` does not live long enough -y = &x; - ^ -note: reference must be valid for the block suffix following statement 0 at -2:16... - let y: &i32; - let x = 5; - y = &x; - - println!("{}", y); -} - -note: ...but borrowed value is only valid for the block suffix following -statement 1 at 3:14 - let x = 5; - y = &x; - - println!("{}", y); -} -``` - -In the above example, `y` is declared before `x`, meaning that `y` lives longer -than `x`, which is not allowed. - diff --git a/src/send-and-sync.md b/src/send-and-sync.md deleted file mode 100644 index 0bc8785ad..000000000 --- a/src/send-and-sync.md +++ /dev/null @@ -1 +0,0 @@ -# `Send` & `Sync` diff --git a/src/smart-pointers.md b/src/smart-pointers.md deleted file mode 100644 index bf8e8d62c..000000000 --- a/src/smart-pointers.md +++ /dev/null @@ -1 +0,0 @@ -# Smart Pointers diff --git a/src/static.md b/src/static.md deleted file mode 100644 index bbd81a857..000000000 --- a/src/static.md +++ /dev/null @@ -1 +0,0 @@ -# `static` diff --git a/src/strings.md b/src/strings.md deleted file mode 100644 index ed218ce9a..000000000 --- a/src/strings.md +++ /dev/null @@ -1 +0,0 @@ -# Strings diff --git a/src/structs-advanced.md b/src/structs-advanced.md deleted file mode 100644 index 931fae06c..000000000 --- a/src/structs-advanced.md +++ /dev/null @@ -1 +0,0 @@ -# Advanced diff --git a/src/structs-generics.md b/src/structs-generics.md deleted file mode 100644 index 292d26b98..000000000 --- a/src/structs-generics.md +++ /dev/null @@ -1 +0,0 @@ -# Generics diff --git a/src/structs-method-syntax.md b/src/structs-method-syntax.md deleted file mode 100644 index 5dfaae2c2..000000000 --- a/src/structs-method-syntax.md +++ /dev/null @@ -1 +0,0 @@ -# Method Syntax diff --git a/src/structs-motivation.md b/src/structs-motivation.md deleted file mode 100644 index 6d769339f..000000000 --- a/src/structs-motivation.md +++ /dev/null @@ -1 +0,0 @@ -# Motivation diff --git a/src/testing.md b/src/testing.md deleted file mode 100644 index 5a9e2de61..000000000 --- a/src/testing.md +++ /dev/null @@ -1,510 +0,0 @@ -# Testing - -> Program testing can be a very effective way to show the presence of bugs, but -> it is hopelessly inadequate for showing their absence. -> -> Edsger W. Dijkstra, "The Humble Programmer" (1972) - -Let's talk about how to test Rust code. What we will not be talking about is -the right way to test Rust code. There are many schools of thought regarding -the right and wrong way to write tests. All of these approaches use the same -basic tools, and so we'll show you the syntax for using them. - -# The `test` attribute - -At its simplest, a test in Rust is a function that's annotated with the `test` -attribute. Let's make a new project with Cargo called `adder`: - -```bash -$ cargo new adder -$ cd adder -``` - -Cargo will automatically generate a simple test when you make a new project. -Here's the contents of `src/lib.rs`: - -```rust -#[test] -fn it_works() { -} -``` - -Note the `#[test]`. This attribute indicates that this is a test function. It -currently has no body. That's good enough to pass! We can run the tests with -`cargo test`: - -```bash -$ cargo test - Compiling adder v0.0.1 (file:///home/you/projects/adder) - Running target/adder-91b3e234d4ed382a - -running 1 test -test it_works ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Doc-tests adder - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured -``` - -Cargo compiled and ran our tests. There are two sets of output here: one -for the test we wrote, and another for documentation tests. We'll talk about -those later. For now, see this line: - -```text -test it_works ... ok -``` - -Note the `it_works`. This comes from the name of our function: - -```rust -fn it_works() { -# } -``` - -We also get a summary line: - -```text -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured -``` - -So why does our do-nothing test pass? Any test which doesn't `panic!` passes, -and any test that does `panic!` fails. Let's make our test fail: - -```rust -#[test] -fn it_works() { - assert!(false); -} -``` - -`assert!` is a macro provided by Rust which takes one argument: if the argument -is `true`, nothing happens. If the argument is `false`, it `panic!`s. Let's run -our tests again: - -```bash -$ cargo test - Compiling adder v0.0.1 (file:///home/you/projects/adder) - Running target/adder-91b3e234d4ed382a - -running 1 test -test it_works ... FAILED - -failures: - ----- it_works stdout ---- - thread 'it_works' panicked at 'assertion failed: false', /projects/adder/src/lib.rs:3 - - - -failures: - it_works - -test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured - -thread '
' panicked at 'Some tests failed', /home/steve/src/rust/src/libtest/lib.rs:247 -``` - -Rust indicates that our test failed: - -```text -test it_works ... FAILED -``` - -And that's reflected in the summary line: - -```text -test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured -``` - -We also get a non-zero status code. We can use `$?` on OS X and Linux: - -```bash -$ echo $? -101 -``` - -On Windows, if you’re using `cmd`: - -```bash -> echo %ERRORLEVEL% -``` - -And if you’re using PowerShell: - -```bash -> echo $LASTEXITCODE # the code itself -> echo $? # a boolean, fail or succeed -``` - -This is useful if you want to integrate `cargo test` into other tooling. - -We can invert our test's failure with another attribute: `should_panic`: - -```rust -#[test] -#[should_panic] -fn it_works() { - assert!(false); -} -``` - -This test will now succeed if we `panic!` and fail if we complete. Let's try it: - -```bash -$ cargo test - Compiling adder v0.0.1 (file:///home/you/projects/adder) - Running target/adder-91b3e234d4ed382a - -running 1 test -test it_works ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Doc-tests adder - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured -``` - -Rust provides another macro, `assert_eq!`, that compares two arguments for -equality: - -```rust -#[test] -#[should_panic] -fn it_works() { - assert_eq!("Hello", "world"); -} -``` - -Does this test pass or fail? Because of the `should_panic` attribute, it -passes: - -```bash -$ cargo test - Compiling adder v0.0.1 (file:///home/you/projects/adder) - Running target/adder-91b3e234d4ed382a - -running 1 test -test it_works ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Doc-tests adder - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured -``` - -`should_panic` tests can be fragile, as it's hard to guarantee that the test -didn't fail for an unexpected reason. To help with this, an optional `expected` -parameter can be added to the `should_panic` attribute. The test harness will -make sure that the failure message contains the provided text. A safer version -of the example above would be: - -```rust -#[test] -#[should_panic(expected = "assertion failed")] -fn it_works() { - assert_eq!("Hello", "world"); -} -``` - -That's all there is to the basics! Let's write one 'real' test: - -```rust,ignore -pub fn add_two(a: i32) -> i32 { - a + 2 -} - -#[test] -fn it_works() { - assert_eq!(4, add_two(2)); -} -``` - -This is a very common use of `assert_eq!`: call some function with -some known arguments and compare it to the expected output. - -# The `ignore` attribute - -Sometimes a few specific tests can be very time-consuming to execute. These -can be disabled by default by using the `ignore` attribute: - -```rust -#[test] -fn it_works() { - assert_eq!(4, add_two(2)); -} - -#[test] -#[ignore] -fn expensive_test() { - // code that takes an hour to run -} -``` - -Now we run our tests and see that `it_works` is run, but `expensive_test` is -not: - -```bash -$ cargo test - Compiling adder v0.0.1 (file:///home/you/projects/adder) - Running target/adder-91b3e234d4ed382a - -running 2 tests -test expensive_test ... ignored -test it_works ... ok - -test result: ok. 1 passed; 0 failed; 1 ignored; 0 measured - - Doc-tests adder - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured -``` - -The expensive tests can be run explicitly using `cargo test -- --ignored`: - -```bash -$ cargo test -- --ignored - Running target/adder-91b3e234d4ed382a - -running 1 test -test expensive_test ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Doc-tests adder - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured -``` - -The `--ignored` argument is an argument to the test binary, and not to Cargo, -which is why the command is `cargo test -- --ignored`. - -# The `tests` module - -There is one way in which our existing example is not idiomatic: it's -missing the `tests` module. The idiomatic way of writing our example -looks like this: - -```rust,ignore -pub fn add_two(a: i32) -> i32 { - a + 2 -} - -#[cfg(test)] -mod tests { - use super::add_two; - - #[test] - fn it_works() { - assert_eq!(4, add_two(2)); - } -} -``` - -There's a few changes here. The first is the introduction of a `mod tests` with -a `cfg` attribute. The module allows us to group all of our tests together, and -to also define helper functions if needed, that don't become a part of the rest -of our crate. The `cfg` attribute only compiles our test code if we're -currently trying to run the tests. This can save compile time, and also ensures -that our tests are entirely left out of a normal build. - -The second change is the `use` declaration. Because we're in an inner module, -we need to bring our test function into scope. This can be annoying if you have -a large module, and so this is a common use of globs. Let's change our -`src/lib.rs` to make use of it: - -```rust,ignore -pub fn add_two(a: i32) -> i32 { - a + 2 -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn it_works() { - assert_eq!(4, add_two(2)); - } -} -``` - -Note the different `use` line. Now we run our tests: - -```bash -$ cargo test - Updating registry `https://github.com/rust-lang/crates.io-index` - Compiling adder v0.0.1 (file:///home/you/projects/adder) - Running target/adder-91b3e234d4ed382a - -running 1 test -test tests::it_works ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Doc-tests adder - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured -``` - -It works! - -The current convention is to use the `tests` module to hold your "unit-style" -tests. Anything that just tests one small bit of functionality makes sense to -go here. But what about "integration-style" tests instead? For that, we have -the `tests` directory. - -# The `tests` directory - -To write an integration test, let's make a `tests` directory, and -put a `tests/lib.rs` file inside, with this as its contents: - -```rust,ignore -extern crate adder; - -#[test] -fn it_works() { - assert_eq!(4, adder::add_two(2)); -} -``` - -This looks similar to our previous tests, but slightly different. We now have -an `extern crate adder` at the top. This is because the tests in the `tests` -directory are an entirely separate crate, and so we need to import our library. -This is also why `tests` is a suitable place to write integration-style tests: -they use the library like any other consumer of it would. - -Let's run them: - -```bash -$ cargo test - Compiling adder v0.0.1 (file:///home/you/projects/adder) - Running target/adder-91b3e234d4ed382a - -running 1 test -test tests::it_works ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Running target/lib-c18e7d3494509e74 - -running 1 test -test it_works ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Doc-tests adder - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured -``` - -Now we have three sections: our previous test is also run, as well as our new -one. - -That's all there is to the `tests` directory. The `tests` module isn't needed -here, since the whole thing is focused on tests. - -Let's finally check out that third section: documentation tests. - -# Documentation tests - -Nothing is better than documentation with examples. Nothing is worse than -examples that don't actually work, because the code has changed since the -documentation has been written. To this end, Rust supports automatically -running examples in your documentation (**note:** this only works in library -crates, not binary crates). Here's a fleshed-out `src/lib.rs` with examples: - -```rust,ignore -//! The `adder` crate provides functions that add numbers to other numbers. -//! -//! # Examples -//! -//! ``` -//! assert_eq!(4, adder::add_two(2)); -//! ``` - -/// This function adds two to its argument. -/// -/// # Examples -/// -/// ``` -/// use adder::add_two; -/// -/// assert_eq!(4, add_two(2)); -/// ``` -pub fn add_two(a: i32) -> i32 { - a + 2 -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn it_works() { - assert_eq!(4, add_two(2)); - } -} -``` - -Note the module-level documentation with `//!` and the function-level -documentation with `///`. Rust's documentation supports Markdown in comments, -and so triple graves mark code blocks. It is conventional to include the -`# Examples` section, exactly like that, with examples following. - -Let's run the tests again: - -```bash -$ cargo test - Compiling adder v0.0.1 (file:///projects/adder) - Running target/adder-91b3e234d4ed382a - -running 1 test -test tests::it_works ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Running target/lib-c18e7d3494509e74 - -running 1 test -test it_works ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Doc-tests adder - -running 2 tests -test add_two_0 ... ok -test _0 ... ok - -test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured -``` - -Now we have all three kinds of tests running! Note the names of the -documentation tests: the `_0` is generated for the module test, and `add_two_0` -for the function test. These will auto increment with names like `add_two_1` as -you add more examples. - -We haven’t covered all of the details with writing documentation tests. For more, -please see the [Documentation chapter](documentation.html) - -One final note: documentation tests *cannot* be run on binary crates. -To see more on file arrangement see the [Crates and -Modules](crates-and-modules.html) section. diff --git a/src/theme/book.css b/src/theme/book.css deleted file mode 100644 index 98c8aa5cd..000000000 --- a/src/theme/book.css +++ /dev/null @@ -1,587 +0,0 @@ -html, -body { - font-family: "Open Sans", sans-serif; - color: #333; -} -.left { - float: left; -} -.right { - float: right; -} -.hidden { - display: none; -} -h2, -h3 { - margin-top: 2.5em; -} -h4, -h5 { - margin-top: 2em; -} -.header + .header h3, -.header + .header h4, -.header + .header h5 { - margin-top: 1em; -} -.sidebar { - position: absolute; - left: 0; - top: 0; - bottom: 0; - width: 300px; - overflow-y: auto; - padding: 10px 10px; - font-size: 0.875em; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - -webkit-overflow-scrolling: touch; - -webkit-transition: left 0.5s; - -moz-transition: left 0.5s; - -o-transition: left 0.5s; - -ms-transition: left 0.5s; - transition: left 0.5s; -} -@media only screen and (max-width: 1060px) { - .sidebar { - left: -300px; - } -} -.sidebar code { - line-height: 2em; -} -.sidebar-hidden .sidebar { - left: -300px; -} -.sidebar-visible .sidebar { - left: 0; -} -.chapter { - list-style: none outside none; - padding-left: 0; - line-height: 1.9em; -} -.chapter li a { - padding: 5px 0; - text-decoration: none; -} -.chapter li a:hover { - text-decoration: none; -} -.chapter .spacer { - width: 100%; - height: 3px; - margin: 10px 0px; -} -.section { - list-style: none outside none; - padding-left: 20px; - line-height: 2.5em; -} -.section li { - -o-text-overflow: ellipsis; - text-overflow: ellipsis; - overflow: hidden; - white-space: nowrap; -} -.page-wrapper { - position: absolute; - overflow-y: auto; - left: 315px; - right: 0; - top: 0; - bottom: 0; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - -webkit-overflow-scrolling: touch; - min-height: 100%; - -webkit-transition: left 0.5s; - -moz-transition: left 0.5s; - -o-transition: left 0.5s; - -ms-transition: left 0.5s; - transition: left 0.5s; -} -@media only screen and (max-width: 1060px) { - .page-wrapper { - left: 15px; - padding-right: 15px; - } -} -.sidebar-hidden .page-wrapper { - left: 15px; -} -.sidebar-visible .page-wrapper { - left: 315px; -} -.page { - position: absolute; - top: 0; - right: 0; - left: 0; - bottom: 0; - padding-right: 15px; - overflow-y: auto; -} -.content { - margin-left: auto; - margin-right: auto; - max-width: 750px; - padding-bottom: 50px; -} -.content a { - text-decoration: none; -} -.content a:hover { - text-decoration: underline; -} -.content img { - max-width: 100%; -} -.menu-bar { - position: relative; - height: 50px; -} -.menu-bar i { - position: relative; - margin: 0 10px; - z-index: 10; - line-height: 50px; - -webkit-transition: color 0.5s; - -moz-transition: color 0.5s; - -o-transition: color 0.5s; - -ms-transition: color 0.5s; - transition: color 0.5s; -} -.menu-bar i:hover { - cursor: pointer; -} -.menu-bar .left-buttons { - float: left; -} -.menu-bar .right-buttons { - float: right; -} -.menu-title { - display: inline-block; - font-weight: 200; - font-size: 20px; - line-height: 50px; - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - text-align: center; - margin: 0; - opacity: 0; - -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; - filter: alpha(opacity=0); - -webkit-transition: opacity 0.5s ease-in-out; - -moz-transition: opacity 0.5s ease-in-out; - -o-transition: opacity 0.5s ease-in-out; - -ms-transition: opacity 0.5s ease-in-out; - transition: opacity 0.5s ease-in-out; -} -.menu-bar:hover .menu-title { - opacity: 1; - -ms-filter: none; - filter: none; -} -.nav-chapters { - font-size: 2.5em; - text-align: center; - text-decoration: none; - position: absolute; - top: 50px /* Height of menu-bar */; - bottom: 0; - margin: 0; - max-width: 150px; - min-width: 90px; - display: -webkit-box; - display: -moz-box; - display: -webkit-flex; - display: -ms-flexbox; - display: box; - display: flex; - -webkit-box-pack: center; - -moz-box-pack: center; - -o-box-pack: center; - -ms-flex-pack: center; - -webkit-justify-content: center; - justify-content: center; - -ms-flex-line-pack: center; - -webkit-align-content: center; - align-content: center; - -webkit-box-orient: vertical; - -moz-box-orient: vertical; - -o-box-orient: vertical; - -webkit-flex-direction: column; - -ms-flex-direction: column; - flex-direction: column; - -webkit-transition: color 0.5s; - -moz-transition: color 0.5s; - -o-transition: color 0.5s; - -ms-transition: color 0.5s; - transition: color 0.5s; -} -.mobile-nav-chapters { - display: none; -} -.nav-chapters:hover { - text-decoration: none; -} -.previous { - left: 0; -} -.next { - right: 15px; -} -.theme-popup { - position: fixed; - left: -40px; - -webkit-border-radius: 4px; - border-radius: 4px; - font-size: 0.7em; -} -.theme-popup .theme { - margin: 0; - padding: 2px 10px; - line-height: 25px; - white-space: nowrap; -} -@media only screen and (max-width: 1250px) { - .nav-chapters { - display: none; - } - .mobile-nav-chapters { - font-size: 2.5em; - text-align: center; - text-decoration: none; - max-width: 150px; - min-width: 90px; - -webkit-box-pack: center; - -moz-box-pack: center; - -o-box-pack: center; - -ms-flex-pack: center; - -webkit-justify-content: center; - justify-content: center; - -ms-flex-line-pack: center; - -webkit-align-content: center; - align-content: center; - position: relative; - display: inline-block; - margin-bottom: 50px; - -webkit-border-radius: 5px; - border-radius: 5px; - } - .next { - float: right; - } - .previous { - float: left; - } -} -.light { -/* Inline code */ - color: #333; - background-color: #fff; -} -.light :not(pre) > .hljs { - display: inline-block; - vertical-align: middle; - padding: 0.1em 0.3em; - -webkit-border-radius: 3px; - border-radius: 3px; -} -.light pre { - position: relative; -} -.light pre > i { - position: absolute; - right: 5px; - top: 5px; - color: #364149; - cursor: pointer; -} -.light pre > i :hover { - color: #008cff; -} -.light .sidebar { - background-color: #fafafa; - color: #364149; -} -.light .chapter li { - color: #aaa; -} -.light .chapter li a { - color: #364149; -} -.light .chapter li .active, -.light .chapter li a:hover { -/* Animate color change */ - color: #008cff; -} -.light .chapter .spacer { - background-color: #f4f4f4; -} -.light .menu-bar, -.light .menu-bar:visited, -.light .nav-chapters, -.light .nav-chapters:visited, -.light .mobile-nav-chapters, -.light .mobile-nav-chapters:visited { - color: #ccc; -} -.light .menu-bar i:hover, -.light .nav-chapters:hover, -.light .mobile-nav-chapters i:hover { - color: #333; -} -.light .mobile-nav-chapters i:hover { - color: #364149; -} -.light .mobile-nav-chapters { - background-color: #fafafa; -} -.light .content a:link, -.light a:visited { - color: #4183c4; -} -.light .theme-popup { - background: #fafafa; - border: 1px solid #ccc; -} -.light .theme-popup .theme:hover { - background-color: #e6e6e6; -} -.coal { -/* Inline code */ - color: #98a3ad; - background-color: #141617; -} -.coal :not(pre) > .hljs { - display: inline-block; - vertical-align: middle; - padding: 0.1em 0.3em; - -webkit-border-radius: 3px; - border-radius: 3px; -} -.coal pre { - position: relative; -} -.coal pre > i { - position: absolute; - right: 5px; - top: 5px; - color: #a1adb8; - cursor: pointer; -} -.coal pre > i :hover { - color: #3473ad; -} -.coal .sidebar { - background-color: #292c2f; - color: #a1adb8; -} -.coal .chapter li { - color: #505254; -} -.coal .chapter li a { - color: #a1adb8; -} -.coal .chapter li .active, -.coal .chapter li a:hover { -/* Animate color change */ - color: #3473ad; -} -.coal .chapter .spacer { - background-color: #393939; -} -.coal .menu-bar, -.coal .menu-bar:visited, -.coal .nav-chapters, -.coal .nav-chapters:visited, -.coal .mobile-nav-chapters, -.coal .mobile-nav-chapters:visited { - color: #43484d; -} -.coal .menu-bar i:hover, -.coal .nav-chapters:hover, -.coal .mobile-nav-chapters i:hover { - color: #b3c0cc; -} -.coal .mobile-nav-chapters i:hover { - color: #a1adb8; -} -.coal .mobile-nav-chapters { - background-color: #292c2f; -} -.coal .content a:link, -.coal a:visited { - color: #2b79a2; -} -.coal .theme-popup { - background: #141617; - border: 1px solid #43484d; -} -.coal .theme-popup .theme:hover { - background-color: #1f2124; -} -.navy { -/* Inline code */ - color: #bcbdd0; - background-color: #161923; -} -.navy :not(pre) > .hljs { - display: inline-block; - vertical-align: middle; - padding: 0.1em 0.3em; - -webkit-border-radius: 3px; - border-radius: 3px; -} -.navy pre { - position: relative; -} -.navy pre > i { - position: absolute; - right: 5px; - top: 5px; - color: #c8c9db; - cursor: pointer; -} -.navy pre > i :hover { - color: #2b79a2; -} -.navy .sidebar { - background-color: #282d3f; - color: #c8c9db; -} -.navy .chapter li { - color: #505274; -} -.navy .chapter li a { - color: #c8c9db; -} -.navy .chapter li .active, -.navy .chapter li a:hover { -/* Animate color change */ - color: #2b79a2; -} -.navy .chapter .spacer { - background-color: #2d334f; -} -.navy .menu-bar, -.navy .menu-bar:visited, -.navy .nav-chapters, -.navy .nav-chapters:visited, -.navy .mobile-nav-chapters, -.navy .mobile-nav-chapters:visited { - color: #737480; -} -.navy .menu-bar i:hover, -.navy .nav-chapters:hover, -.navy .mobile-nav-chapters i:hover { - color: #b7b9cc; -} -.navy .mobile-nav-chapters i:hover { - color: #c8c9db; -} -.navy .mobile-nav-chapters { - background-color: #282d3f; -} -.navy .content a:link, -.navy a:visited { - color: #2b79a2; -} -.navy .theme-popup { - background: #161923; - border: 1px solid #737480; -} -.navy .theme-popup .theme:hover { - background-color: #282e40; -} -.rust { -/* Inline code */ - color: #262625; - background-color: #e1e1db; -} -.rust :not(pre) > .hljs { - display: inline-block; - vertical-align: middle; - padding: 0.1em 0.3em; - -webkit-border-radius: 3px; - border-radius: 3px; -} -.rust pre { - position: relative; -} -.rust pre > i { - position: absolute; - right: 5px; - top: 5px; - color: #c8c9db; - cursor: pointer; -} -.rust pre > i :hover { - color: #e69f67; -} -.rust .sidebar { - background-color: #3b2e2a; - color: #c8c9db; -} -.rust .chapter li { - color: #505254; -} -.rust .chapter li a { - color: #c8c9db; -} -.rust .chapter li .active, -.rust .chapter li a:hover { -/* Animate color change */ - color: #e69f67; -} -.rust .chapter .spacer { - background-color: #45373a; -} -.rust .menu-bar, -.rust .menu-bar:visited, -.rust .nav-chapters, -.rust .nav-chapters:visited, -.rust .mobile-nav-chapters, -.rust .mobile-nav-chapters:visited { - color: #737480; -} -.rust .menu-bar i:hover, -.rust .nav-chapters:hover, -.rust .mobile-nav-chapters i:hover { - color: #262625; -} -.rust .mobile-nav-chapters i:hover { - color: #c8c9db; -} -.rust .mobile-nav-chapters { - background-color: #3b2e2a; -} -.rust .content a:link, -.rust a:visited { - color: #2b79a2; -} -.rust .theme-popup { - background: #e1e1db; - border: 1px solid #b38f6b; -} -.rust .theme-popup .theme:hover { - background-color: #99908a; -} - -/* Everything above is the default theme, below is custom */ -.center { - text-align: center; - display: block; - margin-left: auto; - margin-right: auto; -} - diff --git a/src/theme/index.hbs b/src/theme/index.hbs deleted file mode 100644 index 1b1db22fa..000000000 --- a/src/theme/index.hbs +++ /dev/null @@ -1,120 +0,0 @@ - - - - - {{ title }} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - -
- -
- -
- This book is in the process of being rewritten. Some sections are in form of drafts and - others haven't been rewritten yet. The stable version can be found here. -
-
- - {{{ content }}} -
- - - {{#previous}} - - {{/previous}} - - {{#next}} - - {{/next}} - -
- - {{#previous}} - - {{/previous}} - - {{#next}} - - {{/next}} - -
- - - - - - - - - diff --git a/src/threads.md b/src/threads.md deleted file mode 100644 index f60f3991e..000000000 --- a/src/threads.md +++ /dev/null @@ -1 +0,0 @@ -# Threads diff --git a/src/trait-objects.md b/src/trait-objects.md deleted file mode 100644 index 3af700238..000000000 --- a/src/trait-objects.md +++ /dev/null @@ -1,340 +0,0 @@ -# Trait Objects - -When code involves polymorphism, there needs to be a mechanism to determine -which specific version is actually run. This is called ‘dispatch’. There are -two major forms of dispatch: static dispatch and dynamic dispatch. While Rust -favors static dispatch, it also supports dynamic dispatch through a mechanism -called ‘trait objects’. - -## Background - -For the rest of this chapter, we’ll need a trait and some implementations. -Let’s make a simple one, `Foo`. It has one method that is expected to return a -`String`. - -```rust -trait Foo { - fn method(&self) -> String; -} -``` - -We’ll also implement this trait for `u8` and `String`: - -```rust -# trait Foo { fn method(&self) -> String; } -impl Foo for u8 { - fn method(&self) -> String { format!("u8: {}", *self) } -} - -impl Foo for String { - fn method(&self) -> String { format!("string: {}", *self) } -} -``` - - -## Static dispatch - -We can use this trait to perform static dispatch with trait bounds: - -```rust -# trait Foo { fn method(&self) -> String; } -# impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } } -# impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } } -fn do_something(x: T) { - x.method(); -} - -fn main() { - let x = 5u8; - let y = "Hello".to_string(); - - do_something(x); - do_something(y); -} -``` - -Rust uses ‘monomorphization’ to perform static dispatch here. This means that -Rust will create a special version of `do_something()` for both `u8` and -`String`, and then replace the call sites with calls to these specialized -functions. In other words, Rust generates something like this: - -```rust -# trait Foo { fn method(&self) -> String; } -# impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } } -# impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } } -fn do_something_u8(x: u8) { - x.method(); -} - -fn do_something_string(x: String) { - x.method(); -} - -fn main() { - let x = 5u8; - let y = "Hello".to_string(); - - do_something_u8(x); - do_something_string(y); -} -``` - -This has a great upside: static dispatch allows function calls to be -inlined because the callee is known at compile time, and inlining is -the key to good optimization. Static dispatch is fast, but it comes at -a tradeoff: ‘code bloat’, due to many copies of the same function -existing in the binary, one for each type. - -Furthermore, compilers aren’t perfect and may “optimize” code to become slower. -For example, functions inlined too eagerly will bloat the instruction cache -(cache rules everything around us). This is part of the reason that `#[inline]` -and `#[inline(always)]` should be used carefully, and one reason why using a -dynamic dispatch is sometimes more efficient. - -However, the common case is that it is more efficient to use static dispatch, -and one can always have a thin statically-dispatched wrapper function that does -a dynamic dispatch, but not vice versa, meaning static calls are more flexible. -The standard library tries to be statically dispatched where possible for this -reason. - -## Dynamic dispatch - -Rust provides dynamic dispatch through a feature called ‘trait objects’. Trait -objects, like `&Foo` or `Box`, are normal values that store a value of -*any* type that implements the given trait, where the precise type can only be -known at runtime. - -A trait object can be obtained from a pointer to a concrete type that -implements the trait by *casting* it (e.g. `&x as &Foo`) or *coercing* it -(e.g. using `&x` as an argument to a function that takes `&Foo`). - -These trait object coercions and casts also work for pointers like `&mut T` to -`&mut Foo` and `Box` to `Box`, but that’s all at the moment. Coercions -and casts are identical. - -This operation can be seen as ‘erasing’ the compiler’s knowledge about the -specific type of the pointer, and hence trait objects are sometimes referred to -as ‘type erasure’. - -Coming back to the example above, we can use the same trait to perform dynamic -dispatch with trait objects by casting: - -```rust -# trait Foo { fn method(&self) -> String; } -# impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } } -# impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } } - -fn do_something(x: &Foo) { - x.method(); -} - -fn main() { - let x = 5u8; - do_something(&x as &Foo); -} -``` - -or by coercing: - -```rust -# trait Foo { fn method(&self) -> String; } -# impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } } -# impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } } - -fn do_something(x: &Foo) { - x.method(); -} - -fn main() { - let x = "Hello".to_string(); - do_something(&x); -} -``` - -A function that takes a trait object is not specialized to each of the types -that implements `Foo`: only one copy is generated, often (but not always) -resulting in less code bloat. However, this comes at the cost of requiring -slower virtual function calls, and effectively inhibiting any chance of -inlining and related optimizations from occurring. - -### Why pointers? - -Rust does not put things behind a pointer by default, unlike many managed -languages, so types can have different sizes. Knowing the size of the value at -compile time is important for things like passing it as an argument to a -function, moving it about on the stack and allocating (and deallocating) space -on the heap to store it. - -For `Foo`, we would need to have a value that could be at least either a -`String` (24 bytes) or a `u8` (1 byte), as well as any other type for which -dependent crates may implement `Foo` (any number of bytes at all). There’s no -way to guarantee that this last point can work if the values are stored without -a pointer, because those other types can be arbitrarily large. - -Putting the value behind a pointer means the size of the value is not relevant -when we are tossing a trait object around, only the size of the pointer itself. - -### Representation - -The methods of the trait can be called on a trait object via a special record -of function pointers traditionally called a ‘vtable’ (created and managed by -the compiler). - -Trait objects are both simple and complicated: their core representation and -layout is quite straight-forward, but there are some curly error messages and -surprising behaviors to discover. - -Let’s start simple, with the runtime representation of a trait object. The -`std::raw` module contains structs with layouts that are the same as the -complicated built-in types, [including trait objects][stdraw]: - -```rust -# mod foo { -pub struct TraitObject { - pub data: *mut (), - pub vtable: *mut (), -} -# } -``` - -[stdraw]: ../std/raw/struct.TraitObject.html - -That is, a trait object like `&Foo` consists of a ‘data’ pointer and a ‘vtable’ -pointer. - -The data pointer addresses the data (of some unknown type `T`) that the trait -object is storing, and the vtable pointer points to the vtable (‘virtual method -table’) corresponding to the implementation of `Foo` for `T`. - - -A vtable is essentially a struct of function pointers, pointing to the concrete -piece of machine code for each method in the implementation. A method call like -`trait_object.method()` will retrieve the correct pointer out of the vtable and -then do a dynamic call of it. For example: - -```rust,ignore -struct FooVtable { - destructor: fn(*mut ()), - size: usize, - align: usize, - method: fn(*const ()) -> String, -} - -// u8: - -fn call_method_on_u8(x: *const ()) -> String { - // the compiler guarantees that this function is only called - // with `x` pointing to a u8 - let byte: &u8 = unsafe { &*(x as *const u8) }; - - byte.method() -} - -static Foo_for_u8_vtable: FooVtable = FooVtable { - destructor: /* compiler magic */, - size: 1, - align: 1, - - // cast to a function pointer - method: call_method_on_u8 as fn(*const ()) -> String, -}; - - -// String: - -fn call_method_on_String(x: *const ()) -> String { - // the compiler guarantees that this function is only called - // with `x` pointing to a String - let string: &String = unsafe { &*(x as *const String) }; - - string.method() -} - -static Foo_for_String_vtable: FooVtable = FooVtable { - destructor: /* compiler magic */, - // values for a 64-bit computer, halve them for 32-bit ones - size: 24, - align: 8, - - method: call_method_on_String as fn(*const ()) -> String, -}; -``` - -The `destructor` field in each vtable points to a function that will clean up -any resources of the vtable’s type: for `u8` it is trivial, but for `String` it -will free the memory. This is necessary for owning trait objects like -`Box`, which need to clean-up both the `Box` allocation as well as the -internal type when they go out of scope. The `size` and `align` fields store -the size of the erased type, and its alignment requirements; these are -essentially unused at the moment since the information is embedded in the -destructor, but will be used in the future, as trait objects are progressively -made more flexible. - -Suppose we’ve got some values that implement `Foo`. The explicit form of -construction and use of `Foo` trait objects might look a bit like (ignoring the -type mismatches: they’re all just pointers anyway): - -```rust,ignore -let a: String = "foo".to_string(); -let x: u8 = 1; - -// let b: &Foo = &a; -let b = TraitObject { - // store the data - data: &a, - // store the methods - vtable: &Foo_for_String_vtable -}; - -// let y: &Foo = x; -let y = TraitObject { - // store the data - data: &x, - // store the methods - vtable: &Foo_for_u8_vtable -}; - -// b.method(); -(b.vtable.method)(b.data); - -// y.method(); -(y.vtable.method)(y.data); -``` - -## Object Safety - -Not every trait can be used to make a trait object. For example, vectors implement -`Clone`, but if we try to make a trait object: - -```ignore -let v = vec![1, 2, 3]; -let o = &v as &Clone; -``` - -We get an error: - -```text -error: cannot convert to a trait object because trait `core::clone::Clone` is not object-safe [E0038] -let o = &v as &Clone; - ^~ -note: the trait cannot require that `Self : Sized` -let o = &v as &Clone; - ^~ -``` - -The error says that `Clone` is not ‘object-safe’. Only traits that are -object-safe can be made into trait objects. A trait is object-safe if both of -these are true: - -* the trait does not require that `Self: Sized` -* all of its methods are object-safe - -So what makes a method object-safe? Each method must require that `Self: Sized` -or all of the following: - -* must not have any type parameters -* must not use `Self` - -Whew! As we can see, almost all of these rules talk about `Self`. A good intuition -is “except in special circumstances, if your trait’s method uses `Self`, it is not -object-safe.” diff --git a/src/traits.md b/src/traits.md deleted file mode 100644 index 4d9526623..000000000 --- a/src/traits.md +++ /dev/null @@ -1,523 +0,0 @@ -# Traits - -A trait is a language feature that tells the Rust compiler about -functionality a type must provide. - -Recall the `impl` keyword, used to call a function with [method -syntax][methodsyntax]: - -```rust -struct Circle { - x: f64, - y: f64, - radius: f64, -} - -impl Circle { - fn area(&self) -> f64 { - std::f64::consts::PI * (self.radius * self.radius) - } -} -``` - -[methodsyntax]: method-syntax.html - -Traits are similar, except that we first define a trait with a method -signature, then implement the trait for a type. In this example, we implement the trait `HasArea` for `Circle`: - -```rust -struct Circle { - x: f64, - y: f64, - radius: f64, -} - -trait HasArea { - fn area(&self) -> f64; -} - -impl HasArea for Circle { - fn area(&self) -> f64 { - std::f64::consts::PI * (self.radius * self.radius) - } -} -``` - -As you can see, the `trait` block looks very similar to the `impl` block, -but we don’t define a body, just a type signature. When we `impl` a trait, -we use `impl Trait for Item`, rather than just `impl Item`. - -## Trait bounds on generic functions - -Traits are useful because they allow a type to make certain promises about its -behavior. Generic functions can exploit this to constrain, or [bound][bounds], the types they -accept. Consider this function, which does not compile: - -[bounds]: glossary.html#bounds - -```rust,ignore -fn print_area(shape: T) { - println!("This shape has an area of {}", shape.area()); -} -``` - -Rust complains: - -```text -error: no method named `area` found for type `T` in the current scope -``` - -Because `T` can be any type, we can’t be sure that it implements the `area` -method. But we can add a trait bound to our generic `T`, ensuring -that it does: - -```rust -# trait HasArea { -# fn area(&self) -> f64; -# } -fn print_area(shape: T) { - println!("This shape has an area of {}", shape.area()); -} -``` - -The syntax `` means “any type that implements the `HasArea` trait.” -Because traits define function type signatures, we can be sure that any type -which implements `HasArea` will have an `.area()` method. - -Here’s an extended example of how this works: - -```rust -trait HasArea { - fn area(&self) -> f64; -} - -struct Circle { - x: f64, - y: f64, - radius: f64, -} - -impl HasArea for Circle { - fn area(&self) -> f64 { - std::f64::consts::PI * (self.radius * self.radius) - } -} - -struct Square { - x: f64, - y: f64, - side: f64, -} - -impl HasArea for Square { - fn area(&self) -> f64 { - self.side * self.side - } -} - -fn print_area(shape: T) { - println!("This shape has an area of {}", shape.area()); -} - -fn main() { - let c = Circle { - x: 0.0f64, - y: 0.0f64, - radius: 1.0f64, - }; - - let s = Square { - x: 0.0f64, - y: 0.0f64, - side: 1.0f64, - }; - - print_area(c); - print_area(s); -} -``` - -This program outputs: - -```text -This shape has an area of 3.141593 -This shape has an area of 1 -``` - -As you can see, `print_area` is now generic, but also ensures that we have -passed in the correct types. If we pass in an incorrect type: - -```rust,ignore -print_area(5); -``` - -We get a compile-time error: - -```text -error: the trait `HasArea` is not implemented for the type `_` [E0277] -``` - -## Trait bounds on generic structs - -Your generic structs can also benefit from trait bounds. All you need to -do is append the bound when you declare type parameters. Here is a new -type `Rectangle` and its operation `is_square()`: - -```rust -struct Rectangle { - x: T, - y: T, - width: T, - height: T, -} - -impl Rectangle { - fn is_square(&self) -> bool { - self.width == self.height - } -} - -fn main() { - let mut r = Rectangle { - x: 0, - y: 0, - width: 47, - height: 47, - }; - - assert!(r.is_square()); - - r.height = 42; - assert!(!r.is_square()); -} -``` - -`is_square()` needs to check that the sides are equal, so the sides must be of -a type that implements the [`core::cmp::PartialEq`][PartialEq] trait: - -```ignore -impl Rectangle { ... } -``` - -Now, a rectangle can be defined in terms of any type that can be compared for -equality. - -[PartialEq]: ../core/cmp/trait.PartialEq.html - -Here we defined a new struct `Rectangle` that accepts numbers of any -precision—really, objects of pretty much any type—as long as they can be -compared for equality. Could we do the same for our `HasArea` structs, `Square` -and `Circle`? Yes, but they need multiplication, and to work with that we need -to know more about [operator traits][operators-and-overloading]. - -[operators-and-overloading]: operators-and-overloading.html - -# Rules for implementing traits - -So far, we’ve only added trait implementations to structs, but you can -implement a trait for any type. So technically, we _could_ implement `HasArea` -for `i32`: - -```rust -trait HasArea { - fn area(&self) -> f64; -} - -impl HasArea for i32 { - fn area(&self) -> f64 { - println!("this is silly"); - - *self as f64 - } -} - -5.area(); -``` - -It is considered poor style to implement methods on such primitive types, even -though it is possible. - -This may seem like the Wild West, but there are two restrictions around -implementing traits that prevent this from getting out of hand. The first is -that if the trait isn’t defined in your scope, it doesn’t apply. Here’s an -example: the standard library provides a [`Write`][write] trait which adds -extra functionality to `File`s, for doing file I/O. By default, a `File` -won’t have its methods: - -[write]: ../std/io/trait.Write.html - -```rust,ignore -let mut f = std::fs::File::open("foo.txt").expect("Couldn’t open foo.txt"); -let buf = b"whatever"; // byte string literal. buf: &[u8; 8] -let result = f.write(buf); -# result.unwrap(); // ignore the error -``` - -Here’s the error: - -```text -error: type `std::fs::File` does not implement any method in scope named `write` -let result = f.write(buf); - ^~~~~~~~~~ -``` - -We need to `use` the `Write` trait first: - -```rust,ignore -use std::io::Write; - -let mut f = std::fs::File::open("foo.txt").expect("Couldn’t open foo.txt"); -let buf = b"whatever"; -let result = f.write(buf); -# result.unwrap(); // ignore the error -``` - -This will compile without error. - -This means that even if someone does something bad like add methods to `i32`, -it won’t affect you, unless you `use` that trait. - -There’s one more restriction on implementing traits: either the trait, or the -type you’re writing the `impl` for, must be defined by you. So, we could -implement the `HasArea` type for `i32`, because `HasArea` is in our code. But -if we tried to implement `ToString`, a trait provided by Rust, for `i32`, we could -not, because neither the trait nor the type are in our code. - -One last thing about traits: generic functions with a trait bound use -‘monomorphization’ (mono: one, morph: form), so they are statically dispatched. -What’s that mean? Check out the chapter on [trait objects][to] for more details. - -[to]: trait-objects.html - -# Multiple trait bounds - -You’ve seen that you can bound a generic type parameter with a trait: - -```rust -fn foo(x: T) { - x.clone(); -} -``` - -If you need more than one bound, you can use `+`: - -```rust -use std::fmt::Debug; - -fn foo(x: T) { - x.clone(); - println!("{:?}", x); -} -``` - -`T` now needs to be both `Clone` as well as `Debug`. - -# Where clause - -Writing functions with only a few generic types and a small number of trait -bounds isn’t too bad, but as the number increases, the syntax gets increasingly -awkward: - -```rust -use std::fmt::Debug; - -fn foo(x: T, y: K) { - x.clone(); - y.clone(); - println!("{:?}", y); -} -``` - -The name of the function is on the far left, and the parameter list is on the -far right. The bounds are getting in the way. - -Rust has a solution, and it’s called a ‘`where` clause’: - -```rust -use std::fmt::Debug; - -fn foo(x: T, y: K) { - x.clone(); - y.clone(); - println!("{:?}", y); -} - -fn bar(x: T, y: K) where T: Clone, K: Clone + Debug { - x.clone(); - y.clone(); - println!("{:?}", y); -} - -fn main() { - foo("Hello", "world"); - bar("Hello", "world"); -} -``` - -`foo()` uses the syntax we showed earlier, and `bar()` uses a `where` clause. -All you need to do is leave off the bounds when defining your type parameters, -and then add `where` after the parameter list. For longer lists, whitespace can -be added: - -```rust -use std::fmt::Debug; - -fn bar(x: T, y: K) - where T: Clone, - K: Clone + Debug { - - x.clone(); - y.clone(); - println!("{:?}", y); -} -``` - -This flexibility can add clarity in complex situations. - -`where` is also more powerful than the simpler syntax. For example: - -```rust -trait ConvertTo { - fn convert(&self) -> Output; -} - -impl ConvertTo for i32 { - fn convert(&self) -> i64 { *self as i64 } -} - -// can be called with T == i32 -fn normal>(x: &T) -> i64 { - x.convert() -} - -// can be called with T == i64 -fn inverse() -> T - // this is using ConvertTo as if it were "ConvertTo" - where i32: ConvertTo { - 42.convert() -} -``` - -This shows off the additional feature of `where` clauses: they allow bounds -on the left-hand side not only of type parameters `T`, but also of types (`i32` in this case). In this example, `i32` must implement -`ConvertTo`. Rather than defining what `i32` is (since that's obvious), the -`where` clause here constrains `T`. - -# Default methods - -A default method can be added to a trait definition if it is already known how a typical implementor will define a method. For example, `is_invalid()` is defined as the opposite of `is_valid()`: - -```rust -trait Foo { - fn is_valid(&self) -> bool; - - fn is_invalid(&self) -> bool { !self.is_valid() } -} -``` - -Implementors of the `Foo` trait need to implement `is_valid()` but not `is_invalid()` due to the added default behavior. This default behavior can still be overridden as in: - -```rust -# trait Foo { -# fn is_valid(&self) -> bool; -# -# fn is_invalid(&self) -> bool { !self.is_valid() } -# } -struct UseDefault; - -impl Foo for UseDefault { - fn is_valid(&self) -> bool { - println!("Called UseDefault.is_valid."); - true - } -} - -struct OverrideDefault; - -impl Foo for OverrideDefault { - fn is_valid(&self) -> bool { - println!("Called OverrideDefault.is_valid."); - true - } - - fn is_invalid(&self) -> bool { - println!("Called OverrideDefault.is_invalid!"); - true // overrides the expected value of is_invalid() - } -} - -let default = UseDefault; -assert!(!default.is_invalid()); // prints "Called UseDefault.is_valid." - -let over = OverrideDefault; -assert!(over.is_invalid()); // prints "Called OverrideDefault.is_invalid!" -``` - -# Inheritance - -Sometimes, implementing a trait requires implementing another trait: - -```rust -trait Foo { - fn foo(&self); -} - -trait FooBar : Foo { - fn foobar(&self); -} -``` - -Implementors of `FooBar` must also implement `Foo`, like this: - -```rust -# trait Foo { -# fn foo(&self); -# } -# trait FooBar : Foo { -# fn foobar(&self); -# } -struct Baz; - -impl Foo for Baz { - fn foo(&self) { println!("foo"); } -} - -impl FooBar for Baz { - fn foobar(&self) { println!("foobar"); } -} -``` - -If we forget to implement `Foo`, Rust will tell us: - -```text -error: the trait `main::Foo` is not implemented for the type `main::Baz` [E0277] -``` - -# Deriving - -Implementing traits like `Debug` and `Default` repeatedly can become -quite tedious. For that reason, Rust provides an [attribute][attributes] that -allows you to let Rust automatically implement traits for you: - -```rust -#[derive(Debug)] -struct Foo; - -fn main() { - println!("{:?}", Foo); -} -``` - -[attributes]: attributes.html - -However, deriving is limited to a certain set of traits: - -- [`Clone`](../core/clone/trait.Clone.html) -- [`Copy`](../core/marker/trait.Copy.html) -- [`Debug`](../core/fmt/trait.Debug.html) -- [`Default`](../core/default/trait.Default.html) -- [`Eq`](../core/cmp/trait.Eq.html) -- [`Hash`](../core/hash/trait.Hash.html) -- [`Ord`](../core/cmp/trait.Ord.html) -- [`PartialEq`](../core/cmp/trait.PartialEq.html) -- [`PartialOrd`](../core/cmp/trait.PartialOrd.html) diff --git a/src/transmute.md b/src/transmute.md deleted file mode 100644 index 93ed7dd0f..000000000 --- a/src/transmute.md +++ /dev/null @@ -1 +0,0 @@ -# transmute diff --git a/src/tutorial.md b/src/tutorial.md deleted file mode 100644 index 4f50eccc5..000000000 --- a/src/tutorial.md +++ /dev/null @@ -1 +0,0 @@ -# Tutorial diff --git a/src/ufcs.md b/src/ufcs.md deleted file mode 100644 index 016ecc709..000000000 --- a/src/ufcs.md +++ /dev/null @@ -1,136 +0,0 @@ -# Universal Function Call Syntax - -Sometimes, functions can have the same names. Consider this code: - -```rust -trait Foo { - fn f(&self); -} - -trait Bar { - fn f(&self); -} - -struct Baz; - -impl Foo for Baz { - fn f(&self) { println!("Baz’s impl of Foo"); } -} - -impl Bar for Baz { - fn f(&self) { println!("Baz’s impl of Bar"); } -} - -let b = Baz; -``` - -If we were to try to call `b.f()`, we’d get an error: - -```text -error: multiple applicable methods in scope [E0034] -b.f(); - ^~~ -note: candidate #1 is defined in an impl of the trait `main::Foo` for the type -`main::Baz` - fn f(&self) { println!("Baz’s impl of Foo"); } - ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -note: candidate #2 is defined in an impl of the trait `main::Bar` for the type -`main::Baz` - fn f(&self) { println!("Baz’s impl of Bar"); } - ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -``` - -We need a way to disambiguate which method we need. This feature is called -‘universal function call syntax’, and it looks like this: - -```rust -# trait Foo { -# fn f(&self); -# } -# trait Bar { -# fn f(&self); -# } -# struct Baz; -# impl Foo for Baz { -# fn f(&self) { println!("Baz’s impl of Foo"); } -# } -# impl Bar for Baz { -# fn f(&self) { println!("Baz’s impl of Bar"); } -# } -# let b = Baz; -Foo::f(&b); -Bar::f(&b); -``` - -Let’s break it down. - -```rust,ignore -Foo:: -Bar:: -``` - -These halves of the invocation are the types of the two traits: `Foo` and -`Bar`. This is what ends up actually doing the disambiguation between the two: -Rust calls the one from the trait name you use. - -```rust,ignore -f(&b) -``` - -When we call a method like `b.f()` using [method syntax][methodsyntax], Rust -will automatically borrow `b` if `f()` takes `&self`. In this case, Rust will -not, and so we need to pass an explicit `&b`. - -[methodsyntax]: method-syntax.html - -# Angle-bracket Form - -The form of UFCS we just talked about: - -```rust,ignore -Trait::method(args); -``` - -Is a short-hand. There’s an expanded form of this that’s needed in some -situations: - -```rust,ignore -::method(args); -``` - -The `<>::` syntax is a means of providing a type hint. The type goes inside -the `<>`s. In this case, the type is `Type as Trait`, indicating that we want -`Trait`’s version of `method` to be called here. The `as Trait` part is -optional if it’s not ambiguous. Same with the angle brackets, hence the -shorter form. - -Here’s an example of using the longer form. - -```rust -trait Foo { - fn foo() -> i32; -} - -struct Bar; - -impl Bar { - fn foo() -> i32 { - 20 - } -} - -impl Foo for Bar { - fn foo() -> i32 { - 10 - } -} - -fn main() { - assert_eq!(10, ::foo()); - assert_eq!(20, Bar::foo()); -} -``` - -Using the angle bracket syntax lets you call the trait method instead of the -inherent one. diff --git a/src/unsafe-rust.md b/src/unsafe-rust.md deleted file mode 100644 index 7d269eb83..000000000 --- a/src/unsafe-rust.md +++ /dev/null @@ -1,142 +0,0 @@ -# Unsafe - -Rust’s main draw is its powerful static guarantees about behavior. But safety -checks are conservative by nature: there are some programs that are actually -safe, but the compiler is not able to verify this is true. To write these kinds -of programs, we need to tell the compiler to relax its restrictions a bit. For -this, Rust has a keyword, `unsafe`. Code using `unsafe` has less restrictions -than normal code does. - -Let’s go over the syntax, and then we’ll talk semantics. `unsafe` is used in -four contexts. The first one is to mark a function as unsafe: - -```rust -unsafe fn danger_will_robinson() { - // scary stuff -} -``` - -All functions called from [FFI][ffi] must be marked as `unsafe`, for example. -The second use of `unsafe` is an unsafe block: - -[ffi]: ffi.html - -```rust -unsafe { - // scary stuff -} -``` - -The third is for unsafe traits: - -```rust -unsafe trait Scary { } -``` - -And the fourth is for `impl`ementing one of those traits: - -```rust -# unsafe trait Scary { } -unsafe impl Scary for i32 {} -``` - -It’s important to be able to explicitly delineate code that may have bugs that -cause big problems. If a Rust program segfaults, you can be sure it’s somewhere -in the sections marked `unsafe`. - -# What does ‘safe’ mean? - -Safe, in the context of Rust, means ‘doesn’t do anything unsafe’. It’s also -important to know that there are certain behaviors that are probably not -desirable in your code, but are expressly _not_ unsafe: - -* Deadlocks -* Leaks of memory or other resources -* Exiting without calling destructors -* Integer overflow - -Rust cannot prevent all kinds of software problems. Buggy code can and will be -written in Rust. These things aren’t great, but they don’t qualify as `unsafe` -specifically. - -In addition, the following are all undefined behaviors in Rust, and must be -avoided, even when writing `unsafe` code: - -* Data races -* Dereferencing a null/dangling raw pointer -* Reads of [undef][undef] (uninitialized) memory -* Breaking the [pointer aliasing rules][aliasing] with raw pointers. -* `&mut T` and `&T` follow LLVM’s scoped [noalias][noalias] model, except if - the `&T` contains an `UnsafeCell`. Unsafe code must not violate these - aliasing guarantees. -* Mutating an immutable value/reference without `UnsafeCell` -* Invoking undefined behavior via compiler intrinsics: - * Indexing outside of the bounds of an object with `std::ptr::offset` - (`offset` intrinsic), with - the exception of one byte past the end which is permitted. - * Using `std::ptr::copy_nonoverlapping_memory` (`memcpy32`/`memcpy64` - intrinsics) on overlapping buffers -* Invalid values in primitive types, even in private fields/locals: - * Null/dangling references or boxes - * A value other than `false` (0) or `true` (1) in a `bool` - * A discriminant in an `enum` not included in its type definition - * A value in a `char` which is a surrogate or above `char::MAX` - * Non-UTF-8 byte sequences in a `str` -* Unwinding into Rust from foreign code or unwinding from Rust into foreign - code. - -[noalias]: http://llvm.org/docs/LangRef.html#noalias -[undef]: http://llvm.org/docs/LangRef.html#undefined-values -[aliasing]: http://llvm.org/docs/LangRef.html#pointer-aliasing-rules - -# Unsafe Superpowers - -In both unsafe functions and unsafe blocks, Rust will let you do three things -that you normally can not do. Just three. Here they are: - -1. Access or update a [static mutable variable][static]. -2. Dereference a raw pointer. -3. Call unsafe functions. This is the most powerful ability. - -That’s it. It’s important that `unsafe` does not, for example, ‘turn off the -borrow checker’. Adding `unsafe` to some random Rust code doesn’t change its -semantics, it won’t just start accepting anything. But it will let you write -things that _do_ break some of the rules. - -You will also encounter the `unsafe` keyword when writing bindings to foreign -(non-Rust) interfaces. You're encouraged to write a safe, native Rust interface -around the methods provided by the library. - -Let’s go over the basic three abilities listed, in order. - -## Access or update a `static mut` - -Rust has a feature called ‘`static mut`’ which allows for mutable global state. -Doing so can cause a data race, and as such is inherently not safe. For more -details, see the [static][static] section of the book. - -[static]: const-and-static.html#static - -## Dereference a raw pointer - -Raw pointers let you do arbitrary pointer arithmetic, and can cause a number of -different memory safety and security issues. In some senses, the ability to -dereference an arbitrary pointer is one of the most dangerous things you can -do. For more on raw pointers, see [their section of the book][rawpointers]. - -[rawpointers]: raw-pointers.html - -## Call unsafe functions - -This last ability works with both aspects of `unsafe`: you can only call -functions marked `unsafe` from inside an unsafe block. - -This ability is powerful and varied. Rust exposes some [compiler -intrinsics][intrinsics] as unsafe functions, and some unsafe functions bypass -safety checks, trading safety for speed. - -I’ll repeat again: even though you _can_ do arbitrary things in unsafe blocks -and functions doesn’t mean you should. The compiler will act as though you’re -upholding its invariants, so be careful! - -[intrinsics]: intrinsics.html diff --git a/src/using-rust-from-other-languages.md b/src/using-rust-from-other-languages.md deleted file mode 100644 index 126835a44..000000000 --- a/src/using-rust-from-other-languages.md +++ /dev/null @@ -1,344 +0,0 @@ -# Using Rust From Other Languages - -For our third project, we’re going to choose something that shows off one of -Rust’s greatest strengths: a lack of a substantial runtime. - -As organizations grow, they increasingly rely on a multitude of programming -languages. Different programming languages have different strengths and -weaknesses, and a polyglot stack lets you use a particular language where -its strengths make sense and a different one where it’s weak. - -A very common area where many programming languages are weak is in runtime -performance of programs. Often, using a language that is slower, but offers -greater programmer productivity, is a worthwhile trade-off. To help mitigate -this, they provide a way to write some of your system in C and then call -that C code as though it were written in the higher-level language. This is -called a ‘foreign function interface’, often shortened to ‘FFI’. - -Rust has support for FFI in both directions: it can call into C code easily, -but crucially, it can also be called _into_ as easily as C. Combined with -Rust’s lack of a garbage collector and low runtime requirements, this makes -Rust a great candidate to embed inside of other languages when you need -that extra oomph. - -There is a whole [chapter devoted to FFI][ffi] and its specifics elsewhere in -the book, but in this chapter, we’ll examine this particular use-case of FFI, -with examples in Ruby, Python, and JavaScript. - -[ffi]: ffi.html - -# The problem - -There are many different projects we could choose here, but we’re going to -pick an example where Rust has a clear advantage over many other languages: -numeric computing and threading. - -Many languages, for the sake of consistency, place numbers on the heap, rather -than on the stack. Especially in languages that focus on object-oriented -programming and use garbage collection, heap allocation is the default. Sometimes -optimizations can stack allocate particular numbers, but rather than relying -on an optimizer to do its job, we may want to ensure that we’re always using -primitive number types rather than some sort of object type. - -Second, many languages have a ‘global interpreter lock’ (GIL), which limits -concurrency in many situations. This is done in the name of safety, which is -a positive effect, but it limits the amount of work that can be done at the -same time, which is a big negative. - -To emphasize these two aspects, we’re going to create a little project that -uses these two aspects heavily. Since the focus of the example is to embed -Rust into other languages, rather than the problem itself, we’ll just use a -toy example: - -> Start ten threads. Inside each thread, count from one to five million. After -> all ten threads are finished, print out ‘done!’. - -I chose five million based on my particular computer. Here’s an example of this -code in Ruby: - -```ruby -threads = [] - -10.times do - threads << Thread.new do - count = 0 - - 5_000_000.times do - count += 1 - end - - count - end -end - -threads.each do |t| - puts "Thread finished with count=#{t.value}" -end -puts "done!" -``` - -Try running this example, and choose a number that runs for a few seconds. -Depending on your computer’s hardware, you may have to increase or decrease the -number. - -On my system, running this program takes `2.156` seconds. And, if I use some -sort of process monitoring tool, like `top`, I can see that it only uses one -core on my machine. That’s the GIL kicking in. - -While it’s true that this is a synthetic program, one can imagine many problems -that are similar to this in the real world. For our purposes, spinning up a few -busy threads represents some sort of parallel, expensive computation. - -# A Rust library - -Let’s rewrite this problem in Rust. First, let’s make a new project with -Cargo: - -```bash -$ cargo new embed -$ cd embed -``` - -This program is fairly easy to write in Rust: - -```rust -use std::thread; - -fn process() { - let handles: Vec<_> = (0..10).map(|_| { - thread::spawn(|| { - let mut x = 0; - for _ in 0..5_000_000 { - x += 1 - } - x - }) - }).collect(); - - for h in handles { - println!("Thread finished with count={}", - h.join().map_err(|_| "Could not join a thread!").unwrap()); - } -} -``` - -Some of this should look familiar from previous examples. We spin up ten -threads, collecting them into a `handles` vector. Inside of each thread, we -loop five million times, and add one to `x` each time. Finally, we join on -each thread. - -Right now, however, this is a Rust library, and it doesn’t expose anything -that’s callable from C. If we tried to hook this up to another language right -now, it wouldn’t work. We only need to make two small changes to fix this, -though. The first is to modify the beginning of our code: - -```rust,ignore -#[no_mangle] -pub extern fn process() { -``` - -We have to add a new attribute, `no_mangle`. When you create a Rust library, it -changes the name of the function in the compiled output. The reasons for this -are outside the scope of this tutorial, but in order for other languages to -know how to call the function, we can’t do that. This attribute turns -that behavior off. - -The other change is the `pub extern`. The `pub` means that this function should -be callable from outside of this module, and the `extern` says that it should -be able to be called from C. That’s it! Not a whole lot of change. - -The second thing we need to do is to change a setting in our `Cargo.toml`. Add -this at the bottom: - -```toml -[lib] -name = "embed" -crate-type = ["dylib"] -``` - -This tells Rust that we want to compile our library into a standard dynamic -library. By default, Rust compiles an ‘rlib’, a Rust-specific format. - -Let’s build the project now: - -```bash -$ cargo build --release - Compiling embed v0.1.0 (file:///projects/embed) -``` - -We’ve chosen `cargo build --release`, which builds with optimizations on. We -want this to be as fast as possible! You can find the output of the library in -`target/release`: - -```bash -$ ls target/release/ -build deps examples libembed.so native -``` - -That `libembed.so` is our ‘shared object’ library. We can use this file -just like any shared object library written in C! As an aside, this may be -`embed.dll` (Microsoft Windows) or `libembed.dylib` (Mac OS X), depending on -your operating system. - -Now that we’ve got our Rust library built, let’s use it from our Ruby. - -# Ruby - -Open up an `embed.rb` file inside of our project, and do this: - -```ruby -require 'ffi' - -module Hello - extend FFI::Library - ffi_lib 'target/release/libembed.so' - attach_function :process, [], :void -end - -Hello.process - -puts 'done!' -``` - -Before we can run this, we need to install the `ffi` gem: - -```bash -$ gem install ffi # this may need sudo -Fetching: ffi-1.9.8.gem (100%) -Building native extensions. This could take a while... -Successfully installed ffi-1.9.8 -Parsing documentation for ffi-1.9.8 -Installing ri documentation for ffi-1.9.8 -Done installing documentation for ffi after 0 seconds -1 gem installed -``` - -And finally, we can try running it: - -```bash -$ ruby embed.rb -Thread finished with count=5000000 -Thread finished with count=5000000 -Thread finished with count=5000000 -Thread finished with count=5000000 -Thread finished with count=5000000 -Thread finished with count=5000000 -Thread finished with count=5000000 -Thread finished with count=5000000 -Thread finished with count=5000000 -Thread finished with count=5000000 -done! -done! -$ -``` - -Whoa, that was fast! On my system, this took `0.086` seconds, rather than -the two seconds the pure Ruby version took. Let’s break down this Ruby -code: - -```ruby -require 'ffi' -``` - -We first need to require the `ffi` gem. This lets us interface with our -Rust library like a C library. - -```ruby -module Hello - extend FFI::Library - ffi_lib 'target/release/libembed.so' -``` - -The `Hello` module is used to attach the native functions from the shared -library. Inside, we `extend` the necessary `FFI::Library` module and then call -`ffi_lib` to load up our shared object library. We just pass it the path that -our library is stored, which, as we saw before, is -`target/release/libembed.so`. - -```ruby -attach_function :process, [], :void -``` - -The `attach_function` method is provided by the FFI gem. It’s what -connects our `process()` function in Rust to a Ruby function of the -same name. Since `process()` takes no arguments, the second parameter -is an empty array, and since it returns nothing, we pass `:void` as -the final argument. - -```ruby -Hello.process -``` - -This is the actual call into Rust. The combination of our `module` -and the call to `attach_function` sets this all up. It looks like -a Ruby function but is actually Rust! - -```ruby -puts 'done!' -``` - -Finally, as per our project’s requirements, we print out `done!`. - -That’s it! As we’ve seen, bridging between the two languages is really easy, -and buys us a lot of performance. - -Next, let’s try Python! - -# Python - -Create an `embed.py` file in this directory, and put this in it: - -```python -from ctypes import cdll - -lib = cdll.LoadLibrary("target/release/libembed.so") - -lib.process() - -print("done!") -``` - -Even easier! We use `cdll` from the `ctypes` module. A quick call -to `LoadLibrary` later, and we can call `process()`. - -On my system, this takes `0.017` seconds. Speedy! - -# Node.js - -Node isn’t a language, but it’s currently the dominant implementation of -server-side JavaScript. - -In order to do FFI with Node, we first need to install the library: - -```bash -$ npm install ffi -``` - -After that installs, we can use it: - -```javascript -var ffi = require('ffi'); - -var lib = ffi.Library('target/release/libembed', { - 'process': ['void', []] -}); - -lib.process(); - -console.log("done!"); -``` - -It looks more like the Ruby example than the Python example. We use -the `ffi` module to get access to `ffi.Library()`, which loads up -our shared object. We need to annotate the return type and argument -types of the function, which are `void` for return and an empty -array to signify no arguments. From there, we just call it and -print the result. - -On my system, this takes a quick `0.092` seconds. - -# Conclusion - -As you can see, the basics of doing this are _very_ easy. Of course, -there's a lot more that we could do here. Check out the [FFI][ffi] -chapter for more details. diff --git a/src/vectors.md b/src/vectors.md deleted file mode 100644 index 99cb3be87..000000000 --- a/src/vectors.md +++ /dev/null @@ -1,89 +0,0 @@ -# Vectors - -A ‘vector’ is a dynamic or ‘growable’ array, implemented as the standard -library type [`Vec`][vec]. The `T` means that we can have vectors -of any type (see the chapter on [generics][generic] for more). -Vectors always allocate their data on the heap. -You can create them with the `vec!` macro: - -```rust -let v = vec![1, 2, 3, 4, 5]; // v: Vec -``` - -(Notice that unlike the `println!` macro we’ve used in the past, we use square -brackets `[]` with `vec!` macro. Rust allows you to use either in either situation, -this is just convention.) - -There’s an alternate form of `vec!` for repeating an initial value: - -```rust -let v = vec![0; 10]; // ten zeroes -``` - -## Accessing elements - -To get the value at a particular index in the vector, we use `[]`s: - -```rust -let v = vec![1, 2, 3, 4, 5]; - -println!("The third element of v is {}", v[2]); -``` - -The indices count from `0`, so the third element is `v[2]`. - -It’s also important to note that you must index with the `usize` type: - -```ignore -let v = vec![1, 2, 3, 4, 5]; - -let i: usize = 0; -let j: i32 = 0; - -// works -v[i]; - -// doesn’t -v[j]; -``` - -Indexing with a non-`usize` type gives an error that looks like this: - -```text -error: the trait `core::ops::Index` is not implemented for the type -`collections::vec::Vec<_>` [E0277] -v[j]; -^~~~ -note: the type `collections::vec::Vec<_>` cannot be indexed by `i32` -error: aborting due to previous error -``` - -There’s a lot of punctuation in that message, but the core of it makes sense: -you cannot index with an `i32`. - -## Iterating - -Once you have a vector, you can iterate through its elements with `for`. There -are three versions: - -```rust -let mut v = vec![1, 2, 3, 4, 5]; - -for i in &v { - println!("A reference to {}", i); -} - -for i in &mut v { - println!("A mutable reference to {}", i); -} - -for i in v { - println!("Take ownership of the vector and its element {}", i); -} -``` - -Vectors have many more useful methods, which you can read about in [their -API documentation][vec]. - -[vec]: ../std/vec/index.html -[generic]: generics.html