]> git.lizzy.rs Git - rust.git/blob - src/doc/trpl/README.md
Auto merge of #24865 - bluss:range-size, r=alexcrichton
[rust.git] / src / doc / trpl / README.md
1 % The Rust Programming Language
2
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. Rust also aims to achieve ‘zero-cost abstractions’
12 even though some of these abstractions feel like those of a high-level
13 language. Even then, Rust still allows precise control like a low-level
14 language would.
15
16 [rust]: http://rust-lang.org
17
18 “The Rust Programming Language” is split into seven sections. This introduction
19 is the first. After this:
20
21 * [Getting started][gs] - Set up your computer for Rust development.
22 * [Learn Rust][lr] - Learn Rust programming through small projects.
23 * [Effective Rust][er] - Higher-level concepts for writing excellent Rust code.
24 * [Syntax and Semantics][ss] - Each bit of Rust, broken down into small chunks.
25 * [Nightly Rust][nr] - Cutting-edge features that aren’t in stable builds yet.
26 * [Glossary][gl] - A reference of terms used in the book.
27 * [Academic Research][ar] - Literature that influenced Rust.
28
29 [gs]: getting-started.html
30 [lr]: learn-rust.html
31 [er]: effective-rust.html
32 [ss]: syntax-and-semantics.html
33 [nr]: nightly-rust.html
34 [gl]: glossary.html
35 [ar]: academic-research.html
36
37 After reading this introduction, you’ll want to dive into either ‘Learn Rust’
38 or ‘Syntax and Semantics’, depending on your preference: ‘Learn Rust’ if you
39 want to dive in with a project, or ‘Syntax and Semantics’ if you prefer to
40 start small, and learn a single concept thoroughly before moving onto the next.
41 Copious cross-linking connects these parts together.
42
43 ## A brief introduction to Rust
44
45 Is Rust a language you might be interested in? Let’s examine a few small code
46 samples to show off a few of its strengths.
47
48 The main concept that makes Rust unique is called ‘ownership’. Consider this
49 small example:
50
51 ```rust
52 fn main() {
53     let mut x = vec!["Hello", "world"];
54 }
55 ```
56
57 This program makes a [variable binding][var] named `x`. The value of this
58 binding is a `Vec<T>`, a ‘vector’, that we create through a [macro][macro]
59 defined in the standard library. This macro is called `vec`, and we invoke
60 macros with a `!`. This follows a general principle of Rust: make things
61 explicit. Macros can do significantly more complicated things than function
62 calls, and so they’re visually distinct. The `!` also helps with parsing,
63 making tooling easier to write, which is also important.
64
65 We used `mut` to make `x` mutable: bindings are immutable by default in Rust.
66 We’ll be mutating this vector later in the example.
67
68 It’s also worth noting that we didn’t need a type annotation here: while Rust
69 is statically typed, we didn’t need to explicitly annotate the type. Rust has
70 type inference to balance out the power of static typing with the verbosity of
71 annotating types.
72
73 Rust prefers stack allocation to heap allocation: `x` is placed directly on the
74 stack. However, the `Vec<T>` type allocates space for the elements of the
75 vector on the heap. If you’re not familiar with this distinction, you can
76 ignore it for now, or check out [‘The Stack and the Heap’][heap]. As a systems
77 programming language, Rust gives you the ability to control how your memory is
78 allocated, but when we’re getting started, it’s less of a big deal.
79
80 [var]: variable-bindings.html
81 [macro]: macros.html
82 [heap]: the-stack-and-the-heap.html
83
84 Earlier, we mentioned that ‘ownership’ is the key new concept in Rust. In Rust
85 parlance, `x` is said to ‘own’ the vector. This means that when `x` goes out of
86 scope, the vector’s memory will be de-allocated. This is done deterministically
87 by the Rust compiler, rather than through a mechanism such as a garbage
88 collector. In other words, in Rust, you don’t call functions like `malloc` and
89 `free` yourself: the compiler statically determines when you need to allocate
90 or deallocate memory, and inserts those calls itself. To err is to be human,
91 but compilers never forget.
92
93 Let’s add another line to our example:
94
95 ```rust
96 fn main() {
97     let mut x = vec!["Hello", "world"];
98
99     let y = &x[0];
100 }
101 ```
102
103 We’ve introduced another binding, `y`. In this case, `y` is a ‘reference’ to
104 the first element of the vector. Rust’s references are similar to pointers in
105 other languages, but with additional compile-time safety checks. References
106 interact with the ownership system by [‘borrowing’][borrowing] what they point
107 to, rather than owning it. The difference is, when the reference goes out of
108 scope, it will not deallocate the underlying memory. If it did, we’d
109 de-allocate twice, which is bad!
110
111 [borrowing]: references-and-borrowing.html
112
113 Let’s add a third line. It looks innocent enough, but causes a compiler error:
114
115 ```rust,ignore
116 fn main() {
117     let mut x = vec!["Hello", "world"];
118
119     let y = &x[0];
120
121     x.push("foo");
122 }
123 ```
124
125 `push` is a method on vectors that appends another element to the end of the
126 vector. When we try to compile this program, we get an error:
127
128 ```text
129 error: cannot borrow `x` as mutable because it is also borrowed as immutable
130     x.push(4);
131     ^
132 note: previous borrow of `x` occurs here; the immutable borrow prevents
133 subsequent moves or mutable borrows of `x` until the borrow ends
134     let y = &x[0];
135              ^
136 note: previous borrow ends here
137 fn main() {
138
139 }
140 ^
141 ```
142
143 Whew! The Rust compiler gives quite detailed errors at times, and this is one
144 of those times. As the error explains, while we made our binding mutable, we
145 still cannot call `push`. This is because we already have a reference to an
146 element of the vector, `y`. Mutating something while another reference exists
147 is dangerous, because we may invalidate the reference. In this specific case,
148 when we create the vector, we may have only allocated space for three elements.
149 Adding a fourth would mean allocating a new chunk of memory for all those elements,
150 copying the old values over, and updating the internal pointer to that memory.
151 That all works just fine. The problem is that `y` wouldn’t get updated, and so
152 we’d have a ‘dangling pointer’. That’s bad. Any use of `y` would be an error in
153 this case, and so the compiler has caught this for us.
154
155 So how do we solve this problem? There are two approaches we can take. The first
156 is making a copy rather than using a reference:
157
158 ```rust
159 fn main() {
160     let mut x = vec!["Hello", "world"];
161
162     let y = x[0].clone();
163
164     x.push("foo");
165 }
166 ```
167
168 Rust has [move semantics][move] by default, so if we want to make a copy of some
169 data, we call the `clone()` method. In this example, `y` is no longer a reference
170 to the vector stored in `x`, but a copy of its first element, `"Hello"`. Now
171 that we don’t have a reference, our `push()` works just fine.
172
173 [move]: move-semantics.html
174
175 If we truly want a reference, we need the other option: ensure that our reference
176 goes out of scope before we try to do the mutation. That looks like this:
177
178 ```rust
179 fn main() {
180     let mut x = vec!["Hello", "world"];
181
182     {
183         let y = &x[0];
184     }
185
186     x.push("foo");
187 }
188 ```
189
190 We created an inner scope with an additional set of curly braces. `y` will go out of
191 scope before we call `push()`, and so we’re all good.
192
193 This concept of ownership isn’t just good for preventing danging pointers, but an
194 entire set of related problems, like iterator invalidation, concurrency, and more.