rust/src/doc/trpl
2015-06-16 08:20:57 +00:00
..
academic-research.md
associated-constants.md
associated-types.md usize -> u32 to match previous example 2015-06-12 15:59:39 -04:00
attributes.md
benchmark-tests.md TRPL: Normalize rust Code Block Markers 2015-05-18 21:10:00 +02:00
borrow-and-asref.md Rollup merge of #25580 - killercup:trpl/unify-code-blocks, r=steveklabnik 2015-05-19 18:47:15 +05:30
box-syntax-and-patterns.md Remove mentions of int / uint from public documentation 2015-05-27 19:26:18 -04:00
casting-between-types.md
closures.md Clarify that the following will error 2015-06-15 13:18:07 -04:00
comments.md Update doctest in comments.md 2015-06-07 15:06:58 -04:00
compiler-plugins.md
concurrency.md TRPL: Add rust Marker to Some Code Block 2015-05-18 20:56:00 +02:00
conditional-compilation.md TRPL: Fix Unescaped URL 2015-05-28 16:18:26 +02:00
const-and-static.md Rollup merge of #26144 - steveklabnik:static_doc_fix, r=alexcrichton 2015-06-09 17:24:45 -04:00
crates-and-modules.md TRPL: Normalize rust Code Block Markers 2015-05-18 21:10:00 +02:00
deref-coercions.md
dining-philosophers.md Expand a bit on clone() in Dining Philosophers 2015-06-09 15:24:44 -04:00
documentation.md trpl: Remove tailing semicolon of an inner attribute 2015-05-20 16:55:38 +08:00
drop.md
effective-rust.md
enums.md Mention that enum constructors are functions 2015-06-09 16:12:45 -04:00
error-handling.md Fixes consistency in before/after example 2015-05-30 13:31:46 -07:00
ffi.md Rollup merge of #26146 - steveklabnik:remove_unsafe_pointer, r=Gankro 2015-06-10 22:07:10 +05:30
for-loops.md Added # let lines = "hello\nworld".lines(); to pass the tests 2015-06-01 21:34:31 +02:00
functions.md mend bad Markdown 2015-06-10 16:16:03 +01:00
generics.md book: remove a sentence that is not clear 2015-06-08 23:35:40 +02:00
getting-started.md
glossary.md Add a missing space to the Glossary page of TRPL 2015-05-25 22:40:07 -04:00
guessing-game.md trpl:add missing comma 2015-05-31 18:16:58 +08:00
hello-cargo.md Rollup merge of #24495 - nathanl:nathanl-explain-bin-flag, r=steveklabnik 2015-06-12 11:55:37 +05:30
hello-world.md
if-let.md
if.md
inline-assembly.md TRPL: Add rust Marker to Some Code Block 2015-05-18 20:56:00 +02:00
installing-rust.md Don't link to specific versions of rust in the book. 2015-06-11 17:33:18 -04:00
intrinsics.md TRPL: Add rust Marker to Some Code Block 2015-05-18 20:56:00 +02:00
iterators.md Remove unstable feature from TRPL: iterators 2015-06-12 15:00:21 -04:00
lang-items.md TRPL: Add rust Marker to Some Code Block 2015-05-18 20:56:00 +02:00
learn-rust.md
lifetimes.md Fix up wording in lifetime elision docs 2015-06-12 15:05:09 -04:00
link-args.md
macros.md [Documentation: Macros] Use some more SSL 2015-06-04 15:53:22 +02:00
match.md
method-syntax.md Fix some copyediting in TRPL: method-syntax 2015-06-09 15:49:57 -04:00
mutability.md Link to cell in TRPL: mutability 2015-06-02 09:37:54 -04:00
nightly-rust.md TRPL: Clean up some Markdown links 2015-05-25 15:10:50 +02:00
no-stdlib.md TRPL: Add rust Marker to Some Code Block 2015-05-18 20:56:00 +02:00
operators-and-overloading.md
ownership.md Updated with requested changes 2015-06-08 18:01:40 +02:00
patterns.md Auto merge of #26108 - Marwes:field_pun_docs, r=steveklabnik 2015-06-13 07:00:26 +00:00
primitive-types.md TRPL: Add rust Marker to Some Code Block 2015-05-18 20:56:00 +02:00
raw-pointers.md Exise 'unsafe pointer' in favor of 'raw pointer' 2015-06-09 16:49:24 -04:00
README.md trpl: eight sections, not seven 2015-05-29 14:29:35 -04:00
references-and-borrowing.md Semantic accuracy in borrow scope rules. 2015-06-09 13:08:16 -03:00
release-channels.md
rust-inside-other-languages.md Update example in "Rust Inside Other Languages" 2015-06-15 19:12:34 +02:00
slice-patterns.md
strings.md make note of slicing syntax in TRPL: strings 2015-06-09 16:37:47 -04:00
structs.md
SUMMARY.md trpl: Proofread "Rust Inside Other Languages" 2015-05-18 13:09:21 -05:00
syntax-and-semantics.md
testing.md TRPL: Normalize rust Code Block Markers 2015-05-18 21:10:00 +02:00
the-stack-and-the-heap.md Fix typo in diagram demonstrating stack vs. heap values 2015-05-24 15:18:43 -07:00
trait-objects.md Remove confusing paragraph from Trait Objects 2015-06-15 13:16:16 -04:00
traits.md Auto merge of #26118 - tshepang:define-trait, r=steveklabnik 2015-06-13 08:34:12 +00:00
type-aliases.md
ufcs.md
unsafe.md
unsized-types.md
variable-bindings.md
vectors.md TRPL: Add rust Marker to Some Code Block 2015-05-18 20:56:00 +02:00
while-loops.md TRPL: Normalize rust Code Block Markers 2015-05-18 21:10:00 +02:00

% The Rust Programming Language

Welcome! This book will teach you about the Rust Programming Language. Rust is a systems programming language focused on three goals: safety, speed, and concurrency. It maintains these goals without having a garbage collector, making it a useful language for a number of use cases other languages arent good at: embedding in other languages, programs with specific space and time requirements, and writing low-level code, like device drivers and operating systems. It improves on current languages targeting this space by having a number of compile-time safety checks that produce no runtime overhead, while eliminating all data races. Rust also aims to achieve zero-cost abstractions even though some of these abstractions feel like those of a high-level language. Even then, Rust still allows precise control like a low-level language would.

“The Rust Programming Language” is split into eight sections. This introduction is the first. After this:

After reading this introduction, youll want to dive into either Learn Rust or Syntax and Semantics, depending on your preference: Learn Rust if you want to dive in with a project, or Syntax and Semantics if you prefer to start small, and learn a single concept thoroughly before moving onto the next. Copious cross-linking connects these parts together.

Contributing

The source files from which this book is generated can be found on Github: github.com/rust-lang/rust/tree/master/src/doc/trpl

A brief introduction to Rust

Is Rust a language you might be interested in? Lets examine a few small code samples to show off a few of its strengths.

The main concept that makes Rust unique is called ownership. Consider this small example:

fn main() {
    let mut x = vec!["Hello", "world"];
}

This program makes a variable binding named x. The value of this binding is a Vec<T>, a vector, that we create through a macro defined in the standard library. This macro is called vec, and we invoke macros with a !. This follows a general principle of Rust: make things explicit. Macros can do significantly more complicated things than function calls, and so theyre visually distinct. The ! also helps with parsing, making tooling easier to write, which is also important.

We used mut to make x mutable: bindings are immutable by default in Rust. Well be mutating this vector later in the example.

Its also worth noting that we didnt need a type annotation here: while Rust is statically typed, we didnt need to explicitly annotate the type. Rust has type inference to balance out the power of static typing with the verbosity of annotating types.

Rust prefers stack allocation to heap allocation: x is placed directly on the stack. However, the Vec<T> type allocates space for the elements of the vector on the heap. If youre not familiar with this distinction, you can ignore it for now, or check out The Stack and the Heap. As a systems programming language, Rust gives you the ability to control how your memory is allocated, but when were getting started, its less of a big deal.

Earlier, we mentioned that ownership is the key new concept in Rust. In Rust parlance, x is said to own the vector. This means that when x goes out of scope, the vectors memory will be de-allocated. This is done deterministically by the Rust compiler, rather than through a mechanism such as a garbage collector. In other words, in Rust, you dont call functions like malloc and free yourself: the compiler statically determines when you need to allocate or deallocate memory, and inserts those calls itself. To err is to be human, but compilers never forget.

Lets add another line to our example:

fn main() {
    let mut x = vec!["Hello", "world"];

    let y = &x[0];
}

Weve introduced another binding, y. In this case, y is a reference to the first element of the vector. Rusts references are similar to pointers in other languages, but with additional compile-time safety checks. References interact with the ownership system by borrowing what they point to, rather than owning it. The difference is, when the reference goes out of scope, it will not deallocate the underlying memory. If it did, wed de-allocate twice, which is bad!

Lets add a third line. It looks innocent enough, but causes a compiler error:

fn main() {
    let mut x = vec!["Hello", "world"];

    let y = &x[0];

    x.push("foo");
}

push is a method on vectors that appends another element to the end of the vector. When we try to compile this program, we get an error:

error: cannot borrow `x` as mutable because it is also borrowed as immutable
    x.push("foo");
    ^
note: previous borrow of `x` occurs here; the immutable borrow prevents
subsequent moves or mutable borrows of `x` until the borrow ends
    let y = &x[0];
             ^
note: previous borrow ends here
fn main() {

}
^

Whew! The Rust compiler gives quite detailed errors at times, and this is one 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, copying the old values over, and updating the internal pointer to that memory. That all works just fine. The problem is that y wouldnt get updated, and so wed have a dangling pointer. Thats bad. Any use of y would be an error in this case, and so the compiler has caught this for us.

So how do we solve this problem? There are two approaches we can take. The first is making a copy rather than using a reference:

fn main() {
    let mut x = vec!["Hello", "world"];

    let y = x[0].clone();

    x.push("foo");
}

Rust has move semantics by default, so if we want to make a copy of some data, we call the clone() method. In this example, y is no longer a reference to the vector stored in x, but a copy of its first element, "Hello". Now that we dont have a reference, our push() works just fine.

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:

fn main() {
    let mut x = vec!["Hello", "world"];

    {
        let y = &x[0];
    }

    x.push("foo");
}

We created an inner scope with an additional set of curly braces. y will go out of scope before we call push(), and so were all good.

This concept of ownership isnt just good for preventing dangling pointers, but an entire set of related problems, like iterator invalidation, concurrency, and more.