├── .github
├── FUNDING.yml
└── workflows
│ └── deploy.yml
├── .gitignore
├── LICENSE
├── README.md
├── book.toml
├── src
├── SUMMARY.md
├── about.md
├── advanced_topics.md
├── basic_elements.md
├── functional_programming.md
├── generics.md
├── introduction
│ ├── README.md
│ ├── hello_world.md
│ ├── installation.md
│ ├── prerequisites.md
│ └── roadmap.md
├── ownership_and_borrowing.md
├── project_structure.md
├── structured_programming.md
├── structured_programming
│ ├── README.md
│ ├── decision.md
│ ├── functions.md
│ ├── repetition.md
│ └── sequence.md
├── tools.md
├── training_projects.md
└── types_and_traits.md
└── theme
└── head.hbs
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: [dbofmmbt]
4 |
--------------------------------------------------------------------------------
/.github/workflows/deploy.yml:
--------------------------------------------------------------------------------
1 | name: Deploy mdBook
2 | on: [push]
3 | jobs:
4 | build:
5 | runs-on: ubuntu-latest
6 | steps:
7 | - uses: actions/checkout@v2
8 | - uses: XAMPPRocky/deploy-mdbook@v1.1
9 | with:
10 | token: ${{ secrets.GITHUB_TOKEN }}
11 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | book
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 Eduardo Canellas
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Rust Handbook 🚀
2 |
3 | The goal of this book is to offer guidance on the study of the language: to explain well what is important for everyone to know and offer high-quality references for the learning of more specific or advanced topics.
4 |
5 | Beware that this project is a work in progress. The most recent version of the handbook can be found here:
6 |
7 | Suggestions and feedback are always welcome! Feel free to open an issue or get in touch through Rust Community's Discord.
8 |
9 | ## Contributing
10 |
11 | This book is made with [mdBook](https://github.com/rust-lang/mdBook). Its installation instructions are enough to contribute to this project. For small corrections like typos or broken links, a Pull Request can be submitted directly. In case you want to change something in the content, please open an issue with the proposal before.
12 |
--------------------------------------------------------------------------------
/book.toml:
--------------------------------------------------------------------------------
1 | [book]
2 | description = "Book to guide developers in their Rust learning"
3 | authors = ["Eduardo Canellas de Oliveira"]
4 | language = "en"
5 | multilingual = false
6 | src = "src"
7 |
8 | [rust]
9 | edition = "2021"
10 |
11 | [output.html]
12 | default-theme = "ayu"
13 | git-repository-url = "https://github.com/dbofmmbt/rust-handbook"
14 |
15 | [output.html.playground]
16 | editable = true
17 |
--------------------------------------------------------------------------------
/src/SUMMARY.md:
--------------------------------------------------------------------------------
1 | # Summary
2 |
3 | [About the handbook](./about.md)
4 |
5 | # Guide
6 |
7 | - [Introduction](./introduction/README.md)
8 | - [Pre-requisites](./introduction/prerequisites.md)
9 | \
10 | - [Installation](./introduction/installation.md)
11 | - [Hello, World!](./introduction/hello_world.md)
12 | - [Tools](./tools.md)
13 | - [Basic Elements](./basic_elements.md)
14 |
15 |
16 |
17 |
18 |
19 | - [Ownership & Borrowing](./ownership_and_borrowing.md)
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/src/about.md:
--------------------------------------------------------------------------------
1 | # Rust Handbook
2 |
3 |
4 |
5 | Rust is a very well-thought programming language. It seeks to unite a variety of existing concepts from other languages, industry and academia in order to be a solid language to develop reliable and efficient solutions in a productive manner.
6 |
7 | On the other hand, it gained the fame of being a language with a steep learning curve. I'm not going to fool you: Rust has a lot of resources to help you, but first you need to understand how they work. What I can tell you is that, in general, every choice made in this language has a purpose. Once you get the reasons, something which seemed complicated may become understandable.
8 |
9 | If you intend to develop an application with a high degree of concurrent processing to serve a lot of HTTP requests, you'll probably need to learn about async programming (`async/await`). In case you deal directly with hardware on embedded programming, maybe you'll need to use `unsafe` to interact with the native resource of the target device. While developing a library, it may look interest to implement macros to create a more convenient interface for your users.
10 |
11 | Know that you don't need to learn all of this at once, nor be a specialist on all of the language's resources. Each person can focus on those which are relevant for the fool they want to develop. Do not think that you need to absorb everything at the same time, because nobody should.
12 |
13 | What I propose here is the understanding of the language. There are core concepts which every developer must know to be productive, no matter what kind of the application they do. Those are the ones I aim to teach in this material.
14 |
15 | Besides that, I'll present these concepts in a specific order. Each topic is carefully designed to be based on the previous ones, forming learning layers. You shouldn't try to build the second floor of a building without building the first one, right?
16 |
17 | Any concept or detail that I consider out of the scope of this handbook will have references for high-quality content available elsewhere, in order to complement this guide.
18 |
19 |
20 |
--------------------------------------------------------------------------------
/src/advanced_topics.md:
--------------------------------------------------------------------------------
1 | # Tópicos Avançados
2 |
--------------------------------------------------------------------------------
/src/basic_elements.md:
--------------------------------------------------------------------------------
1 | # Basic Elements
2 |
3 | The elements below, although simple, are an important starting point to code. Most of these concepts are present in other languages.
4 |
5 | ## Primitives Types
6 |
7 | This section is non-exhaustive by a matter of simplicity. There are other primitive types beyond these and you may find information about them on the [primitive types section in the standard library's documentation](https://doc.rust-lang.org/std/index.html#primitives).
8 |
9 | ### **Integers**
10 |
11 | - Signed: `i8`, `i16`, `i32`, `i64`, `i128` e `isize`. (`i` from _integer_).
12 | - e.g.: `0`, `-5`, `1_000_000i32`
13 | - Unsigned: `u8`, `u16`, `u32`, `u64`, `u128` e `usize`.
14 | - It needs to be non-negative. e.g.: `0`, `10`, `42`, `1_000_000usize`
15 |
16 | The number in the type indicates how many bits are used by the integer. This has direct relation with the range of values which are possible to represent on that type. For example, `u8` can only represent a range of 28 values.
17 |
18 | If the type of the integer literal is not explicitly annotated or cannot be inferred, it will be `i32` by default.
19 |
20 | ### **Floats**
21 |
22 | `f32` e `f64`. Examples: `1.0`, `-15.50f32`
23 |
24 | Floating point numbers can represent decimal numbers (with an impression inherent of the floating point representation in the _hardware_). _Floats_, as defined by IEEE-754, can be more a bit more painful to work with than what you're used to in other languages. Rust makes explicit some footguns that could pass unnoticed.
25 |
26 | ### **bool**
27 |
28 | Can be `true` or `false`.
29 |
30 | ### Unit
31 |
32 | This is the type of the empty tuple `()`, which is the only value of this type. It is used in places where there's no meaningful value defined. For example: functions which "return nothing" actually return `()`.
33 |
34 | ## Variables
35 |
36 | A variable stores a value and can be manipulated through its identifier. In Rust, we use `let` to define variables. `let` works with pattern matching, but for now we're not going to take advantage of it to keep things simple.
37 |
38 | Below there's the skeleton of declaration and binding of variables.
39 |
40 | ```rust,ignore
41 | // Declaration
42 | let : ;
43 |
44 | // Declaration with value binding
45 | let [: ] = ;
46 | ```
47 |
48 | Rust variables are immutable by default. If you try to change an immutable variable's content, the compiler will complain:
49 |
50 | ```rust,compile_fail
51 | // If you try to run it, You'll see that this code doesn't compile.
52 | let x = 5;
53 | x = 10;
54 | ```
55 |
56 | As our dear compiler suggests, just add `mut` before the identifier to make the variable mutable.
57 |
58 | ```rust
59 | // It'll work this time!
60 | let mut x = 5;
61 | x = 10;
62 | assert_eq!(x, 10);
63 | ```
64 |
65 | It's important to note that Rust has type inference. This means that it tries to identify undeclared types by using the types of the expressions present in the code. For example:
66 |
67 | ```rust,ignore
68 | let is_raining = true;
69 | ```
70 |
71 | It's not necessary to annotate the type. As `true` is of type `bool`, `is_raining` will also be.
72 |
73 | ## Operators
74 |
75 | A complete list can be found [on this Rust Book appendix](https://doc.rust-lang.org/book/appendix-02-operators.html).
76 |
77 | ### Arithmetic
78 |
79 | `+`, `-`, `/`, `*`, `%`
80 |
81 | In case you don't know, `%` is the division remainder of the first number by the second one.
82 |
83 | These operators can be used together with assignment. For example:
84 |
85 | ```rust
86 | let mut x = 2 + 2;
87 | x += 1;
88 | assert_eq!(x, 5);
89 | ```
90 |
91 | ### Logic
92 |
93 | - Negation: `!`
94 | - logic AND: `&&`
95 | - logic OR: `||`
96 |
97 | ```rust
98 | let x = true && !false;
99 | assert_eq!(x, true);
100 | ```
101 |
102 | ### Relational
103 |
104 | `<`, `<=`, `==`, `!=`, `>=`, `>`
105 |
106 | ```rust
107 | let x = 5 <= 10;
108 | assert_eq!(x, true);
109 |
110 | let y = 3 < 1;
111 | assert_eq!(y, false);
112 | ```
113 |
--------------------------------------------------------------------------------
/src/functional_programming.md:
--------------------------------------------------------------------------------
1 | # Programação Funcional
2 |
--------------------------------------------------------------------------------
/src/generics.md:
--------------------------------------------------------------------------------
1 | # Código Genérico
2 |
--------------------------------------------------------------------------------
/src/introduction/README.md:
--------------------------------------------------------------------------------
1 | # Introduction
2 |
3 | Start here. The idea is to prepare you for the remainder of the book.
4 |
--------------------------------------------------------------------------------
/src/introduction/hello_world.md:
--------------------------------------------------------------------------------
1 | # Hello, World
2 |
3 | It's a tradition, when starting to learn a new programming language, to present a program which consists of showing a `hello, world!` message on the terminal.
4 |
5 | Here we go:
6 |
7 | ```rust
8 | fn main() {
9 | println!("Hello, World!");
10 | }
11 | ```
12 |
13 | You can run this code straight from the book. Just click in the "play" button in the top-right corner of the box which contains the code.
14 |
15 | Just with this little piece of code it's possible to get in touch with a lot of elements of the language, which we'll see with details later. Don't worry trying to understand them deeply now.
16 |
17 | - The `main` function defines the execution's entry point. That's where your application's code starts to run.
18 | - Blocks are defined with a pair of `{` and `}`. Some languages, such as Python, use indentation. Others use keywords such as `begin` and `end`.
19 | - `println!` is a macro. I can say that because of the `!` in the end. When your program is compiled, macros are processed for code generation, which is inserted where they've been called. Don't worry about understanding macros now, just know that we'll use some of them before a deeper explanation.
20 | - `"Hello, World!"`, in a simplified view, can be seen as a text literal. In Rust, there are a few different types of text (e.g. `String`, `str`), each with its use case. It turns out that strings are more complicated than most programmers think, and Rust chose to be explicit about it.
21 | - `println!("Hello, World!");` is a statement which calls a macro passing a text as argument and has the effect of showing a content in the terminal (with a line break in the end). Statements in Rust end with `;`. There are expressions too, which are processed at runtime and reduced to a value. For example: `2 + 2` is reduced to the integer value `4`.
22 |
23 | I think that these information are a good start for a "hello, world!". Now we're starting on the right foot!
24 |
--------------------------------------------------------------------------------
/src/introduction/installation.md:
--------------------------------------------------------------------------------
1 | # Installation
2 |
3 | The most recommended way to install Rust is by using `rustup`, which takes care of the installations and updates of the language's official tools, such as `rustc`, `cargo`, and `clippy`.
4 |
5 | If you decided to install the language on your machine, just follow the instructions in the [rustup's website](https://rustup.rs) and you'll probably be good to go. In case you use Windows, I recommend you to take a look at the [Setup Rust for Windows](https://docs.microsoft.com/pt-br/windows/dev-environment/rust/setup) page, as you may need to install additional dependencies.
6 |
7 | In case you want to do small experiments without having to install the language, a good alternative is to use [the playground](https://play.rust-lang.org/), which is an online editor that allows you to compile and run simple code. It's also a good way to share code snippets with other people in case you need help on specific questions.
8 |
--------------------------------------------------------------------------------
/src/introduction/prerequisites.md:
--------------------------------------------------------------------------------
1 | # Pre-requisites
2 |
3 | In general, I assume that the reader knows how to program, at least in a basic level. If I were to write a guide to teach someone to program from scratch (and I intend to do it someday!) I would explain them about computer fundamentals and programming paradigms, and that would take a while to write well. If you don't know how to program and wants to follow the guide anyway, remember to take it easy and search for additional information on the web when you feel the need.
4 |
5 | Another important requisite is the alignment with my proposal. My focus is on the understanding of the concepts. In software, to understand what you're doing could be the difference between solving a problem in minutes or in days. There'll be examples and exercises throughout the guide, but my focus is always conceptual.
6 |
--------------------------------------------------------------------------------
/src/introduction/roadmap.md:
--------------------------------------------------------------------------------
1 | # Roadmap
2 |
3 | The idea of this page is to give an overview of the guide, briefly explaining each section. As the guide is still WIP, I will leave it for later.
4 |
--------------------------------------------------------------------------------
/src/ownership_and_borrowing.md:
--------------------------------------------------------------------------------
1 | # Ownership and Borrowing
2 |
3 | If you ask me: "what is Rust's most innovative feature?", my answer would be _ownership_. This concept allows the language to be memory-safe without a garbage collector. In practice, you have the performance of a systems language without giving up reliability.
4 |
5 | If you came from languages that are not C or C++, it means that now you have a systems language that feels like programming in the high-level. Anyone can write efficient code without the fear of accidentally corrupt the memory.
6 |
7 | If by chance you now C or C++, you probably needed to debug a series of errors from manual memory management. You'll be happy to know that `rustc` simply rejects programs which can cause these errors with helpful, instructive messages, explaining you what could go wrong.
8 |
9 | ## The Concept
10 |
11 | The ownership rules are pretty simple:
12 |
13 | - Every value has a variable which is its owner.
14 | - the value's ownership can be moved.
15 | - When the owner goes out of the scope, the value is released.
16 |
17 | ```rust,editable
18 | fn main() {
19 | let x = String::from("hello"); // x is the owner of the string
20 | // ...
21 | println!("Initially, x is owner of: {x}");
22 | // ...
23 | let y = x; // The string was moved to `y`. `x` stopped being the owner.
24 | // From this point, trying to access the string through `x` is an invalid operation, since the string was moved.
25 | // ...
26 | // println!("x is owner of: {x}"); // invalid!
27 | // ...
28 | println!("Now, y is owner of: {y}");
29 | // ...
30 | // At the end of this function, `y` goes out of scope and the string will be released.
31 | }
32 | ```
33 |
34 | Besides ownership, we have borrowing:
35 |
36 | - The value's owner can borrow it through shared references (immutable) or unique references (mutable).
37 | - At any moment, there can only be one unique reference or any number or any number of shared references.
38 | - References are always valid. They can't be used after the value they reference is moved or released.
39 |
40 | That's it. By following these rules, we are free from any trouble involving allocation and release of resources. **And the best part**: the compiler check if we're following them automatically.
41 |
42 | Illustrating with an example:
43 |
44 | ```rust,editable
45 |
46 | struct Book {
47 | title: String,
48 | }
49 |
50 | fn shared(book: &Book) {
51 | println!("[shared] The book's title is: {}\n", book.title);
52 | }
53 |
54 | fn unique(book: &mut Book) {
55 | println!("[unique] The book's title was: {}", book.title);
56 | book.title.push_str(" part 2");
57 | println!("[unique] Now the title is: {}\n", book.title);
58 | }
59 |
60 | fn be_owner(book: Book) {
61 | println!("[be_owner] I'm the owner of the book: {}\n", book.title);
62 | }
63 |
64 | fn main() {
65 | let mut first_owner = Book {
66 | title: String::from("How to make friends and influence people") // recommended
67 | };
68 |
69 | // Here, we are lending a shared borrow of the book to the variable `first_borrow`
70 | let first_borrow = &first_owner;
71 |
72 | // We create a second shared reference to pass to the function `shared`
73 | shared(&first_owner);
74 |
75 | // That's okay if you lend a mutable borrow....
76 | unique(&mut first_owner);
77 |
78 | // But you cannot access `first_borrow` anymore!
79 | // println!("title: {}", first_borrow.title);
80 |
81 | // But there's no problem to create a new shared reference.
82 | let second_borrow = &first_owner;
83 |
84 | // The idea is that if you have a shared reference, you cannot access it after it could've been changed (e.g. by a mutable reference or when the value is moved to other owner)
85 |
86 | // Everything okay!
87 | shared(second_borrow);
88 |
89 | // Ownership moved to other owner.
90 | let second_owner = first_owner;
91 |
92 | // All the preceding references stopped being valid because of the move. The old owner stopping being accessible too!
93 | // shared(second_borrow);
94 | // unique(&mut first_owner);
95 |
96 | println!("[main] second owner: {}\n", second_owner.title);
97 |
98 | be_owner(second_owner);
99 |
100 | // The book is not accessible here, since its ownership was passed to the `be_owner` function. At this point, the value has been released. `second_owner` is not accessible too.
101 | // let invalid_borrow = &second_owner;
102 | }
103 | ```
104 |
105 | Feel free to play with this example. Notice the error messages. They are very descriptive and were made to help you having a better understanding of why a given piece of code is invalid.
106 |
107 | All you have seen here affects the whole language. With time, these concepts become natural and you'll start to agree with the borrow checker (part of `rustc` which checks if you're following the rules) instead of fighting it. I even miss these concepts when I go back to other languages, because it's usually easier to understand what's happening in the source code.
108 |
109 | Maybe some people will notice that certain things which cause errors in the `Book` example are possible with integers and floats. The reason is that these types are cheap to copy. So, instead of moving them, the value is copied. It happens because they implement the trait `Copy`. We'll talk about traits ahead, but they're similar to interfaces in other languages.
110 |
111 | Besides that, I omitted the lifetimes concept in purpose. They are necessary for the compiler to guarantee that the references are always valid. However, it seemed more appropriate to get into this concept after explaining generic code, as a lifetime is a sort of generalization over how long a reference is valid.
112 |
113 | ## What `rustc` protects you from
114 |
115 | The following examples are written in C, because it allows to illustrate well how you could cause undefined behavior (UB) in your program, which is basically an elegant way of telling that it can, under any execution, make your application:
116 |
117 | - Abort execution
118 | - Run normally
119 | - Run, but process invalid values
120 |
121 | When you got UB, the best to happen is the execution to be aborted as soon as the corruption occurs. This way, you can try to identify where the improper memory use occurred. Nonetheless, it can work on your machine, but not in production. Yeah, very fun.
122 |
123 | Personally, I just understood all the memory problems below after learning Rust. Before that, I just stumbled on them without fully understanding the kind of error that was happening on my program. In my C learning, no reference I used taught me about those classes of errors in a clear way.
124 |
125 | ### use after free
126 |
127 | It consists in using a memory which you already released to the system. When a memory region is no longer yours, there's no guarantee that you're accessing valid information.
128 |
129 | ```c
130 | void main() {
131 | int *p = malloc(sizeof(int));
132 | // ...
133 | free(p);
134 | *p = 123; // Writing on a released memory region! UB!
135 | }
136 | ```
137 |
138 | In the best case, you'll get a segmentation fault. In the worst, `*p`'s content will be overwritten and you'll process garbage, making the execution fails in other part of the code, or even worse: your program may generate and invalid output. I lost two nights of sleep on this kind of error once.
139 |
140 | In Rust, it doesn't even compile:
141 |
142 | ```rust,compile_fail
143 | fn main() {
144 | let x = String::from("ferris!");
145 | drop(x); // The string's ownership has been moved to `drop`
146 | // ...
147 | println!("{x}");
148 | }
149 | ```
150 |
151 | ### double free
152 |
153 | The same memory address is released twice.
154 |
155 | ```c
156 | void main() {
157 | void *p = malloc(500);
158 | // ...
159 | free(p);
160 | // ...
161 | free(p); // Same address released more than once! UB!
162 | }
163 | ```
164 |
165 | It looks improbable to occur, but it can be easy to introduce on a refactor.
166 |
167 | In Rust, it doesn't even compile:
168 |
169 | ```rust,compile_fail
170 | fn main() {
171 | let x = String::from("ferris!");
172 | drop(x); // The string's ownership has been moved to `drop`
173 | // ...
174 | drop(x); // It isn't possible to pass to `drop` (or to any other fn) a value which has been moved.
175 | }
176 | ```
177 |
178 | ### Dereferencing a null pointer
179 |
180 | [The 1 billion dollars mistake](https://en.wikipedia.org/wiki/Tony_Hoare#Apologies_and_retractions). Even high-level languages, with garbage collection, allow this memory error.
181 |
182 | ```c
183 | void main() {
184 | void *p = malloc(500); // this function may return NULL in case memory hasn't been allocated successfully
185 | // ...
186 | *p = 123; // Following a NULL pointer! UB!
187 | }
188 | ```
189 |
190 | The good side of this error is that it normally aborts the execution instead of processing invalid data. The bad side... This is an error class which is totally avoidable, even without ownership. The sooner errors are fixed, lower are the costs. If your tools stop the introduction of certain kinds of defects, that's even better.
191 |
192 | In Rust... There's no null reference. We use `Option` to represent that a value of type `T` can be present (`Some(value)`) or not (`None`).
193 |
194 | ```rust,editable
195 | fn main() {
196 | let x: Option = Some(String::from("ferris!"));
197 | // ...
198 | // I can't access string directly without first checking if `x`, which is a `Option`, is `Some(...)` or `None`.
199 | match x {
200 | Some(value) => println!("I found this: {value}"),
201 | None => println!("Nothing here!"),
202 | }
203 | }
204 | ```
205 |
206 | ### Memory leak
207 |
208 | Technically, leaking memory isn't considered UB. However, it consumes system resources unnecessarily.
209 |
210 | ```c
211 | void main() {
212 | void *p = malloc(500000000);
213 | // Using p...
214 | // ...
215 | // I don't need `p` anymore, but I forgot to `free` it...
216 | // ...
217 | }
218 | ```
219 |
220 | In Rust, memory will be released automatically once the owner goes out of scope. Even though leaking memory is something safe to do in Rust (i.e. someone could leak memory explicitly if they want/need without using `unsafe`), most of the time it'll be released automatically due to the ownership concept.
221 |
222 | ### Accessing an invalid memory region
223 |
224 | To read or to write information beyond the allocated memory. The memory you accessed isn't yours, so anything can happen.
225 |
226 | ```c
227 | void main() {
228 | int *p = malloc(10 * sizeof(int));
229 | p[10] = 42; // I wrote on the 11th position! UB!
230 | }
231 | ```
232 |
233 | Reasonably easy to happen when using arrays.
234 |
235 | In Rust, the execution will always be aborted, indicating which code tried to perform an invalid access to memory:
236 |
237 | ```rust,should_panic
238 | fn main() {
239 | let x = vec![1, 2, 3];
240 | // ...
241 | let v = x[100_000]; // For sure our `vec` doesn't have all that size
242 | println!("An integer from x: {v}");
243 | }
244 | ```
245 |
246 | ### Manipulate uninitialized memory
247 |
248 | Uninitialized memory may contain anything. In the best case, the memory will be zeroed. In the worst, you'll read anything that was written there before.
249 |
250 | ```c
251 | void main() {
252 | int *p;
253 | // ...
254 | int x = *p; // Dereferencing `p` without initializing it before! UB!
255 | }
256 | ```
257 |
258 | In Rust, it doesn't even compile:
259 |
260 | ```rust,compile_fail
261 | fn main() {
262 | let x: String;
263 | // Oops, we forgot to initialize...
264 | println!("{x}");
265 | }
266 | ```
267 |
268 | ## Conclusion
269 |
270 | Probably, there's other memory problems that I didn't cover. Fortunately, you'll hardly find them. Yes, it's possible to have UB in Rust if you (or your dependency) uses _unsafe_ incorrectly, but it's very likely that you won't need this language resource to develop your software.
271 |
272 | Don't worry about decorating the rules. What is important is to understand what each of them mean. It's the compiler's job to ensure that they are being followed.
273 |
--------------------------------------------------------------------------------
/src/project_structure.md:
--------------------------------------------------------------------------------
1 | # Estrutura de um projeto
2 |
--------------------------------------------------------------------------------
/src/structured_programming.md:
--------------------------------------------------------------------------------
1 | # Programação Estruturada
2 |
--------------------------------------------------------------------------------
/src/structured_programming/README.md:
--------------------------------------------------------------------------------
1 | # Programação Estruturada
2 |
--------------------------------------------------------------------------------
/src/structured_programming/decision.md:
--------------------------------------------------------------------------------
1 | # Decisão
2 |
--------------------------------------------------------------------------------
/src/structured_programming/functions.md:
--------------------------------------------------------------------------------
1 | # Funções
2 |
--------------------------------------------------------------------------------
/src/structured_programming/repetition.md:
--------------------------------------------------------------------------------
1 | # Repetição
2 |
--------------------------------------------------------------------------------
/src/structured_programming/sequence.md:
--------------------------------------------------------------------------------
1 | # Sequência
2 |
--------------------------------------------------------------------------------
/src/tools.md:
--------------------------------------------------------------------------------
1 | # Tools
2 |
3 | Next, there's a list of a few tools which are very important for the language. Each section title has a link to that tool's documentation, in case you want more specific information.
4 |
5 | ## [Rustup](https://rustup.rs)
6 |
7 | Rust's installer. With it you can install and update many language tools. Some of them are described below.
8 |
9 | ## [Rustc](https://doc.rust-lang.org/rustc/index.html)
10 |
11 | Language's compiler. Usually, it's not used directly, because `cargo` simplifies some development-related tasks and deals with the compiler for us.
12 |
13 | ## [Cargo](https://doc.rust-lang.org/cargo/index.html)
14 |
15 | Rust's build tool and package manager. It allows to:
16 |
17 | - Create a package with a standardized structure: `cargo new `
18 | - Perform some development activities:
19 | - Check if the code compiles: `cargo check`
20 | - Run tests: `cargo test`
21 | - Compile the code: `cargo build`
22 | - Compiled **and** run the code: `cargo run`
23 | - Publish a package to be used by other people: `cargo publish`
24 |
25 | There's many other things which can be done using `cargo`, but that's a good start.
26 |
27 | ## [Rustfmt](https://github.com/rust-lang/rustfmt)
28 |
29 | Rust's code formatter. Virtually every project uses it. This standardization reduces repetitive work while coding, facilitates the onboarding on new code bases, ends discussions about style... The advantages compensate (by a lot) the freedom's reduction on the code style choice.
30 |
31 | To use it, just run `cargo fmt` and all your project will be formatted.
32 |
33 | ## [Clippy](https://github.com/rust-lang/rust-clippy)
34 |
35 | Language's linter, which is basically a tool which analyzes your code and is capable of offering suggestions to try to make it better. Specially in the beginning, `cargo clippy` can show you more idiomatic ways to write code. Besides that, it can also identify some common programming mistakes.
36 |
37 | ## [Rustdoc](https://doc.rust-lang.org/rustdoc/what-is-rustdoc.html)
38 |
39 | Rust is known by its ecosystem having above-average documentation and this is due to the excellent documentation generation support we have from `rustdoc`. By running `cargo doc`, the documentation from your project and your dependencies are built and everyone has access to them in an standardized way, reducing the weight of this activity and improving the productivity of those who write or read documentation, which is basically everyone.
40 |
41 | ## IDE Support
42 |
43 | A modern language **needs** to have good support to interact with source code. Although Rust is a new language, there are very good projects to offer this support to code editors.
44 |
45 | ### [Rust-Analyzer](https://rust-analyzer.github.io/)
46 |
47 | It's the Language Server which powers many text editors, like VS Code and Vim. On VS Code, just need to install the `rust-lang.rust-analyzer` extension to have great support.
48 |
49 | ### [Intellij Rust](https://www.jetbrains.com/pt-br/rust/)
50 |
51 | For Intellij-based IDEs, there's a plugin openly developed by JetBrains which brings Rust support for their editors. Just go to the plugins manager and install it to use Rust on Intellij.
52 |
--------------------------------------------------------------------------------
/src/training_projects.md:
--------------------------------------------------------------------------------
1 | # Projetos de Treino
2 |
--------------------------------------------------------------------------------
/src/types_and_traits.md:
--------------------------------------------------------------------------------
1 | # Tipos e Traits
2 |
--------------------------------------------------------------------------------
/theme/head.hbs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------