diff --git a/src/SUMMARY.md b/src/SUMMARY.md index a344ff86e..14b38fd6e 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -24,7 +24,7 @@ - [Structs](structs.md) - [Enums](enums.md) -- [Crates & Modules](crates-and-modules) +- [Crates & Modules](crates-and-modules.md) - [Error Handling](error-handling.md) diff --git a/src/associated-types.md b/src/associated-types.md index 64f7abf57..fe4f27b9d 100644 --- a/src/associated-types.md +++ b/src/associated-types.md @@ -1 +1,202 @@ -# Associated Types +% 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/closures.md b/src/closures.md index 713d5db4d..7d4452a4c 100644 --- a/src/closures.md +++ b/src/closures.md @@ -1 +1,506 @@ -# Closures +% 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/conditional-compilation.md b/src/conditional-compilation.md index fed903ad1..a6ff75db8 100644 --- a/src/conditional-compilation.md +++ b/src/conditional-compilation.md @@ -1 +1,93 @@ -# Conditional Compilation +% 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/crates-and-modules b/src/crates-and-modules deleted file mode 100644 index ecbd4f971..000000000 --- a/src/crates-and-modules +++ /dev/null @@ -1 +0,0 @@ -# Crates & Modules diff --git a/src/crates-and-modules.md b/src/crates-and-modules.md new file mode 100644 index 000000000..4a4648c7b --- /dev/null +++ b/src/crates-and-modules.md @@ -0,0 +1,588 @@ +% 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/enums.md b/src/enums.md index ece8d08a7..e17d3f762 100644 --- a/src/enums.md +++ b/src/enums.md @@ -1 +1,108 @@ -# Enums +% 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/functions.md b/src/functions.md index 0c5faf50f..84cea5dab 100644 --- a/src/functions.md +++ b/src/functions.md @@ -1 +1,310 @@ -# Functions +% Functions + +Every Rust program has at least one function, the `main` function: + +```rust +fn main() { +} +``` + +This is the simplest possible function declaration. As we mentioned before, +`fn` says ‘this is a function’, followed by the name, some parentheses because +this function takes no arguments, and then some curly braces to indicate the +body. Here’s a function named `foo`: + +```rust +fn foo() { +} +``` + +So, what about taking arguments? Here’s a function that prints a number: + +```rust +fn print_number(x: i32) { + println!("x is: {}", x); +} +``` + +Here’s a complete program that uses `print_number`: + +```rust +fn main() { + print_number(5); +} + +fn print_number(x: i32) { + println!("x is: {}", x); +} +``` + +As you can see, function arguments work very similar to `let` declarations: +you add a type to the argument name, after a colon. + +Here’s a complete program that adds two numbers together and prints them: + +```rust +fn main() { + print_sum(5, 6); +} + +fn print_sum(x: i32, y: i32) { + println!("sum is: {}", x + y); +} +``` + +You separate arguments with a comma, both when you call the function, as well +as when you declare it. + +Unlike `let`, you _must_ declare the types of function arguments. This does +not work: + +```rust,ignore +fn print_sum(x, y) { + println!("sum is: {}", x + y); +} +``` + +You get this error: + +```text +expected one of `!`, `:`, or `@`, found `)` +fn print_number(x, y) { +``` + +This is a deliberate design decision. While full-program inference is possible, +languages which have it, like Haskell, often suggest that documenting your +types explicitly is a best-practice. We agree that forcing functions to declare +types while allowing for inference inside of function bodies is a wonderful +sweet spot between full inference and no inference. + +What about returning a value? Here’s a function that adds one to an integer: + +```rust +fn add_one(x: i32) -> i32 { + x + 1 +} +``` + +Rust functions return exactly one value, and you declare the type after an +‘arrow’, which is a dash (`-`) followed by a greater-than sign (`>`). The last +line of a function determines what it returns. You’ll note the lack of a +semicolon here. If we added it in: + +```rust,ignore +fn add_one(x: i32) -> i32 { + x + 1; +} +``` + +We would get an error: + +```text +error: not all control paths return a value +fn add_one(x: i32) -> i32 { + x + 1; +} + +help: consider removing this semicolon: + x + 1; + ^ +``` + +This reveals two interesting things about Rust: it is an expression-based +language, and semicolons are different from semicolons in other ‘curly brace +and semicolon’-based languages. These two things are related. + +## Expressions vs. Statements + +Rust is primarily an expression-based language. There are only two kinds of +statements, and everything else is an expression. + +So what's the difference? Expressions return a value, and statements do not. +That’s why we end up with ‘not all control paths return a value’ here: the +statement `x + 1;` doesn’t return a value. There are two kinds of statements in +Rust: ‘declaration statements’ and ‘expression statements’. Everything else is +an expression. Let’s talk about declaration statements first. + +In some languages, variable bindings can be written as expressions, not just +statements. Like Ruby: + +```ruby +x = y = 5 +``` + +In Rust, however, using `let` to introduce a binding is _not_ an expression. The +following will produce a compile-time error: + +```ignore +let x = (let y = 5); // expected identifier, found keyword `let` +``` + +The compiler is telling us here that it was expecting to see the beginning of +an expression, and a `let` can only begin a statement, not an expression. + +Note that assigning to an already-bound variable (e.g. `y = 5`) is still an +expression, although its value is not particularly useful. Unlike other +languages where an assignment evaluates to the assigned value (e.g. `5` in the +previous example), in Rust the value of an assignment is an empty tuple `()` +because the assigned value can have [just one owner](ownership.html), and any +other returned value would be too surprising: + +```rust +let mut y = 5; + +let x = (y = 6); // x has the value `()`, not `6` +``` + +The second kind of statement in Rust is the *expression statement*. Its +purpose is to turn any expression into a statement. In practical terms, Rust's +grammar expects statements to follow other statements. This means that you use +semicolons to separate expressions from each other. This means that Rust +looks a lot like most other languages that require you to use semicolons +at the end of every line, and you will see semicolons at the end of almost +every line of Rust code you see. + +What is this exception that makes us say "almost"? You saw it already, in this +code: + +```rust +fn add_one(x: i32) -> i32 { + x + 1 +} +``` + +Our function claims to return an `i32`, but with a semicolon, it would return +`()` instead. Rust realizes this probably isn’t what we want, and suggests +removing the semicolon in the error we saw before. + +## Early returns + +But what about early returns? Rust does have a keyword for that, `return`: + +```rust +fn foo(x: i32) -> i32 { + return x; + + // we never run this code! + x + 1 +} +``` + +Using a `return` as the last line of a function works, but is considered poor +style: + +```rust +fn foo(x: i32) -> i32 { + return x + 1; +} +``` + +The previous definition without `return` may look a bit strange if you haven’t +worked in an expression-based language before, but it becomes intuitive over +time. + +## Diverging functions + +Rust has some special syntax for ‘diverging functions’, which are functions that +do not return: + +```rust +fn diverges() -> ! { + panic!("This function never returns!"); +} +``` + +`panic!` is a macro, similar to `println!()` that we’ve already seen. Unlike +`println!()`, `panic!()` causes the current thread of execution to crash with +the given message. Because this function will cause a crash, it will never +return, and so it has the type ‘`!`’, which is read ‘diverges’. + +If you add a main function that calls `diverges()` and run it, you’ll get +some output that looks like this: + +```text +thread ‘
’ panicked at ‘This function never returns!’, hello.rs:2 +``` + +If you want more information, you can get a backtrace by setting the +`RUST_BACKTRACE` environment variable: + +```text +$ RUST_BACKTRACE=1 ./diverges +thread '
' panicked at 'This function never returns!', hello.rs:2 +stack backtrace: + 1: 0x7f402773a829 - sys::backtrace::write::h0942de78b6c02817K8r + 2: 0x7f402773d7fc - panicking::on_panic::h3f23f9d0b5f4c91bu9w + 3: 0x7f402773960e - rt::unwind::begin_unwind_inner::h2844b8c5e81e79558Bw + 4: 0x7f4027738893 - rt::unwind::begin_unwind::h4375279447423903650 + 5: 0x7f4027738809 - diverges::h2266b4c4b850236beaa + 6: 0x7f40277389e5 - main::h19bb1149c2f00ecfBaa + 7: 0x7f402773f514 - rt::unwind::try::try_fn::h13186883479104382231 + 8: 0x7f402773d1d8 - __rust_try + 9: 0x7f402773f201 - rt::lang_start::ha172a3ce74bb453aK5w + 10: 0x7f4027738a19 - main + 11: 0x7f402694ab44 - __libc_start_main + 12: 0x7f40277386c8 - + 13: 0x0 - +``` + +`RUST_BACKTRACE` also works with Cargo’s `run` command: + +```text +$ RUST_BACKTRACE=1 cargo run + Running `target/debug/diverges` +thread '
' panicked at 'This function never returns!', hello.rs:2 +stack backtrace: + 1: 0x7f402773a829 - sys::backtrace::write::h0942de78b6c02817K8r + 2: 0x7f402773d7fc - panicking::on_panic::h3f23f9d0b5f4c91bu9w + 3: 0x7f402773960e - rt::unwind::begin_unwind_inner::h2844b8c5e81e79558Bw + 4: 0x7f4027738893 - rt::unwind::begin_unwind::h4375279447423903650 + 5: 0x7f4027738809 - diverges::h2266b4c4b850236beaa + 6: 0x7f40277389e5 - main::h19bb1149c2f00ecfBaa + 7: 0x7f402773f514 - rt::unwind::try::try_fn::h13186883479104382231 + 8: 0x7f402773d1d8 - __rust_try + 9: 0x7f402773f201 - rt::lang_start::ha172a3ce74bb453aK5w + 10: 0x7f4027738a19 - main + 11: 0x7f402694ab44 - __libc_start_main + 12: 0x7f40277386c8 - + 13: 0x0 - +``` + +A diverging function can be used as any type: + +```should_panic +# fn diverges() -> ! { +# panic!("This function never returns!"); +# } +let x: i32 = diverges(); +let x: String = diverges(); +``` + +## Function pointers + +We can also create variable bindings which point to functions: + +```rust +let f: fn(i32) -> i32; +``` + +`f` is a variable binding which points to a function that takes an `i32` as +an argument and returns an `i32`. For example: + +```rust +fn plus_one(i: i32) -> i32 { + i + 1 +} + +// without type inference +let f: fn(i32) -> i32 = plus_one; + +// with type inference +let f = plus_one; +``` + +We can then use `f` to call the function: + +```rust +# fn plus_one(i: i32) -> i32 { i + 1 } +# let f = plus_one; +let six = f(5); +``` diff --git a/src/if.md b/src/if.md index b146d7dd9..a532dabf8 100644 --- a/src/if.md +++ b/src/if.md @@ -1 +1,73 @@ -# `if` +% if + +Rust’s take on `if` is not particularly complex, but it’s much more like the +`if` you’ll find in a dynamically typed language than in a more traditional +systems language. So let’s talk about it, to make sure you grasp the nuances. + +`if` is a specific form of a more general concept, the ‘branch’. The name comes +from a branch in a tree: a decision point, where depending on a choice, +multiple paths can be taken. + +In the case of `if`, there is one choice that leads down two paths: + +```rust +let x = 5; + +if x == 5 { + println!("x is five!"); +} +``` + +If we changed the value of `x` to something else, this line would not print. +More specifically, if the expression after the `if` evaluates to `true`, then +the block is executed. If it’s `false`, then it is not. + +If you want something to happen in the `false` case, use an `else`: + +```rust +let x = 5; + +if x == 5 { + println!("x is five!"); +} else { + println!("x is not five :("); +} +``` + +If there is more than one case, use an `else if`: + +```rust +let x = 5; + +if x == 5 { + println!("x is five!"); +} else if x == 6 { + println!("x is six!"); +} else { + println!("x is not five or six :("); +} +``` + +This is all pretty standard. However, you can also do this: + +```rust +let x = 5; + +let y = if x == 5 { + 10 +} else { + 15 +}; // y: i32 +``` + +Which we can (and probably should) write like this: + +```rust +let x = 5; + +let y = if x == 5 { 10 } else { 15 }; // y: i32 +``` + +This works because `if` is an expression. The value of the expression is the +value of the last expression in whichever branch was chosen. An `if` without an +`else` always results in `()` as the value. diff --git a/src/iterators.md b/src/iterators.md index 7f511b986..c444f9f2f 100644 --- a/src/iterators.md +++ b/src/iterators.md @@ -1 +1,337 @@ -# Iterators +% 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 index 130cd9f70..68bbd0c98 100644 --- a/src/lifetimes.md +++ b/src/lifetimes.md @@ -1 +1,361 @@ +% 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/loops.md b/src/loops.md index 4b787b4bf..68bb49d2c 100644 --- a/src/loops.md +++ b/src/loops.md @@ -1 +1,211 @@ -# Loops +% Loops + +Rust currently provides three approaches to performing some kind of iterative activity. They are: `loop`, `while` and `for`. Each approach has its own set of uses. + +## loop + +The infinite `loop` is the simplest form of loop available in Rust. Using the keyword `loop`, Rust provides a way to loop indefinitely until some terminating statement is reached. Rust's infinite `loop`s look like this: + +```rust,ignore +loop { + println!("Loop forever!"); +} +``` + +## while + +Rust also has a `while` loop. It looks like this: + +```rust +let mut x = 5; // mut x: i32 +let mut done = false; // mut done: bool + +while !done { + x += x - 3; + + println!("{}", x); + + if x % 5 == 0 { + done = true; + } +} +``` + +`while` loops are the correct choice when you’re not sure how many times +you need to loop. + +If you need an infinite loop, you may be tempted to write this: + +```rust,ignore +while true { +``` + +However, `loop` is far better suited to handle this case: + +```rust,ignore +loop { +``` + +Rust’s control-flow analysis treats this construct differently than a `while +true`, since we know that it will always loop. In general, the more information +we can give to the compiler, the better it can do with safety and code +generation, so you should always prefer `loop` when you plan to loop +infinitely. + +## for + +The `for` loop is used to loop a particular number of times. Rust’s `for` loops +work a bit differently than in other systems languages, however. Rust’s `for` +loop doesn’t look like this “C-style” `for` loop: + +```c +for (x = 0; x < 10; x++) { + printf( "%d\n", x ); +} +``` + +Instead, it looks like this: + +```rust +for x in 0..10 { + println!("{}", x); // x: i32 +} +``` + +In slightly more abstract terms, + +```ignore +for var in expression { + code +} +``` + +The expression is an item that can be converted into an [iterator] using +[`IntoIterator`]. The iterator gives back a series of elements. Each element is +one iteration of the loop. That value is then bound to the name `var`, which is +valid for the loop body. Once the body is over, the next value is fetched from +the iterator, and we loop another time. When there are no more values, the `for` +loop is over. + +[iterator]: iterators.html +[`IntoIterator`]: ../std/iter/trait.IntoIterator.html + +In our example, `0..10` is an expression that takes a start and an end position, +and gives an iterator over those values. The upper bound is exclusive, though, +so our loop will print `0` through `9`, not `10`. + +Rust does not have the “C-style” `for` loop on purpose. Manually controlling +each element of the loop is complicated and error prone, even for experienced C +developers. + +### Enumerate + +When you need to keep track of how many times you already looped, you can use the `.enumerate()` function. + +#### On ranges: + +```rust +for (i,j) in (5..10).enumerate() { + println!("i = {} and j = {}", i, j); +} +``` + +Outputs: + +```text +i = 0 and j = 5 +i = 1 and j = 6 +i = 2 and j = 7 +i = 3 and j = 8 +i = 4 and j = 9 +``` + +Don't forget to add the parentheses around the range. + +#### On iterators: + +```rust +# let lines = "hello\nworld".lines(); +for (linenumber, line) in lines.enumerate() { + println!("{}: {}", linenumber, line); +} +``` + +Outputs: + +```text +0: Content of line one +1: Content of line two +2: Content of line three +3: Content of line four +``` + +## Ending iteration early + +Let’s take a look at that `while` loop we had earlier: + +```rust +let mut x = 5; +let mut done = false; + +while !done { + x += x - 3; + + println!("{}", x); + + if x % 5 == 0 { + done = true; + } +} +``` + +We had to keep a dedicated `mut` boolean variable binding, `done`, to know +when we should exit out of the loop. Rust has two keywords to help us with +modifying iteration: `break` and `continue`. + +In this case, we can write the loop in a better way with `break`: + +```rust +let mut x = 5; + +loop { + x += x - 3; + + println!("{}", x); + + if x % 5 == 0 { break; } +} +``` + +We now loop forever with `loop` and use `break` to break out early. Issuing an explicit `return` statement will also serve to terminate the loop early. + +`continue` is similar, but instead of ending the loop, goes to the next +iteration. This will only print the odd numbers: + +```rust +for x in 0..10 { + if x % 2 == 0 { continue; } + + println!("{}", x); +} +``` + +## Loop labels + +You may also encounter situations where you have nested loops and need to +specify which one your `break` or `continue` statement is for. Like most +other languages, by default a `break` or `continue` will apply to innermost +loop. In a situation where you would like to a `break` or `continue` for one +of the outer loops, you can use labels to specify which loop the `break` or + `continue` statement applies to. This will only print when both `x` and `y` are + odd: + +```rust +'outer: for x in 0..10 { + 'inner: for y in 0..10 { + if x % 2 == 0 { continue 'outer; } // continues the loop over x + if y % 2 == 0 { continue 'inner; } // continues the loop over y + println!("x: {}, y: {}", x, y); + } +} +``` diff --git a/src/macros.md b/src/macros.md index 19921943e..f7f27858c 100644 --- a/src/macros.md +++ b/src/macros.md @@ -1 +1,773 @@ -# Macros +% 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/ownership.md b/src/ownership.md index 77f5a52fa..17b263ef0 100644 --- a/src/ownership.md +++ b/src/ownership.md @@ -1 +1,238 @@ +% Ownership + +This guide is one 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, which you’re reading now +* [borrowing][borrowing], and their associated feature ‘references’ +* [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. + +[borrowing]: references-and-borrowing.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 ownership. + # Ownership + +[Variable bindings][bindings] have a property in Rust: they ‘have ownership’ +of what they’re bound to. This means that when a binding goes out of scope, +Rust will free the bound resources. For example: + +```rust +fn foo() { + let v = vec![1, 2, 3]; +} +``` + +When `v` comes into scope, a new [`Vec`][vect] is created. In this case, the +vector also allocates space on [the heap][heap], for the three elements. When +`v` goes out of scope at the end of `foo()`, Rust will clean up everything +related to the vector, even the heap-allocated memory. This happens +deterministically, at the end of the scope. + +[vect]: ../std/vec/struct.Vec.html +[heap]: the-stack-and-the-heap.html +[bindings]: variable-bindings.html + +# Move semantics + +There’s some more subtlety here, though: Rust ensures that there is _exactly +one_ binding to any given resource. For example, if we have a vector, we can +assign it to another binding: + +```rust +let v = vec![1, 2, 3]; + +let v2 = v; +``` + +But, if we try to use `v` afterwards, we get an error: + +```rust,ignore +let v = vec![1, 2, 3]; + +let v2 = v; + +println!("v[0] is: {}", v[0]); +``` + +It looks like this: + +```text +error: use of moved value: `v` +println!("v[0] is: {}", v[0]); + ^ +``` + +A similar thing happens if we define a function which takes ownership, and +try to use something after we’ve passed it as an argument: + +```rust,ignore +fn take(v: Vec) { + // what happens here isn’t important. +} + +let v = vec![1, 2, 3]; + +take(v); + +println!("v[0] is: {}", v[0]); +``` + +Same error: ‘use of moved value’. When we transfer ownership to something else, +we say that we’ve ‘moved’ the thing we refer to. You don’t need some sort of +special annotation here, it’s the default thing that Rust does. + +## The details + +The reason that we cannot use a binding after we’ve moved it is subtle, but +important. When we write code like this: + +```rust +let v = vec![1, 2, 3]; + +let v2 = v; +``` + +The first line allocates memory for the vector object, `v`, and for the data it +contains. The vector object is stored on the [stack][sh] and contains a pointer +to the content (`[1, 2, 3]`) stored on the [heap][sh]. When we move `v` to `v2`, +it creates a copy of that pointer, for `v2`. Which means that there would be two +pointers to the content of the vector on the heap. It would violate Rust’s +safety guarantees by introducing a data race. Therefore, Rust forbids using `v` +after we’ve done the move. + +[sh]: the-stack-and-the-heap.html + +It’s also important to note that optimizations may remove the actual copy of +the bytes on the stack, depending on circumstances. So it may not be as +inefficient as it initially seems. + +## `Copy` types + +We’ve established that when ownership is transferred to another binding, you +cannot use the original binding. However, there’s a [trait][traits] that changes this +behavior, and it’s called `Copy`. We haven’t discussed traits yet, but for now, +you can think of them as an annotation to a particular type that adds extra +behavior. For example: + +```rust +let v = 1; + +let v2 = v; + +println!("v is: {}", v); +``` + +In this case, `v` is an `i32`, which implements the `Copy` trait. This means +that, just like a move, when we assign `v` to `v2`, a copy of the data is made. +But, unlike a move, we can still use `v` afterward. This is because an `i32` +has no pointers to data somewhere else, copying it is a full copy. + +All primitive types implement the `Copy` trait and their ownership is +therefore not moved like one would assume, following the ´ownership rules´. +To give an example, the two following snippets of code only compile because the +`i32` and `bool` types implement the `Copy` trait. + +```rust +fn main() { + let a = 5; + + let _y = double(a); + println!("{}", a); +} + +fn double(x: i32) -> i32 { + x * 2 +} +``` + +```rust +fn main() { + let a = true; + + let _y = change_truth(a); + println!("{}", a); +} + +fn change_truth(x: bool) -> bool { + !x +} +``` + +If we had used types that do not implement the `Copy` trait, +we would have gotten a compile error because we tried to use a moved value. + +```text +error: use of moved value: `a` +println!("{}", a); + ^ +``` + +We will discuss how to make your own types `Copy` in the [traits][traits] +section. + +[traits]: traits.html + +# More than ownership + +Of course, if we had to hand ownership back with every function we wrote: + +```rust +fn foo(v: Vec) -> Vec { + // do stuff with v + + // hand back ownership + v +} +``` + +This would get very tedious. It gets worse the more things we want to take ownership of: + +```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); +``` + +Ugh! The return type, return line, and calling the function gets way more +complicated. + +Luckily, Rust offers a feature, borrowing, which helps us solve this problem. +It’s the topic of the next section! + diff --git a/src/primitive-types.md b/src/primitive-types.md index ae84efe5d..a8c7a7d41 100644 --- a/src/primitive-types.md +++ b/src/primitive-types.md @@ -1 +1,298 @@ -# Primitive Types +% Primitive Types + +The Rust language has a number of types that are considered ‘primitive’. This +means that they’re built-in to the language. Rust is structured in such a way +that the standard library also provides a number of useful types built on top +of these ones, as well, but these are the most primitive. + +# Booleans + +Rust has a built in boolean type, named `bool`. It has two values, `true` and `false`: + +```rust +let x = true; + +let y: bool = false; +``` + +A common use of booleans is in [`if` conditionals][if]. + +[if]: if.html + +You can find more documentation for `bool`s [in the standard library +documentation][bool]. + +[bool]: ../std/primitive.bool.html + +# `char` + +The `char` type represents a single Unicode scalar value. You can create `char`s +with a single tick: (`'`) + +```rust +let x = 'x'; +let two_hearts = '💕'; +``` + +Unlike some other languages, this means that Rust’s `char` is not a single byte, +but four. + +You can find more documentation for `char`s [in the standard library +documentation][char]. + +[char]: ../std/primitive.char.html + +# Numeric types + +Rust has a variety of numeric types in a few categories: signed and unsigned, +fixed and variable, floating-point and integer. + +These types consist of two parts: the category, and the size. For example, +`u16` is an unsigned type with sixteen bits of size. More bits lets you have +bigger numbers. + +If a number literal has nothing to cause its type to be inferred, it defaults: + +```rust +let x = 42; // x has type i32 + +let y = 1.0; // y has type f64 +``` + +Here’s a list of the different numeric types, with links to their documentation +in the standard library: + +* [i8](../std/primitive.i8.html) +* [i16](../std/primitive.i16.html) +* [i32](../std/primitive.i32.html) +* [i64](../std/primitive.i64.html) +* [u8](../std/primitive.u8.html) +* [u16](../std/primitive.u16.html) +* [u32](../std/primitive.u32.html) +* [u64](../std/primitive.u64.html) +* [isize](../std/primitive.isize.html) +* [usize](../std/primitive.usize.html) +* [f32](../std/primitive.f32.html) +* [f64](../std/primitive.f64.html) + +Let’s go over them by category: + +## Signed and Unsigned + +Integer types come in two varieties: signed and unsigned. To understand the +difference, let’s consider a number with four bits of size. A signed, four-bit +number would let you store numbers from `-8` to `+7`. Signed numbers use +“two’s complement representation”. An unsigned four bit number, since it does +not need to store negatives, can store values from `0` to `+15`. + +Unsigned types use a `u` for their category, and signed types use `i`. The `i` +is for ‘integer’. So `u8` is an eight-bit unsigned number, and `i8` is an +eight-bit signed number. + +## Fixed size types + +Fixed size types have a specific number of bits in their representation. Valid +bit sizes are `8`, `16`, `32`, and `64`. So, `u32` is an unsigned, 32-bit integer, +and `i64` is a signed, 64-bit integer. + +## Variable sized types + +Rust also provides types whose size depends on the size of a pointer of the +underlying machine. These types have ‘size’ as the category, and come in signed +and unsigned varieties. This makes for two types: `isize` and `usize`. + +## Floating-point types + +Rust also has two floating point types: `f32` and `f64`. These correspond to +IEEE-754 single and double precision numbers. + +# Arrays + +Like many programming languages, Rust has list types to represent a sequence of +things. The most basic is the *array*, a fixed-size list of elements of the +same type. By default, arrays are immutable. + +```rust +let a = [1, 2, 3]; // a: [i32; 3] +let mut m = [1, 2, 3]; // m: [i32; 3] +``` + +Arrays have type `[T; N]`. We’ll talk about this `T` notation [in the generics +section][generics]. The `N` is a compile-time constant, for the length of the +array. + +There’s a shorthand for initializing each element of an array to the same +value. In this example, each element of `a` will be initialized to `0`: + +```rust +let a = [0; 20]; // a: [i32; 20] +``` + +You can get the number of elements in an array `a` with `a.len()`: + +```rust +let a = [1, 2, 3]; + +println!("a has {} elements", a.len()); +``` + +You can access a particular element of an array with *subscript notation*: + +```rust +let names = ["Graydon", "Brian", "Niko"]; // names: [&str; 3] + +println!("The second name is: {}", names[1]); +``` + +Subscripts start at zero, like in most programming languages, so the first name +is `names[0]` and the second name is `names[1]`. The above example prints +`The second name is: Brian`. If you try to use a subscript that is not in the +array, you will get an error: array access is bounds-checked at run-time. Such +errant access is the source of many bugs in other systems programming +languages. + +You can find more documentation for `array`s [in the standard library +documentation][array]. + +[array]: ../std/primitive.array.html + +# Slices + +A ‘slice’ is a reference to (or “view” into) another data structure. They are +useful for allowing safe, efficient access to a portion of an array without +copying. For example, you might want to reference just one line of a file read +into memory. By nature, a slice is not created directly, but from an existing +variable binding. Slices have a defined length, can be mutable or immutable. + +## Slicing syntax + +You can use a combo of `&` and `[]` to create a slice from various things. The +`&` indicates that slices are similar to references, and the `[]`s, with a +range, let you define the length of the slice: + +```rust +let a = [0, 1, 2, 3, 4]; +let complete = &a[..]; // A slice containing all of the elements in a +let middle = &a[1..4]; // A slice of a: just the elements 1, 2, and 3 +``` + +Slices have type `&[T]`. We’ll talk about that `T` when we cover +[generics][generics]. + +[generics]: generics.html + +You can find more documentation for slices [in the standard library +documentation][slice]. + +[slice]: ../std/primitive.slice.html + +# `str` + +Rust’s `str` type is the most primitive string type. As an [unsized type][dst], +it’s not very useful by itself, but becomes useful when placed behind a reference, +like [`&str`][strings]. As such, we’ll just leave it at that. + +[dst]: unsized-types.html +[strings]: strings.html + +You can find more documentation for `str` [in the standard library +documentation][str]. + +[str]: ../std/primitive.str.html + +# Tuples + +A tuple is an ordered list of fixed size. Like this: + +```rust +let x = (1, "hello"); +``` + +The parentheses and commas form this two-length tuple. Here’s the same code, but +with the type annotated: + +```rust +let x: (i32, &str) = (1, "hello"); +``` + +As you can see, the type of a tuple looks just like the tuple, but with each +position having a type name rather than the value. Careful readers will also +note that tuples are heterogeneous: we have an `i32` and a `&str` in this tuple. +In systems programming languages, strings are a bit more complex than in other +languages. For now, just read `&str` as a *string slice*, and we’ll learn more +soon. + +You can assign one tuple into another, if they have the same contained types +and [arity]. Tuples have the same arity when they have the same length. + +[arity]: glossary.html#arity + +```rust +let mut x = (1, 2); // x: (i32, i32) +let y = (2, 3); // y: (i32, i32) + +x = y; +``` + +You can access the fields in a tuple through a *destructuring let*. Here’s +an example: + +```rust +let (x, y, z) = (1, 2, 3); + +println!("x is {}", x); +``` + +Remember [before][let] when I said the left-hand side of a `let` statement was more +powerful than just assigning a binding? Here we are. We can put a pattern on +the left-hand side of the `let`, and if it matches up to the right-hand side, +we can assign multiple bindings at once. In this case, `let` “destructures” +or “breaks up” the tuple, and assigns the bits to three bindings. + +[let]: variable-bindings.html + +This pattern is very powerful, and we’ll see it repeated more later. + +You can disambiguate a single-element tuple from a value in parentheses with a +comma: + +```rust +(0,); // single-element tuple +(0); // zero in parentheses +``` + +## Tuple Indexing + +You can also access fields of a tuple with indexing syntax: + + +```rust +let tuple = (1, 2, 3); + +let x = tuple.0; +let y = tuple.1; +let z = tuple.2; + +println!("x is {}", x); +``` + +Like array indexing, it starts at zero, but unlike array indexing, it uses a +`.`, rather than `[]`s. + +You can find more documentation for tuples [in the standard library +documentation][tuple]. + +[tuple]: ../std/primitive.tuple.html + +# Functions + +Functions also have a type! They look like this: + +```rust +fn foo(x: i32) -> i32 { x } + +let x: fn(i32) -> i32 = foo; +``` + +In this case, `x` is a ‘function pointer’ to a function that takes an `i32` and +returns an `i32`. diff --git a/src/raw-pointers.md b/src/raw-pointers.md index 43d155741..679f5489e 100644 --- a/src/raw-pointers.md +++ b/src/raw-pointers.md @@ -1 +1,121 @@ -# Raw Pointers +% 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/references-and-borrowing.md b/src/references-and-borrowing.md index 5f0552e51..d8758e0c6 100644 --- a/src/references-and-borrowing.md +++ b/src/references-and-borrowing.md @@ -1 +1,381 @@ -# References & Borrowing +% References and Borrowing + +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/structs.md b/src/structs.md index c88ba870a..1d70ee278 100644 --- a/src/structs.md +++ b/src/structs.md @@ -1 +1,200 @@ -# Structs +% Structs + +`struct`s are a way of creating more complex data types. For example, if we were +doing calculations involving coordinates in 2D space, we would need both an `x` +and a `y` value: + +```rust +let origin_x = 0; +let origin_y = 0; +``` + +A `struct` lets us combine these two into a single, unified datatype with `x` +and `y` as field labels: + +```rust +struct Point { + x: i32, + y: i32, +} + +fn main() { + let origin = Point { x: 0, y: 0 }; // origin: Point + + println!("The origin is at ({}, {})", origin.x, origin.y); +} +``` + +There’s a lot going on here, so let’s break it down. We declare a `struct` with +the `struct` keyword, and then with a name. By convention, `struct`s begin with +a capital letter and are camel cased: `PointInSpace`, not `Point_In_Space`. + +We can create an instance of our `struct` via `let`, as usual, but we use a `key: +value` style syntax to set each field. The order doesn’t need to be the same as +in the original declaration. + +Finally, because fields have names, we can access them through dot +notation: `origin.x`. + +The values in `struct`s are immutable by default, like other bindings in Rust. +Use `mut` to make them mutable: + +```rust +struct Point { + x: i32, + y: i32, +} + +fn main() { + let mut point = Point { x: 0, y: 0 }; + + point.x = 5; + + println!("The point is at ({}, {})", point.x, point.y); +} +``` + +This will print `The point is at (5, 0)`. + +Rust does not support field mutability at the language level, so you cannot +write something like this: + +```rust,ignore +struct Point { + mut x: i32, + y: i32, +} +``` + +Mutability is a property of the binding, not of the structure itself. If you’re +used to field-level mutability, this may seem strange at first, but it +significantly simplifies things. It even lets you make things mutable on a temporary +basis: + +```rust,ignore +struct Point { + x: i32, + y: i32, +} + +fn main() { + let mut point = Point { x: 0, y: 0 }; + + point.x = 5; + + let point = point; // now immutable + + point.y = 6; // this causes an error +} +``` + +# Update syntax + +A `struct` can include `..` to indicate that you want to use a copy of some +other `struct` for some of the values. For example: + +```rust +struct Point3d { + x: i32, + y: i32, + z: i32, +} + +let mut point = Point3d { x: 0, y: 0, z: 0 }; +point = Point3d { y: 1, .. point }; +``` + +This gives `point` a new `y`, but keeps the old `x` and `z` values. It doesn’t +have to be the same `struct` either, you can use this syntax when making new +ones, and it will copy the values you don’t specify: + +```rust +# struct Point3d { +# x: i32, +# y: i32, +# z: i32, +# } +let origin = Point3d { x: 0, y: 0, z: 0 }; +let point = Point3d { z: 1, x: 2, .. origin }; +``` + +# Tuple structs + +Rust has another data type that’s like a hybrid between a [tuple][tuple] and a +`struct`, called a ‘tuple struct’. Tuple structs have a name, but their fields +don't. They are declared with the `struct` keyword, and then with a name +followed by a tuple: + +[tuple]: primitive-types.html#tuples + +```rust +struct Color(i32, i32, i32); +struct Point(i32, i32, i32); + +let black = Color(0, 0, 0); +let origin = Point(0, 0, 0); +``` +Here, `black` and `origin` are not equal, even though they contain the same +values. + +It is almost always better to use a `struct` than a tuple struct. We +would write `Color` and `Point` like this instead: + +```rust +struct Color { + red: i32, + blue: i32, + green: i32, +} + +struct Point { + x: i32, + y: i32, + z: i32, +} +``` + +Good names are important, and while values in a tuple struct can be +referenced with dot notation as well, a `struct` gives us actual names, +rather than positions. + +There _is_ one case when a tuple struct is very useful, though, and that is when +it has only one element. We call this the ‘newtype’ pattern, because +it allows you to create a new type that is distinct from its contained value +and also expresses its own semantic meaning: + +```rust +struct Inches(i32); + +let length = Inches(10); + +let Inches(integer_length) = length; +println!("length is {} inches", integer_length); +``` + +As you can see here, you can extract the inner integer type through a +destructuring `let`, just as with regular tuples. In this case, the +`let Inches(integer_length)` assigns `10` to `integer_length`. + +# Unit-like structs + +You can define a `struct` with no members at all: + +```rust +struct Electron; + +let x = Electron; +``` + +Such a `struct` is called ‘unit-like’ because it resembles the empty +tuple, `()`, sometimes called ‘unit’. Like a tuple struct, it defines a +new type. + +This is rarely useful on its own (although sometimes it can serve as a +marker type), but in combination with other features, it can become +useful. For instance, a library may ask you to create a structure that +implements a certain [trait][trait] to handle events. If you don’t have +any data you need to store in the structure, you can just create a +unit-like `struct`. + +[trait]: traits.html diff --git a/src/testing.md b/src/testing.md index f00b526a9..32f0d689e 100644 --- a/src/testing.md +++ b/src/testing.md @@ -1 +1,510 @@ -# Testing +% 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', /home/steve/tmp/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:///home/steve/tmp/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/trait-objects.md b/src/trait-objects.md index 0b082bc21..8127b0898 100644 --- a/src/trait-objects.md +++ b/src/trait-objects.md @@ -1 +1,340 @@ -# Trait Objects +% 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 index 445d444b1..f9e3299f9 100644 --- a/src/traits.md +++ b/src/traits.md @@ -1 +1,523 @@ -# Traits +% 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/ufcs.md b/src/ufcs.md index 1e900d51e..772597056 100644 --- a/src/ufcs.md +++ b/src/ufcs.md @@ -1 +1,136 @@ -# UFCS +% 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 index b119af346..1b223365b 100644 --- a/src/unsafe-rust.md +++ b/src/unsafe-rust.md @@ -1 +1,142 @@ -# Unsafe Rust +% 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 index 4b946f1fb..61627c0b5 100644 --- a/src/using-rust-from-other-languages.md +++ b/src/using-rust-from-other-languages.md @@ -1 +1,344 @@ -# Using Rust from Other Languages +% Rust Inside 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:///home/steve/src/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/variable-bindings.md b/src/variable-bindings.md index dd0e09020..f3a5d1dd8 100644 --- a/src/variable-bindings.md +++ b/src/variable-bindings.md @@ -1 +1,252 @@ -# Variable Bindings +% Variable Bindings + +Virtually every non-'Hello World’ Rust program uses *variable bindings*. They +bind some value to a name, so it can be used later. `let` is +used to introduce a binding, just like this: + +```rust +fn main() { + let x = 5; +} +``` + +Putting `fn main() {` in each example is a bit tedious, so we’ll leave that out +in the future. If you’re following along, make sure to edit your `main()` +function, rather than leaving it off. Otherwise, you’ll get an error. + +# Patterns + +In many languages, a variable binding would be called a *variable*, but Rust’s +variable bindings have a few tricks up their sleeves. For example the +left-hand side of a `let` expression is a ‘[pattern][pattern]’, not just a +variable name. This means we can do things like: + +```rust +let (x, y) = (1, 2); +``` + +After this expression is evaluated, `x` will be one, and `y` will be two. +Patterns are really powerful, and have [their own section][pattern] in the +book. We don’t need those features for now, so we’ll just keep this in the back +of our minds as we go forward. + +[pattern]: patterns.html + +# Type annotations + +Rust is a statically typed language, which means that we specify our types up +front, and they’re checked at compile time. So why does our first example +compile? Well, Rust has this thing called ‘type inference’. If it can figure +out what the type of something is, Rust doesn’t require you to actually type it +out. + +We can add the type if we want to, though. Types come after a colon (`:`): + +```rust +let x: i32 = 5; +``` + +If I asked you to read this out loud to the rest of the class, you’d say “`x` +is a binding with the type `i32` and the value `five`.” + +In this case we chose to represent `x` as a 32-bit signed integer. Rust has +many different primitive integer types. They begin with `i` for signed integers +and `u` for unsigned integers. The possible integer sizes are 8, 16, 32, and 64 +bits. + +In future examples, we may annotate the type in a comment. The examples will +look like this: + +```rust +fn main() { + let x = 5; // x: i32 +} +``` + +Note the similarities between this annotation and the syntax you use with +`let`. Including these kinds of comments is not idiomatic Rust, but we'll +occasionally include them to help you understand what the types that Rust +infers are. + +# Mutability + +By default, bindings are *immutable*. This code will not compile: + +```rust,ignore +let x = 5; +x = 10; +``` + +It will give you this error: + +```text +error: re-assignment of immutable variable `x` + x = 10; + ^~~~~~~ +``` + +If you want a binding to be mutable, you can use `mut`: + +```rust +let mut x = 5; // mut x: i32 +x = 10; +``` + +There is no single reason that bindings are immutable by default, but we can +think about it through one of Rust’s primary focuses: safety. If you forget to +say `mut`, the compiler will catch it, and let you know that you have mutated +something you may not have intended to mutate. If bindings were mutable by +default, the compiler would not be able to tell you this. If you _did_ intend +mutation, then the solution is quite easy: add `mut`. + +There are other good reasons to avoid mutable state when possible, but they’re +out of the scope of this guide. In general, you can often avoid explicit +mutation, and so it is preferable in Rust. That said, sometimes, mutation is +what you need, so it’s not verboten. + +# Initializing bindings + +Rust variable bindings have one more aspect that differs from other languages: +bindings are required to be initialized with a value before you're allowed to +use them. + +Let’s try it out. Change your `src/main.rs` file to look like this: + +```rust +fn main() { + let x: i32; + + println!("Hello world!"); +} +``` + +You can use `cargo build` on the command line to build it. You’ll get a +warning, but it will still print "Hello, world!": + +```text + Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world) +src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variable)] + on by default +src/main.rs:2 let x: i32; + ^ +``` + +Rust warns us that we never use the variable binding, but since we never use +it, no harm, no foul. Things change if we try to actually use this `x`, +however. Let’s do that. Change your program to look like this: + +```rust,ignore +fn main() { + let x: i32; + + println!("The value of x is: {}", x); +} +``` + +And try to build it. You’ll get an error: + +```bash +$ cargo build + Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world) +src/main.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x` +src/main.rs:4 println!("The value of x is: {}", x); + ^ +note: in expansion of format_args! +:2:23: 2:77 note: expansion site +:1:1: 3:2 note: in expansion of println! +src/main.rs:4:5: 4:42 note: expansion site +error: aborting due to previous error +Could not compile `hello_world`. +``` + +Rust will not let us use a value that has not been initialized. Next, let’s +talk about this stuff we've added to `println!`. + +If you include two curly braces (`{}`, some call them moustaches...) in your +string to print, Rust will interpret this as a request to interpolate some sort +of value. *String interpolation* is a computer science term that means "stick +in the middle of a string." We add a comma, and then `x`, to indicate that we +want `x` to be the value we’re interpolating. The comma is used to separate +arguments we pass to functions and macros, if you’re passing more than one. + +When you just use the curly braces, Rust will attempt to display the value in a +meaningful way by checking out its type. If you want to specify the format in a +more detailed manner, there are a [wide number of options available][format]. +For now, we'll just stick to the default: integers aren't very complicated to +print. + +[format]: ../std/fmt/index.html + +# Scope and shadowing + +Let’s get back to bindings. Variable bindings have a scope - they are +constrained to live in a block they were defined in. A block is a collection +of statements enclosed by `{` and `}`. Function definitions are also blocks! +In the following example we define two variable bindings, `x` and `y`, which +live in different blocks. `x` can be accessed from inside the `fn main() {}` +block, while `y` can be accessed only from inside the inner block: + +```rust,ignore +fn main() { + let x: i32 = 17; + { + let y: i32 = 3; + println!("The value of x is {} and value of y is {}", x, y); + } + println!("The value of x is {} and value of y is {}", x, y); // This won't work +} +``` + +The first `println!` would print "The value of x is 17 and the value of y is +3", but this example cannot be compiled successfully, because the second +`println!` cannot access the value of `y`, since it is not in scope anymore. +Instead we get this error: + +```bash +$ cargo build + Compiling hello v0.1.0 (file:///home/you/projects/hello_world) +main.rs:7:62: 7:63 error: unresolved name `y`. Did you mean `x`? [E0425] +main.rs:7 println!("The value of x is {} and value of y is {}", x, y); // This won't work + ^ +note: in expansion of format_args! +:2:25: 2:56 note: expansion site +:1:1: 2:62 note: in expansion of print! +:3:1: 3:54 note: expansion site +:1:1: 3:58 note: in expansion of println! +main.rs:7:5: 7:65 note: expansion site +main.rs:7:62: 7:63 help: run `rustc --explain E0425` to see a detailed explanation +error: aborting due to previous error +Could not compile `hello`. + +To learn more, run the command again with --verbose. +``` + +Additionally, variable bindings can be shadowed. This means that a later +variable binding with the same name as another binding, that's currently in +scope, will override the previous binding. + +```rust +let x: i32 = 8; +{ + println!("{}", x); // Prints "8" + let x = 12; + println!("{}", x); // Prints "12" +} +println!("{}", x); // Prints "8" +let x = 42; +println!("{}", x); // Prints "42" +``` + +Shadowing and mutable bindings may appear as two sides of the same coin, but +they are two distinct concepts that can't always be used interchangeably. For +one, shadowing enables us to rebind a name to a value of a different type. It +is also possible to change the mutability of a binding. + +```rust +let mut x: i32 = 1; +x = 7; +let x = x; // x is now immutable and is bound to 7 + +let y = 4; +let y = "I can also be bound to text!"; // y is now of a different type +``` diff --git a/src/vectors.md b/src/vectors.md index 039926570..7b826f08a 100644 --- a/src/vectors.md +++ b/src/vectors.md @@ -1 +1,89 @@ -# Vectors +% 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