Skip to content

Commit d9a78a0

Browse files
committed
TRPL: new introduction
1 parent e57410c commit d9a78a0

File tree

1 file changed

+207
-25
lines changed

1 file changed

+207
-25
lines changed

src/doc/trpl/README.md

+207-25
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,221 @@
11
% The Rust Programming Language
22

3-
Welcome! This book will teach you about [the Rust Programming
4-
Language](http://www.rust-lang.org/). Rust is a modern systems programming
5-
language focusing on safety and speed. It accomplishes these goals by being
6-
memory safe without using garbage collection.
3+
Welcome! This book will teach you about the [Rust Programming Language][rust].
4+
Rust is a systems programming language focused on three goals: safety, speed,
5+
and concurrency. It maintains these goals without having a garbage collector,
6+
making it a useful language for a number of use cases other languages aren’t
7+
good at: embedding in other languages, programs with specific space and time
8+
requirements, and writing low-level code, like device drivers and operating
9+
systems. It improves on current languages targeting this space by having a
10+
number of compile-time safety checks that produce no runtime overhead, while
11+
eliminating all data races. These checks can be used to form ‘zero-cost
12+
abstractions’, making Rust _feel_ like a high-level language, while giving you
13+
precise control like a low-level language.
714

8-
"The Rust Programming Language" is split into three sections, which you can
9-
navigate through the menu on the left.
15+
[rust]: http://rust-lang.org
1016

11-
<h2 class="section-header"><a href="basic.html">Basics</a></h2>
17+
“The Rust Programming Language” is split into seven sections. This introduction
18+
is the first. After this:
1219

13-
This section is a linear introduction to the basic syntax and semantics of
14-
Rust. It has individual sections on each part of Rust's syntax.
20+
* [Getting started][gs] - Set up your computer for Rust development.
21+
* [Learn Rust][lr] - Learn Rust programming through small projects.
22+
* [Effective Rust][er] - Higher-level concepts for writing excellent Rust code.
23+
* [Syntax and Semantics][ss] - Each bit of Rust, broken down into small chunks.
24+
* [Nightly Rust][nr] - Cutting-edge features that aren’t in stable builds yet.
25+
* [Glossary][gl] - A reference of terms used in the book.
1526

16-
After reading "Basics," you will have a good foundation to learn more about
17-
Rust, and can write very simple programs.
27+
[gs]: getting-started.html
28+
[lr]: learn-rust.html
29+
[er]: effective-rust.html
30+
[ss]: syntax-and-semantics.html
31+
[nr]: nightly-rust.html
32+
[gl]: glossary.html
1833

19-
<h2 class="section-header"><a href="intermediate.html">Intermediate</a></h2>
34+
After reading this introduction, you’ll want to dive into either ‘Learn Rust’
35+
or ‘Syntax and Semantics’, depending on your preference: ‘Learn Rust’ if you
36+
want to dive in with a project, or ‘Syntax and Semantics’ if you prefer to
37+
start small, and learn a single concept thoroughly before moving onto the next.
38+
Copious cross-linking will help connect these parts together.
2039

21-
This section contains individual chapters, which are self-contained. They focus
22-
on specific topics, and can be read in any order.
40+
## A brief introduction to Rust
2341

24-
After reading "Intermediate," you will have a solid understanding of Rust,
25-
and will be able to understand most Rust code and write more complex programs.
42+
Is Rust a language you might be interested in? Let’s examine a few small code
43+
samples to show off a few of Rust’s strengths.
2644

27-
<h2 class="section-header"><a href="advanced.html">Advanced</a></h2>
45+
The main concept that makes Rust unique is called ‘ownership’. Consider this
46+
small example:
2847

29-
In a similar fashion to "Intermediate," this section is full of individual,
30-
deep-dive chapters, which stand alone and can be read in any order. These
31-
chapters focus on Rust's most complex features.
48+
```rust
49+
fn main() {
50+
let x = vec![1, 2, 3];
51+
}
52+
```
3253

33-
<h2 class="section-header"><a href="unstable.html">Unstable</a></h2>
54+
This program makes a [variable binding][var] named `x`. The value of this
55+
binding is a `Vec<T>`, a ‘vector’, that we create through a [macro][macro]
56+
defined in the standard library. This macro is called `vec`, and we invoke
57+
macros with a `!`. This follows a general principle of Rust: make things
58+
explicit. Macros can do significantly more complicated things than function
59+
calls, and so they’re visually distinct. The `!` also helps with parsing,
60+
making tooling easier to write, which is also important.
3461

35-
In a similar fashion to "Intermediate," this section is full of individual,
36-
deep-dive chapters, which stand alone and can be read in any order.
62+
It’s also worth noting that we didn’t need a type annotation here: while Rust
63+
is statically typed, we didn’t need to explicitly annotate the type. Rust has
64+
type inference to balance out the power of static typing with the verbosity of
65+
a simple implementation of it. If we wanted to annotate the type, we could:
3766

38-
This chapter contains things that are only available on the nightly channel of
39-
Rust.
67+
```rust
68+
fn main() {
69+
let x: Vec<i32> = vec![1, 2, 3];
70+
}
71+
```
72+
73+
Generally, these annotations are only added if there’s some kind of ambiguity
74+
to resolve.
75+
76+
Rust prefers stack allocation to heap allocation, and `x` is allocated on the
77+
stack. However, the `Vec<T>` type allocates space for the elements of the
78+
vector on the heap. If you’re not familiar with this distinction, you can
79+
ignore it for now, or check out [‘The Stack and the Heap’][heap]. As a systems
80+
programming language, Rust gives you the ability to control how your memory is
81+
allocated, but when we’re getting started, it’s less of a big deal.
82+
83+
[var]: variable-bindings.html
84+
[macro]: macros.html
85+
[heap]: the-stack-and-the-heap.html
86+
87+
Earlier, we mentioned that ‘ownership’ is the key new concept in Rust. In Rust
88+
parlance, `x` is said to ‘own’ the vector. This means that when `x` goes out of
89+
scope, the vector’s memory will be de-allocated. This is done deterministically
90+
by the Rust compiler, rather than through a mechanism such as a garbage
91+
collector. In other words, in Rust, you don’t call functions like `malloc` and
92+
`free` yourself: the compiler statically determines when you need to allocate
93+
or deallocate memory, and inserts those calls itself. To err is to be human,
94+
but compilers never forget.
95+
96+
Let’s add another line to our example:
97+
98+
```rust
99+
fn main() {
100+
let x = vec![1, 2, 3];
101+
102+
let y = &x[0];
103+
}
104+
```
105+
106+
We’ve introduced another binding, `y`. In this case, `y` is a ‘reference’ to
107+
the first element of the vector. Rust’s references are similar to pointers in
108+
other languages, but with additional compile-time safety checks. References
109+
interact with the ownership system by [‘borrowing’][borrowing] what they point
110+
to, rather than owning it. The difference is, when the reference goes out of
111+
scope, it will not deallocate the underlying memory. If it did, we’d
112+
de-allocate twice, which is bad!
113+
114+
[borrowing]: references-and-borrowing.html
115+
116+
Let’s add a third line. It looks innocent enough, but causes a compiler error:
117+
118+
```rust,ignore
119+
fn main() {
120+
let x = vec![1, 2, 3];
121+
122+
let y = &x[0];
123+
124+
x.push(4);
125+
}
126+
```
127+
128+
`push` is a method on vectors that appends another element to the end of the
129+
vector. When we try to compile this program, we get an error:
130+
131+
```text
132+
error: cannot borrow immutable local variable `x` as mutable
133+
x.push(4);
134+
^
135+
```
136+
137+
Because `push` mutates the vector, it needs the vector to be mutable. But,
138+
bindings are immutable by default in Rust, and so we get a compile-time error
139+
telling us so. It’s easy to make the binding mutable: we add `mut` before
140+
the name of the binding. While that fixes our first error, it introduces
141+
another:
142+
143+
```rust,ignore
144+
fn main() {
145+
let mut x = vec![1, 2, 3];
146+
147+
let y = &x[0];
148+
149+
x.push(4);
150+
}
151+
```
152+
153+
Here’s the error:
154+
155+
```text
156+
error: cannot borrow `x` as mutable because it is also borrowed as immutable
157+
x.push(4);
158+
^
159+
note: previous borrow of `x` occurs here; the immutable borrow prevents
160+
subsequent moves or mutable borrows of `x` until the borrow ends
161+
let y = &x[0];
162+
^
163+
note: previous borrow ends here
164+
fn main() {
165+
166+
}
167+
^
168+
```
169+
170+
Whew! The Rust compiler gives quite detailed errors at times, and this is one
171+
of those times. As the error explains, while we made our binding mutable, we
172+
still cannot call `push`. This is because we already have a reference to an
173+
element of the vector, `y`. Mutating something while another reference exists
174+
is dangerous, because we may invalidate the reference. In this specific case,
175+
when we create the vector, we may have only allocated space for three elements.
176+
Adding a fourth would mean allocating a new chunk of memory for all those elements,
177+
copying the old values over, and updating the internal pointer to that memory.
178+
That all works just fine. The problem is that `y` wouldn’t get updated, and so
179+
we’d have a ‘dangling pointer’. That’s bad. Any use of `y` would be an error in
180+
this case, and so the compiler has caught this for us.
181+
182+
So how do we solve this problem? There are two approaches we can take. The first
183+
is making a copy rather than using a reference:
184+
185+
```rust
186+
fn main() {
187+
let mut x = vec![1, 2, 3];
188+
189+
let y = x[0].clone();
190+
191+
x.push(4);
192+
}
193+
```
194+
195+
Rust has [move semantics][move] by default, so if we want to make a copy of some
196+
data, we call the `clone()` method. In this example, `y` is no longer a reference
197+
to the vector stored in `x`, but a copy of its first element, `1`. Now that we
198+
don’t have a reference, our `push()` works just fine.
199+
200+
[move]: move-semantics.html
201+
202+
If we truly want a reference, we need the other option: ensure that our reference
203+
goes out of scope before we try to do the mutation. That looks like this:
204+
205+
```rust
206+
fn main() {
207+
let mut x = vec![1, 2, 3];
208+
209+
{
210+
let y = &x[0];
211+
}
212+
213+
x.push(4);
214+
}
215+
```
216+
217+
We created an inner scope with an additional set of curly braces. `y` will go out of
218+
scope before we call `push()`, and so we’re all good.
219+
220+
This concept of ownership isn’t just good for preventing danging pointers, but an
221+
entire set of related problems, like iterator invalidation, concurrency, and more.

0 commit comments

Comments
 (0)