Skip to content

Instantly share code, notes, and snippets.

@killercup
Created June 1, 2015 18:42
Show Gist options
  • Save killercup/e3a1f4642f8b1e81da4c to your computer and use it in GitHub Desktop.
Save killercup/e3a1f4642f8b1e81da4c to your computer and use it in GitHub Desktop.
diff --git a/src/doc/trpl/README.md b/src/doc/trpl/README.md
index d7f810d..89f0db8 100644
--- a/src/doc/trpl/README.md
+++ b/src/doc/trpl/README.md
@@ -150,8 +150,8 @@ of those times. As the error explains, while we made our binding mutable, we
still cannot call `push`. This is because we already have a reference to an
element of the vector, `y`. Mutating something while another reference exists
is dangerous, because we may invalidate the reference. In this specific case,
-when we create the vector, we may have only allocated space for two elements.
-Adding a third would mean allocating a new chunk of memory for all those elements,
+when we create the vector, we may have only allocated space for three elements.
+Adding a fourth would mean allocating a new chunk of memory for all those elements,
copying the old values over, and updating the internal pointer to that memory.
That all works just fine. The problem is that `y` wouldn’t get updated, and so
we’d have a ‘dangling pointer’. That’s bad. Any use of `y` would be an error in
@@ -175,7 +175,7 @@ data, we call the `clone()` method. In this example, `y` is no longer a referenc
to the vector stored in `x`, but a copy of its first element, `"Hello"`. Now
that we don’t have a reference, our `push()` works just fine.
-[move]: ownership.html#move-semantics
+[move]: move-semantics.html
If we truly want a reference, we need the other option: ensure that our reference
goes out of scope before we try to do the mutation. That looks like this:
diff --git a/src/doc/trpl/SUMMARY.md b/src/doc/trpl/SUMMARY.md
index ca3381f..584f24b 100644
--- a/src/doc/trpl/SUMMARY.md
+++ b/src/doc/trpl/SUMMARY.md
@@ -7,7 +7,7 @@
* [Learn Rust](learn-rust.md)
* [Guessing Game](guessing-game.md)
* [Dining Philosophers](dining-philosophers.md)
- * [Rust Inside Other Languages](rust-inside-other-languages.md)
+ * [Rust inside other languages](rust-inside-other-languages.md)
* [Effective Rust](effective-rust.md)
* [The Stack and the Heap](the-stack-and-the-heap.md)
* [Testing](testing.md)
diff --git a/src/doc/trpl/associated-constants.md b/src/doc/trpl/associated-constants.md
index 1c097be..2f23af5 100644
--- a/src/doc/trpl/associated-constants.md
+++ b/src/doc/trpl/associated-constants.md
@@ -2,7 +2,7 @@
With the `associated_consts` feature, you can define constants like this:
-```rust
+```rust,ignore
#![feature(associated_consts)]
trait Foo {
@@ -41,7 +41,7 @@ error: not all trait items implemented, missing: `ID` [E0046]
A default value can be implemented as well:
-```rust
+```rust,ignore
#![feature(associated_consts)]
trait Foo {
@@ -68,7 +68,7 @@ add our own definition.
Associated constants don’t have to be associated with a trait. An `impl` block
for a `struct` works fine too:
-```rust
+```rust,ignore
#![feature(associated_consts)]
struct Foo;
diff --git a/src/doc/trpl/benchmark-tests.md b/src/doc/trpl/benchmark-tests.md
index 797ec94..8879653 100644
--- a/src/doc/trpl/benchmark-tests.md
+++ b/src/doc/trpl/benchmark-tests.md
@@ -3,7 +3,7 @@
Rust supports benchmark tests, which can test the performance of your
code. Let's make our `src/lib.rs` look like this (comments elided):
-```rust,ignore
+```{rust,ignore}
#![feature(test)]
extern crate test;
@@ -77,7 +77,7 @@ the benchmark is no longer benchmarking what one expects. For example, the
compiler might recognize that some calculation has no external effects and
remove it entirely.
-```rust,ignore
+```{rust,ignore}
#![feature(test)]
extern crate test;
diff --git a/src/doc/trpl/borrow-and-asref.md b/src/doc/trpl/borrow-and-asref.md
index 1cfeb26..f5f314f 100644
--- a/src/doc/trpl/borrow-and-asref.md
+++ b/src/doc/trpl/borrow-and-asref.md
@@ -47,11 +47,11 @@ This is because the standard library has `impl Borrow<str> for String`.
For most types, when you want to take an owned or borrowed type, a `&T` is
enough. But one area where `Borrow` is effective is when there’s more than one
-kind of borrowed value. This is especially true of references and slices: you
-can have both an `&T` or a `&mut T`. If we wanted to accept both of these types,
-`Borrow` is up for it:
+kind of borrowed value. Slices are an area where this is especially true: you
+can have both an `&[T]` or a `&mut [T]`. If we wanted to accept both of these
+types, `Borrow` is up for it:
-```rust
+```
use std::borrow::Borrow;
use std::fmt::Display;
diff --git a/src/doc/trpl/box-syntax-and-patterns.md b/src/doc/trpl/box-syntax-and-patterns.md
index 1cf84bf..839f07d 100644
--- a/src/doc/trpl/box-syntax-and-patterns.md
+++ b/src/doc/trpl/box-syntax-and-patterns.md
@@ -5,7 +5,7 @@ Also it is not possible in stable Rust to destructure a `Box` in a match
pattern. The unstable `box` keyword can be used to both create and destructure
a `Box`. An example usage would be:
-```rust
+```
#![feature(box_syntax, box_patterns)]
fn main() {
@@ -34,7 +34,7 @@ because the syntax may still change in the future.
In many languages with pointers, you'd return a pointer from a function
so as to avoid copying a large data structure. For example:
-```rust
+```{rust}
struct BigStruct {
one: i32,
two: i32,
diff --git a/src/doc/trpl/closures.md b/src/doc/trpl/closures.md
index d2fe9c6..d7fa847 100644
--- a/src/doc/trpl/closures.md
+++ b/src/doc/trpl/closures.md
@@ -54,9 +54,9 @@ The second is that the syntax is similar, but a bit different. I’ve added spac
here to make them look a little closer:
```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 ;
+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 in ways.
@@ -136,7 +136,7 @@ This gives us:
note: `nums` moved into closure environment here because it has type
`[closure(()) -> collections::vec::Vec<i32>]`, which is non-copyable
let takes_nums = || nums;
- ^~~~~~~
+ ^~~~~~~
```
`Vec<T>` has ownership over its contents, and therefore, when we refer to it
@@ -352,8 +352,8 @@ error: the trait `core::marker::Sized` is not implemented for the type
factory() -> (Fn(i32) -> Vec<i32>) {
^~~~~~~~~~~~~~~~~~~~~
note: `core::ops::Fn(i32) -> collections::vec::Vec<i32>` does not have a constant size known at compile-time
-factory() -> (Fn(i32) -> Vec<i32>) {
- ^~~~~~~~~~~~~~~~~~~~~
+fa ctory() -> (Fn(i32) -> Vec<i32>) {
+ ^~~~~~~~~~~~~~~~~~~~~
```
diff --git a/src/doc/trpl/concurrency.md b/src/doc/trpl/concurrency.md
index ccd7690..d6590e9 100644
--- a/src/doc/trpl/concurrency.md
+++ b/src/doc/trpl/concurrency.md
@@ -6,7 +6,7 @@ and more cores, yet many programmers aren't prepared to fully utilize them.
Rust's memory safety features also apply to its concurrency story too. Even
concurrent Rust programs must be memory safe, having no data races. Rust's type
-system is up to the task, and gives you powerful ways to reason about
+system is up to the thread, and gives you powerful ways to reason about
concurrent code at compile time.
Before we talk about the concurrency features that come with Rust, it's important
@@ -59,7 +59,7 @@ place!
Rust's standard library provides a library for threads, which allow you to
run Rust code in parallel. Here's a basic example of using `std::thread`:
-```rust
+```
use std::thread;
fn main() {
@@ -73,7 +73,7 @@ The `thread::spawn()` method accepts a closure, which is executed in a
new thread. It returns a handle to the thread, that can be used to
wait for the child thread to finish and extract its result:
-```rust
+```
use std::thread;
fn main() {
@@ -189,7 +189,7 @@ guard across thread boundaries, which gives us our error.
We can use `Arc<T>` to fix this. Here's the working version:
-```rust
+```
use std::sync::{Arc, Mutex};
use std::thread;
@@ -248,7 +248,7 @@ threads with each other. Let's talk about one of them: channels.
Here's a version of our code that uses channels for synchronization, rather
than waiting for a specific time:
-```rust
+```
use std::sync::{Arc, Mutex};
use std::thread;
use std::sync::mpsc;
@@ -281,7 +281,7 @@ a simple `()` down the channel, and then wait for ten of them to come back.
While this channel is just sending a generic signal, we can send any data that
is `Send` over the channel!
-```rust
+```
use std::thread;
use std::sync::mpsc;
@@ -311,7 +311,7 @@ the answer, and then it `send()`s us the answer over the channel.
A `panic!` will crash the currently executing thread. You can use Rust's
threads as a simple isolation mechanism:
-```rust
+```
use std::thread;
let result = thread::spawn(move || {
diff --git a/src/doc/trpl/const-and-static.md b/src/doc/trpl/const-and-static.md
index f309dd0..be0c873 100644
--- a/src/doc/trpl/const-and-static.md
+++ b/src/doc/trpl/const-and-static.md
@@ -31,8 +31,10 @@ static N: i32 = 5;
Unlike [`let`][let] bindings, you must annotate the type of a `static`.
+[let]: variable-bindings.html
+
Statics live for the entire lifetime of a program, and therefore any
-reference stored in a constant has a [`'static` lifetime][lifetimes]:
+reference stored in a constant has a [`’static` lifetime][lifetimes]:
```rust
static NAME: &'static str = "Steve";
diff --git a/src/doc/trpl/const.md b/src/doc/trpl/const.md
new file mode 100644
index 0000000..9234c4f
--- /dev/null
+++ b/src/doc/trpl/const.md
@@ -0,0 +1,3 @@
+% `const`
+
+Coming soon!
diff --git a/src/doc/trpl/crates-and-modules.md b/src/doc/trpl/crates-and-modules.md
index 63fdef0..3ab3401 100644
--- a/src/doc/trpl/crates-and-modules.md
+++ b/src/doc/trpl/crates-and-modules.md
@@ -75,7 +75,7 @@ above.
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 {
}
@@ -126,7 +126,7 @@ ways.
Instead of declaring a module like this:
-```rust,ignore
+```{rust,ignore}
mod english {
// contents of our module go here
}
@@ -134,7 +134,7 @@ mod english {
We can instead declare our module like this:
-```rust,ignore
+```{rust,ignore}
mod english;
```
@@ -173,7 +173,7 @@ $ tree .
`src/lib.rs` is our crate root, and looks like this:
-```rust,ignore
+```{rust,ignore}
mod english;
mod japanese;
```
@@ -184,7 +184,7 @@ 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
+```{rust,ignore}
mod greetings;
mod farewells;
```
@@ -297,7 +297,7 @@ 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
+```{rust,ignore}
extern crate phrases;
fn main() {
@@ -308,21 +308,21 @@ fn main() {
In our `src/lib.rs`, let’s add `pub` to the `english` module declaration:
-```rust,ignore
+```{rust,ignore}
pub mod english;
mod japanese;
```
And in our `src/english/mod.rs`, let’s make both `pub`:
-```rust,ignore
+```{rust,ignore}
pub mod greetings;
pub mod farewells;
```
In our `src/english/greetings.rs`, let’s add `pub` to our `fn` declaration:
-```rust,ignore
+```{rust,ignore}
pub fn hello() -> String {
"Hello!".to_string()
}
@@ -330,7 +330,7 @@ pub fn hello() -> String {
And also in `src/english/farewells.rs`:
-```rust,ignore
+```{rust,ignore}
pub fn goodbye() -> String {
"Goodbye.".to_string()
}
@@ -365,7 +365,7 @@ refer to them with shorter names. Let’s talk about `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
+```{rust,ignore}
extern crate phrases;
use phrases::english::greetings;
@@ -382,7 +382,7 @@ the functions by a much shorter name. By convention, when importing functions, i
considered best practice to import the module, rather than the function directly. In
other words, you _can_ do this:
-```rust,ignore
+```{rust,ignore}
extern crate phrases;
use phrases::english::greetings::hello;
@@ -400,7 +400,7 @@ 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
+```{rust,ignore}
extern crate phrases;
use phrases::english::greetings::hello;
@@ -426,14 +426,14 @@ 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
+```{rust,ignore}
use phrases::english::greetings;
use phrases::english::farewells;
```
We can use this shortcut:
-```rust,ignore
+```{rust,ignore}
use phrases::english::{greetings, farewells};
```
@@ -445,7 +445,7 @@ 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
+```{rust,ignore}
extern crate phrases;
use phrases::english::{greetings,farewells};
@@ -462,14 +462,14 @@ fn main() {
Then, modify your `src/lib.rs` to make the `japanese` mod public:
-```rust,ignore
+```{rust,ignore}
pub mod english;
pub mod japanese;
```
Next, make the two functions public, first in `src/japanese/greetings.rs`:
-```rust,ignore
+```{rust,ignore}
pub fn hello() -> String {
"こんにちは".to_string()
}
@@ -477,7 +477,7 @@ pub fn hello() -> String {
And then in `src/japanese/farewells.rs`:
-```rust,ignore
+```{rust,ignore}
pub fn goodbye() -> String {
"さようなら".to_string()
}
@@ -485,7 +485,7 @@ pub fn goodbye() -> String {
Finally, modify your `src/japanese/mod.rs` to read like this:
-```rust,ignore
+```{rust,ignore}
pub use self::greetings::hello;
pub use self::farewells::goodbye;
diff --git a/src/doc/trpl/debug-and-display.md b/src/doc/trpl/debug-and-display.md
new file mode 100644
index 0000000..918f4c4
--- /dev/null
+++ b/src/doc/trpl/debug-and-display.md
@@ -0,0 +1,3 @@
+% Debug and Display
+
+Coming soon!
diff --git a/src/doc/trpl/dining-philosophers.md b/src/doc/trpl/dining-philosophers.md
index 7e37473..b1bea4f 100644
--- a/src/doc/trpl/dining-philosophers.md
+++ b/src/doc/trpl/dining-philosophers.md
@@ -2,28 +2,26 @@
For our second project, let’s look at a classic concurrency problem. It’s
called ‘the dining philosophers’. It was originally conceived by Dijkstra in
-1965, but we’ll use a lightly adapted version from [this paper][paper] by Tony
-Hoare in 1985.
+1965, but we’ll use the version from [this paper][paper] by Tony Hoare in 1985.
[paper]: http://www.usingcsp.com/cspbook.pdf
> In ancient times, a wealthy philanthropist endowed a College to accommodate
-> five eminent philosophers. Each philosopher had a room in which they could
-> engage in their professional activity of thinking; there was also a common
+> five eminent philosophers. Each philosopher had a room in which he could
+> engage in his professional activity of thinking; there was also a common
> dining room, furnished with a circular table, surrounded by five chairs, each
> labelled by the name of the philosopher who was to sit in it. They sat
> anticlockwise around the table. To the left of each philosopher there was
> laid a golden fork, and in the centre stood a large bowl of spaghetti, which
-> was constantly replenished. A philosopher was expected to spend most of
-> their time thinking; but when they felt hungry, they went to the dining
-> room, sat down in their own chair, picked up their own fork on their left,
-> and plunged it into the spaghetti. But such is the tangled nature of
-> spaghetti that a second fork is required to carry it to the mouth. The
-> philosopher therefore had also to pick up the fork on their right. When
-> they were finished they would put down both their forks, get up from their
-> chair, and continue thinking. Of course, a fork can be used by only one
-> philosopher at a time. If the other philosopher wants it, they just have
-> to wait until the fork is available again.
+> was constantly replenished. A philosopher was expected to spend most of his
+> time thinking; but when he felt hungry, he went to the dining room, sat down
+> in his own chair, picked up his own fork on his left, and plunged it into the
+> spaghetti. But such is the tangled nature of spaghetti that a second fork is
+> required to carry it to the mouth. The philosopher therefore had also to pick
+> up the fork on his right. When we was finished he would put down both his
+> forks, get up from his chair, and continue thinking. Of course, a fork can be
+> used by only one philosopher at a time. If the other philosopher wants it, he
+> just has to wait until the fork is available again.
This classic problem shows off a few different elements of concurrency. The
reason is that it's actually slightly tricky to implement: a simple
@@ -62,10 +60,10 @@ impl Philosopher {
}
fn main() {
- let p1 = Philosopher::new("Judith Butler");
+ let p1 = Philosopher::new("Baruch Spinoza");
let p2 = Philosopher::new("Gilles Deleuze");
let p3 = Philosopher::new("Karl Marx");
- let p4 = Philosopher::new("Emma Goldman");
+ let p4 = Philosopher::new("Friedrich Nietzsche");
let p5 = Philosopher::new("Michel Foucault");
}
```
@@ -75,9 +73,6 @@ a name is all we need. We choose the [`String`][string] type for the name,
rather than `&str`. Generally speaking, working with a type which owns its
data is easier than working with one that uses references.
-[struct]: structs.html
-[string]: strings.html
-
Let’s continue:
```rust
@@ -161,10 +156,10 @@ look at `main()` again:
# }
#
fn main() {
- let p1 = Philosopher::new("Judith Butler");
+ let p1 = Philosopher::new("Baruch Spinoza");
let p2 = Philosopher::new("Gilles Deleuze");
let p3 = Philosopher::new("Karl Marx");
- let p4 = Philosopher::new("Emma Goldman");
+ let p4 = Philosopher::new("Friedrich Nietzsche");
let p5 = Philosopher::new("Michel Foucault");
}
```
@@ -178,10 +173,10 @@ that `new()` function, it would look like this:
# name: String,
# }
fn main() {
- let p1 = Philosopher { name: "Judith Butler".to_string() };
+ let p1 = Philosopher { name: "Baruch Spinoza".to_string() };
let p2 = Philosopher { name: "Gilles Deleuze".to_string() };
let p3 = Philosopher { name: "Karl Marx".to_string() };
- let p4 = Philosopher { name: "Emma Goldman".to_string() };
+ let p4 = Philosopher { name: "Friedrich Nietzche".to_string() };
let p5 = Philosopher { name: "Michel Foucault".to_string() };
}
```
@@ -213,10 +208,10 @@ impl Philosopher {
fn main() {
let philosophers = vec![
- Philosopher::new("Judith Butler"),
+ Philosopher::new("Baruch Spinoza"),
Philosopher::new("Gilles Deleuze"),
Philosopher::new("Karl Marx"),
- Philosopher::new("Emma Goldman"),
+ Philosopher::new("Friedrich Nietzsche"),
Philosopher::new("Michel Foucault"),
];
@@ -249,10 +244,10 @@ mention they’re done eating. Running this program should give you the followin
output:
```text
-Judith Butler is done eating.
+Baruch Spinoza is done eating.
Gilles Deleuze is done eating.
Karl Marx is done eating.
-Emma Goldman is done eating.
+Friedrich Nietzsche is done eating.
Michel Foucault is done eating.
```
@@ -287,10 +282,10 @@ impl Philosopher {
fn main() {
let philosophers = vec![
- Philosopher::new("Judith Butler"),
+ Philosopher::new("Baruch Spinoza"),
Philosopher::new("Gilles Deleuze"),
Philosopher::new("Karl Marx"),
- Philosopher::new("Emma Goldman"),
+ Philosopher::new("Friedrich Nietzsche"),
Philosopher::new("Michel Foucault"),
];
@@ -322,17 +317,17 @@ from the standard library, and so we need to `use` it.
We now print out two messages, with a `sleep_ms()` in the middle. This will
simulate the time it takes a philosopher to eat.
-If you run this program, you should see each philosopher eat in turn:
+If you run this program, You should see each philosopher eat in turn:
```text
-Judith Butler is eating.
-Judith Butler is done eating.
+Baruch Spinoza is eating.
+Baruch Spinoza is done eating.
Gilles Deleuze is eating.
Gilles Deleuze is done eating.
Karl Marx is eating.
Karl Marx is done eating.
-Emma Goldman is eating.
-Emma Goldman is done eating.
+Friedrich Nietzsche is eating.
+Friedrich Nietzsche is done eating.
Michel Foucault is eating.
Michel Foucault is done eating.
```
@@ -368,10 +363,10 @@ impl Philosopher {
fn main() {
let philosophers = vec![
- Philosopher::new("Judith Butler"),
+ Philosopher::new("Baruch Spinoza"),
Philosopher::new("Gilles Deleuze"),
Philosopher::new("Karl Marx"),
- Philosopher::new("Emma Goldman"),
+ Philosopher::new("Friedrich Nietzsche"),
Philosopher::new("Michel Foucault"),
];
@@ -398,7 +393,7 @@ let handles: Vec<_> = philosophers.into_iter().map(|p| {
}).collect();
```
-While this is only five lines, they’re a dense five. Let’s break it down.
+While this is only five lines, they’re a dense four. Let’s break it down.
```rust,ignore
let handles: Vec<_> =
@@ -455,16 +450,16 @@ which blocks execution until the thread has completed execution. This ensures
that the threads complete their work before the program exits.
If you run this program, you’ll see that the philosophers eat out of order!
-We have multi-threading!
+We have mult-threading!
```text
Gilles Deleuze is eating.
Gilles Deleuze is done eating.
-Emma Goldman is eating.
-Emma Goldman is done eating.
+Friedrich Nietzsche is eating.
+Friedrich Nietzsche is done eating.
Michel Foucault is eating.
-Judith Butler is eating.
-Judith Butler is done eating.
+Baruch Spinoza is eating.
+Baruch Spinoza is done eating.
Karl Marx is eating.
Karl Marx is done eating.
Michel Foucault is done eating.
@@ -482,7 +477,7 @@ struct Table {
}
```
-This `Table` has a vector of `Mutex`es. A mutex is a way to control
+This `Table` has an vector of `Mutex`es. A mutex is a way to control
concurrency: only one thread can access the contents at once. This is exactly
the property we need with our forks. We use an empty tuple, `()`, inside the
mutex, since we’re not actually going to use the value, just hold onto it.
@@ -534,10 +529,10 @@ fn main() {
]});
let philosophers = vec![
- Philosopher::new("Judith Butler", 0, 1),
+ Philosopher::new("Baruch Spinoza", 0, 1),
Philosopher::new("Gilles Deleuze", 1, 2),
Philosopher::new("Karl Marx", 2, 3),
- Philosopher::new("Emma Goldman", 3, 4),
+ Philosopher::new("Friedrich Nietzsche", 3, 4),
Philosopher::new("Michel Foucault", 0, 4),
];
@@ -645,10 +640,10 @@ count will go up, and when each thread ends, it will go back down.
```rust,ignore
let philosophers = vec![
- Philosopher::new("Judith Butler", 0, 1),
+ Philosopher::new("Baruch Spinoza", 0, 1),
Philosopher::new("Gilles Deleuze", 1, 2),
Philosopher::new("Karl Marx", 2, 3),
- Philosopher::new("Emma Goldman", 3, 4),
+ Philosopher::new("Friedrich Nietzsche", 3, 4),
Philosopher::new("Michel Foucault", 0, 4),
];
```
@@ -681,12 +676,12 @@ and so you’ll get some output like this:
```text
Gilles Deleuze is eating.
-Emma Goldman is eating.
-Emma Goldman is done eating.
+Friedrich Nietzsche is eating.
+Friedrich Nietzsche is done eating.
Gilles Deleuze is done eating.
-Judith Butler is eating.
+Baruch Spinoza is eating.
Karl Marx is eating.
-Judith Butler is done eating.
+Baruch Spinoza is done eating.
Michel Foucault is eating.
Karl Marx is done eating.
Michel Foucault is done eating.
diff --git a/src/doc/trpl/documentation.md b/src/doc/trpl/documentation.md
index 53754e2..b28343e 100644
--- a/src/doc/trpl/documentation.md
+++ b/src/doc/trpl/documentation.md
@@ -42,7 +42,7 @@ Documentation comments are written in Markdown.
Rust keeps track of these comments, and uses them when generating
documentation. This is important when documenting things like enums:
-```rust
+```
/// The `Option` type. See [the module level documentation](../) for more.
enum Option<T> {
/// No value
@@ -80,7 +80,7 @@ thing after that last comment.
Anyway, let's cover each part of this comment in detail:
-```rust
+```
/// Constructs a new `Rc<T>`.
# fn foo() {}
```
@@ -88,7 +88,7 @@ Anyway, let's cover each part of this comment in detail:
The first line of a documentation comment should be a short summary of its
functionality. One sentence. Just the basics. High level.
-```rust
+```
///
/// Other details about constructing `Rc<T>`s, maybe describing complicated
/// semantics, maybe additional options, all kinds of stuff.
@@ -101,7 +101,7 @@ we could have added more explanation in a new paragraph.
#### Special sections
-```rust
+```
/// # Examples
# fn foo() {}
```
@@ -110,7 +110,7 @@ Next, are special sections. These are indicated with a header, `#`. There
are three kinds of headers that are commonly used. They aren't special syntax,
just convention, for now.
-```rust
+```
/// # Panics
# fn foo() {}
```
@@ -120,7 +120,7 @@ usually indicated by panics, which kill the whole current thread at the very
least. If your function has a non-trivial contract like this, that is
detected/enforced by panics, documenting it is very important.
-```rust
+```
/// # Failures
# fn foo() {}
```
@@ -130,7 +130,7 @@ conditions under which it returns `Err(E)` is a nice thing to do. This is
slightly less important than `Panics`, because failure is encoded into the type
system, but it's still a good thing to do.
-```rust
+```
/// # Safety
# fn foo() {}
```
@@ -138,7 +138,7 @@ system, but it's still a good thing to do.
If your function is `unsafe`, you should explain which invariants the caller is
responsible for upholding.
-```rust
+```
/// # Examples
///
/// ```
@@ -154,7 +154,7 @@ method, and your users will love you for it. These examples go inside of
code block annotations, which we'll talk about in a moment, and can have
more than one section:
-```rust
+```
/// # Examples
///
/// Simple `&str` patterns:
@@ -179,7 +179,7 @@ Let's discuss the details of these code blocks.
To write some Rust code in a comment, use the triple graves:
-```rust
+```
/// ```
/// println!("Hello, world");
/// ```
@@ -188,7 +188,7 @@ To write some Rust code in a comment, use the triple graves:
If you want something that's not Rust code, you can add an annotation:
-```rust
+```
/// ```c
/// printf("Hello, world\n");
/// ```
@@ -208,7 +208,7 @@ generate the documentation.
Let's discuss our sample example documentation:
-```rust
+```
/// ```
/// println!("Hello, world");
/// ```
@@ -219,7 +219,7 @@ You'll notice that you don't need a `fn main()` or anything here. `rustdoc` will
automatically add a main() wrapper around your code, and in the right place.
For example:
-```rust
+```
/// ```
/// use std::rc::Rc;
///
@@ -230,7 +230,7 @@ For example:
This will end up testing:
-```rust
+```
fn main() {
use std::rc::Rc;
let five = Rc::new(5);
@@ -259,7 +259,7 @@ with `///` we've been talking about? The raw text:
looks different than the output:
-```rust
+```
/// Some documentation.
# fn foo() {}
```
@@ -274,7 +274,7 @@ it makes the example more clear. You can use this technique to explain
longer examples in detail, while still preserving the testability of your
documentation. For example, this code:
-```rust
+```
let x = 5;
let y = 6;
println!("{}", x + y);
@@ -284,7 +284,7 @@ Here's an explanation, rendered:
First, we set `x` to five:
-```rust
+```
let x = 5;
# let y = 6;
# println!("{}", x + y);
@@ -292,7 +292,7 @@ let x = 5;
Next, we set `y` to six:
-```rust
+```
# let x = 5;
let y = 6;
# println!("{}", x + y);
@@ -300,7 +300,7 @@ let y = 6;
Finally, we print the sum of `x` and `y`:
-```rust
+```
# let x = 5;
# let y = 6;
println!("{}", x + y);
@@ -340,7 +340,7 @@ explanation.
Here’s an example of documenting a macro:
-```rust
+```
/// Panic with a given message unless an expression evaluates to true.
///
/// # Examples
@@ -388,7 +388,7 @@ but with a binary, there’s nothing to link to.
There are a few more annotations that are useful to help `rustdoc` do the right
thing when testing your code:
-```rust
+```
/// ```ignore
/// fn foo() {
/// ```
@@ -400,7 +400,7 @@ what you want, as it's the most generic. Instead, consider annotating it
with `text` if it's not code, or using `#`s to get a working example that
only shows the part you care about.
-```rust
+```
/// ```should_panic
/// assert!(false);
/// ```
@@ -410,7 +410,7 @@ only shows the part you care about.
`should_panic` tells `rustdoc` that the code should compile correctly, but
not actually pass as a test.
-```rust
+```
/// ```no_run
/// loop {
/// println!("Hello, world");
@@ -427,7 +427,7 @@ which you would want to make sure compile, but might run in an infinite loop!
Rust has another kind of doc comment, `//!`. This comment doesn't document the next item, but the enclosing item. In other words:
-```rust
+```
mod foo {
//! This is documentation for the `foo` module.
//!
@@ -440,7 +440,7 @@ mod foo {
This is where you'll see `//!` used most often: for module documentation. If
you have a module in `foo.rs`, you'll often open its code and see this:
-```rust
+```
//! A module for using `foo`s.
//!
//! The `foo` module contains a lot of useful functionality blah blah blah
@@ -461,7 +461,7 @@ are written in Markdown, they're often `.md` files.
When you write documentation in Markdown files, you don't need to prefix
the documentation with comments. For example:
-```rust
+```
/// # Examples
///
/// ```
@@ -499,7 +499,7 @@ This `%` line needs to be the very first line of the file.
At a deeper level, documentation comments are sugar for documentation attributes:
-```rust
+```
/// this
# fn foo() {}
@@ -509,7 +509,7 @@ At a deeper level, documentation comments are sugar for documentation attributes
are the same, as are these:
-```rust
+```
//! this
#![doc="/// this"]
@@ -546,10 +546,10 @@ pub use foo::bar;
You can control a few aspects of the HTML that `rustdoc` generates through the
`#![doc]` version of the attribute:
-```rust
+```
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
- html_root_url = "http://doc.rust-lang.org/")]
+ html_root_url = "http://doc.rust-lang.org/")];
```
This sets a few different options, with a logo, favicon, and a root URL.
diff --git a/src/doc/trpl/enums.md b/src/doc/trpl/enums.md
index 01905ca..ad15d19 100644
--- a/src/doc/trpl/enums.md
+++ b/src/doc/trpl/enums.md
@@ -55,6 +55,9 @@ fn process_color_change(msg: Message) {
}
```
+Both variants are named `Digit`, but since they’re scoped to the `enum` name
+there's no ambiguity.
+
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
@@ -63,4 +66,3 @@ equality yet, but we’ll find out in the [`traits`][traits] section.
[match]: match.html
[if-let]: if-let.html
-[traits]: traits.html
diff --git a/src/doc/trpl/error-handling.md b/src/doc/trpl/error-handling.md
index 7b47559..b368996 100644
--- a/src/doc/trpl/error-handling.md
+++ b/src/doc/trpl/error-handling.md
@@ -49,7 +49,7 @@ We use `assert!` to declare that something is true. If it's not true, something
is very wrong. Wrong enough that we can't continue with things in the current
state. Another example is using the `unreachable!()` macro:
-```rust,ignore
+```{rust,ignore}
enum Event {
NewRelease,
}
@@ -181,14 +181,12 @@ match version {
This function makes use of an enum, `ParseError`, to enumerate the various
errors that can occur.
-The [`Debug`](../std/fmt/trait.Debug.html) trait is what lets us print the enum value using the `{:?}` format operation.
-
# Non-recoverable errors with `panic!`
In the case of an error that is unexpected and not recoverable, the `panic!`
macro will induce a panic. This will crash the current thread, and give an error:
-```rust,ignore
+```{rust,ignore}
panic!("boom");
```
@@ -212,7 +210,7 @@ handle and possibly recover from error.
If we don't want to handle this error, and would rather just abort the program,
we can use the `unwrap()` method:
-```rust,ignore
+```{rust,ignore}
io::stdin().read_line(&mut buffer).unwrap();
```
@@ -223,7 +221,7 @@ shorter. Sometimes, just crashing is appropriate.
There's another way of doing this that's a bit nicer than `unwrap()`:
-```rust,ignore
+```{rust,ignore}
let mut buffer = String::new();
let input = io::stdin().read_line(&mut buffer)
.ok()
diff --git a/src/doc/trpl/ffi.md b/src/doc/trpl/ffi.md
index 9ede835..2c5e6b2 100644
--- a/src/doc/trpl/ffi.md
+++ b/src/doc/trpl/ffi.md
@@ -81,7 +81,7 @@ vectors as pointers to memory. Rust's vectors are guaranteed to be a contiguous
length is number of elements currently contained, and the capacity is the total size in elements of
the allocated memory. The length is less than or equal to the capacity.
-```rust
+```
# #![feature(libc)]
# extern crate libc;
# use libc::{c_int, size_t};
@@ -106,7 +106,7 @@ required capacity to hold the compressed output. The vector can then be passed t
`snappy_compress` function as an output parameter. An output parameter is also passed to retrieve
the true length after compression for setting the length.
-```rust
+```
# #![feature(libc)]
# extern crate libc;
# use libc::{size_t, c_int};
@@ -133,7 +133,7 @@ pub fn compress(src: &[u8]) -> Vec<u8> {
Decompression is similar, because snappy stores the uncompressed size as part of the compression
format and `snappy_uncompressed_length` will retrieve the exact buffer size required.
-```rust
+```
# #![feature(libc)]
# extern crate libc;
# use libc::{size_t, c_int};
@@ -375,7 +375,7 @@ the compiler that the unsafety does not leak out of the block.
Unsafe functions, on the other hand, advertise it to the world. An unsafe function is written like
this:
-```rust
+```
unsafe fn kaboom(ptr: *const i32) -> i32 { *ptr }
```
@@ -439,7 +439,7 @@ Most foreign code exposes a C ABI, and Rust uses the platform's C calling conven
calling foreign functions. Some foreign functions, most notably the Windows API, use other calling
conventions. Rust provides a way to tell the compiler which convention to use:
-```rust
+```
# #![feature(libc)]
extern crate libc;
@@ -516,7 +516,7 @@ function pointer using the C ABI.
You may wish to compile Rust code in a way so that it can be called from C. This is
fairly easy, but requires a few things:
-```rust
+```
#[no_mangle]
pub extern fn hello_rust() -> *const u8 {
"Hello, world!\0".as_ptr()
diff --git a/src/doc/trpl/functions.md b/src/doc/trpl/functions.md
index 21a29f0..87af485 100644
--- a/src/doc/trpl/functions.md
+++ b/src/doc/trpl/functions.md
@@ -146,7 +146,7 @@ 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 `()`:
-```rust
+```
let mut y = 5;
let x = (y = 6); // x has the value `()`, not `6`
@@ -204,7 +204,7 @@ time.
Rust has some special syntax for ‘diverging functions’, which are functions that
do not return:
-```rust
+```
fn diverges() -> ! {
panic!("This function never returns!");
}
diff --git a/src/doc/trpl/generics.md b/src/doc/trpl/generics.md
index f8f1962..517a6e6 100644
--- a/src/doc/trpl/generics.md
+++ b/src/doc/trpl/generics.md
@@ -110,7 +110,7 @@ Generic functions are most useful with ‘trait bounds’, which we’ll cover i
You can store a generic type in a `struct` as well:
-```rust
+```
struct Point<T> {
x: T,
y: T,
diff --git a/src/doc/trpl/guessing-game.md b/src/doc/trpl/guessing-game.md
index 41d4146..e5702ed 100644
--- a/src/doc/trpl/guessing-game.md
+++ b/src/doc/trpl/guessing-game.md
@@ -27,7 +27,7 @@ Check out the generated `Cargo.toml`:
[package]
name = "guessing_game"
-version = "0.1.0"
+version = "0.0.1"
authors = ["Your Name <you@example.com>"]
```
@@ -46,7 +46,7 @@ Let’s try compiling what Cargo gave us:
```{bash}
$ cargo build
- Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
+ Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
```
Excellent! Open up your `src/main.rs` again. We’ll be writing all of
@@ -58,7 +58,7 @@ Try it out:
```bash
$ cargo run
- Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
+ Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
Running `target/debug/guessing_game`
Hello, world!
```
@@ -148,10 +148,10 @@ a few tricks up their sleeves.
For example, they’re [immutable][immutable] by default. That’s why our example
uses `mut`: it makes a binding mutable, rather than immutable. `let` doesn’t
take a name on the left hand side, it actually accepts a
-‘[pattern][patterns]’. We’ll use patterns later. It’s easy enough
+‘[pattern][patterns]’. We’ll use patterns more later. It’s easy enough
to use for now:
-```rust
+```
let foo = 5; // immutable.
let mut bar = 5; // mutable
```
@@ -213,12 +213,12 @@ The next part will use this handle to get input from the user:
```
Here, we call the [`read_line()`][read_line] method on our handle.
-[Methods][method] are like associated functions, but are only available on a
+[Method][method]s are like associated functions, but are only available on a
particular instance of a type, rather than the type itself. We’re also passing
one argument to `read_line()`: `&mut guess`.
[read_line]: ../std/io/struct.Stdin.html#method.read_line
-[method]: method-syntax.html
+[method]: methods.html
Remember how we bound `guess` above? We said it was mutable. However,
`read_line` doesn’t take a `String` as an argument: it takes a `&mut String`.
@@ -637,7 +637,7 @@ When we wrote `let guess = String::new()`, Rust was able to infer that `guess`
should be a `String`, and so it doesn’t make us write out the type. And with
our `secret_number`, there are a number of types which can have a value
between one and a hundred: `i32`, a thirty-two-bit number, or `u32`, an
-unsigned thirty-two-bit number, or `i64`, a sixty-four-bit number or others.
+unsigned thirty-two-bit number, or `i64`, a sixty-four-bit number. Or others.
So far, that hasn’t mattered, and so Rust defaults to an `i32`. However, here,
Rust doesn’t know how to compare the `guess` and the `secret_number`. They
need to be the same type. Ultimately, we want to convert the `String` we
@@ -727,7 +727,7 @@ Let’s try our program out!
```bash
$ cargo run
- Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
+ Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
Running `target/guessing_game`
Guess the number!
The secret number is: 58
@@ -792,7 +792,7 @@ and quit. Observe:
```bash
$ cargo run
- Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
+ Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
Running `target/guessing_game`
Guess the number!
The secret number is: 59
@@ -929,7 +929,7 @@ Now we should be good! Let’s try:
```bash
$ cargo run
- Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)
+ Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
Running `target/guessing_game`
Guess the number!
The secret number is: 61
diff --git a/src/doc/trpl/inline-assembly.md b/src/doc/trpl/inline-assembly.md
index 4d9166d..58c2a98 100644
--- a/src/doc/trpl/inline-assembly.md
+++ b/src/doc/trpl/inline-assembly.md
@@ -25,7 +25,7 @@ crate to allow) and of course requires an `unsafe` block.
The `assembly template` is the only required parameter and must be a
literal string (i.e. `""`)
-```rust
+```
#![feature(asm)]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
@@ -51,7 +51,7 @@ fn main() {
Output operands, input operands, clobbers and options are all optional
but you must add the right number of `:` if you skip them:
-```rust
+```
# #![feature(asm)]
# #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
# fn main() { unsafe {
@@ -65,7 +65,7 @@ asm!("xor %eax, %eax"
Whitespace also doesn't matter:
-```rust
+```
# #![feature(asm)]
# #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
# fn main() { unsafe {
@@ -79,7 +79,7 @@ Input and output operands follow the same format: `:
"constraints1"(expr1), "constraints2"(expr2), ..."`. Output operand
expressions must be mutable lvalues, or not yet assigned:
-```rust
+```
# #![feature(asm)]
# #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn add(a: i32, b: i32) -> i32 {
@@ -106,7 +106,7 @@ you want, and you are required to put the specific size of the
operand. This is useful for very low level programming, where
which register you use is important:
-```rust
+```
# #![feature(asm)]
# #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
# unsafe fn read_byte_in(port: u16) -> u8 {
@@ -123,7 +123,7 @@ different values so we use the clobbers list to indicate to the
compiler not to assume any values loaded into those registers will
stay valid.
-```rust
+```
# #![feature(asm)]
# #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
# fn main() { unsafe {
@@ -155,7 +155,7 @@ Current valid options are:
the compiler to insert its usual stack alignment code
3. *intel* - use intel syntax instead of the default AT&T.
-```rust
+```
# #![feature(asm)]
# #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
# fn main() {
diff --git a/src/doc/trpl/installing-rust.md b/src/doc/trpl/installing-rust.md
index cc1ffdd..b8230f0 100644
--- a/src/doc/trpl/installing-rust.md
+++ b/src/doc/trpl/installing-rust.md
@@ -23,8 +23,8 @@ $ sh rustup.sh
If you're on Windows, please download either the [32-bit installer][win32] or
the [64-bit installer][win64] and run it.
-[win32]: https://static.rust-lang.org/dist/rust-1.0.0-i686-pc-windows-gnu.msi
-[win64]: https://static.rust-lang.org/dist/rust-1.0.0-x86_64-pc-windows-gnu.msi
+[win32]: https://static.rust-lang.org/dist/rust-1.0.0-beta-i686-pc-windows-gnu.msi
+[win64]: https://static.rust-lang.org/dist/rust-1.0.0-beta-x86_64-pc-windows-gnu.msi
## Uninstalling
@@ -43,11 +43,11 @@ Some people, and somewhat rightfully so, get very upset when we tell you to
`curl | sh`. Basically, when you do this, you are trusting that the good
people who maintain Rust aren't going to hack your computer and do bad things.
That's a good instinct! If you're one of those people, please check out the
-documentation on [building Rust from Source][from-source], or [the official
-binary downloads][install-page].
+documentation on [building Rust from Source][from source], or [the official
+binary downloads][install page].
-[from-source]: https://github.com/rust-lang/rust#building-from-source
-[install-page]: http://www.rust-lang.org/install.html
+[from source]: https://github.com/rust-lang/rust#building-from-source
+[install page]: http://www.rust-lang.org/install.html
Oh, we should also mention the officially supported platforms:
@@ -74,7 +74,7 @@ $ rustc --version
You should see the version number, commit hash, commit date and build date:
```bash
-rustc 1.0.0 (a59de37e9 2015-05-13) (built 2015-05-14)
+rustc 1.0.0-beta (9854143cb 2015-04-02) (built 2015-04-02)
```
If you did, Rust has been installed successfully! Congrats!
diff --git a/src/doc/trpl/intrinsics.md b/src/doc/trpl/intrinsics.md
index e0a8bb5..25f7c54 100644
--- a/src/doc/trpl/intrinsics.md
+++ b/src/doc/trpl/intrinsics.md
@@ -10,7 +10,7 @@ context, but wished to be able to `transmute` between types, and
perform efficient pointer arithmetic, one would import those functions
via a declaration like
-```rust
+```
# #![feature(intrinsics)]
# fn main() {}
diff --git a/src/doc/trpl/iterators.md b/src/doc/trpl/iterators.md
index 80c0def..e0cc45c 100644
--- a/src/doc/trpl/iterators.md
+++ b/src/doc/trpl/iterators.md
@@ -42,7 +42,7 @@ 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. Before we talk about those, we should talk about a
+to accomplish various threads. Before we talk about those, we should talk about a
Rust anti-pattern. And that's using ranges like this.
Yes, we just talked about how ranges are cool. But ranges are also very
@@ -116,7 +116,7 @@ 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
+```{rust,ignore}
let one_to_one_hundred = (1..101).collect();
```
@@ -253,7 +253,7 @@ we need to talk about with regards to iterators. Let's get to it!
*Iterator adapters* take an iterator and modify it somehow, producing
a new iterator. The simplest one is called `map`:
-```rust,ignore
+```{rust,ignore}
(1..100).map(|x| x + 1);
```
@@ -272,7 +272,7 @@ warning: unused result which must be used: iterator adaptors are lazy and
Laziness strikes again! That closure will never execute. This example
doesn't print any numbers:
-```rust,ignore
+```{rust,ignore}
(1..100).map(|x| println!("{}", x));
```
diff --git a/src/doc/trpl/lang-items.md b/src/doc/trpl/lang-items.md
index 8e7504c..4808ad6 100644
--- a/src/doc/trpl/lang-items.md
+++ b/src/doc/trpl/lang-items.md
@@ -15,7 +15,7 @@ For example, `Box` pointers require two lang items, one for allocation
and one for deallocation. A freestanding program that uses the `Box`
sugar for dynamic allocations via `malloc` and `free`:
-```rust
+```
#![feature(lang_items, box_syntax, start, no_std, libc)]
#![no_std]
diff --git a/src/doc/trpl/lifetimes.md b/src/doc/trpl/lifetimes.md
index 0039f90..342de41 100644
--- a/src/doc/trpl/lifetimes.md
+++ b/src/doc/trpl/lifetimes.md
@@ -219,7 +219,7 @@ 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
+forbidden in item signatures to allow reasoning about the types just based in
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
diff --git a/src/doc/trpl/macros.md b/src/doc/trpl/macros.md
index 9c883ef..d504fab 100644
--- a/src/doc/trpl/macros.md
+++ b/src/doc/trpl/macros.md
@@ -30,8 +30,8 @@ mind.
# Defining a macro
-You may have seen the `vec!` macro, used to initialize a [vector][vector] with
-any number of elements.
+You may have seen the `vec!` macro, used to initialize a [vector][] with any
+number of elements.
[vector]: vectors.html
@@ -349,7 +349,7 @@ fn main() {
}
```
-This holds for `let` bindings and loop labels, but not for [items][items].
+This holds for `let` bindings and loop labels, but not for [items][].
So the following code does compile:
```rust
@@ -470,15 +470,15 @@ which syntactic form it matches.
* `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;`.
+* `item`: an [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: `=> , =`
+* `expr` variables must be followed by one of: `=> , ;`
+* `ty` and `path` variables must be followed by one of: `=> , : = > as`
+* `pat` variables must be followed by one of: `=> , =`
* Other variables may be followed by any token.
These rules provide some flexibility for Rust’s syntax to evolve without
@@ -683,9 +683,9 @@ 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:
+These two macros are used in tests. `assert!` takes a boolean, and `assert_eq!`
+takes two values and compares them. Truth passes, success `panic!`s. Like
+this:
```rust,no_run
// A-ok!
@@ -698,7 +698,6 @@ assert_eq!(5, 3 + 2);
assert!(5 < 3);
assert_eq!(5, 3);
```
-
## try!
`try!` is used for error handling. It takes something that can return a
diff --git a/src/doc/trpl/match.md b/src/doc/trpl/match.md
index 113e218..2bb2359 100644
--- a/src/doc/trpl/match.md
+++ b/src/doc/trpl/match.md
@@ -97,4 +97,4 @@ Unlike the previous uses of `match`, you can’t use the normal `if`
statement to do this. You can use the [`if let`][if-let] statement,
which can be seen as an abbreviated form of `match`.
-[if-let]: if-let.html
+[if-let][if-let.html]
diff --git a/src/doc/trpl/method-syntax.md b/src/doc/trpl/method-syntax.md
index e5f490e..1527d9c 100644
--- a/src/doc/trpl/method-syntax.md
+++ b/src/doc/trpl/method-syntax.md
@@ -89,7 +89,7 @@ So, now we know how to call a method, such as `foo.bar()`. But what about our
original example, `foo.bar().baz()`? This is called ‘method chaining’, and we
can do it by returning `self`.
-```rust
+```
struct Circle {
x: f64,
y: f64,
@@ -117,7 +117,7 @@ fn main() {
Check the return type:
-```rust
+```
# struct Circle;
# impl Circle {
fn grow(&self) -> Circle {
@@ -156,7 +156,7 @@ fn main() {
This ‘associated function’ builds a new `Circle` for us. Note that associated
functions are called with the `Struct::function()` syntax, rather than the
-`ref.method()` syntax. Some other languages call associated functions ‘static
+`ref.method()` syntax. Some other langauges call associated functions ‘static
methods’.
# Builder Pattern
@@ -167,7 +167,7 @@ and `y` attributes will be `0.0`, and the `radius` will be `1.0`. Rust doesn’t
have method overloading, named arguments, or variable arguments. We employ
the builder pattern instead. It looks like this:
-```rust
+```
struct Circle {
x: f64,
y: f64,
diff --git a/src/doc/trpl/move-semantics.md b/src/doc/trpl/move-semantics.md
new file mode 100644
index 0000000..6917d7f
--- /dev/null
+++ b/src/doc/trpl/move-semantics.md
@@ -0,0 +1,3 @@
+% Move Semantics
+
+Coming Soon
diff --git a/src/doc/trpl/mutability.md b/src/doc/trpl/mutability.md
index fe41def..674d659 100644
--- a/src/doc/trpl/mutability.md
+++ b/src/doc/trpl/mutability.md
@@ -35,7 +35,7 @@ let y = &mut x;
`y` is an immutable binding to a mutable reference, which means that you can’t
bind `y` to something else (`y = &mut z`), but you can mutate the thing that’s
-bound to `y` (`*y = 5`). A subtle distinction.
+bound to `y`. (`*y = 5`) A subtle distinction.
Of course, if you need both:
@@ -161,7 +161,7 @@ b.x = 10; // error: cannot assign to immutable field `b.x`
However, by using `Cell<T>`, you can emulate field-level mutability:
-```rust
+```
use std::cell::Cell;
struct Point {
diff --git a/src/doc/trpl/nightly-rust.md b/src/doc/trpl/nightly-rust.md
index c5aae5a..2f3055d 100644
--- a/src/doc/trpl/nightly-rust.md
+++ b/src/doc/trpl/nightly-rust.md
@@ -26,8 +26,8 @@ $ sh rustup.sh --channel=nightly
If you're on Windows, please download either the [32-bit installer][win32] or
the [64-bit installer][win64] and run it.
-[win32]: https://static.rust-lang.org/dist/rust-nightly-i686-pc-windows-gnu.msi
-[win64]: https://static.rust-lang.org/dist/rust-nightly-x86_64-pc-windows-gnu.msi
+[win32]: https://static.rust-lang.org/dist/rust-1.0.0-beta-i686-pc-windows-gnu.msi
+[win64]: https://static.rust-lang.org/dist/rust-1.0.0-beta-x86_64-pc-windows-gnu.msi
## Uninstalling
@@ -46,11 +46,11 @@ Some people, and somewhat rightfully so, get very upset when we tell you to
`curl | sh`. Basically, when you do this, you are trusting that the good
people who maintain Rust aren't going to hack your computer and do bad things.
That's a good instinct! If you're one of those people, please check out the
-documentation on [building Rust from Source][from-source], or [the official
-binary downloads][install-page].
+documentation on [building Rust from Source][from source], or [the official
+binary downloads][install page].
-[from-source]: https://github.com/rust-lang/rust#building-from-source
-[install-page]: http://www.rust-lang.org/install.html
+[from source]: https://github.com/rust-lang/rust#building-from-source
+[install page]: http://www.rust-lang.org/install.html
Oh, we should also mention the officially supported platforms:
@@ -91,9 +91,9 @@ If not, there are a number of places where you can get help. The easiest is
[the #rust IRC channel on irc.mozilla.org][irc], which you can access through
[Mibbit][mibbit]. Click that link, and you'll be chatting with other Rustaceans
(a silly nickname we call ourselves), and we can help you out. Other great
-resources include [the user’s forum][users], and [Stack Overflow][stackoverflow].
+resources include [the user’s forum][users], and [Stack Overflow][stack overflow].
[irc]: irc://irc.mozilla.org/#rust
[mibbit]: http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust
[users]: http://users.rust-lang.org/
-[stackoverflow]: http://stackoverflow.com/questions/tagged/rust
+[stack overflow]: http://stackoverflow.com/questions/tagged/rust
diff --git a/src/doc/trpl/no-stdlib.md b/src/doc/trpl/no-stdlib.md
index 0a98533..67db919 100644
--- a/src/doc/trpl/no-stdlib.md
+++ b/src/doc/trpl/no-stdlib.md
@@ -20,7 +20,7 @@ default shim for the C `main` function with your own.
The function marked `#[start]` is passed the command line parameters
in the same format as C:
-```rust
+```
#![feature(lang_items, start, no_std, libc)]
#![no_std]
diff --git a/src/doc/trpl/patterns.md b/src/doc/trpl/patterns.md
index 93df0f1..266c1ca 100644
--- a/src/doc/trpl/patterns.md
+++ b/src/doc/trpl/patterns.md
@@ -66,7 +66,7 @@ match x {
}
```
-This prints `something else`.
+This prints `something else`
# Bindings
@@ -152,7 +152,7 @@ match x {
}
```
-This prints `Got an int!`.
+This prints `Got an int!`
# ref and ref mut
diff --git a/src/doc/trpl/primitive-types.md b/src/doc/trpl/primitive-types.md
index 027909d..d3bf614 100644
--- a/src/doc/trpl/primitive-types.md
+++ b/src/doc/trpl/primitive-types.md
@@ -251,7 +251,7 @@ 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
```
@@ -283,7 +283,7 @@ documentation][tuple].
Functions also have a type! They look like this:
-```rust
+```
fn foo(x: i32) -> i32 { x }
let x: fn(i32) -> i32 = foo;
diff --git a/src/doc/trpl/references-and-borrowing.md b/src/doc/trpl/references-and-borrowing.md
index bb5adac..c434371 100644
--- a/src/doc/trpl/references-and-borrowing.md
+++ b/src/doc/trpl/references-and-borrowing.md
@@ -297,7 +297,7 @@ We can’t modify `v` because it’s borrowed by the loop.
References must live as long as 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
+If Rust didn’t check that this property, we could accidentally use a reference
which was invalid. For example:
```rust,ignore
diff --git a/src/doc/trpl/rust-inside-other-languages.md b/src/doc/trpl/rust-inside-other-languages.md
index 0a18607..a1ae50a 100644
--- a/src/doc/trpl/rust-inside-other-languages.md
+++ b/src/doc/trpl/rust-inside-other-languages.md
@@ -6,24 +6,24 @@ 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.
+its strengths make sense, and use a different language 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
+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
+the 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.
+some 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.
+with three examples, in Ruby, Python, and JavaScript.
[ffi]: ffi.html
@@ -40,18 +40,18 @@ 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
+Second, many languages have a ‘global interpreter lock’, 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
+uses these two aspects heavily. Since the focus of the example is the embedding
+of Rust into the 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!’.
+> 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:
@@ -69,7 +69,7 @@ threads = []
end
end
-threads.each { |t| t.join }
+threads.each {|t| t.join }
puts "done!"
```
@@ -82,12 +82,12 @@ 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
+that are similar to this in the real world. For our purposes, spinning up some
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
+Let’s re-write this problem in Rust. First, let’s make a new project with
Cargo:
```bash
@@ -104,7 +104,7 @@ fn process() {
let handles: Vec<_> = (0..10).map(|_| {
thread::spawn(|| {
let mut _x = 0;
- for _ in (0..5_000_000) {
+ for _ in (0..5_000_001) {
_x += 1
}
})
@@ -129,7 +129,7 @@ src/lib.rs:3 fn process() {
src/lib.rs:4 let handles: Vec<_> = (0..10).map(|_| {
src/lib.rs:5 thread::spawn(|| {
src/lib.rs:6 let mut x = 0;
-src/lib.rs:7 for _ in (0..5_000_000) {
+src/lib.rs:7 for _ in (0..5_000_001) {
src/lib.rs:8 x += 1
...
src/lib.rs:6:17: 6:22 warning: variable `x` is assigned to, but never used, #[warn(unused_variables)] on by default
@@ -151,7 +151,7 @@ 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:
+though. The first is modify the beginning of our code:
```rust,ignore
#[no_mangle]
@@ -161,7 +161,7 @@ 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
+know how to call the function, we need to not do that. This attribute turns
that behavior off.
The other change is the `pub extern`. The `pub` means that this function should
@@ -178,7 +178,7 @@ 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.
+library. By default, Rust compiles into an ‘rlib’, a Rust-specific format.
Let’s build the project now:
@@ -204,7 +204,7 @@ 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:
+Open up a `embed.rb` file inside of our project, and do this:
```ruby
require 'ffi'
@@ -217,7 +217,7 @@ end
Hello.process
-puts 'done!'
+puts "done!”
```
Before we can run this, we need to install the `ffi` gem:
@@ -241,7 +241,7 @@ done!
$
```
-Whoa, that was fast! On my system, this took `0.086` seconds, rather than
+Whoah, 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:
@@ -258,11 +258,11 @@ module Hello
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`.
+The `ffi` gem’s authors recommend using a module to scope the functions
+we’ll import 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
@@ -280,10 +280,10 @@ 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!
+a Ruby function, but is actually Rust!
```ruby
-puts 'done!'
+puts "done!"
```
Finally, as per our project’s requirements, we print out `done!`.
@@ -329,7 +329,7 @@ After that installs, we can use it:
var ffi = require('ffi');
var lib = ffi.Library('target/release/libembed', {
- 'process': ['void', []]
+ 'process': [ 'void', [] ]
});
lib.process();
@@ -340,7 +340,7 @@ 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
+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.
diff --git a/src/doc/trpl/static.md b/src/doc/trpl/static.md
new file mode 100644
index 0000000..b29c495
--- /dev/null
+++ b/src/doc/trpl/static.md
@@ -0,0 +1,3 @@
+% `static`
+
+Coming soon!
diff --git a/src/doc/trpl/strings.md b/src/doc/trpl/strings.md
index 5515403..61a6ec3 100644
--- a/src/doc/trpl/strings.md
+++ b/src/doc/trpl/strings.md
@@ -16,11 +16,11 @@ Rust has two main types of strings: `&str` and `String`. Let’s talk about
`&'static str`:
```rust
-let greeting = "Hello there."; // greeting: &'static str
+let string = "Hello there."; // string: &'static str
```
This string is statically allocated, meaning that it’s saved inside our
-compiled program, and exists for the entire duration it runs. The `greeting`
+compiled program, and exists for the entire duration it runs. The `string`
binding is a reference to this statically allocated string. String slices
have a fixed size, and cannot be mutated.
@@ -38,7 +38,7 @@ println!("{}", s);
`String`s will coerce into `&str` with an `&`:
-```rust
+```
fn takes_slice(slice: &str) {
println!("Got: {}", slice);
}
@@ -49,20 +49,6 @@ fn main() {
}
```
-This coercion does not happen for functions that accept one of `&str`’s traits
-instead of `&str`. For example, [`TcpStream::connect`][connect] has a parameter
-of type `ToSocketAddrs`. A `&str` is okay but a `String` must be explicitly
-converted using `&*`.
-
-```rust,no_run
-use std::net::TcpStream;
-
-TcpStream::connect("192.168.0.1:3000"); // &str parameter
-
-let addr_string = "192.168.0.1:3000".to_string();
-TcpStream::connect(&*addr_string); // convert addr_string to &str
-```
-
Viewing a `String` as a `&str` is cheap, but converting the `&str` to a
`String` involves allocating memory. No reason to do that unless you have to!
@@ -137,8 +123,7 @@ let world = "world!".to_string();
let hello_world = hello + &world;
```
-This is because `&String` can automatically coerce to a `&str`. This is a
+This is because `&String` can automatically coerece to a `&str`. This is a
feature called ‘[`Deref` coercions][dc]’.
[dc]: deref-coercions.html
-[connect]: ../std/net/struct.TcpStream.html#method.connect
diff --git a/src/doc/trpl/structs.md b/src/doc/trpl/structs.md
index 5729aee..ad7ead9 100644
--- a/src/doc/trpl/structs.md
+++ b/src/doc/trpl/structs.md
@@ -196,5 +196,3 @@ 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/doc/trpl/testing.md b/src/doc/trpl/testing.md
index 7595431..45f87a6 100644
--- a/src/doc/trpl/testing.md
+++ b/src/doc/trpl/testing.md
@@ -195,7 +195,7 @@ 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() {
@@ -205,7 +205,7 @@ fn it_works() {
That's all there is to the basics! Let's write one 'real' test:
-```rust,ignore
+```{rust,ignore}
pub fn add_two(a: i32) -> i32 {
a + 2
}
@@ -225,7 +225,7 @@ 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
+```{rust,ignore}
pub fn add_two(a: i32) -> i32 {
a + 2
}
@@ -253,7 +253,7 @@ 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 the `glob` feature. Let's change
our `src/lib.rs` to make use of it:
-```rust,ignore
+```{rust,ignore}
pub fn add_two(a: i32) -> i32 {
a + 2
@@ -302,7 +302,7 @@ 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
+```{rust,ignore}
extern crate adder;
#[test]
@@ -359,7 +359,7 @@ documentation has been written. To this end, Rust supports automatically
running examples in your documentation. Here's a fleshed-out `src/lib.rs`
with examples:
-```rust,ignore
+```{rust,ignore}
//! The `adder` crate provides functions that add numbers to other numbers.
//!
//! # Examples
diff --git a/src/doc/trpl/the-stack-and-the-heap.md b/src/doc/trpl/the-stack-and-the-heap.md
index 2c5f592..7b1cd7d 100644
--- a/src/doc/trpl/the-stack-and-the-heap.md
+++ b/src/doc/trpl/the-stack-and-the-heap.md
@@ -80,7 +80,7 @@ This memory is kind of like a giant array: addresses start at zero and go
up to the final number. So here’s a diagram of our first stack frame:
| Address | Name | Value |
-|---------|------|-------|
++---------+------+-------+
| 0 | x | 42 |
We’ve got `x` located at address `0`, with the value `42`.
@@ -88,7 +88,7 @@ We’ve got `x` located at address `0`, with the value `42`.
When `foo()` is called, a new stack frame is allocated:
| Address | Name | Value |
-|---------|------|-------|
++---------+------+-------+
| 2 | z | 100 |
| 1 | y | 5 |
| 0 | x | 42 |
@@ -107,7 +107,7 @@ value being stored.
After `foo()` is over, its frame is deallocated:
| Address | Name | Value |
-|---------|------|-------|
++---------+------+-------+
| 0 | x | 42 |
And then, after `main()`, even this last value goes away. Easy!
@@ -142,13 +142,13 @@ fn main() {
Okay, first, we call `main()`:
| Address | Name | Value |
-|---------|------|-------|
++---------+------+-------+
| 0 | x | 42 |
Next up, `main()` calls `foo()`:
| Address | Name | Value |
-|---------|------|-------|
++---------+------+-------+
| 3 | c | 1 |
| 2 | b | 100 |
| 1 | a | 5 |
@@ -157,7 +157,7 @@ Next up, `main()` calls `foo()`:
And then `foo()` calls `bar()`:
| Address | Name | Value |
-|---------|------|-------|
++---------+------+-------+
| 4 | i | 6 |
| 3 | c | 1 |
| 2 | b | 100 |
@@ -170,7 +170,7 @@ After `bar()` is over, its frame is deallocated, leaving just `foo()` and
`main()`:
| Address | Name | Value |
-|---------|------|-------|
++---------+------+-------+
| 3 | c | 1 |
| 2 | b | 100 |
| 1 | a | 5 |
@@ -179,7 +179,7 @@ After `bar()` is over, its frame is deallocated, leaving just `foo()` and
And then `foo()` ends, leaving just `main()`
| Address | Name | Value |
-|---------|------|-------|
++---------+------+-------+
| 0 | x | 42 |
And then we’re done. Getting the hang of it? It’s like piling up dishes: you
@@ -206,7 +206,7 @@ fn main() {
Here’s what happens in memory when `main()` is called:
| Address | Name | Value |
-|---------|------|--------|
++---------+------+--------+
| 1 | y | 42 |
| 0 | x | ?????? |
@@ -218,7 +218,7 @@ it allocates some memory for the heap, and puts `5` there. The memory now looks
like this:
| Address | Name | Value |
-|-----------------|------|----------------|
++-----------------+------+----------------+
| 2<sup>30</sup> | | 5 |
| ... | ... | ... |
| 1 | y | 42 |
@@ -243,7 +243,7 @@ layout of a program which has been running for a while now:
| Address | Name | Value |
-|----------------------|------|----------------------|
++----------------------+------+----------------------+
| 2<sup>30</sup> | | 5 |
| (2<sup>30</sup>) - 1 | | |
| (2<sup>30</sup>) - 2 | | |
@@ -266,20 +266,20 @@ Rust programs use [jemalloc][jemalloc] for this purpose.
Anyway, back to our example. Since this memory is on the heap, it can stay
alive longer than the function which allocates the box. In this case, however,
it doesn’t.[^moving] When the function is over, we need to free the stack frame
-for `main()`. `Box<T>`, though, has a trick up its sleeve: [Drop][drop]. The
+for `main()`. `Box<T>`, though, has a trick up its sleve: [Drop][drop]. The
implementation of `Drop` for `Box` deallocates the memory that was allocated
when it was created. Great! So when `x` goes away, it first frees the memory
allocated on the heap:
| Address | Name | Value |
-|---------|------|--------|
++---------+------+--------+
| 1 | y | 42 |
| 0 | x | ?????? |
[drop]: drop.html
-[^moving]: We can make the memory live longer by transferring ownership,
- sometimes called ‘moving out of the box’. More complex examples will
- be covered later.
+[moving]: We can make the memory live longer by transferring ownership,
+ sometimes called ‘moving out of the box’. More complex examples will
+ be covered later.
And then the stack frame goes away, freeing all of our memory.
@@ -305,7 +305,7 @@ fn main() {
When we enter `main()`, memory looks like this:
| Address | Name | Value |
-|---------|------|-------|
++---------+------+-------+
| 1 | y | 0 |
| 0 | x | 5 |
@@ -315,7 +315,7 @@ memory location that `x` lives at, which in this case is `0`.
What about when we call `foo()`, passing `y` as an argument?
| Address | Name | Value |
-|---------|------|-------|
++---------+------+-------+
| 3 | z | 42 |
| 2 | i | 0 |
| 1 | y | 0 |
@@ -367,7 +367,7 @@ fn main() {
First, we call `main()`:
| Address | Name | Value |
-|-----------------|------|----------------|
++-----------------+------+----------------+
| 2<sup>30</sup> | | 20 |
| ... | ... | ... |
| 2 | j | 0 |
@@ -380,7 +380,7 @@ value pointing there.
Next, at the end of `main()`, `foo()` gets called:
| Address | Name | Value |
-|-----------------|------|----------------|
++-----------------+------+----------------+
| 2<sup>30</sup> | | 20 |
| ... | ... | ... |
| 5 | z | 4 |
@@ -397,7 +397,7 @@ since `j` points at `h`.
Next, `foo()` calls `baz()`, passing `z`:
| Address | Name | Value |
-|-----------------|------|----------------|
++-----------------+------+----------------+
| 2<sup>30</sup> | | 20 |
| ... | ... | ... |
| 7 | g | 100 |
@@ -413,7 +413,7 @@ We’ve allocated memory for `f` and `g`. `baz()` is very short, so when it’s
over, we get rid of its stack frame:
| Address | Name | Value |
-|-----------------|------|----------------|
++-----------------+------+----------------+
| 2<sup>30</sup> | | 20 |
| ... | ... | ... |
| 5 | z | 4 |
@@ -426,11 +426,11 @@ over, we get rid of its stack frame:
Next, `foo()` calls `bar()` with `x` and `z`:
| Address | Name | Value |
-|----------------------|------|----------------------|
++----------------------+------+----------------------+
| 2<sup>30</sup> | | 20 |
| (2<sup>30</sup>) - 1 | | 5 |
| ... | ... | ... |
-| 10 | e | 9 |
+| 10 | e | 4 |
| 9 | d | (2<sup>30</sup>) - 1 |
| 8 | c | 5 |
| 7 | b | 4 |
@@ -449,13 +449,13 @@ case, we set up the variables as usual.
At the end of `bar()`, it calls `baz()`:
| Address | Name | Value |
-|----------------------|------|----------------------|
++----------------------+------+----------------------+
| 2<sup>30</sup> | | 20 |
| (2<sup>30</sup>) - 1 | | 5 |
| ... | ... | ... |
| 12 | g | 100 |
-| 11 | f | 9 |
-| 10 | e | 9 |
+| 11 | f | 4 |
+| 10 | e | 4 |
| 9 | d | (2<sup>30</sup>) - 1 |
| 8 | c | 5 |
| 7 | b | 4 |
@@ -473,11 +473,11 @@ far.
After `baz()` is over, we get rid of `f` and `g`:
| Address | Name | Value |
-|----------------------|------|----------------------|
++----------------------+------+----------------------+
| 2<sup>30</sup> | | 20 |
| (2<sup>30</sup>) - 1 | | 5 |
| ... | ... | ... |
-| 10 | e | 9 |
+| 10 | e | 4 |
| 9 | d | (2<sup>30</sup>) - 1 |
| 8 | c | 5 |
| 7 | b | 4 |
@@ -493,7 +493,7 @@ Next, we return from `bar()`. `d` in this case is a `Box<T>`, so it also frees
what it points to: (2<sup>30</sup>) - 1.
| Address | Name | Value |
-|-----------------|------|----------------|
++-----------------+------+----------------+
| 2<sup>30</sup> | | 20 |
| ... | ... | ... |
| 5 | z | 4 |
@@ -506,7 +506,7 @@ what it points to: (2<sup>30</sup>) - 1.
And after that, `foo()` returns:
| Address | Name | Value |
-|-----------------|------|----------------|
++-----------------+------+----------------+
| 2<sup>30</sup> | | 20 |
| ... | ... | ... |
| 2 | j | 0 |
diff --git a/src/doc/trpl/traits.md b/src/doc/trpl/traits.md
index efa16f2..51ee4bf 100644
--- a/src/doc/trpl/traits.md
+++ b/src/doc/trpl/traits.md
@@ -183,8 +183,7 @@ won’t have its methods:
```rust,ignore
let mut f = std::fs::File::open("foo.txt").ok().expect("Couldn’t open foo.txt");
-let buf = b"whatever"; // byte string literal. buf: &[u8; 8]
-let result = f.write(buf);
+let result = f.write("whatever".as_bytes());
# result.unwrap(); // ignore the error
```
@@ -192,8 +191,9 @@ Here’s the error:
```text
error: type `std::fs::File` does not implement any method in scope named `write`
-let result = f.write(buf);
- ^~~~~~~~~~
+
+let result = f.write(b"whatever");
+ ^~~~~~~~~~~~~~~~~~
```
We need to `use` the `Write` trait first:
@@ -202,14 +202,13 @@ We need to `use` the `Write` trait first:
use std::io::Write;
let mut f = std::fs::File::open("foo.txt").ok().expect("Couldn’t open foo.txt");
-let buf = b"whatever";
-let result = f.write(buf);
+let result = f.write("whatever".as_bytes());
# result.unwrap(); // ignore the error
```
This will compile without error.
-This means that even if someone does something bad like add methods to `i32`,
+This means that even if someone does something bad like add methods to `int`,
it won’t affect you, unless you `use` that trait.
There’s one more restriction on implementing traits. Either the trait or the
@@ -253,7 +252,7 @@ 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<T: Clone, K: Clone + Debug>(x: T, y: K) {
@@ -268,7 +267,7 @@ 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<T: Clone, K: Clone + Debug>(x: T, y: K) {
@@ -294,7 +293,7 @@ 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<T, K>(x: T, y: K)
@@ -311,7 +310,7 @@ This flexibility can add clarity in complex situations.
`where` is also more powerful than the simpler syntax. For example:
-```rust
+```
trait ConvertTo<Output> {
fn convert(&self) -> Output;
}
diff --git a/src/doc/trpl/tuple-structs.md b/src/doc/trpl/tuple-structs.md
new file mode 100644
index 0000000..8fba658
--- /dev/null
+++ b/src/doc/trpl/tuple-structs.md
@@ -0,0 +1,56 @@
+% Tuple Structs
+
+Rust has another data type that's like a hybrid between a tuple and a struct,
+called a *tuple struct*. Tuple structs do have a name, but their fields don't:
+
+```{rust}
+struct Color(i32, i32, i32);
+struct Point(i32, i32, i32);
+```
+
+These two will not be equal, even if they have the same values:
+
+```{rust}
+# struct Color(i32, i32, i32);
+# struct Point(i32, i32, i32);
+let black = Color(0, 0, 0);
+let origin = Point(0, 0, 0);
+```
+
+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,
+}
+```
+
+Now, we have actual names, rather than positions. Good names are important,
+and with a struct, we have actual names.
+
+There _is_ one case when a tuple struct is very useful, though, and that's a
+tuple struct with only one element. We call this the *newtype* pattern, because
+it allows you to create a new type, distinct from that of its contained value
+and expressing 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`, as we discussed previously in 'tuples.' In this case, the
+`let Inches(integer_length)` assigns `10` to `integer_length`.
diff --git a/src/doc/trpl/unsafe-code.md b/src/doc/trpl/unsafe-code.md
new file mode 100644
index 0000000..b641f2b
--- /dev/null
+++ b/src/doc/trpl/unsafe-code.md
@@ -0,0 +1,183 @@
+% Unsafe Code
+
+# Introduction
+
+Rust aims to provide safe abstractions over the low-level details of
+the CPU and operating system, but sometimes one needs to drop down and
+write code at that level. This guide aims to provide an overview of
+the dangers and power one gets with Rust's unsafe subset.
+
+Rust provides an escape hatch in the form of the `unsafe { ... }`
+block which allows the programmer to dodge some of the compiler's
+checks and do a wide range of operations, such as:
+
+- dereferencing [raw pointers](#raw-pointers)
+- calling a function via FFI ([covered by the FFI guide](ffi.html))
+- casting between types bitwise (`transmute`, aka "reinterpret cast")
+- [inline assembly](#inline-assembly)
+
+Note that an `unsafe` block does not relax the rules about lifetimes
+of `&` and the freezing of borrowed data.
+
+Any use of `unsafe` is the programmer saying "I know more than you" to
+the compiler, and, as such, the programmer should be very sure that
+they actually do know more about why that piece of code is valid. In
+general, one should try to minimize the amount of unsafe code in a
+code base; preferably by using the bare minimum `unsafe` blocks to
+build safe interfaces.
+
+> **Note**: the low-level details of the Rust language are still in
+> flux, and there is no guarantee of stability or backwards
+> compatibility. In particular, there may be changes that do not cause
+> compilation errors, but do cause semantic changes (such as invoking
+> undefined behaviour). As such, extreme care is required.
+
+# Pointers
+
+## References
+
+One of Rust's biggest features is memory safety. This is achieved in
+part via [the ownership system](ownership.html), which is how the
+compiler can guarantee that every `&` reference is always valid, and,
+for example, never pointing to freed memory.
+
+These restrictions on `&` have huge advantages. However, they also
+constrain how we can use them. For example, `&` doesn't behave
+identically to C's pointers, and so cannot be used for pointers in
+foreign function interfaces (FFI). Additionally, both immutable (`&`)
+and mutable (`&mut`) references have some aliasing and freezing
+guarantees, required for memory safety.
+
+In particular, if you have an `&T` reference, then the `T` must not be
+modified through that reference or any other reference. There are some
+standard library types, e.g. `Cell` and `RefCell`, that provide inner
+mutability by replacing compile time guarantees with dynamic checks at
+runtime.
+
+An `&mut` reference has a different constraint: when an object has an
+`&mut T` pointing into it, then that `&mut` reference must be the only
+such usable path to that object in the whole program. That is, an
+`&mut` cannot alias with any other references.
+
+Using `unsafe` code to incorrectly circumvent and violate these
+restrictions is undefined behaviour. For example, the following
+creates two aliasing `&mut` pointers, and is invalid.
+
+```
+use std::mem;
+let mut x: u8 = 1;
+
+let ref_1: &mut u8 = &mut x;
+let ref_2: &mut u8 = unsafe { mem::transmute(&mut *ref_1) };
+
+// oops, ref_1 and ref_2 point to the same piece of data (x) and are
+// both usable
+*ref_1 = 10;
+*ref_2 = 20;
+```
+
+## Raw pointers
+
+Rust offers two additional pointer types (*raw pointers*), written as
+`*const T` and `*mut T`. They're an approximation of C's `const T*` and `T*`
+respectively; indeed, one of their most common uses is for FFI,
+interfacing with external C libraries.
+
+Raw pointers have much fewer guarantees than other pointer types
+offered by the Rust language and libraries. For example, 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`.
+
+Fortunately, they come with a redeeming feature: the weaker guarantees
+mean weaker restrictions. The missing restrictions make raw pointers
+appropriate as a building block for implementing things like smart
+pointers and vectors inside libraries. For example, `*` pointers are
+allowed to alias, allowing them to be used to write shared-ownership
+types like reference counted and garbage collected pointers, and even
+thread-safe shared memory types (`Rc` and the `Arc` types are both
+implemented entirely in Rust).
+
+There are two things that you are required to be careful about
+(i.e. require an `unsafe { ... }` block) with raw pointers:
+
+- dereferencing: they can have any value: so possible results include
+ a crash, a read of uninitialised memory, a use-after-free, or
+ reading data as normal.
+- pointer arithmetic via the `offset` [intrinsic](#intrinsics) (or
+ `.offset` method): this intrinsic uses so-called "in-bounds"
+ arithmetic, that is, it is only defined behaviour if the result is
+ inside (or one-byte-past-the-end) of the object from which the
+ original pointer came.
+
+The latter assumption allows the compiler to optimize more
+effectively. As can be seen, actually *creating* a raw pointer is not
+unsafe, and neither is converting to an integer.
+
+### 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
+
+```
+let i: u32 = 1;
+// explicit cast
+let p_imm: *const u32 = &i as *const u32;
+let mut m: u32 = 2;
+// implicit coercion
+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`).
+
+
+
+## Making the unsafe safe(r)
+
+There are various ways to expose a safe interface around some unsafe
+code:
+
+- store pointers privately (i.e. not in public fields of public
+ structs), so that you can see and control all reads and writes to
+ the pointer in one place.
+- use `assert!()` a lot: since you can't rely on the protection of the
+ compiler & type-system to ensure that your `unsafe` code is correct
+ at compile-time, use `assert!()` to verify that it is doing the
+ right thing at run-time.
+- implement the `Drop` for resource clean-up via a destructor, and use
+ RAII (Resource Acquisition Is Initialization). This reduces the need
+ for any manual memory management by users, and automatically ensures
+ that clean-up is always run, even when the thread panics.
+- ensure that any data stored behind a raw pointer is destroyed at the
+ appropriate time.
diff --git a/src/doc/trpl/vectors.md b/src/doc/trpl/vectors.md
index d8b894a..6170bdb 100644
--- a/src/doc/trpl/vectors.md
+++ b/src/doc/trpl/vectors.md
@@ -16,7 +16,7 @@ this is just convention.)
There’s an alternate form of `vec!` for repeating an initial value:
-```rust
+```
let v = vec![0; 10]; // ten zeroes
```
diff --git a/src/doc/trpl/while-loops.md b/src/doc/trpl/while-loops.md
index 0f5c3c6..e71d203 100644
--- a/src/doc/trpl/while-loops.md
+++ b/src/doc/trpl/while-loops.md
@@ -2,8 +2,8 @@
Rust also has a `while` loop. It looks like this:
-```rust
-let mut x = 5; // mut x: i32
+```{rust}
+let mut x = 5; // mut x: u32
let mut done = false; // mut done: bool
while !done {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment