1 % The Rust Programming Language
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
16 [rust]: http://rust-lang.org
18 “The Rust Programming Language” is split into seven sections. This introduction
19 is the first. After this:
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.
29 [gs]: getting-started.html
31 [er]: effective-rust.html
32 [ss]: syntax-and-semantics.html
33 [nr]: nightly-rust.html
35 [ar]: academic-research.html
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.
43 ## A brief introduction to Rust
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.
48 The main concept that makes Rust unique is called ‘ownership’. Consider this
53 let mut x = vec!["Hello", "world"];
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.
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.
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
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.
80 [var]: variable-bindings.html
82 [heap]: the-stack-and-the-heap.html
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.
93 Let’s add another line to our example:
97 let mut x = vec!["Hello", "world"];
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!
111 [borrowing]: references-and-borrowing.html
113 Let’s add a third line. It looks innocent enough, but causes a compiler error:
117 let mut x = vec!["Hello", "world"];
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:
129 error: cannot borrow `x` as mutable because it is also borrowed as immutable
132 note: previous borrow of `x` occurs here; the immutable borrow prevents
133 subsequent moves or mutable borrows of `x` until the borrow ends
136 note: previous borrow ends here
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.
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:
160 let mut x = vec!["Hello", "world"];
162 let y = x[0].clone();
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.
173 [move]: move-semantics.html
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:
180 let mut x = vec!["Hello", "world"];
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.
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.