├── .gitignore ├── .prettierrc ├── 00_intro.md ├── 01_variables.md ├── 02_functions.md ├── 03_control_flow.md ├── 04_primitives.md ├── 05_ownership.md ├── 06_references.md ├── 07_slices.md ├── 08_structs.md ├── 09_enums.md ├── 10_generics.md ├── 11_traits.md ├── 12_types.md ├── 13_effects.md ├── 14_lifetimes.md ├── 15_closures.md ├── 16_iterators.md ├── 17_collections.md ├── 18_strings.md ├── 19_smart_pointers.md ├── 20_patterns.md ├── 21_modules.md ├── 22_cargo.md ├── 23_tests.md ├── 24_attributes.md ├── 25_threads.md ├── 26_macros.md ├── 27_unsafe.md ├── 28_async.md ├── README.md ├── assets ├── string_ptr.svg ├── string_ptr_ref.svg └── string_slice.svg └── exercises ├── collections ├── Cargo.lock ├── Cargo.toml └── src │ └── main.rs ├── guessing_game ├── Cargo.lock ├── Cargo.toml └── src │ └── main.rs └── minigrep ├── Cargo.lock ├── Cargo.toml ├── poem.txt └── src ├── lib.rs └── main.rs /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .idea/ 3 | .tmp/ 4 | target/ 5 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "proseWrap": "always" 3 | } 4 | -------------------------------------------------------------------------------- /00_intro.md: -------------------------------------------------------------------------------- 1 | # Intro 2 | 3 | **Rust** is a compiled, statically and strongly typed language. Main features: 4 | 5 | - memory safety 6 | - low-level performance 7 | - zero-cost abstractions 8 | - non-nullable references 9 | 10 | Install Rust via `rustup`, which installs all Rust tools and `cargo` — Rust's 11 | official package manager and orchestration tool. 12 | 13 | For a playground during learning, run `cargo new playground`, edit `main.rs` and 14 | run by `cargo run` in the project root directory. 15 | 16 | ## Constructs 17 | 18 | * **primitives** like `i32`, `f64`, `bool` 19 | * **arrays** are fixed-size collections of values of the same type, `[i32; 100]` 20 | * **tuples** are collections of values of different types, `(i32, i32, &str)` 21 | * **references** allow _borrowing_ data, `&value` 22 | * **slices** offer referencing data sequences with a variable size, `[T]`, `str` 23 | * **structs** hold related data and define related **methods** 24 | , `vector.normalize()` 25 | * **enums** define _variants_ of types, `Result` and its `Ok(T)`, `Err(E)` 26 | * **generics** allow parameters of different types `Vec` 27 | * **traits** define behavior that types have like `ToString` 28 | * **DSTs** are types with size not known at compile-time, `dyn Trait`, `[T]` 29 | , `str` 30 | * **lifetimes** ensure data validity, `'static`,`'a` 31 | * **closures** are anonymous functions that capture their context, `|x| x * 2` 32 | * **attributes** are metadata for crates, modules or items, `#[attr]` 33 | , `#![crate_attr]` 34 | * **macros** for metaprogramming, declarative and 35 | procedural, `println!("a macro")` or `#[derive(Debug)]` 36 | 37 | ## Comments 38 | 39 | Comments are specified after `//`. No special multiline syntax. 40 | 41 | ## Conventions 42 | 43 | * `snake_case` for _crates_, but prefer single-word 44 | * `snake_case` for _functions_, _variables_, _macros_ and _lifetimes_ 45 | * `PascalCase` for _enums_, _structs_, _generics_ and _traits_ 46 | * `SCREAMING_SNAKE_CASE` for _constants_ and _statics_ 47 | -------------------------------------------------------------------------------- /01_variables.md: -------------------------------------------------------------------------------- 1 | # Variables 2 | 3 | Every variable and reference is **immutable** by default. 4 | 5 | ## Declaration 6 | 7 | * `let` declares a variable 8 | * `let mut` declares a _mutable_ variable 9 | * `const` declares a constant that gets inlined during compilation 10 | * `static` declares a variable with a static location in memory 11 | * `static mut` declares a _mutable_ variable with a static location in memory 12 | 13 | ## Variables 14 | 15 | Variables declared using `let` or `let mut`: 16 | 17 | ```rust 18 | fn main() { 19 | let x: i32 = 5; 20 | 21 | let mut y: i32 = 10; 22 | y = 12; 23 | } 24 | ``` 25 | 26 | Type can be inferred: 27 | 28 | ```rust 29 | fn main() { 30 | let x = -4; // i32 31 | } 32 | ``` 33 | 34 | Initialization can be deferred, _type annotation_ is optional: 35 | 36 | ```rust 37 | fn main() { 38 | let z; 39 | // ... 40 | z = 6; 41 | } 42 | ``` 43 | 44 | Initializing the same variable multiple times _shadows_ the previous 45 | declaration, types can differ: 46 | 47 | ```rust 48 | fn main() { 49 | let x = 5; 50 | // ... 51 | let x = "kek"; 52 | } 53 | ``` 54 | 55 | ## Statics 56 | 57 | Static variables are declared using `static` in the global scope. They can be 58 | _mutable_, although mutable static variables is a bad practice because they're 59 | not thread safe. They must have a _type annotation_. 60 | 61 | Static variables have a static place in memory and can be passed around as 62 | references. 63 | 64 | ```rust 65 | static NICKNAME: &str = "henchbruv"; 66 | static mut PLAYERS: u32 = 0; // :( 67 | ``` 68 | 69 | ## Constants 70 | 71 | Constants are declared using `const` and are values that are inlined during 72 | compilation. They can be declared in any scope. They must have a _type 73 | annotation_. 74 | 75 | ```rust 76 | const MAX_VALUE: u32 = 1337; 77 | ``` 78 | 79 | Unless interior mutability or a static place in memory is required, constants 80 | are preferred over statics. 81 | -------------------------------------------------------------------------------- /02_functions.md: -------------------------------------------------------------------------------- 1 | # Functions 2 | 3 | Declared using `fn` and arguments, return type by `->`. 4 | 5 | ```rust 6 | fn add_one(x: i32) -> i32 { 7 | x + 1 8 | } 9 | ``` 10 | 11 | Functions can be used before they are declared: 12 | 13 | ```rust 14 | fn add_two(x: i32) -> i32 { 15 | add_one(add_one(x)) 16 | } 17 | 18 | fn add_one(x: i32) -> i32 { 19 | x + 1 20 | } 21 | ``` 22 | 23 | ## Return 24 | 25 | Like in regular blocks, the last _expression_ in a function block is the _return 26 | value_: 27 | 28 | ```rust 29 | fn add_one(x: i32) -> i32 { 30 | x + 1 31 | } 32 | 33 | // is the same as 34 | fn add_one_return(x: i32) -> i32 { 35 | return x + 1; 36 | } 37 | ``` 38 | 39 | ## Main 40 | 41 | Function `main` in `src/main.rs` is the application entrypoint. 42 | 43 | It returns either `()`: 44 | 45 | ```rust 46 | // src/main.rs 47 | fn main() { 48 | println!("kek"); 49 | } 50 | ``` 51 | 52 | Or `Result<(), E>`: 53 | 54 | ```rust 55 | use std::num::ParseIntError; 56 | 57 | fn main() -> Result<(), ParseIntError> { 58 | let number_str = "10"; 59 | let number = match number_str.parse::() { 60 | Ok(number) => number, 61 | Err(e) => return Err(e), 62 | }; 63 | println!("{}", number); 64 | Ok(()) 65 | } 66 | ``` 67 | 68 | ## Pointers 69 | 70 | Functions can be passed around as _pointers_: 71 | 72 | ```rust 73 | fn add_one(x: i32) -> i32 { 74 | x + 1 75 | } 76 | 77 | fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 { 78 | f(arg) + f(arg) 79 | } 80 | 81 | fn add_two(x: i32) -> i32 { 82 | do_twice(add_one, x) 83 | } 84 | ``` 85 | 86 | ## Const functions 87 | 88 | Functions that only operate with arguments and operations performable at 89 | _compile-time_ can be marked as `const fn` and used in such contexts: 90 | 91 | ```rust 92 | const X: i32 = 1337; 93 | const X_TWO: i32 = double(X); // 2674 94 | 95 | const fn double(x: i32) -> i32 { 96 | x * 2 97 | } 98 | ``` 99 | -------------------------------------------------------------------------------- /03_control_flow.md: -------------------------------------------------------------------------------- 1 | # Control flow 2 | 3 | Most of the control flow constructs except `for` and `while` loops are 4 | _expressions_. 5 | 6 | ## Block 7 | 8 | Blocks create their own _scope_. They are an _expression_ with the value of the 9 | last expression in the block: 10 | 11 | ```rust 12 | fn main() { 13 | let x = { 14 | let y = 5; 15 | println!("y = {}", y); 16 | y 17 | }; 18 | println!("x = {}", x); 19 | } 20 | ``` 21 | 22 | Note that the last expression cannot be followed by `;` or it would be 23 | considered a _statement_ instead. 24 | 25 | ## If 26 | 27 | Works like in most languages, except is an _expression_: 28 | 29 | ```rust 30 | fn main() { 31 | let ternary = if x < 5 { "small" } else { "big" }; 32 | } 33 | 34 | fn rng(x: i32) -> i32 { 35 | if x < 5 { 36 | x 37 | } else if x < 10 { 38 | x * 2 39 | } else { 40 | x * 3 41 | } 42 | } 43 | ``` 44 | 45 | ## Match 46 | 47 | A switch-like expression that matches patterns and values. Must be _exhaustive_ 48 | — all possible patterns and values must be matched at least in one arm: 49 | 50 | ```rust 51 | fn main() { 52 | let text = match val { 53 | Some(5) => "five", 54 | Some(x) => "some other number", 55 | None => "nothing", 56 | }; 57 | } 58 | ``` 59 | 60 | ### If let 61 | 62 | Syntax sugar for `match` that matches one pattern does nothing with the rest: 63 | 64 | ```rust 65 | fn main() { 66 | if let Some(x) = val { 67 | println!("x = {}", x); 68 | } 69 | } 70 | ``` 71 | 72 | Can also have `else` and `else if` like regular `if` expressions. 73 | 74 | ## Loop 75 | 76 | Loops forever. The `break` statement can be called with a value to return a 77 | value from the `loop`. 78 | 79 | ```rust 80 | fn main() { 81 | let mut counter = 0; 82 | let result = loop { 83 | counter += 1; 84 | 85 | if counter == 10 { 86 | break counter * 2; 87 | } 88 | }; 89 | } 90 | ``` 91 | 92 | ## For 93 | 94 | Looping through iterables is done with a `for` statement: 95 | 96 | ```rust 97 | fn main() { 98 | for number in 1..4 { 99 | println!("{}", number); 100 | } 101 | } 102 | ``` 103 | 104 | ## While 105 | 106 | Runs `while` the condition evaluates to `true`: 107 | 108 | ```rust 109 | fn main() { 110 | let a = [10, 20, 30, 40, 50]; 111 | let mut index = 0; 112 | 113 | while index < 5 { 114 | println!("the value is: {}", a[index]); 115 | index += 1; 116 | } 117 | } 118 | ``` 119 | 120 | ### While let 121 | 122 | Runs `while` the pattern matches, like in `if let`: 123 | 124 | ```rust 125 | fn main() { 126 | let mut stack: Vec = vec![3, 33, 44]; 127 | while let Some(num) = stack.pop() { 128 | println!("popped {}", num); 129 | } 130 | } 131 | ``` 132 | -------------------------------------------------------------------------------- /04_primitives.md: -------------------------------------------------------------------------------- 1 | # Primitives 2 | 3 | Rust has a wide variety of primitive values. 4 | 5 | ## Scalars 6 | 7 | * signed ints `i8`, `i16`, `i32`, `i64`, `i128` and `isize` (pointer size) 8 | * unsigned ints `u8`, `u16`, `u32`, `u64`, `u128` and `usize` (pointer size) 9 | * floats `f32`, `f64` 10 | * `char` **Unicode** scalar values like `'a'`, `'α'` and `'∞'` (4 bytes each) 11 | * `bool` either `true` or `false` 12 | * unit type `()`, which is an empty tuple 13 | 14 | ### Literals 15 | 16 | Integers `420`, floats `13.37`, chars `'a'`, strings `"kek"`, booleans `true` 17 | and the union type `()` can be expressed as literals. 18 | 19 | Integers can have a prefix to change their expression: 20 | 21 | - `0x` hexadecimals 22 | - `0o` octals 23 | - `0b` binary 24 | 25 | Numbers can have a suffix like `100u32` to set their type. Numeric literals can 26 | have `_` placed in them for readability, like `1_000_000`. 27 | 28 | Operators and their precedence is similar to **C-like** languages: 29 | 30 | ```rust 31 | fn main() { 32 | // Short-circuiting boolean logic 33 | println!("true AND false is {}", true && false); 34 | println!("true OR false is {}", true || false); 35 | println!("NOT true is {}", !true); 36 | 37 | // Bitwise operations 38 | println!("0011 AND 0101 is {:04b}", 0b0011u32 & 0b0101); 39 | println!("0011 OR 0101 is {:04b}", 0b0011u32 | 0b0101); 40 | println!("0011 XOR 0101 is {:04b}", 0b0011u32 ^ 0b0101); 41 | println!("1 << 5 is {}", 1u32 << 5); 42 | println!("0x80 >> 2 is 0x{:x}", 0x80u32 >> 2); 43 | } 44 | ``` 45 | 46 | ## Tuples 47 | 48 | A fixed-size collection of values: 49 | 50 | ```rust 51 | fn main() { 52 | let vector = (1, 3, 3.7); 53 | let single = (420, ); // trailing comma needed for single element tuples 54 | } 55 | ``` 56 | 57 | Types can differ: 58 | 59 | ```rust 60 | fn main() { 61 | let mishmash = (420, "blazeit"); 62 | } 63 | ``` 64 | 65 | They're indexed with `.` and a number, e.g. `.0` for the first element. Their 66 | type can be specified in arguments: 67 | 68 | ```rust 69 | fn multiply_vector(v: (i32, i32, i32), n: i32) -> (i32, i32, i32) { 70 | (v.0 * n, v.1 * n, v.2 * n) 71 | } 72 | ``` 73 | 74 | ## Arrays 75 | 76 | A collection of objects of the same type. Their length is known at _compile 77 | time_. Their signature is `[T; length]`. 78 | 79 | ```rust 80 | fn main() { 81 | let xs = [1, 2, 3, 4, 5]; // type [i32; 5] 82 | } 83 | ``` 84 | 85 | Creating an array with certain length and a default value: 86 | 87 | ```rust 88 | fn main() { 89 | let xs = [0; 500]; // type [i32, 500] 90 | } 91 | ``` 92 | -------------------------------------------------------------------------------- /05_ownership.md: -------------------------------------------------------------------------------- 1 | # Ownership 2 | 3 | Rust's ownership system follows these rules: 4 | 5 | - Each value has a variable that’s called its _owner_ 6 | - There can only be one owner at a time 7 | - When the owner goes out of scope, the value will be dropped 8 | 9 | Values have to have a _fixed size_ known at _compile-time_ to be stored on the 10 | _stack_. 11 | 12 | Variable- or dynamically-sized data are stored on the _heap_, and their 13 | _pointer_ is stored on the stack. 14 | 15 | ## RAII 16 | 17 | Rust enforces [RAII](https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization) 18 | (Resource Acquisition Is Initialization). In addition to holding data on the 19 | stack, variables also _own_ resources allocated on the heap. 20 | 21 | Variable bindings have a _scope_, and are constrained to live in a _block_. 22 | Variables are valid as long as their scope is valid: 23 | 24 | ```rust 25 | fn main() { 26 | let w = "kek"; 27 | { // s is not valid here, it’s not yet declared 28 | let s = "hello"; // s is valid from this point forward 29 | // ... 30 | } // this scope is now over, and s is no longer valid 31 | // w valid, s invalid 32 | } 33 | ``` 34 | 35 | When a variable goes out of scope, its `Drop` trait destructor is called and its 36 | resources are freed. 37 | 38 | ### Stack 39 | 40 | When a primitive value is assigned to another variable or passed to a function, 41 | its value is _copied_ and stored in the function's stack. This copy has its own 42 | scope in the function: 43 | 44 | ```rust 45 | fn main() { 46 | let n1 = 5; 47 | let n2 = n1; // n1 copied to n2, both valid 48 | 49 | gimme_string(n2); 50 | // both n1 and n2 valid 51 | } 52 | 53 | fn gimme_number(n: i32) { // n copied, has the scope of the function 54 | println!("Got a number: {}", n); 55 | } // nothing special happens 56 | ``` 57 | 58 | When a function ends, the function's stack data are popped. 59 | 60 | ### Heap 61 | 62 | When a dynamic memory is allocated, a _fat pointer_ to this data is stored into 63 | a variable. 64 | 65 | > A _fat pointer_ is a pointer containing additional metadata, like length 66 | > and capacity. 67 | 68 | When this variable goes out of scope, its owned resources are freed: 69 | 70 | ```rust 71 | fn print_kek() { 72 | let s1 = "hello".to_string(); // s1 points to the allocated data 73 | println!("{}", s1); 74 | } // s1 goes out of scope, data freed 75 | ``` 76 | 77 | This is how a `String` fat pointer looks like: 78 | 79 | ![String pointer](assets/string_ptr.svg) 80 | 81 | ## Moving 82 | 83 | When a fat pointer is assigned to a variable, the variable becomes the pointer's 84 | _owner_. If the pointer is assigned to another variable or passed to a function, 85 | the pointer is _moved_ and gets a new owner: 86 | 87 | ```rust 88 | fn main() { 89 | let s1 = "hello".to_string(); 90 | let s2 = s1; // s1 moved to s2, s1 is no longer valid 91 | 92 | gimme_string(s2); 93 | // cannot use s2 anymore :( 94 | } 95 | 96 | fn gimme_string(s: String) { // s moved, now owned by the function 97 | println!("Now I own: {}", s); 98 | } // s no longer valid and deallocated 99 | ``` 100 | 101 | When returning fat pointers from functions, their ownership is moved: 102 | 103 | ```rust 104 | fn main() { 105 | let s = make_string(); // s owns the return value of make_string() 106 | } 107 | 108 | fn make_string() -> String { 109 | "lmao".to_string() 110 | } 111 | ``` 112 | -------------------------------------------------------------------------------- /06_references.md: -------------------------------------------------------------------------------- 1 | # References 2 | 3 | Reference to a value is taken by the `&` operator. This creates a _thin pointer_ 4 | to the data. Taking a reference to a value is called _borrowing_. 5 | 6 | ```rust 7 | fn main() { 8 | let s = "kek".to_string(); 9 | println!("Length is {}", string_length(&s)); 10 | } 11 | 12 | fn string_length(s: &String) -> usize { 13 | s.len() 14 | } 15 | ``` 16 | 17 | Reference to a fat pointer to a value stored on the heap: 18 | 19 | ![Reference to a fat pointer](assets/string_ptr_ref.svg) 20 | 21 | References are _immutable_ by default. Only mutable variables can be borrowed as 22 | mutable. Use `&mut` to make a reference _mutable_: 23 | 24 | ```rust 25 | fn main() { 26 | let mut s = "top".to_string(); 27 | append_kek(&mut s); // s is now topkek 28 | } 29 | 30 | fn append_kek(s: &mut String) { 31 | s.push_str("kek"); 32 | } 33 | ``` 34 | 35 | References must obey the following rules: 36 | 37 | - there can be any number of _immutable_ references 38 | - there can be only one _mutable_ reference 39 | - when a _mutable_ reference exists, no _immutable_ reference can exist 40 | 41 | ## Scope 42 | 43 | Same as variables, references are valid until the end of their _scope_. 44 | Immutable references are no longer valid after a _mutable borrow_: 45 | 46 | ```rust 47 | fn main() { 48 | let mut number = 5; 49 | let x = &number; // valid 50 | let y = &number; // valid 51 | println!("Numbers: {}, {}", x, y); 52 | 53 | let z = &mut number; // x and y no longer valid! 54 | println!("Number: {}", z); 55 | } 56 | ``` 57 | 58 | References whose values were created inside a function cannot be returned from 59 | within the function. Functions can only return created _primitives_ and _fat 60 | pointers_: 61 | 62 | ```rust 63 | // OK, value copied 64 | fn gimme_primitive() -> i32 { 65 | 1337 66 | } 67 | 68 | // OK, ownership moved 69 | fn gimme_pointer() -> String { 70 | "yep".to_string() 71 | } 72 | 73 | // Error! 74 | fn bad_function() -> &String { 75 | let s = "nope".to_string(); 76 | &s // compilation error! 77 | } // s no longer valid here, cannot return from the function 78 | ``` 79 | 80 | ## Dereferencing 81 | 82 | Mutating referenced values is done by _dereferencing_ using the `*` operator: 83 | 84 | ```rust 85 | fn main() { 86 | let mut n = 10; 87 | to_five(&mut n); // n is now 5 88 | } 89 | 90 | fn to_five(x: &mut i32) { 91 | *x = 5; // changes the value where the reference points at to 5 92 | } 93 | ``` 94 | 95 | Note that the reference must be a `&mut`. 96 | 97 | ### Deref coercion 98 | 99 | A compiler feature called `Deref` coercion automatically dereferences types 100 | implementing the `Deref` trait if the supplied type to a function call doesn't 101 | match the expected type. 102 | 103 | The supplied type is being _dereferenced_ until the suitable type is found: 104 | 105 | ```rust 106 | fn gib_num(x: &i32) { 107 | // ... 108 | } 109 | 110 | fn main() { 111 | let x = Box::new(5); 112 | gib_num(&*x); // is the explicit form 113 | gib_num(&x); // turns into &*x 114 | gib_num(&&&x); // turns into &*&*&*x 115 | } 116 | ``` 117 | 118 | This feature is most commonly used by _fat pointers_ and _slices_. 119 | -------------------------------------------------------------------------------- /07_slices.md: -------------------------------------------------------------------------------- 1 | # Slices 2 | 3 | Slices are a type of _references_ that reference contiguous sequence of elements 4 | in a collection rather than the whole collection: 5 | 6 | ```rust 7 | fn main() { 8 | let s = "hello world".to_string(); 9 | 10 | let hello = &s[..5]; 11 | let world = &s[6..]; 12 | } 13 | ``` 14 | 15 | This is how slices are stored in memory: 16 | 17 | ![Slice in memory](assets/string_slice.svg) 18 | 19 | ## Range 20 | 21 | Ranges are defined using the `..` syntax for exclusive, and `..=` for inclusive 22 | range. The first or last index can be dropped to capture the start or end of a 23 | collection: 24 | 25 | ```rust 26 | fn main() { 27 | let a = [1, 2, 3, 4, 5]; 28 | 29 | let s = &a[0..5]; // [1, 2, 3, 4, 5] 30 | let s = &a[0..=4]; // [1, 2, 3, 4, 5] 31 | let s = &a[..]; // [1, 2, 3, 4, 5] 32 | let s = &a[1..]; // [ 2, 3, 4, 5] 33 | let s = &a[..4]; // [1, 2, 3, 4 ] 34 | let s = &a[2..=3]; // [ 3, 4 ] 35 | } 36 | ``` 37 | 38 | ## Collections 39 | 40 | More complex collections such as `Vec` or `String` use primitive collections 41 | such as arrays and `str` data under the hood. They mainly serve as an 42 | abstraction for data manipulation using methods such as `Vec::push` 43 | or `String::push_str`. 44 | 45 | ### Dereferencing 46 | 47 | Data types that use primitive collections under the hood implement the `Deref` 48 | trait so that they return a slice of the underlying data when sliced: 49 | 50 | ```rust 51 | fn main() { 52 | let a = [1, 2, 3, 4]; 53 | let v = vec![1, 2, 3, 4]; 54 | 55 | let s1 = &a[..]; // &[i32] 56 | let s2 = &v[..]; // &[i32] 57 | // s1 == s2 58 | } 59 | ``` 60 | 61 | ### Arguments 62 | 63 | When a funciton does an _immutable borrow_ of a collection, the best practice is 64 | to use slices as arguments instead of a specific collection implementation. This 65 | allows passing both raw values and more abstract data types: 66 | 67 | ```rust 68 | fn main() { 69 | let s = after_n(3, "lolkekbur"); // &str string literal slice directly 70 | let s = after_n(3, &"lolkekbur".to_string()); // Deref-coerced &String -> &str 71 | 72 | let (x, y) = split_half(&[1, 2, 3, 4]); // &[i32] array slice directly 73 | let (x, y) = split_half(&vec![1, 2, 3, 4]); // Deref-coerced &Vec -> &[i32] 74 | } 75 | 76 | fn after_n(n: usize, s: &str) -> &str { 77 | &s[n..] 78 | } 79 | 80 | fn split_half(a: &[i32]) -> (&[i32], &[i32]) { 81 | let len = a.len() / 2; 82 | (&a[..len], &a[len..]) 83 | } 84 | ``` 85 | 86 | `Deref` coercion _slices_ collections that wrap slices: 87 | 88 | ```rust 89 | fn main() { 90 | let word = "lolkekbur".to_string(); 91 | 92 | let s = after_n(3, &word[..]); // is the explicit form 93 | let s = after_n(3, &word); // turns into &word[..] 94 | let s = after_n(3, &&&word); // turns into *&*&&word[..] 95 | } 96 | 97 | fn after_n(n: usize, s: &str) -> &str { 98 | &s[n..] 99 | } 100 | ``` 101 | 102 | -------------------------------------------------------------------------------- /08_structs.md: -------------------------------------------------------------------------------- 1 | # Structs 2 | 3 | Structs hold related data of different types together and have a name: 4 | 5 | ```rust 6 | // Named fields struct 7 | struct User { 8 | username: String, 9 | email: String, 10 | credits: u64, 11 | } 12 | 13 | // Tuple struct 14 | struct Point(i32, i32, i32); 15 | 16 | // Unit struct 17 | struct Empty; 18 | ``` 19 | 20 | ## Instances 21 | 22 | Because Rust has no zero or nullish values, structs need to be instantiated with 23 | all their fields filled: 24 | 25 | ```rust 26 | fn main() { 27 | let user1 = User { 28 | username: "xxx_BILLY_xxx".to_string(), 29 | email: "blaze@michael.it".to_string(), 30 | credits: 0, 31 | }; 32 | } 33 | ``` 34 | 35 | A structure needs to be marked as `mut` to allow updating values: 36 | 37 | ```rust 38 | fn main() { 39 | let mut user1 = User { 40 | username: "xxx_BILLY_xxx".to_string(), 41 | email: "blaze@michael.it".to_string(), 42 | credits: 0, 43 | }; 44 | 45 | user1.email = "crash@team.racing".to_string(); 46 | } 47 | ``` 48 | 49 | Fields with the same name as an existing binding in the current scope can use 50 | the shorthand syntax for field assignment: 51 | 52 | ```rust 53 | fn main() { 54 | let username = "xxx_BILLY_xxx".to_string(); 55 | 56 | let user1 = User { 57 | username, // username: username 58 | email: "blaze@michael.it".to_string(), 59 | credits: 0, 60 | }; 61 | } 62 | ``` 63 | 64 | Creating new structures from existing ones can be done using destructuring with 65 | the `..` syntax: 66 | 67 | ```rust 68 | fn main() { 69 | // ... 70 | 71 | let user2 = User { 72 | username: "_____samo_____".to_string(), 73 | ..user1 74 | }; 75 | } 76 | ``` 77 | 78 | ## Methods 79 | 80 | Methods on structs are defined using the `impl` block and can reference 81 | themselves using `self` as the first parameter: 82 | 83 | ```rust 84 | struct Rectangle { 85 | width: u32, 86 | height: u32, 87 | } 88 | 89 | impl Rectangle { 90 | fn area(&self) -> u32 { 91 | self.width * self.height 92 | } 93 | } 94 | ``` 95 | 96 | Ownership rules apply for the `self` parameter, so it can be specified as an 97 | immutable reference `&self` (most common), mutable reference `&mut self` or take 98 | the ownership of the value when specified as `self`. 99 | 100 | ### Self 101 | 102 | A special type `Self` is available in method definition that refers to the type 103 | the method is defined on: 104 | 105 | ```rust 106 | struct Rectangle { 107 | x: i32, 108 | y: i32, 109 | } 110 | 111 | impl Rectangle { 112 | fn square(side: i32) -> Self { 113 | Self { x: side, y: side }; 114 | } 115 | } 116 | ``` 117 | 118 | The `self` parameter notation is just a syntax sugar. The explicit forms look 119 | like this: 120 | 121 | - `self` is `self: Self` 122 | - `&self` is `self: &Self` 123 | - `&mut self` is `self: &mut Self` 124 | 125 | ### Automatic ref/deref 126 | 127 | Rust's _automatic referencing and dereferencing_ feature allows uniform syntax 128 | when calling methods on types regardless of the type of `self` and the value. It 129 | adds `&`, `&mut` or `*` on the value before the method call as needed: 130 | 131 | ```rust 132 | struct Point(i32, i32, i32); 133 | 134 | impl Point { 135 | fn det(&self, other: &Point) -> i32 { 136 | self.0 * other.0 + self.1 * other.1 + self.2 * other.2 137 | } 138 | } 139 | 140 | fn main() { 141 | let p1 = Point(13, 37, 7); 142 | let p2 = Point(4, 2, 0); 143 | 144 | p1.det(&p2); 145 | // turns into 146 | (&p1).det(&p2); 147 | } 148 | ``` 149 | 150 | ## Associated functions 151 | 152 | Associated functions are defined in an `impl` block and don't use the `self` 153 | parameter. They are accessed on the structure name using `::`: 154 | 155 | ```rust 156 | struct Point(i32, i32); 157 | 158 | impl Point { 159 | fn new() -> Self { 160 | Point(0, 0) 161 | } 162 | } 163 | 164 | fn main() { 165 | let p = Point::new(); 166 | } 167 | ``` 168 | 169 | ## Fully qualified syntax 170 | 171 | The _fully qualified syntax_ for function calls of a type is: 172 | 173 | - `Type::function(receiver_if_method, args..)` 174 | 175 | ```rust 176 | fn main() { 177 | let mut v = vec![1, 2, 3]; 178 | 179 | v.push(4); 180 | // same as 181 | Vec::push(&mut v, 4); 182 | } 183 | ``` 184 | 185 | Methods called with the full syntax allows the method to be used as a _function 186 | pointer_. 187 | -------------------------------------------------------------------------------- /09_enums.md: -------------------------------------------------------------------------------- 1 | # Enums 2 | 3 | Enums define a type by enumerating its possible _variants_: 4 | 5 | ```rust 6 | enum IpAddr { 7 | V4, 8 | V6, 9 | } 10 | ``` 11 | 12 | Variants can hold various types of data: 13 | 14 | ```rust 15 | enum Message { 16 | Quit, // no data 17 | Move { x: i32, y: i32 }, // anonymous struct 18 | Write(String), // single type 19 | ChangeColor(i32, i32, i32), // tuple 20 | } 21 | ``` 22 | 23 | Variant constructors can be passed around as _function pointers_, since they are 24 | functions that return their instance: 25 | 26 | ```rust 27 | enum MaybeNum { 28 | None, 29 | Num(i32), 30 | } 31 | 32 | fn main() { 33 | let v: Vec = (1..=4).map(MaybeNum::Num).collect(); 34 | } 35 | ``` 36 | 37 | ## C-like 38 | 39 | Enums can be defined in a _C-like_ manner where they're actual enumerations when 40 | all variants are unit-like. They implicitly start at `0`: 41 | 42 | ```rust 43 | enum Number { 44 | Zero, // 0 45 | One, // 1 46 | Two, // 2 47 | } 48 | 49 | fn main() { 50 | println!("Zero = {}", Number::Zero as i32); 51 | } 52 | ``` 53 | 54 | Explicit denominators can be specified: 55 | 56 | ```rust 57 | enum Color { 58 | Red = 0xff0000, 59 | Green = 0x00ff00, 60 | Blue = 0x0000ff, 61 | } 62 | 63 | fn main() { 64 | println!("Red = #{:x}", Color::Red as i32); 65 | } 66 | ``` 67 | 68 | ## Methods 69 | 70 | Enums can define methods whose `self` parameter has the type of the enum: 71 | 72 | ```rust 73 | enum Action { 74 | Quit, 75 | Message(String), 76 | } 77 | 78 | impl Action { 79 | fn call(&self) { 80 | // ... 81 | } 82 | } 83 | ``` 84 | 85 | ## Match 86 | 87 | The `match` and `if let` expressions allow matching different `enum` variants: 88 | 89 | ```rust 90 | enum Coin { 91 | Penny, 92 | Nickel, 93 | Dime, 94 | Quarter, 95 | } 96 | 97 | fn cents(coin: Coin) -> u8 { 98 | match coin { 99 | Coin::Penny => 1, 100 | Coin::Nickel => 5, 101 | Coin::Dime => 10, 102 | Coin::Quarter => 25, 103 | } 104 | } 105 | 106 | fn main() { 107 | let coin = Coin::Dime; 108 | 109 | if let Coin::Penny = coin { 110 | println!("Penny!"); 111 | } 112 | } 113 | ``` 114 | -------------------------------------------------------------------------------- /10_generics.md: -------------------------------------------------------------------------------- 1 | # Generics 2 | 3 | Generics allow specifying placeholders for _concrete types_: 4 | 5 | ```rust 6 | struct Point { 7 | x: T, 8 | y: T, 9 | } 10 | 11 | impl Point { 12 | fn x(&self) -> &T { 13 | &self.x 14 | } 15 | } 16 | ``` 17 | 18 | The compiler substitutes these placeholders for concrete types at compile-time. 19 | 20 | ## Turbofish 21 | 22 | Specifying _type parameters_ explicitly on generic types is done with the 23 | **turbofish** syntax `::<>`: 24 | 25 | ```rust 26 | fn main() { 27 | let v = (1..10).collect::>(); 28 | } 29 | ``` 30 | 31 | This is useful in case the compiler cannot infer the type, or you want to change 32 | the inferred type to something different. 33 | 34 | ## Defaults 35 | 36 | The type can be defaulted using the `T = Default` syntax: 37 | 38 | ```rust 39 | struct Point(T, T); 40 | 41 | fn main() { 42 | let p = Point(13, 37); // u64 43 | let p = Point::(4, 20); // i32 44 | } 45 | ``` 46 | 47 | ## Constants 48 | 49 | The so-called `const` generics allow using _constant values_ as generic 50 | parameters: 51 | 52 | ```rust 53 | struct Matrix([[i32; S]; S]); 54 | 55 | type Matrix3D = Matrix<3>; 56 | 57 | fn main() { 58 | let m: Matrix3D = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]); 59 | } 60 | ``` 61 | 62 | They're defined using the `const T: type` syntax. 63 | 64 | ## Associated type 65 | 66 | Associated types are a type of generics whose purpose is to simplify code 67 | management. 68 | 69 | > Code using the associated type can be replaced with code using the generic 70 | > type, but not the other way around. 71 | 72 | Associated type is specified using `type` in the `impl` block and can be 73 | accessed with `::`: 74 | 75 | ```rust 76 | trait Graph { 77 | type N; 78 | type E; 79 | fn has_edge(&self, start: &N, end: &N) -> bool; 80 | } 81 | 82 | fn distance(graph: &G, start: &G::N, end: &G::N) -> uint { 83 | // ... 84 | } 85 | ``` 86 | 87 | The same defined using generics is a lot less readable: 88 | 89 | ```rust 90 | trait Graph { 91 | fn has_edge(&self, start: &N, end: &N) -> bool; 92 | } 93 | 94 | fn distance>(graph: &G, start: &N, end: &N) -> uint { 95 | // ... 96 | } 97 | ``` 98 | 99 | Associated types can be defaulted, allowing both flexibility and clean syntax: 100 | 101 | ```rust 102 | trait Add { 103 | type Output = Rhs; 104 | fn add(&self, rhs: Rhs) -> Self::Output; 105 | } 106 | 107 | struct Meters(u32); 108 | 109 | struct Millimeters(u32); 110 | 111 | impl Add for Meters { 112 | type Output = Meters; 113 | 114 | fn add(self, rhs: Meters) -> Meters { 115 | Meters(self.0 + rhs.0) 116 | } 117 | } 118 | 119 | impl Add for Millimeters { 120 | type Output = Millimeters; 121 | 122 | fn add(self, rhs: Meters) -> Millimeters { 123 | Millimeters(self.0 + (rhs.0 * 1000)) 124 | } 125 | } 126 | ``` 127 | -------------------------------------------------------------------------------- /11_traits.md: -------------------------------------------------------------------------------- 1 | # Traits 2 | 3 | Traits give types _behaviour_ via methods they implement, such as: 4 | 5 | * `Add` trait allows the use of `+` 6 | * `PartialOrd` makes types comparable 7 | * `Display` enables automatic formatting 8 | 9 | > The **orphan rule** states that either the _trait_, or the _implementor_ 10 | > have to be internal types. _External traits_ cannot be implemented on 11 | > _external types_. 12 | 13 | They are defined using the `trait` keyword, and a list of methods a type should 14 | implement: 15 | 16 | ```rust 17 | trait Summary { 18 | fn summarize(&self) -> String; 19 | } 20 | ``` 21 | 22 | Traits are then implemented as on specific types in an `impl` block that 23 | specifies the interface, and the type after the `for` keyword: 24 | 25 | ```rust 26 | struct Point(i32, i32); 27 | 28 | impl Summary for Point { 29 | fn summarize(&self) -> String { 30 | format!("Point({}, {})", self.0, self.1) 31 | } 32 | } 33 | ``` 34 | 35 | Traits can have a default implementation: 36 | 37 | ```rust 38 | trait Summary { 39 | fn summarize(&self) -> String { 40 | "Summarized...".to_string() 41 | } 42 | } 43 | 44 | struct Point(i32, i32); 45 | 46 | impl Summary for Point {} // default implementation used 47 | ``` 48 | 49 | Referencing the _implementor type_ is done via the `Self` type: 50 | 51 | ```rust 52 | trait Creator { 53 | fn duplicate() -> Self; 54 | fn equals(other: &Self) -> bool; 55 | } 56 | ``` 57 | 58 | Traits can also define _associated functions_: 59 | 60 | ```rust 61 | trait Spawner { 62 | fn new() -> Self; 63 | } 64 | 65 | struct Point(i32, i32); 66 | 67 | impl Spawner for Point { 68 | fn new() -> Self { 69 | Point(0, 0) 70 | } 71 | } 72 | ``` 73 | 74 | ## Trait bounds 75 | 76 | To restrict generic parameters to only allow types with certain functionality, 77 | _trait bounds_ can be specified: 78 | 79 | ```rust 80 | fn largest(s: &[T]) -> Option<&T> { 81 | s.iter().reduce(|acc, x| if x > acc { x } else { acc }) 82 | } 83 | ``` 84 | 85 | The `PartialOrd` trait allows comparing values. The `T` generic parameter here 86 | is restricted to only allow slices of comparable types. 87 | 88 | Multiple trait bounds can be combined using `+`: 89 | 90 | ```rust 91 | fn print_largest(s: &[T]) { 92 | let res = s.iter().reduce(|acc, x| if x > acc { x } else { acc }); 93 | 94 | if let Some(l) = res { 95 | println!("largest is {}", l); 96 | } 97 | } 98 | ``` 99 | 100 | An alternative `where` syntax exists for when there are too many generic 101 | parameters with many trait bounds: 102 | 103 | ```rust 104 | fn some_function(t: &T, u: &U) 105 | where 106 | T: Display + Clone, 107 | U: PartialOrd + Debug, 108 | { 109 | // ... 110 | } 111 | ``` 112 | 113 | ### Method implementation 114 | 115 | Trait bounds can be used for conditionally implementing methods on generic types 116 | in case the concrete type satisfies the bounds: 117 | 118 | ```rust 119 | struct Pair { 120 | x: T, 121 | y: T, 122 | } 123 | 124 | impl Pair { 125 | fn new(x: T, y: T) -> Self { 126 | Self { x, y } 127 | } 128 | } 129 | 130 | impl Pair { 131 | fn cmp_display(&self) { 132 | if self.x >= self.y { 133 | println!("The largest member is x = {}", self.x); 134 | } else { 135 | println!("The largest member is y = {}", self.y); 136 | } 137 | } 138 | } 139 | ``` 140 | 141 | Methods can also be conditionally implemented for concrete types: 142 | 143 | ```rust 144 | struct Pair { 145 | x: T, 146 | y: T, 147 | } 148 | 149 | impl Pair { 150 | fn new(x: T, y: T) -> Self { 151 | Self { x, y } 152 | } 153 | } 154 | 155 | impl Pair { 156 | fn sum(&self) -> i32 { 157 | self.x + self.y 158 | } 159 | } 160 | ``` 161 | 162 | ## Blanket implementation 163 | 164 | Implementation of a trait by satisfying another trait's bounds is called 165 | _blanket implementation_: 166 | 167 | ```rust 168 | use std::fmt::Display; 169 | 170 | trait Trashtalk { 171 | fn talk_trash(&self); 172 | } 173 | 174 | impl Trashtalk for T { 175 | fn talk_trash(&self) { 176 | println!("{} says: y'all should lift", self); 177 | } 178 | } 179 | 180 | fn main() { 181 | 1337.talk_trash(); 182 | "Bobby".talk_trash(); 183 | } 184 | ``` 185 | 186 | ## Trait objects 187 | 188 | The `dyn Trait` syntax allows specifying _trait objects_ — dynamic objects that 189 | implement the trait's behavior. They consist of two pointers: 190 | 191 | - pointer to the actual data 192 | - pointer to the object's _virtual method table_ 193 | 194 | Only _object-safe_ traits can be used in trait objects. The trait's methods must 195 | follow these rules: 196 | 197 | - the return type is not `Self` 198 | - there are no generic type parameters 199 | 200 | ```rust 201 | trait Draw { 202 | fn draw(&self); 203 | } 204 | 205 | struct Button; 206 | 207 | struct Select; 208 | 209 | impl Draw for Button { 210 | fn draw(&self) {} 211 | } 212 | 213 | impl Draw for Select { 214 | fn draw(&self) {} 215 | } 216 | 217 | fn main() { 218 | let ui: Vec> = vec![ 219 | Box::new(Button), 220 | Box::new(Select), 221 | ]; 222 | 223 | for el in ui.iter() { 224 | el.draw(); 225 | } 226 | } 227 | ``` 228 | 229 | Trait objects are mainly useful when it is impossible to use an `enum`, like 230 | when the number of possible types satisfying the trait is unknown. 231 | 232 | ## Type `impl Trait` 233 | 234 | The `impl Trait` type annotation can be used in function _arguments_ and as a 235 | _return_ type. It allows specifying unnamed, but concrete types that implement a 236 | trait: 237 | 238 | ```rust 239 | trait Trait {} 240 | 241 | fn foo(arg: impl Trait) {} 242 | 243 | fn bar() -> impl Trait {} 244 | ``` 245 | 246 | ### Arguments 247 | 248 | When used as an argument, it is almost the same as using a _generic_ parameter 249 | with a _trait bound_: 250 | 251 | ```rust 252 | trait Trait {} 253 | 254 | fn foo(arg: T) {} 255 | 256 | fn bar(arg: impl Trait) {} 257 | ``` 258 | 259 | The only difference is that the generic syntax allows specifying the type `T` 260 | using the turbofish syntax as with `foo::(1)`. 261 | 262 | ### Return 263 | 264 | The `impl Trait` syntax can be used when returning values from functions. 265 | Contrary to using `Box`, this does not cause the value to be stored 266 | on the heap: 267 | 268 | ```rust 269 | trait Trait {} 270 | 271 | impl Trait for i32 {} 272 | 273 | fn blazeit() -> impl Trait { 274 | 420 275 | } 276 | ``` 277 | 278 | The main usage of this pattern is with _closures_, as they don't have a specific 279 | type, they only satisfy the `Fn` family of traits: 280 | 281 | ```rust 282 | fn returns_closure() -> impl Fn(i32) -> i32 { 283 | |x| x + 1 284 | } 285 | ``` 286 | 287 | ## Supertraits 288 | 289 | Traits can require implementors to also implement other traits, becoming their 290 | _supertraits_: 291 | 292 | ```rust 293 | trait Mlg: Display { 294 | fn mlg(&self) -> String { 295 | format!("xxx_{}_xxx", self) 296 | } 297 | } 298 | ``` 299 | 300 | Multiple trait implementations can be required by joining traits with `+`: 301 | 302 | ```rust 303 | trait Mlg: Display + PartialOrd { 304 | fn winner(&self, other: &Self) -> String { 305 | if self > other { 306 | format!("xxx_{}_xxx", self) 307 | } else { 308 | format!("blazeit_{}", other) 309 | } 310 | } 311 | } 312 | ``` 313 | 314 | ## Fully qualified syntax 315 | 316 | The _fully qualified syntax_ for function calls in the context of traits is: 317 | 318 | - `Trait::function(receiver, args..)` for methods 319 | - `::function(args..)` for associated functions 320 | 321 | A struct can implement a method that collides with the name of an implemented 322 | trait's method. Calling an associated function on the _trait_ with the struct as 323 | the _receiver_ calls the trait implementation: 324 | 325 | ```rust 326 | trait Pilot { 327 | fn fly(&self); 328 | } 329 | 330 | struct Human; 331 | 332 | impl Human { 333 | fn fly(&self) { 334 | println!("*waving arms furiously*"); 335 | } 336 | } 337 | 338 | impl Pilot for Human { 339 | fn fly(&self) { 340 | println!("This is your captain speaking."); 341 | } 342 | } 343 | 344 | fn main() { 345 | let h = Human; 346 | Pilot::fly(&h); // This is your captain speaking. 347 | h.fly(); // *waving arms furiously* 348 | } 349 | ``` 350 | 351 | The full form would be `::fly(&h);`, but since Rust knows that 352 | `&h` is of type `&Human`, it knows which implementation of the `Pilot` trait to 353 | call. 354 | 355 | When a struct's and a trait's associated function names collide, the struct has 356 | to be cast to the trait using `as` to call the trait's implementation: 357 | 358 | ```rust 359 | trait Animal { 360 | fn baby_name() -> String; 361 | } 362 | 363 | struct Dog; 364 | 365 | impl Dog { 366 | fn baby_name() -> String { 367 | "Spot".to_string() 368 | } 369 | } 370 | 371 | impl Animal for Dog { 372 | fn baby_name() -> String { 373 | "puppy".to_string() 374 | } 375 | } 376 | 377 | fn main() { 378 | println!("{}", Dog::baby_name()); // Spot 379 | println!("{}", ::baby_name()); // puppy 380 | } 381 | ``` 382 | 383 | The short form `Animal::baby_name()` cannot be called, because Rust cannot infer 384 | the concrete implementation. 385 | -------------------------------------------------------------------------------- /12_types.md: -------------------------------------------------------------------------------- 1 | # Types 2 | 3 | The type system has various patterns and advanced constructs to be aware of. 4 | 5 | ## Casting 6 | 7 | Casting can be done either implicitly by _ascribing_, or explicitly via the `as` 8 | keyword: 9 | 10 | ```rust 11 | fn main() { 12 | let int = 13; 13 | let u: u8 = int; 14 | let u = int as u8; 15 | } 16 | ``` 17 | 18 | The `as` keyword allows more _coersion_ than ascribing: 19 | 20 | ```rust 21 | fn main() { 22 | let float = 13.5; 23 | // let u: u8 = float; // nope 🙀 24 | let u = float as u8; // ok 25 | } 26 | ``` 27 | 28 | Type placeholder `_` can be used in places where a type can be inferred: 29 | 30 | ```rust 31 | fn main() { 32 | let v: Vec<_> = (1..10).collect(); // Vec<_> is Vec 33 | } 34 | ``` 35 | 36 | The `as` syntax can also be used with the type placeholder `_`, commonly used 37 | with pointers: 38 | 39 | ```rust 40 | fn main() { 41 | let n = 1337; 42 | let r = &n; 43 | let r = r as *const _; 44 | } 45 | ``` 46 | 47 | ## Type alias 48 | 49 | Type aliases can be specified using the `type` keyword and used in-place of the 50 | original type: 51 | 52 | ```rust 53 | type ID = i32; 54 | 55 | fn main() { 56 | let i: i32 = 1337; 57 | let id: ID = i; 58 | } 59 | ``` 60 | 61 | They are mainly useful for creating an alias for more complex types to reduce 62 | duplication and simplify code: 63 | 64 | ```rust 65 | type Thunk = Box i32>; 66 | 67 | fn wrap_add(f: Thunk, a: i32) -> Thunk { 68 | Box::new(move |x| f(a) + a) 69 | } 70 | ``` 71 | 72 | ## Newtype 73 | 74 | The _newtype_ pattern (name from **Haskell**) is wrapping a single type in a 75 | struct. It is mainly useful for: 76 | 77 | - implementing _external traits_ on _external types_ 78 | - enforcing type safety on more abstract types 79 | - hiding implementation details 80 | 81 | There's no runtime penalty, the wrapper is removed at compile-time. 82 | 83 | Avoiding the _orphan rule_ by wrapping `Vec` and implementing `Display`: 84 | 85 | ```rust 86 | struct Wrapper(Vec); 87 | 88 | impl Display for Wrapper { 89 | fn fmt(&self, f: &mut Formatter) -> Result { 90 | write!(f, "Vec[{}]", self.0.join(", ")) 91 | } 92 | } 93 | ``` 94 | 95 | Giving types more explicit names and implementing additional functionality on 96 | them has the additional benefit of type safety: 97 | 98 | ```rust 99 | use std::ops::Add; 100 | 101 | struct Meters(u32); 102 | 103 | struct Millimeters(u32); 104 | 105 | impl Meters { 106 | fn to_millimeters(&self) -> Millimeters { 107 | Millimeters(self.0 * 1000) 108 | } 109 | } 110 | 111 | impl Add for Millimeters { 112 | type Output = Millimeters; 113 | fn add(self, rhs: Meters) -> Millimeters { 114 | Millimeters(self.0 + (rhs.0 * 1000)) 115 | } 116 | } 117 | ``` 118 | 119 | Implementing units as `u32` would make keeping track of what is what extremely 120 | difficult. 121 | 122 | Wrapping more abstract types can also help hide implementation details: 123 | 124 | ```rust 125 | struct Person; 126 | 127 | struct People(HashMap); 128 | 129 | impl People { 130 | fn new() -> People { 131 | People(HashMap::new()) 132 | } 133 | 134 | fn add(&mut self, id: u32, person: Person) { 135 | self.0.insert(id, person); 136 | } 137 | } 138 | ``` 139 | 140 | Consumers of this code do not need to know that `People` is implemented as 141 | a `HashMap`, which allows restricting the public API and makes refactoring a lot 142 | easier. 143 | 144 | ## Conversion 145 | 146 | The `From` and `Into` traits are used for _conversion_ of types from one into 147 | another. 148 | 149 | It is enough to implement the `From` trait, as the `Into` trait's implementation 150 | uses `From` trait bound in a _blanket implementation_: 151 | 152 | ```rust 153 | struct Number { 154 | value: i32, 155 | } 156 | 157 | impl From for Number { 158 | fn from(value: i32) -> Self { 159 | Number { value } 160 | } 161 | } 162 | 163 | fn main() { 164 | let a = 420; 165 | 166 | let n = Number::from(a); // using From directly 167 | let n: Number = a.into(); // blanket Into implementation 168 | } 169 | ``` 170 | 171 | For conversions that can fail, `TryFrom` and `TryInto` traits exist that return 172 | `Result`. 173 | 174 | ## Never 175 | 176 | The `!` stands for the _never_ type for functions that never return, meaning 177 | they either loop forever or exit the program: 178 | 179 | ```rust 180 | fn loophole() -> ! { 181 | loop { 182 | println!("RIP ☠️"); 183 | } 184 | } 185 | 186 | fn int_or_bye(o: Option) -> i32 { 187 | // Formally, the ! type can be coerced into any other type 188 | match o { 189 | Some(x) => x, 190 | None => loophole(), 191 | } 192 | } 193 | ``` 194 | 195 | One of the main functions that exit the program is the `panic!` macro: 196 | 197 | ```rust 198 | fn int_or_bye(o: Option) -> i32 { 199 | match o { 200 | Some(x) => x, 201 | None => panic!("bye 👋"), 202 | } 203 | } 204 | ``` 205 | 206 | ## DSTs 207 | 208 | _Dynamically sized types_ are types whose size is not known at compile-time. The 209 | two major DSTs exposed by the language are: 210 | 211 | - trait objects `dyn Trait` 212 | - references like `[T]` and `str` 213 | 214 | DSTs **must** exist behind a fat pointer, which contains information that 215 | _complete_ the pointer with necessary information, like the _vtable_ of a trait 216 | object, or a slice's size. 217 | 218 | By default, generic parameters implicitly have the `Sized` trait bound which 219 | only allows statically sized types: 220 | 221 | ```rust 222 | // fn sized(a: T) { 223 | // turns into: 224 | fn sized(a: T) { 225 | // ... 226 | } 227 | ``` 228 | 229 | Allowing DSTs is possible with specifying the `?Sized` trait bound, but only a 230 | reference to this type can be passed: 231 | 232 | ```rust 233 | fn sized(a: &T) { 234 | println!("sized {}", a); 235 | } 236 | 237 | fn nonsized(a: &T) { 238 | println!("nonsized {}", a); 239 | } 240 | 241 | fn main() { 242 | nonsized("kek"); // ok 243 | // sized("kek"); // nope! 244 | } 245 | ``` 246 | 247 | A convention is to write the `?Sized` trait bound next to the generic type 248 | definition even when using the `where` syntax: 249 | 250 | ```rust 251 | fn some_function(t: &T, u: &U) 252 | where 253 | T: Display + Clone, 254 | U: PartialOrd + Debug, 255 | { 256 | // ... 257 | } 258 | ``` 259 | -------------------------------------------------------------------------------- /13_effects.md: -------------------------------------------------------------------------------- 1 | # Effects 2 | 3 | Constructs for handling errors and optional values. 4 | 5 | ## Option 6 | 7 | The `Option` enum is for optional values: 8 | 9 | ```rust 10 | enum Option { 11 | Some(T), 12 | None, 13 | } 14 | ``` 15 | 16 | It serves as a replacement for `nil` or empty values: 17 | 18 | ```rust 19 | fn only_big_nums(x: i32) -> Option { 20 | if x > 1000 { Some(x) } else { None } 21 | } 22 | 23 | fn main() { 24 | let n = only_big_nums(1337); 25 | 26 | match n { 27 | Some(_) => println!("That is big!"), 28 | None => println!("Small"), 29 | } 30 | } 31 | ``` 32 | 33 | ## Result 34 | 35 | The `Result` enum is for operations that can fail and contains either a 36 | _value_ or an _error_: 37 | 38 | ```rust 39 | enum Result { 40 | Ok(T), 41 | Err(E), 42 | } 43 | ``` 44 | 45 | The main use is for operations that can fail with a recoverable error: 46 | 47 | ```rust 48 | fn read_username_from_file() -> Result { 49 | let f = File::open("username.txt"); 50 | 51 | let mut f = match f { 52 | Ok(file) => file, 53 | Err(e) => return Err(e), 54 | }; 55 | 56 | let mut s = String::new(); 57 | 58 | match f.read_to_string(&mut s) { 59 | Ok(_) => Ok(s), 60 | Err(e) => Err(e), 61 | } 62 | } 63 | ``` 64 | 65 | An easy way to convert `Option` to `Result` is using the `.ok_or(E)` or 66 | `.ok_or_else(FnOnce() -> E)` function: 67 | 68 | ```rust 69 | fn read_username() -> Result { 70 | let username = Some("kekega".to_string()); 71 | 72 | username.ok_or("Failed to read username".to_string()) 73 | } 74 | ``` 75 | 76 | ## Operator `?` 77 | 78 | The `?` operator can be used with both `Option` and `Result` when calling 79 | functions that return these types: 80 | 81 | ```rust 82 | fn read_username_from_file() -> Result { 83 | let mut f = File::open("username.txt")?; 84 | let mut s = String::new(); 85 | 86 | f.read_to_string(&mut s)?; 87 | 88 | Ok(s) 89 | } 90 | ``` 91 | 92 | The `?` operator placed after a function that returns an `Option` or `Result` 93 | _unwraps_ the value if the result is `Some(T)` or `Ok(T)`. If the funciton ends 94 | with `None` or `Err(E)`, it is returned from with this value. 95 | 96 | ## Panic 97 | 98 | The `panic!` macro is used for _unrecoverable errors_. It and terminates the 99 | current thread with an error message: 100 | 101 | ```rust 102 | fn main() { 103 | let f = File::open("dataset.txt"); 104 | 105 | let mut f = match f { 106 | Ok(file) => file, 107 | Err(e) => panic!("could not open dataset"), // boom 💥 108 | }; 109 | // ... 110 | } 111 | ``` 112 | 113 | A `panic!` called in the main thread terminates all other threads and exits the 114 | program with an error code `101`. 115 | 116 | ### Unwrap 117 | 118 | Calling the `.unwrap()` method on `Option` or `Result` values unwraps the 119 | underlying value if it is `Some(T)` or `Ok(T)`, and calls `panic!` otherwise: 120 | 121 | ```rust 122 | fn main() { 123 | let mut f = File::open("dataset.txt").unwrap(); // boom 💥 or file 🗂 124 | // ... 125 | } 126 | ``` 127 | 128 | Variants: 129 | 130 | - `.unwrap_or(T)` returns the supplied default if `None` or `Err(E)` 131 | - `.unwrap_or_default()` returns the type's default value if `None` or `Err(E)` 132 | - `.unwrap_or_else(Fn(E) -> T)` calls the closure if `None` or `Err(E)` 133 | - `.unwrap_err()` panics with the value if value is `Some(T)` or `Ok(T)` 134 | 135 | Useful when the programmer knows more than the compiler, and is sure that the 136 | code at hand will never fail. 137 | 138 | ### Expect 139 | 140 | The same as `.unwrap()`, but with a meaningful error message: 141 | 142 | ```rust 143 | fn main() { 144 | let mut f = File::open("dataset.txt").expect("oops"); // boom 💥 or file 🗂 145 | // ... 146 | } 147 | ``` 148 | 149 | Variants: 150 | 151 | - `.expect_err()` panics with the value if value is `Some(T)` or `Ok(T)` 152 | -------------------------------------------------------------------------------- /14_lifetimes.md: -------------------------------------------------------------------------------- 1 | # Lifetimes 2 | 3 | Lifetimes ensure that _references_ point to a valid memory. Lifetime of a 4 | reference is as big as is the _scope_ of a variable: 5 | 6 | ```rust 7 | fn main() { 8 | let x = 13; // --------+- 'a 9 | let xr = &x; // | 10 | { // | 11 | let y = 37; // --+- 'b | 12 | let yr = &y; // | | 13 | } // --+ | 14 | } // --------+ 15 | ``` 16 | 17 | _Lifetime_ denotes scope, _lifetime-parameter_ denotes parameters that the 18 | compiler substitutes with a real lifetime, same as inferring types of generics. 19 | 20 | Lifetime-parameters are named `'a`, an apostrophe and a lowercase name, often 21 | just a single letter, notable exception being `'static`. As generics, they're 22 | declared using the `<>` syntax: 23 | 24 | ```rust 25 | fn gimme_bigger<'a>(s1: &'a str, s2: &'a str) -> &'a str { 26 | if s1.len() > s2.len() { 27 | s1 28 | } else { 29 | s2 30 | } 31 | } 32 | ``` 33 | 34 | In this case, references `s1` and `s2` may have different lifetimes, and it is 35 | impossible to determine the returned reference's lifetime at compile-time. 36 | 37 | When a lifetime-parameter is used on multiple references, the compiler choses 38 | _the shortest lifetime_ of all to ensure that the returned reference lives long 39 | enough: 40 | 41 | ```rust 42 | fn gimme_bigger<'a>(s1: &'a str, s2: &'a str) -> &'a str { 43 | if s1.len() > s2.len() { 44 | s1 45 | } else { 46 | s2 47 | } 48 | } 49 | 50 | fn main() { 51 | let s1 = "kekega".to_string(); // --------+- 'a 52 | let res; // | 53 | { // | 54 | let s2 = "bur".to_string(); // --+- 'b | 55 | res = gimme_bigger(&s1, &s2); // | | res has lifetime 'b 56 | } // --+ | 57 | // println!("bigger is {}", res); // | nope 😿 'b is invalid 58 | } // --------+ 59 | ``` 60 | 61 | The `res` reference has the shorter lifetime `'b`. When used in the `println!` 62 | macro, `'b` already out of scope, and so is `res`, the program will not compile. 63 | 64 | Lifetime-parameters can also be used with _mutable references_: 65 | 66 | - `&i32` - a reference 67 | - `&'a i32` - a reference with a lifetime-parameterr 68 | - `&'a mut i32` - a _mutable_ reference with a lifetime parameter 69 | 70 | ## Subtyping 71 | 72 | _Subtyping_ is a type of compile-time polymorphism that check whether operations 73 | working with a _supertype_ of type `T`, say `F`, can operate also on type `T` 74 | . 75 | 76 | In the context of lifetimes, if lifetime `'a` lives _longer_ than lifetime `'b` 77 | then `'a` is a _subtype_ of `'b`. 78 | 79 | ## Elision 80 | 81 | Rust has a set of _lifetime elision_ rules built into the compiler for cases 82 | when a function's parameter and return value's lifetime-parameters can be 83 | inferred. 84 | 85 | The first rule states that all _input references_ get their own 86 | lifetime-parameter: 87 | 88 | ```rust 89 | fn print_longest<'a, 'b>(s1: &'a str, s2: &'b str) { 90 | println!("{}", if s1.len() > s2.len() { s1 } else { s2 }); 91 | } 92 | 93 | // elides to 94 | fn print_longest(s1: &str, s2: &str) { 95 | println!("{}", if s1.len() > s2.len() { s1 } else { s2 }); 96 | } 97 | ``` 98 | 99 | The second rule is that when the function takes a _single reference_ as an 100 | argument and _returns references_, the returned references' lifetime is the same 101 | as the input reference's lifetime: 102 | 103 | ```rust 104 | fn first_half<'a>(s: &'a str) -> &'a str { 105 | let h = s.len() / 2; 106 | &s[..h] 107 | } 108 | 109 | // elides to 110 | fn first_half(s: &str) -> &str { 111 | let h = s.len() / 2; 112 | &s[..h] 113 | } 114 | ``` 115 | 116 | The third rule states that when a method that takes `&self` returns references, 117 | the returned references' lifetime is the same as the lifetime of `&self`, even 118 | if it also takes other references: 119 | 120 | ```rust 121 | struct Text<'a> { 122 | text: &'a str, 123 | } 124 | 125 | impl<'a> Text<'a> { 126 | fn print_other_get<'b>(self: &'a Self, s: &'b str) -> &'a str { 127 | println!("other is {}", s); 128 | self.text 129 | } 130 | // elides to 131 | fn print_other_get(&self, s: &str) -> &str { 132 | println!("other is {}", s); 133 | self.text 134 | } 135 | } 136 | ``` 137 | 138 | This works only if it returns a reference from `&self`. Returning a different 139 | reference needs explicit lifetime-parameters: 140 | 141 | ```rust 142 | struct Text<'a> { 143 | text: &'a str, 144 | } 145 | 146 | impl<'a> Text<'a> { 147 | fn or_longer(&self, s: &'a str) -> &'a str { 148 | if self.text.len() > s.len() { 149 | self.text 150 | } else { 151 | s 152 | } 153 | } 154 | } 155 | ``` 156 | 157 | ## Static 158 | 159 | The `'static` lifetime is the _subtype_ of all other lifetimes — it lives for 160 | the entire duration of the program. 161 | 162 | The most notable example is _string literals_, whose full type is 163 | `&'static str`: 164 | 165 | ```rust 166 | fn gimme_bigger<'a>(s1: &'a str, s2: &'a str) -> &'a str { 167 | if s1.len() > s2.len() { 168 | s1 169 | } else { 170 | s2 171 | } 172 | } 173 | 174 | fn main() { 175 | let s1 = "kekega"; // &'static str 176 | let res; 177 | { 178 | let s2 = "bur"; // &'static str 179 | res = gimme_bigger(&s1, &s2); // res has lifetime 'static 180 | } 181 | println!("bigger is {}", res); // ok 🎉 182 | } 183 | ``` 184 | 185 | Other references `'static` lifetimes are ones created in the _global scope_ 186 | declared as `static`. 187 | -------------------------------------------------------------------------------- /15_closures.md: -------------------------------------------------------------------------------- 1 | # Closures 2 | 3 | Anonymous functions that can _capture their environment_: 4 | 5 | - by reference `&T` 6 | - by mutable reference `&mut T` 7 | - by value `T` 8 | 9 | The preference goes from top-to-bottom — if possible borrow by immutable or 10 | mutable reference, and only capture by value when really needed. 11 | 12 | ```rust 13 | fn main() { 14 | let var = 4; // var declared here 15 | let add_var = |x| x + var; // closure captures var 16 | 17 | println!("{} + 3 = {}", var, add_var(3)); 18 | } 19 | ``` 20 | 21 | If the closure only contains a single expression, the block brackets `{}` can be 22 | left out. Closures can be type-annotated as regular functions, but types are 23 | inferrable: 24 | 25 | ```rust 26 | fn main() { 27 | let squared = |x: i32| -> i32 { x * x }; // full syntax 28 | let squared = |x: i32| -> i32 x * x; // no block 29 | let squared = |x| { x * x }; // inferred type (more flexible) 30 | let squared = |x| x * x; // inferred type and no block 31 | } 32 | ``` 33 | 34 | ## Borrowing 35 | 36 | When only immutable values are captured, and they're not _consumed_, they're 37 | borrowed by reference: 38 | 39 | ```rust 40 | fn main() { 41 | let var = 4; 42 | let add_var = |x| x + var; // var is &var here 43 | 44 | println!("{} + 3 = {}", var, add_var(3)); 45 | } 46 | ``` 47 | 48 | Mutable values are captured as `&mut T` and the closure needs to be stored 49 | as `mut` as well: 50 | 51 | ```rust 52 | fn main() { 53 | let mut count = 0; 54 | let mut inc_print = || { // is mut because it mutates the environment 55 | count += 1; // count is &mut count here 56 | println!("count is {}", count); 57 | }; 58 | 59 | inc_print(); 60 | inc_print(); 61 | } 62 | ``` 63 | 64 | Values that do not implement the `Copy` trait and are consumed in the closure 65 | get their ownership moved: 66 | 67 | ```rust 68 | fn main() { 69 | let a = "hello".to_string(); // String does not implement Copy 70 | let fs = || { 71 | let b = a; // a moved into b 72 | println!("we got {}", b); 73 | }; 74 | // println!("a is {}", a); // nope 🙀 a is moved 75 | } 76 | ``` 77 | 78 | If `a` was `i32`, this code would work, because `i32` implements `Copy`, and `a` 79 | would get captured as `&a`. The `b` variable would get a copy of the value. 80 | 81 | ## Keyword `move` 82 | 83 | The `move` keyword transforms captured variabled by _reference_ or _mutable 84 | reference_ to _owned by value_: 85 | 86 | ```rust 87 | use std::ops::Add; 88 | 89 | fn make_adder + Copy>(x: T) -> impl Fn(T) -> T { 90 | move |y| x + y 91 | } 92 | 93 | fn main() { 94 | let add_5 = make_adder(5); 95 | println!("5 + 10 = {}", add_5(10)); 96 | } 97 | ``` 98 | 99 | ## The `Fn` trait 100 | 101 | There are _three_ traits in the `Fn` family: 102 | 103 | - `Fn` with the `call` method that takes `&self` 104 | - `FnMut` (supertrait of `Fn`) with the `call_mut` method that takes `&mut self` 105 | - `FnOnce` (supertrait of `FnMut`) with the `call_once` method that takes `self` 106 | 107 | Closures that capture by _reference_ implement the `Fn` trait. Closures that 108 | capture by _mutable reference_ implement `FnMut` and allow mutating the 109 | environment. Closures capturing by _value_ implement `FnOnce`, because once 110 | they're called, the values are moved, and cannot be called again. 111 | 112 | ### Functions 113 | 114 | Function pointers implement the `Fn` trait and can be used as such: 115 | 116 | ```rust 117 | fn apply_twice(f: impl Fn(T) -> T, a: T) -> T { 118 | f(f(a)) 119 | } 120 | 121 | fn times_two(x: i32) -> i32 { 122 | x * 2 123 | } 124 | 125 | fn main() { 126 | println!("function: {}", apply_twice(times_two, 3)); 127 | println!("closure: {}", apply_twice(|x| x * 2, 5)); 128 | } 129 | ``` 130 | 131 | ### As structs 132 | 133 | Closures are actually implemented as _structs_ created at compile-time. The 134 | captured environment becomes the struct's fields. The created struct implements 135 | the proper `Fn` trait. 136 | 137 | Implementing a pseudo-closure struct implementing the `Fn` trait would look 138 | something like this: 139 | 140 | ```rust 141 | // captured environment 142 | struct Adder<'a> { 143 | x: &'a i32, 144 | } 145 | 146 | // quasi Fn impl 147 | impl<'a> Adder<'a> { 148 | fn call(&self, y: i32) -> i32 { 149 | self.x + y 150 | } 151 | } 152 | 153 | fn main() { 154 | let x = 5; 155 | let f = Adder { x: &x }; // capture the environment 156 | println!("{} + 3 = {}", x, f.call(3)); // would f(3) with a regular closure 157 | } 158 | ``` 159 | 160 | A similar example for `FnMut` also shows why closures that mutate the 161 | environment _must_ be marked as `mut` — the environment is a mutable `struct`: 162 | 163 | ```rust 164 | // captured mutable environment 165 | struct Counter<'a> { 166 | count: &'a mut i32, 167 | } 168 | 169 | // quasi FnMut impl 170 | impl<'a> Counter<'a> { 171 | fn call_mut(&mut self) { 172 | *self.count += 1; 173 | println!("count is {}", self.count) 174 | } 175 | } 176 | 177 | fn main() { 178 | let mut count = 0; 179 | let mut counter = Counter { 180 | count: &mut count, // capture the mutable environment 181 | }; 182 | counter.call_mut(); // would counter() with a regular closure 183 | counter.call_mut(); // would counter() with a regular closure 184 | } 185 | ``` 186 | 187 | Finally, showing how the `FnOnce` trait consumes the environment: 188 | 189 | ```rust 190 | // captured owned environment 191 | struct Spawner { 192 | s: String, 193 | } 194 | 195 | // quasi FnOnce impl 196 | impl Spawner { 197 | fn call_once(self) { 198 | let a = self.s; 199 | println!("spawn a thread or something with {}", a); 200 | } 201 | } 202 | 203 | fn main() { 204 | let s = "yolo".to_string(); 205 | let spawn = Spawner { s }; 206 | spawn.call_once(); // would spawn() with a regular closure 207 | // spawn.call_once(); // nope 🙀 spawner is moved 208 | // println!("s is {}", s); // nope 🙀 s is moved 209 | } 210 | ``` 211 | -------------------------------------------------------------------------------- /16_iterators.md: -------------------------------------------------------------------------------- 1 | # Iterators 2 | 3 | Types that implement the `Iterator` trait. The functional way of processing a 4 | collection of items: 5 | 6 | ```rust 7 | struct User { 8 | name: String, 9 | money: u32, 10 | active: bool, 11 | } 12 | 13 | fn average_active_users_money(users: &[User]) -> f64 { 14 | users 15 | .iter() 16 | .filter(|u| u.active) 17 | .map(|u| u.money as f64) 18 | .sum::() 19 | / users.len() as f64 20 | } 21 | ``` 22 | 23 | ## Definition 24 | 25 | The `Iterator` trait defines one non-defaulted `next` method that returns the 26 | iterator's next element, if any. The definition looks like this: 27 | 28 | ```rust 29 | trait Iterator { 30 | type Item; 31 | fn next(&mut self) -> Option; 32 | 33 | // methods with default implementations elided 34 | } 35 | ``` 36 | 37 | The `next`'s method's responsibility is to: 38 | 39 | - return the next element, if any 40 | - mutate the iterator to advance on the next element 41 | 42 | ### Trait `IntoIterator` 43 | 44 | Types that describe a collection commonly implement the `IntoIterator` trait 45 | that defines how the type will be converted into an _iterator_: 46 | 47 | ```rust 48 | trait IntoIterator { 49 | type Item; 50 | type IntoIter: Iterator; 51 | fn into_iter(self) -> Self::IntoIter; 52 | } 53 | ``` 54 | 55 | Note that the `into_iter` method takes `self` as an argument, thus taking 56 | ownership of the type that implements the trait. 57 | 58 | ### Trait `FromIterator` 59 | 60 | In addition to `IntoIterator`, collection types can implement the `FromIterator` 61 | trait to allow usage of the `.collect()` method: 62 | 63 | ```rust 64 | trait FromIterator { 65 | fn from_iter(iter: T) -> Self 66 | where 67 | T: IntoIterator; 68 | } 69 | ``` 70 | 71 | The `IntoIterator` and `FromIterator` traits can be used in conjunction to 72 | iterate over values and collect them back: 73 | 74 | ```rust 75 | fn main() { 76 | let nums = vec![1, 2, 3, 4, 5, 6]; 77 | 78 | let big_nums: Vec<_> = nums.into_iter().filter(|&x| x > 3).collect(); 79 | } 80 | ``` 81 | 82 | ### In `for` loops 83 | 84 | The `for` loop is actually a syntax sugar for iterators. 85 | Implementing `IntoIterator` 86 | allows usage in `for` loops: 87 | 88 | ```rust 89 | fn main() { 90 | // the for loop 91 | let names = vec!["Bobby", "Michael", "Alaine"]; 92 | for name in names { 93 | println!("{}", name); 94 | } 95 | 96 | // desugars into something like 97 | let names = vec!["Bobby", "Michael", "Alaine"]; 98 | let mut iterator = names.into_iter(); 99 | while let Some(name) = iterator.next() { 100 | println!("{}", name); 101 | } 102 | } 103 | ``` 104 | 105 | ### Conventions 106 | 107 | The convention is to define and call methods: 108 | 109 | - `into_iter(self)` for iterating over `T` via the `IntoIterator` trait 110 | - `iter(&self)` for iterating over `&T` by _convention_ 111 | - `iter_mut(&mut self)` for iterating over `&mut T` by _convention_ 112 | 113 | Types commonly implement the `IntoIterator` trait **3-times**, once for each 114 | variant. For example, `Vec` implementations are: 115 | 116 | - `impl IntoIterator for Vec` 117 | - `impl<'a, T> IntoIterator for &'a Vec` that calls `iter(&self)` 118 | - `impl<'a, T> IntoIterator for &'a mut Vec` that calls `iter_mut(&mut self)` 119 | 120 | The first implementation on `Vec` directly yields _by value_. The other two 121 | are references themselves, so even though the `into_iter(self)` method takes 122 | `self` by value, the value is actually a reference in both cases. They yield 123 | _references_ to their content: 124 | 125 | ```rust 126 | fn main() { 127 | let v = vec![1, 2, 3, 4, 5]; 128 | 129 | // Vec, values copied or ownership moved 130 | for n in v { 131 | println!("copy of n = {}", n); 132 | } 133 | 134 | // &Vec, values are &T 135 | for n in &v { 136 | println!("ref of &n = {}", n); 137 | } 138 | 139 | // &mut Vec, values are &mut T 140 | let mut v = v; 141 | for n in &mut v { 142 | *n *= 2; 143 | } 144 | } 145 | ``` 146 | 147 | Using the generic `into_iter` method directly **is context dependent** and can 148 | sometimes yield unexpected results. It is recommended calling `iter` 149 | or `iter_mut` explicitly, if available. 150 | 151 | ## Methods 152 | 153 | In addition to the mandatory `next` method, `Iterator` has a set of _consuming_ 154 | and _producing_ methods called _adaptors_. 155 | 156 | Iterators are **lazy** — no adaptors get called until the iterator is actually 157 | consumed by calling the `next` function. 158 | 159 | ### Consuming 160 | 161 | A _consuming adaptor_ is one that consumes the iterator by calling `next` until 162 | there are no more items to iterate over, such as `fold` or `sum`: 163 | 164 | ```rust 165 | fn first_or_second(nums: &[i32]) -> (i32, i32) { 166 | nums.iter().fold( 167 | (0, 0), 168 | |(a, b), x| if a < b { (a + x, b) } else { (a, b + x) }, 169 | ) 170 | } 171 | ``` 172 | 173 | ### Producing 174 | 175 | A method that produces a new iterator is called an _iterator adaptor_. They 176 | perform transformations such as _mapping_, _filtering_, _zipping_, and others: 177 | 178 | ```rust 179 | fn long_ass_function(a1: &[i32], a2: &[i32]) -> i32 { 180 | a1.iter() 181 | .zip(a2) 182 | .filter(|(&a, &b)| a > 0 && b > 0) 183 | .map(|(a, b)| a * b) 184 | .sum() 185 | } 186 | ``` 187 | 188 | Check 189 | the [official docs](https://doc.rust-lang.org/std/iter/trait.Iterator.html#provided-methods) 190 | for the full list of functions, many are useful in everyday programming! 191 | -------------------------------------------------------------------------------- /17_collections.md: -------------------------------------------------------------------------------- 1 | # Collections 2 | 3 | Rust has a _lot_ of built-in collection data types. The most commonly used ones 4 | are `Vec` and `HashMap`. All collections are located in the 5 | `std::collections` module. 6 | 7 | ## Vectors 8 | 9 | The `Vec` type's an ordered collection of items with a variable length: 10 | 11 | ```rust 12 | fn main() { 13 | let mut v = Vec::new(); 14 | 15 | v.push(1337); 16 | v.push(420); 17 | } 18 | ``` 19 | 20 | ### Initialization 21 | 22 | A new zero-length vector is created using the `Vec::new()` associated function. 23 | To instantiate a vector with values, use the `vec!` macro: 24 | 25 | ```rust 26 | fn main() { 27 | let v = vec!["a", "bunch", "of", "string", "refs"]; 28 | } 29 | ``` 30 | 31 | To allocate space beforehand, use `Vec::with_capacity(usize)`. 32 | 33 | ### Reading 34 | 35 | There's a _safe_, and an _unsafe_ way to get a value at a specific index. 36 | 37 | Using the `Index` trait will _panic_ when accessing an element beyond the 38 | vector's size. It is only recommended using in situations where the element is 39 | guaranteed to exist: 40 | 41 | ```rust 42 | fn main() { 43 | let v = vec![1, 2, 3]; 44 | 45 | let second = v[1]; // ok 46 | // let fourth = v[3]; // boom 💥 47 | } 48 | ``` 49 | 50 | The safe way is using the `get` method, which returns `Option`: 51 | 52 | ```rust 53 | fn main() { 54 | let v = vec![1, 2, 3]; 55 | 56 | let second = v.get(1); // Some(2) 57 | let fourth = v.get(3); // None 58 | } 59 | ``` 60 | 61 | ## Hash maps 62 | 63 | Key-value pairs are most commonly stored in `HashMap`. Any type that 64 | implements the `Eq` and `Hash` trait can be used as the key: 65 | 66 | ```rust 67 | use std::collections::HashMap; 68 | 69 | fn main() { 70 | let mut fav_nums = HashMap::new(); 71 | 72 | fav_nums.insert("Bobby", "1337"); 73 | fav_nums.insert("Michael", "420"); 74 | } 75 | ``` 76 | 77 | Hash maps are initialized using `HashMap::new()` for an empty one, or 78 | `HashMap::with_capacity(usize)` with pre-allocated space. Hash maps shrink when 79 | they occupy too much space after removing elements. 80 | 81 | ### Entries 82 | 83 | Normally, values are retrieved using the `get` method, which returns an 84 | `Option`. Using `entry` returns the `Entry` enum, which is either _occupied_ 85 | or _vacant_. 86 | 87 | The `Entry` enum allows performing useful operations, such as `or_insert`: 88 | 89 | ```rust 90 | fn main() { 91 | let mut users: HashMap = HashMap::new(); 92 | // ... 93 | let leet = users.entry(1337).or_insert("Bobby"); 94 | // leet is now either an existing entry, or "Bobby" was inserted and returned 95 | } 96 | ``` 97 | 98 | ### Iteration 99 | 100 | Hashmaps implement the `Iterable` trait and produce a sequence of `(K, V)` 101 | tuples: 102 | 103 | ```rust 104 | fn main() { 105 | let mut fav_nums = HashMap::new(); 106 | 107 | fav_nums.insert("Bobby", "1337"); 108 | fav_nums.insert("Michael", "420"); 109 | // ... 110 | 111 | fav_nums.iter().for_each(|(name, number)| { 112 | println!("{}'s favorite number is {}", name, number); 113 | }); 114 | } 115 | ``` 116 | -------------------------------------------------------------------------------- /18_strings.md: -------------------------------------------------------------------------------- 1 | # Strings 2 | 3 | The _slice string_ type `&str` points to a **UTF-8** valid collection of bytes 4 | of type `&[u8]`. 5 | 6 | Tye `String` type is a UTF-8 valid wrapper around `Vec` that contains 7 | utility methods for string manipulation: 8 | 9 | ```rust 10 | fn main() { 11 | let mut s = String::new(); 12 | 13 | for c in "Hello".chars() { 14 | s.push(c); 15 | } 16 | s.push_str(", world!"); 17 | 18 | println!("{}", s); 19 | } 20 | ``` 21 | 22 | ## Characters 23 | 24 | The `char` type is a _4-byte_ primitive type that holds a single _Unicode code 25 | point_. These code points form _graphemes_, either individually, or as 26 | _grapheme clusters_: 27 | 28 | ```rust 29 | fn main() { 30 | let chars: &[char] = &['न', 'म', 'स', '्', 'त', 'े']; 31 | let graphemes = ["न", "म", "स्", "ते"]; //'स', '्' makes "स्", 'त', 'े' makes "ते" 32 | } 33 | ``` 34 | 35 | Individual string characters can be iterated using the `chars` method: 36 | 37 | ```rust 38 | fn main() { 39 | for c in "नमस्ते".chars() { 40 | println!("{}", c); // prints न म स ् त े 41 | } 42 | } 43 | ``` 44 | 45 | Individual characters take up more space than strings, because `char` is always 46 | 4-bytes in size, compared to many string characters being 1 to 3-bytes in size. 47 | 48 | ## Indexing 49 | 50 | Indexing strings is ambiguous, because it is not clear whether _bytes_ or 51 | _chars_ are being indexed. For this reason, indexing strings is done explicitly 52 | via: 53 | 54 | - `.chars().nth(i)` for _chars_ 55 | - `.bytes().nth(i)` for _bytes_ 56 | 57 | ```rust 58 | fn main() { 59 | let ciao = "Здравствуйте"; 60 | 61 | // prints 12 characters 62 | for i in 0..ciao.chars().count() { 63 | println!("ciao.chars().nth({}) = {}", i, ciao.chars().nth(i).unwrap()); 64 | } 65 | 66 | // prints 24 bytes 67 | for i in 0..ciao.len() { 68 | println!("ciao.bytes().nth({}) = {}", i, ciao.bytes().nth(i).unwrap()); 69 | } 70 | } 71 | ``` 72 | 73 | Note that the `len` method returns the number of _bytes_ of a string, not 74 | _chars_. 75 | 76 | ## Escaping 77 | 78 | The ``\`` character is used for escaping. To write a literal ``\``, it has to be 79 | escaped with `\\`. String or character literal delimeters within a literal must 80 | be escaped: 81 | 82 | ```rust 83 | fn main() { 84 | println!("backslash: \\"); 85 | println!("chars: {}", '\''); 86 | println!("strings: {}", "\""); 87 | } 88 | ``` 89 | 90 | Escaping can be used for writing _bytes_ by their hexadecimal value, or _Unicode 91 | code points_: 92 | 93 | ```rust 94 | fn main() { 95 | println!("how about \x74\x68\x65\x20\x67\x61\x6d\x65"); // bytes 96 | println!("Unicode char U+211D is \u{211D}"); // Unicode 97 | } 98 | ``` 99 | 100 | Escaping allows writing _multiline strings_ with escaped whitespace: 101 | 102 | ```rust 103 | fn main() { 104 | let s = "Did your \ 105 | mother fuck \ 106 | a snowman?"; 107 | 108 | println!("{}", s); 109 | } 110 | ``` 111 | 112 | ### Raw strings 113 | 114 | Useful when no escaping at all is desired. They can be declared using `r""` and 115 | optionally an arbitrary number of `#` pairs outside of `""`, depending on 116 | whether `"` is in the string and how many `#` characters are used within the 117 | string: 118 | 119 | ```rust 120 | fn main() { 121 | let raw = r"nope: \u{211D}, nope: \x67\x61\x6d\x65"; 122 | let raw = r#"even more "nope" here"#; 123 | let raw = r###"nope #nope ##nope"###; 124 | } 125 | ``` 126 | 127 | ### Byte strings 128 | 129 | Strings of bytes that are mostly text are created using `b""` and are stored as 130 | an array of type `[u8; N]`: 131 | 132 | ```rust 133 | fn main() { 134 | let bytes = b"raw bytes amirite?"; // type &[u8; 18] 135 | } 136 | ``` 137 | 138 | They allow escaping the same way as regular strings, except for Unicode code 139 | points: 140 | 141 | ```rust 142 | fn main() { 143 | let bytes = b"the \x67\x61\x6d\x65 again lmao"; // ok 144 | // let bytes = b"nope \u{211D}"; // nope 🙀 145 | } 146 | ``` 147 | 148 | Byte strings don't have to be a valid UTF-8: 149 | 150 | ```rust 151 | use std::str; 152 | 153 | fn main() { 154 | let shift_jis = b"\x82\xe6\x82\xa8\x82\xb1\x82\xbb"; // "ようこそ" in SHIFT-JIS 155 | 156 | match str::from_utf8(shift_jis) { 157 | Ok(s) => println!("Like that's ever going to happen: {}", s), 158 | Err(e) => println!("Told ya: {}", e), 159 | }; 160 | } 161 | ``` 162 | 163 | They can be made _raw_ the same way as regular strings: 164 | 165 | ```rust 166 | fn main() { 167 | let rbs = br##"hashtag #raw "strings" amirite?"##; // type &[u8; 31] 168 | } 169 | ``` 170 | 171 | ## Formatting 172 | 173 | Concatenating can be done using the `+` operator: 174 | 175 | ```rust 176 | fn main() { 177 | let s = "top".to_string(); 178 | println!("{}", s + "kek"); // topkek 179 | } 180 | ``` 181 | 182 | More complex formatting can be done using the `format!` macro: 183 | 184 | ```rust 185 | fn main() { 186 | let s = format!("{}, {}!", "hello", "world"); 187 | } 188 | ``` 189 | 190 | ### Styles 191 | 192 | The formatting syntax has the form `{:}`, both parts being 193 | optional. When none are supplied also the `:` can be omitted. It is verified at 194 | compile-time. 195 | 196 | The `` part can be the argument position, or a named argument: 197 | 198 | ```rust 199 | fn main() { 200 | println!("Rofl {}", "lmao"); // implicit position 201 | println!("Rofl {0}", "lmao"); // explicit position 202 | println!("Rofl {arg}", arg = "lmao"); // named position 203 | } 204 | ``` 205 | 206 | The `` part determines which trait to use when formatting: 207 | 208 | - nothing for `Display` 209 | - `?` for `Debug` 210 | - `o` for `Octal` 211 | - `x` for `LowerHex` 212 | - `X` for `UpperHex` 213 | - `p` for `Pointer` 214 | - `b` for `Binary` 215 | - `e` for `LowerExp` 216 | - `E` for `UpperExp` 217 | 218 | ```rust 219 | fn main() { 220 | println!("{:?}", 1337); // debug 221 | println!("{:b}", 1337); // binary 222 | println!("{:X}", 1337); // upper-case hexadecimal 223 | 224 | println!("1337 = {leet:X}, 420 = {:?}", 420, leet = 1337); // mishmash 225 | } 226 | ``` 227 | 228 | Further traits can be added in the future. 229 | -------------------------------------------------------------------------------- /19_smart_pointers.md: -------------------------------------------------------------------------------- 1 | # Smart pointers 2 | 3 | Smart pointers are basically _fat pointers_ with additional capabilities, like 4 | all the containers like `Vec` or `String`, as well as `Box`, `Rc` 5 | and `RefCell`. 6 | 7 | These pointers implement the `Deref` and `Drop` traits. `Deref` is useful for 8 | automatic dereferencing, so the types can be used both as references and 9 | utilise _deref coersion_, and as pointers themselves. The `Drop` trait frees 10 | memory, and optionally contains additional cleanup logic. 11 | 12 | ## Box 13 | 14 | Values are allocated on the _stack_ by default. Putting them into a `Box` 15 | stores them on the _heap_: 16 | 17 | ```rust 18 | fn main() { 19 | let x = 5; // on the stack 20 | let y = Box::new(5); // on the heap 21 | } 22 | ``` 23 | 24 | Using `Box` is necessary when working with _DSTs_, like slices 25 | or `dyn Trait`: 26 | 27 | ```rust 28 | use std::fmt::Display; 29 | 30 | fn gimme_displayable(num: bool) -> Box { 31 | Box::new(if num { 1337 } else { "yo".to_string() }) 32 | } 33 | ``` 34 | 35 | ## Rc 36 | 37 | The `Rc` type is used when multiple ownership is needed. The acronym stands 38 | for _reference counting_. 39 | 40 | The `clone` method creates a _strong_ clone that contribute to the 41 | _strong count_ of references. The number of strong clones can be checked using 42 | `Rc::strong_count`. When the strong count reaches zero, the value is dropped: 43 | 44 | ```rust 45 | use std::rc::Rc; 46 | 47 | fn main() { 48 | let x = Rc::new(5); // Rc 49 | let y = x.clone(); // Rc 50 | let z = x.clone(); // Rc 51 | println!("strong count: {}", Rc::strong_count(&x)); // x, y, and z, so 3 52 | } 53 | ``` 54 | 55 | The `Rc::downgrade` method can be used when working with potential reference 56 | cycles. It creates a `Weak` and increases the _weak count_. The difference is 57 | that the weak count can be non-zero for the value to be dropped: 58 | 59 | ```rust 60 | use std::rc::Rc; 61 | 62 | fn main() { 63 | let x = Rc::new(5); // Rc 64 | let y = x.clone(); // Rc 65 | let z = Rc::downgrade(&x); // Weak 66 | println!("strong count: {}", Rc::strong_count(&x)); // x and y, so 2 67 | println!("strong count: {}", Rc::weak_count(&x)); // z, so 1 68 | } 69 | ``` 70 | 71 | `Weak` is especially useful when dealing with graphs or double linked lists 72 | where reference cycles are common. 73 | 74 | ## Cell 75 | 76 | The _interior mutability pattern_ refers to the ability to mutate data referred 77 | to by immutable references. 78 | 79 | The `Cell` type allows _zero-cost_ mutating data for types that implement 80 | the `Copy` trait: 81 | 82 | ```rust 83 | use std::cell::Cell; 84 | 85 | fn main() { 86 | let x = Cell::new(4); 87 | let y = &x; 88 | 89 | y.set(20); 90 | println!("x = {}, y = {}", x.get(), y.get()); // x = 20, y = 20 91 | } 92 | ``` 93 | 94 | The `RefCell` type holds a reference to a type and defers enforcing ownership 95 | rules at _runtime_: 96 | 97 | ```rust 98 | use std::cell::RefCell; 99 | 100 | fn append(s: &RefCell, what: &str) { 101 | s.borrow_mut().push_str(what) 102 | } // borrowed mutable value goes out of scope 103 | 104 | fn print(s: &RefCell) { 105 | println!("s = \"{}\"", s.borrow()); 106 | } // borrowed value goes out of scope 107 | 108 | fn main() { 109 | let s = RefCell::new("kek".to_string()); 110 | 111 | print(&s); // s = "kek" 112 | append(&s, "ega"); 113 | print(&s); // s = "kekega" 114 | } 115 | ``` 116 | -------------------------------------------------------------------------------- /20_patterns.md: -------------------------------------------------------------------------------- 1 | # Patterns 2 | 3 | Patterns can be _matched_ and _destructured_ in various ways: 4 | 5 | ```rust 6 | fn main() { 7 | let t = (1, 3, 37); 8 | let (x, y, z) = t; 9 | let r = match t { 10 | (420, ..) => "blazeit", 11 | (0, 0, 0) => "unit", 12 | _ => "other stuff", 13 | }; 14 | } 15 | ``` 16 | 17 | ## Destructuring 18 | 19 | Values can be destructured in `match`-like expressions and whenever they're 20 | being assigned to a name, like _variable declaration_ or _function arguments_: 21 | 22 | ```rust 23 | fn double_vec((x, y): (i32, i32)) -> (i32, i32) { 24 | (x * 2, y * 2) 25 | } 26 | 27 | fn main() { 28 | let v = (4, 2, 0); 29 | let (x, y, z) = v; 30 | } 31 | ``` 32 | 33 | Literals can be matched directly or as a _range_, or bind to a name: 34 | 35 | ```rust 36 | fn main() { 37 | let n = 5; 38 | match n { 39 | 1337 => println!("leet"), 40 | 0..=10 => prinln!("zero to ten"), 41 | x => println!("got a number {}", x), 42 | }; 43 | } 44 | ``` 45 | 46 | Bound literals can _shadow_ names: 47 | 48 | ```rust 49 | fn main() { 50 | let n = Some(5); 51 | if let Some(n) = n { 52 | println!("got Some({})", n); 53 | }; 54 | } 55 | ``` 56 | 57 | A catch-all placeholder can be specified using `_`: 58 | 59 | ```rust 60 | fn main() { 61 | let n = 5; 62 | match n { 63 | 1..=10 => prinln!("one to ten"), 64 | _ => println!("some irrelevant number"), 65 | }; 66 | } 67 | ``` 68 | 69 | Destructuring is recursive: 70 | 71 | ```rust 72 | fn main() { 73 | let x = Some(((13, 37), 15, "omg")); 74 | if let Some(((x, y), ..)) = x { 75 | println!("x = {}, y = {}", x, y); 76 | }; 77 | } 78 | ``` 79 | 80 | ### Tuples 81 | 82 | Tuples can be destructured into individual components. The lead or tail part of 83 | a tuple can be ignored using the `..` syntax: 84 | 85 | ```rust 86 | fn main() { 87 | let v = (1, 3, 7); 88 | match v { 89 | (4, 2, 0) => println!("blaze it"), 90 | (x, y, 0) => println!("2D vector {:?}", (x, y)), 91 | (1, ..) => println!("1 is first"), 92 | (.., 1) => println!("1 is last"), 93 | (x, y, z) => println!("x = {}, y = {}, z = {}", x, y, z), 94 | }; 95 | } 96 | ``` 97 | 98 | ### Structs 99 | 100 | Structs can be destructured to individual fields. Fields can be ignored using 101 | the `..` syntax. A shorthand for field destructuring can be used when binding to 102 | the same name as the field name: 103 | 104 | ```rust 105 | struct Screen { 106 | width: i32, 107 | height: i32, 108 | } 109 | 110 | fn main() { 111 | let s = Screen { 112 | width: 1337, 113 | height: 420, 114 | }; 115 | 116 | match s { 117 | Screen { 118 | width: 1920, 119 | height: 1080, 120 | } => println!("1080p"), 121 | Screen { width: 0..=480, .. } => println!("what a narrow screen"), 122 | Screen { width: 1000, height } => println!("width 1000 with height {}", height), 123 | Screen { width: w, height: h } => println!("{}x{}", w, h), 124 | }; 125 | } 126 | ``` 127 | 128 | ### Pointers 129 | 130 | References can be destructured into values: 131 | 132 | ```rust 133 | fn main() { 134 | let n = &5; 135 | match n { 136 | &val => println!("n by value: {}", val), 137 | } 138 | } 139 | ``` 140 | 141 | Values can be made into references using `ref` or `ref mut`: 142 | 143 | ```rust 144 | fn main() { 145 | let s = "Hello".to_string(); 146 | match s { 147 | ref s => println!("not moved! just ref'd: {}", s), 148 | } 149 | 150 | let mut s = s; 151 | match s { 152 | ref mut s => { 153 | s.push_str(", world!"); 154 | } 155 | } 156 | println!("{}", s); 157 | } 158 | ``` 159 | 160 | ### Enums 161 | 162 | Individual enum variants can be matched and further destructured: 163 | 164 | ```rust 165 | enum Attribute { 166 | Empty, 167 | Color(u8, u8, u8), 168 | Text(String), 169 | Place { x: i32, y: i32 }, 170 | } 171 | 172 | fn main() { 173 | let a = Attribute::Empty; 174 | match a { 175 | Attribute::Empty => println!("empty 🤷"), 176 | Attribute::Color(255, ..) => println!("something with red"), 177 | Attribute::Text(ref s) => println!("got text \"{}\"", s), 178 | Attribute::Place { x: 0, y: 0 } => println!("origin"), 179 | _ => println!("something different"), 180 | }; 181 | } 182 | ``` 183 | 184 | ## Guards 185 | 186 | Match _guards_ are created using the `if` keyword and a boolean expression: 187 | 188 | ```rust 189 | fn main() { 190 | let pair = (2, -2); 191 | match pair { 192 | (x, y) if x == y => println!("same numbers"), 193 | (x, y) if x + y == 0 => println!("opposites"), 194 | (x, _) if x % 2 == 1 => println!("odd first"), 195 | _ => println!("something different"), 196 | } 197 | } 198 | ``` 199 | 200 | ## Or 201 | 202 | Multiple patterns can be matched using `|`: 203 | 204 | ```rust 205 | fn main() { 206 | let s = "lol"; 207 | let cnd = false; 208 | match s { 209 | "lol" | "kek" | "bur" => println!("lmao"), 210 | "omg" | "wtf" if cnd => println!("conditional or"), 211 | _ => println!("shrug"), 212 | }; 213 | } 214 | ``` 215 | 216 | ## Binding 217 | 218 | Matched literals can be bound to a name using the `@` symbol: 219 | 220 | ```rust 221 | fn main() { 222 | let n = 5; 223 | match n { 224 | x @ 0 => println!("zero"), 225 | x @ 1..=10 => println!("one to ten, got {}" x), 226 | _ => println!("something different"), 227 | }; 228 | } 229 | ``` 230 | 231 | ## Unused names 232 | 233 | Bound names starting with `_` are not checked as _unused_ by the compiler: 234 | 235 | ```rust 236 | fn main() { 237 | let _x = 5; // whatever 238 | } 239 | ``` 240 | -------------------------------------------------------------------------------- /21_modules.md: -------------------------------------------------------------------------------- 1 | # Modules 2 | 3 | Modules control the organization, scope and privacy. They're defined by the 4 | `mod` keyword: 5 | 6 | ```rust 7 | mod blazer { 8 | // ... 9 | } 10 | ``` 11 | 12 | ## Crates 13 | 14 | Crate is a _compilation unit_, an application entrypoint. They can be compiled: 15 | 16 | - as a _binary_ using `rustc .rs` 17 | - as a _library_ using `rustc --crate-type=lib .rs` 18 | 19 | > It is recommended to use `cargo` for compiling configured in `Cargo.toml` 20 | > instead of using `rustc` directly. 21 | 22 | Absolute paths within a crate can be referenced using the `crate` keyword: 23 | 24 | ```rust 25 | mod yolo { 26 | pub enum YoloSwag { 27 | Yolo, 28 | Swag, 29 | } 30 | } 31 | 32 | fn main() { 33 | use crate::yolo::YoloSwag; 34 | // ... 35 | } 36 | ``` 37 | 38 | ## Privacy 39 | 40 | Everything is **private by default** and only made public by the `pub` keyword: 41 | 42 | ```rust 43 | mod blazer { 44 | fn light_me_up() { 45 | // ... 46 | } 47 | 48 | pub fn blaze_it() { 49 | // ... 50 | } 51 | } 52 | ``` 53 | 54 | This applies to all module's items, like _functions_, _traits_, _structs_, 55 | _enums_, etc... 56 | 57 | ### Structs 58 | 59 | Structs have per-field visibility which is private by default and made public 60 | using `pub`: 61 | 62 | ```rust 63 | mod auth { 64 | pub struct User { 65 | pub name: &str, 66 | // public 67 | created_at: u64, // private 68 | } 69 | } 70 | ``` 71 | 72 | Only _public_ structs can have public fields. 73 | 74 | ### Methods 75 | 76 | Methods defined in `impl` blocks need to also be made public explicitly using 77 | `pub`: 78 | 79 | ```rust 80 | mod c { 81 | pub struct Count { 82 | count: u32, 83 | } 84 | 85 | impl Count { 86 | // public api 87 | pub fn inc(&mut self, times: u32) { 88 | for _ in 0..times { 89 | self.inc_by_one(); 90 | } 91 | } 92 | 93 | // private implementation 94 | fn inc_by_one(&mut self) { 95 | self.count += 1; 96 | } 97 | } 98 | } 99 | ``` 100 | 101 | ### Scopes `self` and `super` 102 | 103 | The `self` keyword is used for removing ambiguity, and accessing items 104 | _relative_ to the current module, rather than using an _absolute_ path of the 105 | current crate: 106 | 107 | ```rust 108 | mod yolo { 109 | mod swag { 110 | pub enum YoloSwag { 111 | Yolo, 112 | Swag, 113 | } 114 | } 115 | 116 | fn go() { 117 | use self::swag::YoloSwag; // use crate::yolo::swag::YoloSwag; 118 | // ... 119 | } 120 | } 121 | ``` 122 | 123 | The `super` keyword works as `self`, except it refers to the _parent module_: 124 | 125 | ```rust 126 | mod yolo { 127 | mod swag { 128 | pub enum YoloSwag { 129 | Yolo, 130 | Swag, 131 | } 132 | } 133 | 134 | mod runner { 135 | fn go() { 136 | use super::swag::YoloSwag; // use crate::yolo::swag::YoloSwag; 137 | // ... 138 | } 139 | } 140 | } 141 | ``` 142 | 143 | ### Scope visibility 144 | 145 | The `pub` keyword's scope can be specified explicitly: 146 | 147 | - `pub(in path)` makes an item visible in the specified _path_ which must be an 148 | ancestor of the target item's module 149 | - `pub(crate)` makes an item visible to the _crate_ 150 | - `pub(super)` makes an item visible to the _parent module_, same 151 | as `pub(in super)` 152 | - `pub(self)` makes an item visible to the _current module_, same as 153 | `pub(in self)` or not using `pub` at all, thus being _private_ 154 | 155 | The _path_ specifier in `pub(in path)` must start with one of `crate`, `self` or 156 | `super`. 157 | 158 | ## Use 159 | 160 | The `use` keyword binds a full path to a new name, for easier access: 161 | 162 | ```rust 163 | use std::collections::HashMap; 164 | use std::fs; 165 | 166 | fn main() { 167 | let file = fs::read_to_string("file.txt")?; 168 | let m = HashMap::new(); 169 | // ... 170 | } 171 | ``` 172 | 173 | Multiple items can be specified within a path using `{}`: 174 | 175 | ```rust 176 | use std::io::{self, Result}; 177 | 178 | fn main() -> Result<()> { 179 | let e = io::empty(); 180 | // ... 181 | Ok(()) 182 | } 183 | ``` 184 | 185 | An _alias_ can be specified for an item using `as`: 186 | 187 | ```rust 188 | use std::fs as stdfs; 189 | 190 | fn main() { 191 | let file = stdfs::read_to_string("file.txt")?; 192 | // ... 193 | } 194 | ``` 195 | 196 | Paths are _relative_ by default. An _absolute path_ can be specified for 197 | disambiguation: 198 | 199 | ```rust 200 | mod std { 201 | pub fn fs() { 202 | // ... 203 | } 204 | } 205 | 206 | fn main() { 207 | use ::std::fs as stdfs; // absolute external crate path 208 | use self::std::fs; // explicit relative path 209 | } 210 | ``` 211 | 212 | ### Re-exporting 213 | 214 | Names can be _re-exported_ using `pub use` to create flatter APIs: 215 | 216 | ```rust 217 | mod yolo { 218 | mod swag { 219 | pub enum YoloSwag { 220 | Yolo, 221 | Swag, 222 | } 223 | } 224 | 225 | pub use swag::{YoloSwag}; 226 | } 227 | 228 | fn main() { 229 | use yolo::{YoloSwag}; // instead of yolo::swag::{YoloSwag} 230 | // ... 231 | } 232 | ``` 233 | 234 | A wildcard `*` can be used for using everything, although commonly only used 235 | with re-exporting: 236 | 237 | ```rust 238 | pub use lib::nested::*; 239 | ``` 240 | 241 | ### Enum variants 242 | 243 | Enum variants are sometimes used within a function for cleaner `match` syntax: 244 | 245 | ```rust 246 | mod swag { 247 | pub enum YoloSwag { 248 | Yolo, 249 | Swag, 250 | } 251 | } 252 | 253 | fn main() { 254 | use swag::YoloSwag::*; 255 | 256 | let s = Yolo; 257 | match s { 258 | Yolo => println!("Yolo"), 259 | Swag => println!("Swag"), 260 | }; 261 | } 262 | ``` 263 | 264 | ### Conventions 265 | 266 | The `use` path binding conventions are: 267 | 268 | - using whole modules for their public API, `use std::io;` 269 | - using _structs_, _enums_ and _traits_ directly, 270 | `use std::collections::HashMap;` 271 | - sometimes using _enum variants_ with wildcards in 272 | functions, `use lib::Enum::*;` 273 | - re-exporting to create flatter APIs, `pub use lib::nested::*;` 274 | 275 | ## File hierarchy 276 | 277 | _Files_ and _folders_ can act as modules. The `mod ;` declaration can be 278 | used to bring `.rs` or `/mod.rs` items under the current scope 279 | inside a module named ``: 280 | 281 | ```rust 282 | // /custom.rs or /custom/mod.rs 283 | pub fn do_stuff() { 284 | // ... 285 | } 286 | 287 | // some file in 288 | mod custom; 289 | 290 | fn stuff() { 291 | custom::do_stuff(); 292 | } 293 | ``` 294 | 295 | The `pub mod ;` declaration can be used for re-exporting: 296 | 297 | ```rust 298 | // /custom/core.rs 299 | pub fn do_stuff() { 300 | // ... 301 | } 302 | 303 | // /custom/mod.rs 304 | pub mod core; 305 | 306 | // some file in 307 | mod custom; 308 | 309 | fn stuff() { 310 | custom::core::do_stuff(); 311 | } 312 | ``` 313 | -------------------------------------------------------------------------------- /22_cargo.md: -------------------------------------------------------------------------------- 1 | # Cargo 2 | 3 | The official package manager for Rust. The `cargo` CLI contains various tools 4 | for working with Rust and its bundled tools like `rustc` and `rustfmt`. 5 | 6 | Overview of the most common commands: 7 | 8 | - `cargo new ` creates a new _binary_ project 9 | - `cargo new --lib ` creates a new _library_ project 10 | - `cargo install ` installs a dependency from [Crates.io](https://crates.io) 11 | - `cargo fmt` formats source code 12 | - `cargo fix` fixes source code based on compiler hints 13 | - `cargo test` runs tests 14 | - `cargo run` runs a binary, `src/main.rs` by default 15 | - `cargo build` builds the development version 16 | - `cargo build --release` builds the production version 17 | - `cargo doc` generates documentation 18 | - `cargo publish` publishes a library 19 | 20 | The `Cargo.toml` file contains `cargo` configuration, like the crate name, 21 | dependencies, language version. 22 | 23 | ## New project 24 | 25 | For a binary, run `cargo new `, which generates: 26 | 27 | ``` 28 | src/ 29 | main.rs 30 | Cargo.lock 31 | Cargo.toml 32 | ``` 33 | 34 | For a library, run `cargo new --lib `, which generates: 35 | 36 | ``` 37 | src/ 38 | lib.rs 39 | Cargo.lock 40 | Cargo.toml 41 | ``` 42 | 43 | Can also have CLI in `src/main.rs`. 44 | 45 | ## Dependencies 46 | 47 | The `Cargo.toml` file specifies the project's _version_ and _dependencies_. The 48 | common convention is following _SemVer_ for versioning. 49 | 50 | Specifying a verion number as a crate version downloads the library 51 | from [Crates.io](https://crates.io). Fetching a specific _Git_ repository or a _ 52 | file path_: 53 | 54 | ```toml 55 | [package] 56 | name = "yolo" 57 | version = "4.2.0" 58 | authors = ["oreqizer"] 59 | 60 | [dependencies] 61 | clap = "^2.27.1" # from crates.io 62 | slap = { version = "^1.3.37", registry = "kratos.io" } # from custom registry 63 | rand = { git = "https://github.com/rust-lang-nursery/rand" } # from online repo 64 | swag = { path = "../swag" } # from a path in the local filesystem 65 | ``` 66 | 67 | A library project can be published to [Crates.io](https://crates.io) by running 68 | `cargo publish`. 69 | 70 | ## Binaries 71 | 72 | In addition to the main `src/main.rs` binary, other binaries can be specified in 73 | the `bin` folder: 74 | 75 | ``` 76 | src/ 77 | bin/ 78 | stuff1.rs 79 | stuff2.rs 80 | ... 81 | Cargo.lock 82 | Cargo.toml 83 | ``` 84 | 85 | In order to work with these binaries instad of `src/main.rs`, the `--bin` flag 86 | can be specified like `cargo run --bin stuff1` 87 | 88 | ## Build script 89 | 90 | The `build.rs` can be created to run a script before the build begins, such as 91 | code generation or native code. 92 | 93 | The file name can be adjusted in `Cargo.toml`: 94 | 95 | ```toml 96 | [package] 97 | build = "build.rs" 98 | ``` 99 | 100 | ## Workspaces 101 | 102 | Growing projects can be assembled in the form of _workspaces_. Specifying 103 | workspaces is done by creating a root `Cargo.toml` file: 104 | 105 | ```toml 106 | [workspace] 107 | members = [ 108 | # ... 109 | ] 110 | ``` 111 | 112 | In this folder, create members by `cargo run` and add their names to 113 | the `members` array in root `Cargo.toml`. The structure looks something like: 114 | 115 | ``` 116 | app/ 117 | src/ 118 | main.rs 119 | Cargo.lock 120 | Cargo.toml 121 | utils/ 122 | src/ 123 | lib.rs 124 | Cargo.lock 125 | Cargo.toml 126 | Cargo.toml 127 | ``` 128 | 129 | The root `Cargo.toml`: 130 | 131 | ```toml 132 | [workspace] 133 | members = [ 134 | "app", 135 | "utils", 136 | ] 137 | ``` 138 | 139 | To import `utils` into `app`, specify a relative path 140 | in `app/Cargo.toml`: 141 | 142 | ```toml 143 | [depencencies] 144 | utils = { path = "../utils" } 145 | ``` 146 | 147 | Commands are meant to be run directly in the _root of the project_, such as 148 | `cargo test` or `cargo build`. 149 | 150 | Some commands like `cargo run` require the `-p` flag that specifies which 151 | project to run the command on, like `cargo run -p app`. 152 | -------------------------------------------------------------------------------- /23_tests.md: -------------------------------------------------------------------------------- 1 | # Tests 2 | 3 | Tests can be run by `rustc --test` or `cargo test`, which runs functions marked 4 | with the `#[test]` attribute. 5 | 6 | ## Unit 7 | 8 | The convention is writing _unit tests_ right next to the production code: 9 | 10 | ```rust 11 | fn do_stuff() { 12 | // ... 13 | } 14 | 15 | #[test] 16 | fn test_do_stuff() { 17 | do_stuff(); 18 | } 19 | ``` 20 | 21 | It is common to declare a module marked with `#[cfg(test)]` to co-locate tests 22 | and testing utilities: 23 | 24 | ```rust 25 | fn do_stuff() { 26 | // ... 27 | } 28 | 29 | #[cfg(test)] 30 | mod tests { 31 | use super::*; 32 | 33 | #[test] 34 | fn test_do_stuff() { 35 | do_stuff(); 36 | } 37 | 38 | #[test] 39 | fn test_do_stuff_twice() { 40 | do_stuff(); 41 | } 42 | } 43 | ``` 44 | 45 | ## Integration 46 | 47 | Integration tests live in the `tests` folder next to the `src` folder. They're 48 | meant to test the crate's public API: 49 | 50 | ```rust 51 | // Crate 'yolo': 52 | // src/lib.rs 53 | fn swag() { 54 | // ... 55 | } 56 | 57 | // tests/lib.rs 58 | use yolo; 59 | 60 | #[test] 61 | fn test_swag() { 62 | yolo::swag(); 63 | } 64 | ``` 65 | 66 | No need to use the `#[cfg(test)]` attribute in the `tests` folder, as everything 67 | is a test. 68 | 69 | ## Assertions 70 | 71 | The `assert!` macro asserts a boolean expression. All assertions can optionally 72 | have a custom message: 73 | 74 | ```rust 75 | #[test] 76 | fn test_stuff() { 77 | assert!(2 + 2 == 4); // uses the default assertion message 78 | assert!(2 + 2 == 4, "two plus two better fucking equal four"); 79 | } 80 | ``` 81 | 82 | The `assert_eq!` and `assert_ne!` macros are used for comparing equality: 83 | 84 | ```rust 85 | #[test] 86 | fn test_stuff() { 87 | assert_eq!(2 + 2, 4); 88 | assert_ne!(2 + 2, 5); 89 | } 90 | ``` 91 | 92 | By default, if a test panics, it is considered failed. The `#[should_panic]` 93 | attribute is useful when a test _should_ panic: 94 | 95 | ```rust 96 | fn do_wild_things() { 97 | panic!("Yoooooo!"); 98 | } 99 | 100 | #[test] 101 | #[should_panic] 102 | fn test_wild_stuff() { 103 | do_wild_things(); 104 | } 105 | ``` 106 | 107 | To avoid accidentally passing an unexpected `panic!` call, an expected substring 108 | of the panic message can be specified: 109 | 110 | ```rust 111 | fn do_wild_things() { 112 | panic!("Yoooooo!"); 113 | } 114 | 115 | #[test] 116 | #[should_panic(expected = "Yooo")] 117 | fn test_wild_stuff() { 118 | do_wild_things(); 119 | } 120 | ``` 121 | 122 | Tests can also return `Result` instead of panicking, which allows using 123 | the `?` operator: 124 | 125 | ```rust 126 | fn blaze_it() -> Result { 127 | // ... 128 | Ok(420) 129 | } 130 | 131 | #[test] 132 | fn test_blaze_it() -> Result<(), String> { 133 | let n = blaze_it()?; 134 | match n { 135 | 420 => Ok(()), 136 | _ => Err("wrong 🙀".to_string()), 137 | } 138 | } 139 | ``` 140 | 141 | ## Docs 142 | 143 | The `cargo doc` command generates documentation, optionally with the `--open` 144 | flag, based on special comments written in **Markdown**. 145 | 146 | Comments starting as `//!` are used for documenting _crates_ as a whole, or 147 | individual _modules_. They're put at the top of a file: 148 | 149 | ```rust 150 | //! # Calcx 151 | //! 152 | //! `calcx` is a collection of utilities to make performing certain 153 | //! calculations more convenient. 154 | ``` 155 | 156 | Comments in the form `///` document individual items in a module: 157 | 158 | ```rust 159 | /// Adds one to the number given. 160 | pub fn add_one(x: i32) -> i32 { 161 | x + 1 162 | } 163 | ``` 164 | 165 | Commonly seen sections: 166 | 167 | - `# Examples` minimal examples that show the usage of the item 168 | - `# Panics` describes scenarios when a function calls `panic!` 169 | - `# Errors` when returning `Result`, this section describes cases when 170 | `Err` is returned 171 | - `# Safety` if the function uses `unsafe` code, specifies invariants that the 172 | function expects callers to uphold 173 | 174 | ### Doc tests 175 | 176 | When specifying code blocks in `///` comment docs for libraries, `cargo test` 177 | runs these tests, and they have their own section called _doc-tests_: 178 | 179 | ```rust 180 | /// Adds one to the number given. 181 | /// 182 | /// # Examples 183 | /// 184 | /// ``` 185 | /// let arg = 5; 186 | /// let answer = calcx::add_one(arg); 187 | /// 188 | /// assert_eq!(6, answer); 189 | /// ``` 190 | pub fn add_one(x: i32) -> i32 { 191 | x + 1 192 | } 193 | ``` 194 | 195 | Running this will produce: 196 | 197 | ``` 198 | Doc-tests calcx 199 | 200 | running 1 test 201 | test src/lib.rs - add_one (line 5) ... ok 202 | 203 | test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.34s 204 | ``` 205 | -------------------------------------------------------------------------------- /24_attributes.md: -------------------------------------------------------------------------------- 1 | # Attributes 2 | 3 | An attribute is metadata applied to some module, crate or item. Syntax: 4 | 5 | - crate-wide attributes `#![crate_attribute]` 6 | - module and item attributes `#[item_attribute]` 7 | 8 | Attributes can take arguments: 9 | 10 | - `#[attr = "value"]` 11 | - `#[attr(key = "value")]` 12 | - `#[attr(value)]` 13 | 14 | ## Disabling lints 15 | 16 | Attribute `#[allow]` can be used for ignoring compiler warnings when linting: 17 | 18 | ```rust 19 | #[allow(dead_code)] 20 | fn yo() { 21 | println!("do I even exist?"); 22 | } 23 | 24 | fn main() { 25 | println!("totally not calling 'yo'"); 26 | } 27 | ``` 28 | 29 | ## Crates 30 | 31 | Some common crate attributes include: 32 | 33 | - `#![crate_type]` for differentiating binaries and libraries, has no effect 34 | when using `cargo` and can be specified via `rustc`'s `--crate-type` flag 35 | - `#![crate_name]` for naming the crate, has no effect when using `cargo` and 36 | can be specified via `rustc`'s `--crate-name` flag 37 | - `#![feature(...)]` for enabling experimental compiler features in **Nightly 38 | Rust** 39 | 40 | ## Cfg 41 | 42 | The `#[cfg(...)]` attribute and `cfg!(...)` macro can be used for conditional 43 | compilation and runtime compiler checks: 44 | 45 | ```rust 46 | #[cfg(target_os = "linux")] 47 | fn on_linux() { 48 | // compiled on Linux 49 | println!("Nerd"); 50 | } 51 | 52 | #[cfg(not(target_os = "linux"))] 53 | fn not_on_linux() { 54 | // compiled on everything but Linux 55 | println!("Still a nerd"); 56 | } 57 | 58 | fn main() { 59 | // checked at runtime 60 | if cfg!(target_os = "linux") { 61 | println!("Nerd"); 62 | } else { 63 | println!("Still a nerd"); 64 | } 65 | } 66 | ``` 67 | 68 | This pattern is useful for building libraries with different feature set based 69 | on the compilation environment or feature flagging. 70 | 71 | ### Features 72 | 73 | The convention of `cargo` for feature flagging is using the `feature` config 74 | attribute: 75 | 76 | ```rust 77 | #[cfg(feature = "yolo")] 78 | pub mod yolo { 79 | // ... 80 | } 81 | 82 | #[cfg(feature = "swag")] 83 | pub mod swag { 84 | // ... uses 'yolo' internally 85 | } 86 | ``` 87 | 88 | The `Cargo.toml` file then specifies the list of possible features with their 89 | feature dependencies: 90 | 91 | ```toml 92 | [features] 93 | yolo = [] # no feature dependencies 94 | swag = ["yolo"] # also enables 'yolo' 95 | ``` 96 | 97 | The optional `default` feature can specify features that are enabled by default: 98 | 99 | ```toml 100 | [features] 101 | default = ["yolo"] 102 | yolo = [] 103 | swag = ["yolo"] 104 | ``` 105 | 106 | The default featue set can be disabled using `--no-default-features`. See 107 | [Cargo feature docs](https://doc.rust-lang.org/cargo/reference/features.html) 108 | for more details and how to consume feature flags in dependencies. 109 | 110 | ### Custom 111 | 112 | Some conditions like `target_os` are built into the compiler. Custom ones can 113 | be specified when compiling with the `--cfg` flag: 114 | 115 | ```rust 116 | #[cfg(yolo)] 117 | fn yolo() { 118 | println!("swag"); 119 | } 120 | 121 | fn main() { 122 | yolo(); 123 | } 124 | ``` 125 | 126 | This code will only work when compiling using `rustc --cfg yolo`. 127 | -------------------------------------------------------------------------------- /25_threads.md: -------------------------------------------------------------------------------- 1 | # Threads 2 | 3 | Rust has a _1:1 thread system_ — every thread is a physical thread managed by 4 | the OS. Thread is spawned using `thread::spawn`: 5 | 6 | ```rust 7 | use std::thread; 8 | 9 | fn main() { 10 | for i in 1..10 { 11 | // may or may not finish 12 | thread::spawn(move || { 13 | println!("i = {}", i); 14 | }); 15 | } 16 | } 17 | ``` 18 | 19 | To wait for a thread from the parent thread, the spawned thread's _handle_ can 20 | be _joined_ using the `join` method: 21 | 22 | ```rust 23 | use std::thread; 24 | 25 | fn main() { 26 | (1..10) 27 | .map(|i| thread::spawn(move || println!("i = {}", i))) 28 | .for_each(|h| h.join().unwrap()) // all will finish 29 | } 30 | ``` 31 | 32 | ## `Send` and `Sync` traits 33 | 34 | The only two language features for concurrency — all others are just an 35 | abstraction above these. 36 | 37 | The `Send` trait indicates that the type's ownership can be _transferred between 38 | threads_. Almost all types implement this automatically, except `Rc`, raw 39 | pointers, and few others. 40 | 41 | The `Sync` trait indicates that it is safe for the type implementing `Sync` to 42 | be referenced from multiple threads. Most types are `Sync`, except runtime 43 | borrow types like `RefCell`. 44 | 45 | > Any type `T` is `Sync` if `&T` is `Send`. 46 | 47 | All compound types that are composed of types that implement `Send` also 48 | implicitly implement `Send`. Same goes for `Sync`. 49 | 50 | ## Arc 51 | 52 | Thread safe version of `Rc`, the `Arc`, or _atomic reference counter_, 53 | implements the `Clone` trait that creates a reference pointer to a value on the 54 | heap: 55 | 56 | ```rust 57 | use std::sync::Arc; 58 | use std::thread; 59 | 60 | fn main() { 61 | let swag = Arc::new("swag"); 62 | 63 | for _ in 0..10 { 64 | let swag = swag.clone(); 65 | 66 | thread::spawn(move || { 67 | println!("{:?}", swag); // swag is moved 68 | }); 69 | } 70 | } 71 | ``` 72 | 73 | It behaves just like `Rc`, but has a slight performance cost due to the 74 | thread safety. 75 | 76 | ## Channels 77 | 78 | Channels send data from multiple threads into a single consuming thread to 79 | process the results: 80 | 81 | ```rust 82 | use std::sync::mpsc; // multiple producers single consumer 83 | use std::thread; 84 | 85 | fn main() { 86 | let (tx, rx) = mpsc::channel(); 87 | 88 | thread::spawn(move || { 89 | tx.send("swag").unwrap(); 90 | }); 91 | 92 | let r = rx.recv().unwrap(); 93 | println!("yolo {}", r); 94 | } 95 | ``` 96 | 97 | The `rx` receiver can also be used as an _iterator_. 98 | 99 | The _transmitter_ `tx` needs to be cloned to be used in multiple threads: 100 | 101 | ```rust 102 | use std::sync::mpsc; 103 | use std::thread; 104 | 105 | fn main() { 106 | let (tx, rx) = mpsc::channel(); 107 | 108 | (1..10) 109 | .map(|x| { 110 | let tx = tx.clone(); 111 | thread::spawn(move || { 112 | tx.send(x).unwrap(); 113 | }) 114 | }) 115 | .for_each(|h| h.join().unwrap()); 116 | 117 | drop(tx); // rx waits until all clones of tx are dropped 118 | for r in rx { 119 | println!("{}", r); 120 | } 121 | } 122 | ``` 123 | 124 | ## Mutex and RwLock 125 | 126 | Short for _mutual exclusion_, it is a mechanism for ensuring only a single 127 | thread accesses a mutable memory at one time. 128 | 129 | ```rust 130 | use std::sync::Mutex; 131 | 132 | fn main() { 133 | let m = Mutex::new(5); 134 | 135 | { 136 | let mut num = m.lock().unwrap(); 137 | *num = 6; 138 | } // MutexGuard goes out of scope, mutex is released 139 | 140 | println!("m = {:?}", m); 141 | } 142 | ``` 143 | 144 | The type `T` in a `Mutex` must be `Send`. 145 | 146 | Sharing a `Mutex` instance between multiple threads is achieved using 147 | `Arc` that handles reference counting: 148 | 149 | ```rust 150 | use std::sync::{Arc, Mutex}; 151 | use std::thread; 152 | 153 | fn main() { 154 | let counter = Arc::new(Mutex::new(0)); 155 | 156 | (0..10) 157 | .map(|_| { 158 | let counter = Arc::clone(&counter); 159 | 160 | thread::spawn(move || { 161 | let mut num = counter.lock().unwrap(); 162 | *num += 1; 163 | }) 164 | }) 165 | .for_each(|h| h.join().unwrap()); 166 | 167 | println!("Result: {}", *counter.lock().unwrap()); 168 | } 169 | ``` 170 | 171 | ### RwLock 172 | 173 | Basically `Mutex`, except it allows _multiple readers_ and _one writer_: 174 | 175 | ```rust 176 | use std::sync::{Arc, RwLock}; 177 | use std::thread; 178 | use std::time::Duration; 179 | 180 | fn main() { 181 | let counter = Arc::new(RwLock::new(0)); 182 | 183 | let pc = counter.clone(); 184 | let producer = thread::spawn(move || loop { 185 | if let Ok(mut w) = pc.write() { 186 | *w += 1; 187 | thread::sleep(Duration::from_millis(500)); 188 | } 189 | }); 190 | 191 | let rc_1 = counter.clone(); 192 | let consumer_1 = thread::spawn(move || loop { 193 | if let Ok(v) = rc_1.read() { 194 | // One reads here 195 | println!("counter = {}", v); 196 | thread::sleep(Duration::from_millis(250)); 197 | } 198 | }); 199 | 200 | let rc_2 = counter.clone(); 201 | let consumer_2 = thread::spawn(move || loop { 202 | if let Ok(v) = rc_2.read() { 203 | // Another one reads here, Mutex would deadlock 204 | println!("counter^2 = {}", *v * *v); 205 | thread::sleep(Duration::from_millis(250)); 206 | } 207 | }); 208 | 209 | producer.join().unwrap(); 210 | consumer_1.join().unwrap(); 211 | consumer_2.join().unwrap(); 212 | } 213 | ``` 214 | 215 | If this was done with a `Mutex`, the readers would get deadlocked. The 216 | drawback is that in `RwSync`, the `T` must be both `Send` and `Sync`. 217 | -------------------------------------------------------------------------------- /26_macros.md: -------------------------------------------------------------------------------- 1 | # Macros 2 | 3 | Rust's way of metaprogramming. Macros allow _compile-time_ code generation that 4 | generates source code based on supplied parameters. 5 | 6 | ## Declarative macros 7 | 8 | Macros that utilize 9 | [special DSL](https://doc.rust-lang.org/reference/macros-by-example.html) to 10 | write source code in a concise and readable way. 11 | 12 | > Current `macro_rules!` will be deprecated and replaced with 13 | > [declarative macros 2.0](https://github.com/rust-lang/rust/issues/39412) 14 | 15 | Declarative macros are invoked like functions ending with `!`, like `println!`. 16 | They are created using the `macro_rules!` keyword followed by the macro name. 17 | 18 | Arguments passed to macros are matched against the pattern specified by the DSL, 19 | consisting of _designators_ bound to names prefixed with `$`: 20 | 21 | ```rust 22 | #[macro_export] 23 | macro_rules! create_function { 24 | ($name:ident) => { 25 | fn $name() { 26 | println!("You called {:?}", stringify!($name)); 27 | } 28 | }; 29 | } 30 | 31 | create_function!(kek); // expands into: 32 | // fn kek() { 33 | // println!("You called {:?}", "kek"); 34 | // } 35 | 36 | fn main() { 37 | kek(); // You called "kek" 38 | } 39 | ``` 40 | 41 | Macros can optionally be exported by the `#[macro_export]` macro. They're then 42 | brought into scope when the crate they're in is brought into scope. 43 | 44 | ### Designators 45 | 46 | There's a bunch of available designators to match against: 47 | 48 | - `block` 49 | - `expr` is used for expressions 50 | - `ident` is used for variable/function names 51 | - `item` 52 | - `literal` is used for literal constants 53 | - `pat` _(pattern)_ 54 | - `path` 55 | - `stmt` _(statement)_ 56 | - `tt` _(token tree)_ 57 | - `ty` _(type)_ 58 | - `vis` _(visibility qualifier)_ 59 | 60 | This macro prints the expression and its result: 61 | 62 | ```rust 63 | macro_rules! print_result { 64 | ($e:expr) => { 65 | println!("{:?} = {:?}", stringify!($e), $e); 66 | }; 67 | } 68 | 69 | fn main() { 70 | print_result(2 * 2); // "2 * 2" = 4 71 | print_result!({ 72 | let x = 1u32; 73 | 74 | x * x + 2 * x - 1 75 | }); // "{ let x = 1u32; x * x + 2 * x - 1 }" = 2 76 | } 77 | ``` 78 | 79 | ### Repetitions 80 | 81 | Arbitrary number of designators, including optional ones, can be _matched_ and 82 | _expanded_ using: 83 | 84 | - `*` for 0 to infinity 85 | - `+` for 1 to infinity 86 | - `?` for 0 or 1 87 | 88 | A naïve implementation of `vec!` without memory optimization would look like 89 | this: 90 | 91 | ```rust 92 | macro_rules! vec { 93 | ($($x:expr),*) => { 94 | { 95 | let mut temp_vec = Vec::new(); 96 | $( 97 | temp_vec.push($x); 98 | )* // repeats as many times as $x 99 | temp_vec 100 | } 101 | }; 102 | } 103 | 104 | fn main() { 105 | let _v = vec!(1, 2, 3); 106 | } 107 | ``` 108 | 109 | When expanding, the same kind and nesting must be used than when matching. When 110 | expanding multiple matchers in one repetition, their number of fragments must be 111 | the same. 112 | 113 | ### Matching 114 | 115 | Macro pattern matching is done against lexical tokens and allows _multiple 116 | signatures_ and _recursion_: 117 | 118 | ```rust 119 | macro_rules! find_min { 120 | ($x:expr) => ($x); 121 | ($x:expr, $($y:expr),+) => ( 122 | std::cmp::min($x, find_min!($($y),+)) 123 | ) 124 | } 125 | 126 | fn main() { 127 | println!("{}", find_min!(1)); 128 | println!("{}", find_min!(1 + 2, 2)); 129 | println!("{}", find_min!(5, 2 * 3, 4)); 130 | } 131 | ``` 132 | 133 | Arbitrary tokens can be matched: 134 | 135 | ```rust 136 | macro_rules! assert_many { 137 | ($($next:expr),*; one $msg:tt) => { 138 | assert!(false $(|| $next)*, stringify!($msg)); 139 | }; 140 | ($($next:expr),*; all $msg:tt) => { 141 | assert!(true $(&& $next)*, stringify!($msg)); 142 | }; 143 | } 144 | 145 | fn main() { 146 | assert_many!(2 == 2, 5 > 8; one "one is enough"); 147 | assert_many!(2 == 2, 5 < 8; all "all must pass"); 148 | } 149 | ``` 150 | 151 | ## Procedural macros 152 | 153 | _Procedural macros_ are functions that take `TokenStream` input and output a 154 | modified `TokenStream`. There are three kinds: 155 | 156 | - Function-like macros - `custom!(...)` 157 | - Derive macros - `#[derive(Custom)]` 158 | - Attribute macros - `#[custom]` 159 | 160 | Procedural macros have to be defined in a separate crate with the following 161 | field in `Cargo.toml`: 162 | 163 | ```toml 164 | [lib] 165 | proc-macro = true 166 | ``` 167 | 168 | ### Function-like macros 169 | 170 | These macros are invoked with the `custom!()` syntax. They're defined using the 171 | `#[proc_macro]` attribute: 172 | 173 | ```rust 174 | // custom_macros crate 175 | use proc_macro::TokenStream; 176 | 177 | #[proc_macro] 178 | pub fn custom(_input: TokenStream) -> TokenStream { 179 | // normally you'd modify input here and return the result 180 | r#"fn yolo() -> &'static str { "swag" }"#.parse().unwrap() 181 | } 182 | ``` 183 | 184 | You then include it as a dependency in your regular crate and use it: 185 | 186 | ```rust 187 | // your regular crate 188 | use custom_macros::custom; 189 | 190 | custom!(); 191 | 192 | fn main() { 193 | println!("yolo {}", yolo()); // yolo swag 194 | } 195 | ``` 196 | 197 | ### Derive macros 198 | 199 | _Derive macros_ define inputs for the `#[derive(...)]` attribute. They can be 200 | applied on `struct`, `enum` or `union` token streams: 201 | 202 | ```rust 203 | // custom_macros crate 204 | use proc_macro::TokenStream; 205 | use quote::quote; 206 | use syn; 207 | 208 | #[proc_macro_derive(Blaze)] 209 | pub fn blaze_derive(input: TokenStream) -> TokenStream { 210 | let ast: syn::DeriveInput = syn::parse(input).unwrap(); 211 | 212 | let name = &ast.ident; 213 | let gen = quote! { 214 | impl Blaze for #name { 215 | fn it() { 216 | println!("🔥"); 217 | } 218 | } 219 | }; 220 | gen.into() 221 | } 222 | ``` 223 | 224 | The macro only needs the trait's _name_, it does not need to actually be in 225 | scope when defining the macro function. 226 | 227 | Bringing the derive trait's name into scope applies the macro: 228 | 229 | ```rust 230 | // your regular crate 231 | use custom_macros::Blaze; 232 | 233 | pub trait Blaze { 234 | fn it(); 235 | } 236 | 237 | #[derive(Blaze)] 238 | struct Snoop; 239 | 240 | fn main() { 241 | Snoop::it(); // 🔥 242 | } 243 | ``` 244 | 245 | Derive macros can define _helper attributes_: 246 | 247 | ```rust 248 | // custom_macros crate 249 | use proc_macro::TokenStream; 250 | 251 | #[proc_macro_derive(Custom, attributes(custom))] 252 | pub fn custom_derive_attr(input: TokenStream) -> TokenStream { 253 | println!("input = {}", input.to_string()); 254 | TokenStream::new() 255 | } 256 | ``` 257 | 258 | These are _inert_ and can be specified on items as additional information: 259 | 260 | ```rust 261 | // your regular crate 262 | use custom_macros::Custom; 263 | 264 | pub trait Custom { 265 | fn it(); 266 | } 267 | 268 | // prints during compilation: 269 | // input = struct Struct { #[custom] field : u32 } 270 | #[derive(Custom)] 271 | struct Struct { 272 | #[custom] field: u32 273 | } 274 | ``` 275 | 276 | ### Attribute macros 277 | 278 | _Attribute macros_ define new outer attributes using the 279 | `#[proc_macro_attribute]` attribute. They take the _attribute token stream_ and 280 | the _item token stream_ as arguments: 281 | 282 | ```rust 283 | // custom_macros crate 284 | use proc_macro::TokenStream; 285 | 286 | #[proc_macro_attribute] 287 | pub fn print_tokens(attr: TokenStream, item: TokenStream) -> TokenStream { 288 | println!("attr: {}", attr.to_string()); 289 | println!("item: {}", item.to_string()); 290 | item 291 | } 292 | ``` 293 | 294 | Attribute macros can take arbitrary arguments to adjust their behavior: 295 | 296 | ```rust 297 | // custom_macros regular crate 298 | use custom_macros::print_tokens; 299 | 300 | // prints during compilation: 301 | // attr: GET, "/:id" 302 | // item: fn get_username(id : u8) -> String { "xxx_bobby_xxx".to_string() } 303 | #[print_tokens(GET, "/:id")] 304 | fn get_username(_id: u8) -> String { 305 | "xxx_bobby_xxx".to_string() 306 | } 307 | ``` 308 | -------------------------------------------------------------------------------- /27_unsafe.md: -------------------------------------------------------------------------------- 1 | # Unsafe 2 | 3 | The `unsafe` keyword turns off memory safety checks by the compiler. It is used 4 | to mark code that can potentially be unsafe, such as: 5 | 6 | - dereferencing raw pointers 7 | - calling other unsafe functions 8 | - implementing unsafe traits 9 | - accessing or modifying a static mutable variable 10 | - foreign function interfacing 11 | 12 | ## Raw pointers 13 | 14 | Immutable raw pointers are created by `*const T`, mutable ones by `*mut T`. 15 | Creating raw pointers is considered _safe_, only their dereferencing is not: 16 | 17 | ```rust 18 | fn main() { 19 | let mut num = 5; 20 | 21 | let r1 = &num as *const i32; // immutable "borrow" 22 | let r2 = &mut num as *mut i32; // can have mutable "borrow" 🙀 23 | 24 | unsafe { 25 | println!("r1 = {}", *r1); // r1 = 5 26 | println!("r2 = {}", *r2); // r2 = 5 27 | } 28 | } 29 | ``` 30 | 31 | Arbitrary address can be pointed to: 32 | 33 | ```rust 34 | fn main() { 35 | let shithole = 0x12345 as *const i32; 36 | // println!("what is here? {}", *shithole); // please don't 🙀 37 | } 38 | ``` 39 | 40 | ## Unsafe functions 41 | 42 | Functions can be marked unsafe using the `unsafe fn` declaration: 43 | 44 | ```rust 45 | unsafe fn do_danger() { 46 | // ... 47 | } 48 | ``` 49 | 50 | Calling unsafe functions is considered unsafe. To use these functions in a safe 51 | environment, a safe abstraction can be created: 52 | 53 | ```rust 54 | use std::slice; 55 | 56 | fn split_at_mut(slice: &mut [T], mid: usize) -> (&mut [T], &mut [T]) { 57 | let len = slice.len(); 58 | let ptr = slice.as_mut_ptr(); 59 | 60 | assert!(mid <= len); 61 | 62 | unsafe { 63 | ( 64 | // slice::from_raw_parts_mut is an unsafe function 65 | slice::from_raw_parts_mut(ptr, mid), 66 | slice::from_raw_parts_mut(ptr.add(mid), len - mid), 67 | ) 68 | } 69 | } 70 | 71 | fn main() { 72 | let mut s = "420blazeit".chars().collect::>(); 73 | let (a, b) = split_at_mut(&mut s, 3); 74 | 75 | println!("a = {:?}", a); // a = ['4', '2', '0'] 76 | println!("b = {:?}", b); // b = ['b', 'l', 'a', 'z', 'e', 'i', 't'] 77 | } 78 | ``` 79 | 80 | ## Unsafe traits 81 | 82 | Implementing an `unsafe` trait is considered unsafe: 83 | 84 | ```rust 85 | unsafe trait Yolo { 86 | // 87 | } 88 | 89 | unsafe impl Yolo for i32 { 90 | // 91 | } 92 | ``` 93 | 94 | An example of an unsafe trait is creating a trait that holds a type that is not 95 | `Send` or `Sync` such as a raw pointer, and we want to mark the trait as `Send` 96 | or `Sync`. 97 | 98 | ## Mutable static variables 99 | 100 | Accessing and mutating _mutable static variables_ is unsafe: 101 | 102 | ```rust 103 | static mut GLOBAL_ID: i32 = 0; 104 | 105 | fn main() { 106 | unsafe { 107 | GLOBAL_ID += 1; 108 | println!("id = {}", GLOBAL_ID); 109 | } 110 | } 111 | ``` 112 | 113 | ## FFI 114 | 115 | Calling a _foreign function interface_ functions defined in `extern` 116 | declarations is unsafe: 117 | 118 | ```rust 119 | extern "C" { 120 | fn abs(input: i32) -> i32; 121 | } 122 | 123 | fn main() { 124 | unsafe { 125 | println!("abs(-420) according to C is {}", abs(-420)); 126 | } 127 | } 128 | ``` 129 | -------------------------------------------------------------------------------- /28_async.md: -------------------------------------------------------------------------------- 1 | # Async 2 | 3 | Asynchronous programming is a _concurrent programming model_ allowing executing 4 | many concurrent tasks on a small number of OS threads. 5 | 6 | Rust's implementation of async is: 7 | 8 | - **zero-cost** - can be performed without heap allocations and dynamic dispatch 9 | - **lazy** - progress is made only when polled 10 | - **zero-runtime** - runtime implementation is provided by community crates 11 | - **single- and multi-threaded** - depending on implementation 12 | 13 | Asynchronous tasks are defined in `async fn` functions and `async` blocks. These 14 | produce types that satisfy the `Future` trait. Futures can be awaited using 15 | `.await`: 16 | 17 | ```rust,ignore 18 | async fn fetch_number() -> i32 { 19 | 1337 20 | } 21 | 22 | async fn double_fetched() -> i32 { 23 | let n = fetch_number().await; 24 | 25 | n * 2 26 | } 27 | ``` 28 | 29 | These `async` blocks get compiled to anonymous futures in the form of _finite 30 | state machines_, which keep track of the future's progress, as well as their 31 | scope contents. 32 | 33 | ## The `Future` trait 34 | 35 | Implementing the `Future` trait allows using the `async/await` syntax on a type. 36 | The trait is defined like this: 37 | 38 | ```rust,ignore 39 | use std::pin::Pin; 40 | use std::task::Context; 41 | 42 | enum Poll { 43 | Ready(T), 44 | Pending, 45 | } 46 | 47 | trait Future { 48 | type Output; 49 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll; 50 | } 51 | ``` 52 | 53 | Futures are executed by calling the `poll` function, which advances them into 54 | their next state. 55 | 56 | When the coroutine executes and hasn't reached its final state yet, it returns 57 | `Poll::Pending` and marks itself back to be polled via `cx` when it is ready. 58 | 59 | When the coroutine is polled and finishes execution, it returns `Poll::Ready(T)` 60 | with the result. 61 | 62 | ## Task waking 63 | 64 | The `Context` type in `std::task` is used to carry context between coroutines, 65 | as well as provide access to the `Waker` instance, which is used to let the 66 | executor know that a future is ready to proceed. 67 | 68 | Each time a future is polled, it is polled as a _task_, which is a top-level 69 | future that is submitted to an _executor_. 70 | 71 | The following example is a simple `Future` implementation that simply waits a 72 | certain duration before resolving, and returns nothing: 73 | 74 | ```rust,ignore 75 | use std::{ 76 | future::Future, 77 | pin::Pin, 78 | sync::{Arc, Mutex}, 79 | task::{Context, Poll, Waker}, 80 | }; 81 | 82 | struct SharedState { 83 | completed: bool, 84 | waker: Option, 85 | } 86 | 87 | pub struct TimerFuture { 88 | shared_state: Arc>, 89 | } 90 | 91 | impl Future for TimerFuture { 92 | type Output = (); 93 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 94 | let mut shared_state = self.shared_state.lock().unwrap(); 95 | if shared_state.completed { 96 | Poll::Ready(()) 97 | } else { 98 | shared_state.waker = Some(cx.waker().clone()); 99 | Poll::Pending 100 | } 101 | } 102 | } 103 | ``` 104 | 105 | The `poll` function simply checks whether the state is completed. If not, it 106 | clones the waker to ensure it is located in the proper task, since futures are 107 | passed around between tasks after being polled. 108 | 109 | Constructing a new future: 110 | 111 | ```rust,ignore 112 | use std::{ 113 | sync::{Arc, Mutex}, 114 | thread, 115 | time::Duration, 116 | }; 117 | 118 | impl TimerFuture { 119 | pub fn new(duration: Duration) -> Self { 120 | let shared_state = Arc::new(Mutex::new(SharedState { 121 | completed: false, 122 | waker: None, 123 | })); 124 | 125 | let thread_shared_state = shared_state.clone(); 126 | thread::spawn(move || { 127 | thread::sleep(duration); 128 | let mut shared_state = thread_shared_state.lock().unwrap(); 129 | shared_state.completed = true; 130 | if let Some(waker) = shared_state.waker.take() { 131 | waker.wake() 132 | } 133 | }); 134 | 135 | TimerFuture { shared_state } 136 | } 137 | } 138 | ``` 139 | 140 | The future spawns a thread that simply waits a certain duration before marking 141 | the future as complete, and waking the task using the `Waker` instance. 142 | 143 | ## Executors 144 | 145 | An _executor_ takes _tasks_ and concurrently runs them to completion by calling 146 | `poll` whenever they're ready to make progress. 147 | 148 | ### Task 149 | 150 | To build a simple executor, a task has to be defined first. It is going to use 151 | the `futures` crate which contains utilities for building executors: 152 | 153 | ```rust,ignore 154 | use { 155 | futures::{ 156 | future::BoxFuture, 157 | task::ArcWake, 158 | }, 159 | std::{ 160 | sync::mpsc::SyncSender, 161 | sync::{Arc, Mutex}, 162 | }, 163 | }; 164 | 165 | struct Task { 166 | future: Mutex>>, 167 | task_sender: SyncSender>, 168 | } 169 | 170 | impl ArcWake for Task { 171 | fn wake_by_ref(arc_self: &Arc) { 172 | let cloned = arc_self.clone(); 173 | arc_self 174 | .task_sender 175 | .send(cloned) 176 | .expect("too many tasks queued"); 177 | } 178 | } 179 | ``` 180 | 181 | On the `Task` struct itself: 182 | 183 | - `future` contains the underlying future to execute 184 | - `task_sender` is a channel used by the task to send itself back into the queue 185 | 186 | The `ArcWake` trait implementation allows waking up a specific task. It clones 187 | the task itself and sends it to the sender. 188 | 189 | ### Spawner 190 | 191 | Next, a `Spawner` is needed to create new tasks: 192 | 193 | ```rust,ignore 194 | use std::sync::{Arc, Mutex, mpsc::SyncSender}; 195 | 196 | #[derive(Clone)] 197 | struct Spawner { 198 | task_sender: SyncSender>, 199 | } 200 | 201 | impl Spawner { 202 | fn spawn(&self, future: impl Future + 'static + Send) { 203 | let future = future.boxed(); 204 | let task = Arc::new(Task { 205 | future: Mutex::new(Some(future)), 206 | task_sender: self.task_sender.clone(), 207 | }); 208 | self.task_sender.send(task).expect("too many tasks queued"); 209 | } 210 | } 211 | ``` 212 | 213 | The role of `Spawner` is submitting new tasks to the sender. The `spawn` 214 | function takes a future, boxes it, assigns it to a task and sends for execution. 215 | 216 | ### Executor 217 | 218 | Finally, `Executor` holds queue of tasks ready to be executed and handles the 219 | event loop: 220 | 221 | ```rust,ignore 222 | use { 223 | futures::task::waker_ref, 224 | std::{ 225 | sync::mpsc::Receiver, 226 | sync::Arc, 227 | task::Context, 228 | }, 229 | }; 230 | 231 | struct Executor { 232 | ready_queue: Receiver>, 233 | } 234 | 235 | impl Executor { 236 | fn run(&self) { 237 | while let Ok(task) = self.ready_queue.recv() { 238 | let mut future_slot = task.future.lock().unwrap(); 239 | if let Some(mut future) = future_slot.take() { 240 | let waker = waker_ref(&task); 241 | let context = &mut Context::from_waker(&*waker); 242 | if future.as_mut().poll(context).is_pending() { 243 | *future_slot = Some(future); 244 | } 245 | } 246 | } 247 | } 248 | } 249 | ``` 250 | 251 | The `run` function accepts incoming tasks. The task's future is taken, and in 252 | case it hasn't been completed yet, it is polled in an attempt to complete it. 253 | 254 | If the future is still not complete after being polled, the future's returned to 255 | the task, which will submit it to the `ready_queue` when it is able to proceed. 256 | 257 | ### Running 258 | 259 | With everything set up, the spawner and executor can begin running tasks: 260 | 261 | ```rust,ignore 262 | use std::{ 263 | sync::mpsc::sync_channel, 264 | time::Duration, 265 | }; 266 | 267 | fn new_executor_and_spawner() -> (Executor, Spawner) { 268 | const MAX_QUEUED_TASKS: usize = 10_000; // just to make `sync_channel` happy 269 | let (task_sender, ready_queue) = sync_channel(MAX_QUEUED_TASKS); 270 | (Executor { ready_queue }, Spawner { task_sender }) 271 | } 272 | 273 | fn main() { 274 | let (executor, spawner) = new_executor_and_spawner(); 275 | 276 | spawner.spawn(async { 277 | println!("yolo"); 278 | TimerFuture::new(Duration::new(2, 0)).await; 279 | println!("swag"); 280 | }); 281 | 282 | // Tells the executor that no more tasks will be coming 283 | drop(spawner); 284 | 285 | executor.run(); 286 | } 287 | ``` 288 | 289 | This prints `yolo`, and after two seconds prints `swag`. 🎉 290 | 291 | There are many community runtimes available, such as `tokio`, that abstract 292 | these low level details like implementing custom futures and building custom 293 | executors. 294 | 295 | ## Pinning 296 | 297 | By default, all types are _movable_. Primitive types like `i32` are passed 298 | by-value, while fat pointers like `Box` and `&mut T` allow swapping their 299 | contents. 300 | 301 | The type `Pin

` ensures that any _pointee_ of pointer `P` has stable location 302 | in memory. This is essential for _self-referential types_, which many futures 303 | are: 304 | 305 | ```rust,ignore 306 | async { 307 | let mut x = [0; 128]; 308 | let read_into_buf_fut = read_into_buf(&mut x); 309 | read_into_buf_fut.await; 310 | println!("{:?}", x); 311 | } 312 | ``` 313 | 314 | This compiles down to something like this: 315 | 316 | ```rust,ignore 317 | struct ReadIntoBuf<'a> { 318 | buf: &'a mut [u8], // points to `x` below 319 | } 320 | 321 | struct AsyncFuture { 322 | x: [u8; 128], 323 | read_into_buf_fut: ReadIntoBuf<'what_lifetime?>, 324 | } 325 | ``` 326 | 327 | In case the future was moved, the `buf` pointer to `x` would suddenly have 328 | pointed to an unknown location. To prevent this, `AsyncFuture` has to be 329 | _pinned_ in order for `x` to stay in the same place. 330 | 331 | For that reason, the `Future` trait's `poll` function takes a `Pin<&mut Self>` 332 | as a receiver, ensuring that he future is pinned. This ensures it is not moved, 333 | for example between threads. 334 | 335 | ### The `Unpin` trait 336 | 337 | Primitive types are always freely movable because they do not require a stable 338 | address in memory, such as `i32`, `bool` and references, as well as other types 339 | composed of these types. 340 | 341 | Types that do not need pinning implement the `Unpin` auto trait, which cancels 342 | the effect of `Pin

`. For `T: Unpin`, `Pin>` is the same as `Box`, 343 | same for `Pin<&mut T>` and `&mut T`. 344 | 345 | The `Unpin` trait only affects the _pointee_, not the _pointer_. In case of 346 | `Pin>`, the `T` must be `Unpin`, and not `Box`. 347 | 348 | ### The `!Unpin` marker 349 | 350 | Self-referential types have to be marked as `!Unpin` using 351 | `std::marker::PhantomPinned`, since they're not movable _without being pinned_: 352 | 353 | ```rust 354 | use std::marker::PhantomPinned; 355 | 356 | struct Test { 357 | text: String, 358 | ptr: *const String, 359 | _pin: PhantomPinned, 360 | } 361 | 362 | impl Test { 363 | fn new(text: &str) -> Self { 364 | let mut s = Self { 365 | text: text.to_string(), 366 | ptr: std::ptr::null(), 367 | _pin: PhantomPinned, 368 | }; 369 | s.ptr = &s.text; 370 | s 371 | } 372 | 373 | fn text(&self) -> &str { 374 | &self.text 375 | } 376 | 377 | fn ptr(&self) -> &str { 378 | unsafe { &*(self.ptr) } 379 | } 380 | } 381 | 382 | fn main() { 383 | let mut test1 = Test::new("test1"); 384 | let mut test2 = Test::new("test2"); 385 | 386 | println!("{}, {}", test1.text(), test1.ptr()); // test1, test1 387 | std::mem::swap(&mut test1, &mut test2); 388 | println!("{}, {}", test2.text(), test2.ptr()); // test1, test2 389 | } 390 | ``` 391 | 392 | Without pinning, swapping the memory of `test1` and `test2` causes `test2.ptr` 393 | to suddenly point to a wrong location — the pointer _still_ points to the 394 | `test1` struct, which already contains the `"test2"` string now. 395 | 396 | For this type, operations like `std::mem::swap` are illegal, since they break 397 | the pointer behavior. To prevent this, `Pin` can be used to pin the `Test` 398 | object into memory, so the `ptr` pointer will point to the correct location. 399 | 400 | ### Pinning to the stack 401 | 402 | Pinning can be done on the _stack_ directly: 403 | 404 | ```rust 405 | use std::marker::PhantomPinned; 406 | use std::pin::Pin; 407 | 408 | struct Test { 409 | text: String, 410 | ptr: *const String, 411 | _pin: PhantomPinned, 412 | } 413 | 414 | impl Test { 415 | fn new(text: &str) -> Self { 416 | let mut s = Self { 417 | text: text.to_string(), 418 | ptr: std::ptr::null(), 419 | _pin: PhantomPinned, 420 | }; 421 | s.ptr = &s.text; 422 | s 423 | } 424 | 425 | fn text(self: Pin<&Self>) -> &str { 426 | &self.get_ref().text 427 | } 428 | 429 | fn ptr(self: Pin<&Self>) -> &str { 430 | unsafe { &*(self.ptr) } 431 | } 432 | } 433 | 434 | fn main() { 435 | let mut test1 = Test::new("test1"); 436 | let mut test1 = unsafe { Pin::new_unchecked(&mut test1) }; 437 | let mut test2 = Test::new("test2"); 438 | let mut test2 = unsafe { Pin::new_unchecked(&mut test2) }; 439 | 440 | println!("{}, {}", test1.as_ref().text(), test1.as_ref().ptr()); 441 | // std::mem::swap(test1.get_mut(), test2.get_mut()); // compilation error 🙀 442 | println!("{}, {}", test2.as_ref().text(), test2.as_ref().ptr()); 443 | } 444 | ``` 445 | 446 | The `std::mem::swap` function can no longer be used, because both `Test` objects 447 | are now pinned and marked as `!Unpin`. 448 | 449 | ### Pinning to the heap 450 | 451 | The `Box::pin` function can be used to pin objects to the heap: 452 | 453 | ```rust 454 | use std::marker::PhantomPinned; 455 | use std::pin::Pin; 456 | 457 | struct Test { 458 | text: String, 459 | ptr: *const String, 460 | _pin: PhantomPinned, 461 | } 462 | 463 | impl Test { 464 | fn new(text: &str) -> Pin> { 465 | let mut s = Self { 466 | text: text.to_string(), 467 | ptr: std::ptr::null(), 468 | _pin: PhantomPinned, 469 | }; 470 | let mut boxed = Box::pin(s); 471 | unsafe { boxed.as_mut().get_unchecked_mut().ptr = &boxed.as_ref().text as *const String }; 472 | boxed 473 | } 474 | 475 | fn text(self: Pin<&Self>) -> &str { 476 | &self.get_ref().text 477 | } 478 | 479 | fn ptr(self: Pin<&Self>) -> &str { 480 | unsafe { &*(self.ptr) } 481 | } 482 | } 483 | 484 | fn main() { 485 | let mut test1 = Test::new("test1"); 486 | let mut test2 = Test::new("test2"); 487 | 488 | println!("{}, {}", test1.as_ref().text(), test1.as_ref().ptr()); 489 | // std::mem::swap(test1.get_mut(), test2.get_mut()); // compilation error 🙀 490 | println!("{}, {}", test2.as_ref().text(), test2.as_ref().ptr()); 491 | } 492 | ``` 493 | 494 | The `ptr` field has to be populated _after_ the object is _boxed and pinned_, so 495 | that it points to the correct location. 496 | 497 | ## Streams 498 | 499 | The `Stream` trait is basically `Future` that yields multiple values: 500 | 501 | ```rust 502 | use std::pin::Pin; 503 | use std::task::{Context, Poll}; 504 | 505 | trait Stream { 506 | type Item; 507 | fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) 508 | -> Poll>; 509 | } 510 | ``` 511 | 512 | The `poll_next` function returns `Poll::Pending` when the stream is waiting. 513 | When values are ready, it returns `Poll::Ready(Some(T))`, and 514 | `Poll::Ready(None)` when the stream is finished. 515 | 516 | The `futures` crate has tools for both synchronous and asynchronous processing 517 | of yielded values. 518 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rust 2 | 3 | Notes I take during learning **Rust** from 4 | [The Rust book](https://doc.rust-lang.org/stable/book/) and 5 | [Rust by example](https://doc.rust-lang.org/rust-by-example/). 🦀 6 | 7 | Further reading: 8 | 9 | - [Async](https://rust-lang.github.io/async-book/) for details on asynchronous 10 | programming 11 | - [TLBORM](https://veykril.github.io/tlborm/) for details on macros 12 | - [Rustonomicon](https://doc.rust-lang.org/stable/nomicon/) for raw guts of the 13 | language 🙀 14 | 15 | ## Topics 16 | 17 | 0. [Intro](00_intro.md) 18 | 1. [Variables](01_variables.md) 19 | 2. [Functions](02_functions.md) 20 | 3. [Control flow](03_control_flow.md) 21 | 4. [Primitives](04_primitives.md) 22 | 5. [Ownership](05_ownership.md) 23 | 6. [References](06_references.md) 24 | 7. [Slices](07_slices.md) 25 | 8. [Structs](08_structs.md) 26 | 9. [Enums](09_enums.md) 27 | 10. [Generics](10_generics.md) 28 | 11. [Traits](11_traits.md) 29 | 12. [Types](12_types.md) 30 | 13. [Effects](13_effects.md) 31 | 14. [Lifetimes](14_lifetimes.md) 32 | 15. [Closures](15_closures.md) 33 | 16. [Iterators](16_iterators.md) 34 | 17. [Collections](17_collections.md) 35 | 18. [Strings](18_strings.md) 36 | 19. [Smart pointers](19_smart_pointers.md) 37 | 20. [Patterns](20_patterns.md) 38 | 21. [Modules](21_modules.md) 39 | 22. [Cargo](22_cargo.md) 40 | 23. [Tests](23_tests.md) 41 | 24. [Attributes](24_attributes.md) 42 | 25. [Threads](25_threads.md) 43 | 26. [Macros](26_macros.md) 44 | 27. [Unsafe](27_unsafe.md) 45 | 28. [Async](28_async.md) 46 | -------------------------------------------------------------------------------- /assets/string_ptr.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | %3 11 | 12 | 13 | 14 | table0 15 | 16 | s1 17 | 18 | name 19 | 20 | value 21 | 22 | ptr 23 | 24 | 25 | len 26 | 27 | 5 28 | 29 | capacity 30 | 31 | 5 32 | 33 | 34 | 35 | table1 36 | 37 | index 38 | 39 | value 40 | 41 | 0 42 | 43 | h 44 | 45 | 1 46 | 47 | e 48 | 49 | 2 50 | 51 | l 52 | 53 | 3 54 | 55 | l 56 | 57 | 4 58 | 59 | o 60 | 61 | 62 | 63 | table0:c->table1:pointee 64 | 65 | 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /assets/string_ptr_ref.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | %3 11 | 12 | 13 | 14 | table0 15 | 16 | s 17 | 18 | name 19 | 20 | value 21 | 22 | ptr 23 | 24 | 25 | 26 | 27 | table1 28 | 29 | s1 30 | 31 | name 32 | 33 | value 34 | 35 | ptr 36 | 37 | 38 | len 39 | 40 | 5 41 | 42 | capacity 43 | 44 | 5 45 | 46 | 47 | 48 | table0:c->table1:borrowee 49 | 50 | 51 | 52 | 53 | 54 | table2 55 | 56 | index 57 | 58 | value 59 | 60 | 0 61 | 62 | h 63 | 64 | 1 65 | 66 | e 67 | 68 | 2 69 | 70 | l 71 | 72 | 3 73 | 74 | l 75 | 76 | 4 77 | 78 | o 79 | 80 | 81 | 82 | table1:c->table2:pointee 83 | 84 | 85 | 86 | 87 | 88 | -------------------------------------------------------------------------------- /assets/string_slice.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | %3 11 | 12 | 13 | 14 | table0 15 | 16 | world 17 | 18 | name 19 | 20 | value 21 | 22 | ptr 23 | 24 | 25 | len 26 | 27 | 5 28 | 29 | 30 | 31 | table4 32 | 33 | index 34 | 35 | value 36 | 37 | 0 38 | 39 | h 40 | 41 | 1 42 | 43 | e 44 | 45 | 2 46 | 47 | l 48 | 49 | 3 50 | 51 | l 52 | 53 | 4 54 | 55 | o 56 | 57 | 5 58 | 59 | 60 | 61 | 6 62 | 63 | w 64 | 65 | 7 66 | 67 | o 68 | 69 | 8 70 | 71 | r 72 | 73 | 9 74 | 75 | l 76 | 77 | 10 78 | 79 | d 80 | 81 | 82 | 83 | table0:c->table4:pointee2 84 | 85 | 86 | 87 | 88 | 89 | table3 90 | 91 | s 92 | 93 | name 94 | 95 | value 96 | 97 | ptr 98 | 99 | 100 | len 101 | 102 | 11 103 | 104 | capacity 105 | 106 | 11 107 | 108 | 109 | 110 | table3:c->table4:pointee 111 | 112 | 113 | 114 | 115 | 116 | -------------------------------------------------------------------------------- /exercises/collections/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "exercises" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /exercises/collections/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "exercises" 3 | version = "0.1.0" 4 | authors = ["oreqizer "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /exercises/collections/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | use std::io; 3 | 4 | fn main() { 5 | // Task 1 6 | let res = task_1(&vec![1, 3, 3, 7, 4, 2, 0]); 7 | println!("Task 1: {:?}", res); 8 | 9 | // Task 2 10 | println!("Task 2 — 'first' -> {}", task2("first")); 11 | println!("Task 2 — 'apple' -> {}", task2("apple")); 12 | 13 | // Task 3 14 | task3(); 15 | } 16 | 17 | #[derive(Debug)] 18 | struct Task1Result { 19 | mean: f64, 20 | median: i32, 21 | mode: i32, 22 | } 23 | 24 | // 1. 25 | // Given a list of integers, use a vector and return the mean (the average value), 26 | // median (when sorted, the value in the middle position), and mode (the value that 27 | // occurs most often; a hash map will be helpful here) of the list 28 | fn task_1(list: &Vec) -> Task1Result { 29 | let len = list.len(); 30 | let mut sorted = list.clone(); 31 | sorted.sort(); 32 | 33 | let mean = (list.iter().sum::() as f64) / (len as f64); 34 | let median = sorted[((len + 1) / 2)]; 35 | let mut map: HashMap = HashMap::new(); 36 | for &i in list { 37 | let count = map.entry(i).or_insert(1); 38 | *count += 1; 39 | } 40 | let mut mode: i32 = 0; 41 | let count = 0; 42 | for (c, i) in map { 43 | if c > count { 44 | mode = i; 45 | } 46 | } 47 | 48 | Task1Result { mean, median, mode } 49 | } 50 | 51 | // 2. 52 | // Convert strings to pig latin. The first consonant of each word is moved 53 | // to the end of the word and “ay” is added, so “first” becomes “irst-fay.” 54 | // Words that start with a vowel have “hay” added to the end instead (“apple” 55 | // becomes “apple-hay”). Keep in mind the details about UTF-8 encoding! 56 | fn task2(word: &str) -> String { 57 | let mut woveled = false; 58 | for c in "aeiouy".chars() { 59 | if word.starts_with(c) { 60 | woveled = true; 61 | break; 62 | } 63 | } 64 | 65 | let mut res = word.to_string(); 66 | let mut postfix = "".to_string(); 67 | if woveled { 68 | postfix.push('h'); 69 | } else { 70 | res.drain(..1); 71 | postfix.push(word.chars().next().unwrap()); 72 | } 73 | 74 | format!("{}-{}ay", res, postfix) 75 | } 76 | 77 | // 3. 78 | // Using a hash map and vectors, create a text interface to allow a user 79 | // to add employee names to a department in a company. For example, “Add Sally 80 | // to Engineering” or “Add Amir to Sales.” Then let the user retrieve a list of 81 | // all people in a department or all people in the company by department, sorted 82 | // alphabetically. 83 | enum Command { 84 | Add(String, String), 85 | List(Option), 86 | Quit(), 87 | } 88 | 89 | impl Command { 90 | fn parse(input: &String) -> Option { 91 | let parts = input.trim().split_whitespace().collect::>(); 92 | if parts.len() == 1 { 93 | if parts[0] == "List" { 94 | return Some(Command::List(None)); 95 | } 96 | if parts[0] == "Quit" { 97 | return Some(Command::Quit()); 98 | } 99 | return None; 100 | } 101 | if parts.len() == 2 { 102 | if parts[0] == "List" { 103 | let department = parts[1].to_string(); 104 | 105 | return Some(Command::List(Some(department))); 106 | } 107 | return None; 108 | } 109 | if parts.len() == 4 { 110 | if parts[0] != "Add" && parts[2] != "to" { 111 | return None; 112 | } 113 | let person = parts[1].to_string(); 114 | let department = parts[3].to_string(); 115 | 116 | return Some(Command::Add(department, person)); 117 | } 118 | None 119 | } 120 | } 121 | 122 | fn task3() { 123 | println!("Company register! Available commands:"); 124 | println!(" 1. Add to "); 125 | println!(" 2. List"); 126 | println!(" 3. Quit"); 127 | 128 | let mut company: HashMap> = HashMap::new(); 129 | loop { 130 | let mut line = String::new(); 131 | 132 | io::stdin() 133 | .read_line(&mut line) 134 | .expect("Failed to read line"); 135 | 136 | if let Some(cmd) = Command::parse(&line) { 137 | match cmd { 138 | Command::Add(department, person) => { 139 | company.entry(department).or_insert(Vec::new()).push(person); 140 | } 141 | Command::List(None) => { 142 | for (dep, vec) in company.iter() { 143 | for person in vec { 144 | println!("{} ({})", person, dep); 145 | } 146 | } 147 | } 148 | Command::List(Some(department)) => { 149 | if let Some(vec) = company.get(&department) { 150 | for person in vec { 151 | println!("{}", person); 152 | } 153 | } else { 154 | println!("No such department"); 155 | } 156 | } 157 | Command::Quit() => { 158 | break; 159 | } 160 | } 161 | } else { 162 | println!("Invalid command! Try again"); 163 | println!(" 1. Add to "); 164 | println!(" 2. List"); 165 | println!(" 3. Quit"); 166 | } 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /exercises/guessing_game/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "autocfg" 5 | version = "0.1.7" 6 | source = "registry+https://github.com/rust-lang/crates.io-index" 7 | checksum = "1d49d90015b3c36167a20fe2810c5cd875ad504b39cff3d4eae7977e6b7c1cb2" 8 | 9 | [[package]] 10 | name = "bitflags" 11 | version = "1.2.1" 12 | source = "registry+https://github.com/rust-lang/crates.io-index" 13 | checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" 14 | 15 | [[package]] 16 | name = "cloudabi" 17 | version = "0.0.3" 18 | source = "registry+https://github.com/rust-lang/crates.io-index" 19 | checksum = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" 20 | dependencies = [ 21 | "bitflags", 22 | ] 23 | 24 | [[package]] 25 | name = "fuchsia-cprng" 26 | version = "0.1.1" 27 | source = "registry+https://github.com/rust-lang/crates.io-index" 28 | checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" 29 | 30 | [[package]] 31 | name = "guessing_game" 32 | version = "0.1.0" 33 | dependencies = [ 34 | "rand", 35 | ] 36 | 37 | [[package]] 38 | name = "libc" 39 | version = "0.2.93" 40 | source = "registry+https://github.com/rust-lang/crates.io-index" 41 | checksum = "9385f66bf6105b241aa65a61cb923ef20efc665cb9f9bb50ac2f0c4b7f378d41" 42 | 43 | [[package]] 44 | name = "rand" 45 | version = "0.6.5" 46 | source = "registry+https://github.com/rust-lang/crates.io-index" 47 | checksum = "6d71dacdc3c88c1fde3885a3be3fbab9f35724e6ce99467f7d9c5026132184ca" 48 | dependencies = [ 49 | "autocfg", 50 | "libc", 51 | "rand_chacha", 52 | "rand_core 0.4.2", 53 | "rand_hc", 54 | "rand_isaac", 55 | "rand_jitter", 56 | "rand_os", 57 | "rand_pcg", 58 | "rand_xorshift", 59 | "winapi", 60 | ] 61 | 62 | [[package]] 63 | name = "rand_chacha" 64 | version = "0.1.1" 65 | source = "registry+https://github.com/rust-lang/crates.io-index" 66 | checksum = "556d3a1ca6600bfcbab7c7c91ccb085ac7fbbcd70e008a98742e7847f4f7bcef" 67 | dependencies = [ 68 | "autocfg", 69 | "rand_core 0.3.1", 70 | ] 71 | 72 | [[package]] 73 | name = "rand_core" 74 | version = "0.3.1" 75 | source = "registry+https://github.com/rust-lang/crates.io-index" 76 | checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" 77 | dependencies = [ 78 | "rand_core 0.4.2", 79 | ] 80 | 81 | [[package]] 82 | name = "rand_core" 83 | version = "0.4.2" 84 | source = "registry+https://github.com/rust-lang/crates.io-index" 85 | checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" 86 | 87 | [[package]] 88 | name = "rand_hc" 89 | version = "0.1.0" 90 | source = "registry+https://github.com/rust-lang/crates.io-index" 91 | checksum = "7b40677c7be09ae76218dc623efbf7b18e34bced3f38883af07bb75630a21bc4" 92 | dependencies = [ 93 | "rand_core 0.3.1", 94 | ] 95 | 96 | [[package]] 97 | name = "rand_isaac" 98 | version = "0.1.1" 99 | source = "registry+https://github.com/rust-lang/crates.io-index" 100 | checksum = "ded997c9d5f13925be2a6fd7e66bf1872597f759fd9dd93513dd7e92e5a5ee08" 101 | dependencies = [ 102 | "rand_core 0.3.1", 103 | ] 104 | 105 | [[package]] 106 | name = "rand_jitter" 107 | version = "0.1.4" 108 | source = "registry+https://github.com/rust-lang/crates.io-index" 109 | checksum = "1166d5c91dc97b88d1decc3285bb0a99ed84b05cfd0bc2341bdf2d43fc41e39b" 110 | dependencies = [ 111 | "libc", 112 | "rand_core 0.4.2", 113 | "winapi", 114 | ] 115 | 116 | [[package]] 117 | name = "rand_os" 118 | version = "0.1.3" 119 | source = "registry+https://github.com/rust-lang/crates.io-index" 120 | checksum = "7b75f676a1e053fc562eafbb47838d67c84801e38fc1ba459e8f180deabd5071" 121 | dependencies = [ 122 | "cloudabi", 123 | "fuchsia-cprng", 124 | "libc", 125 | "rand_core 0.4.2", 126 | "rdrand", 127 | "winapi", 128 | ] 129 | 130 | [[package]] 131 | name = "rand_pcg" 132 | version = "0.1.2" 133 | source = "registry+https://github.com/rust-lang/crates.io-index" 134 | checksum = "abf9b09b01790cfe0364f52bf32995ea3c39f4d2dd011eac241d2914146d0b44" 135 | dependencies = [ 136 | "autocfg", 137 | "rand_core 0.4.2", 138 | ] 139 | 140 | [[package]] 141 | name = "rand_xorshift" 142 | version = "0.1.1" 143 | source = "registry+https://github.com/rust-lang/crates.io-index" 144 | checksum = "cbf7e9e623549b0e21f6e97cf8ecf247c1a8fd2e8a992ae265314300b2455d5c" 145 | dependencies = [ 146 | "rand_core 0.3.1", 147 | ] 148 | 149 | [[package]] 150 | name = "rdrand" 151 | version = "0.4.0" 152 | source = "registry+https://github.com/rust-lang/crates.io-index" 153 | checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" 154 | dependencies = [ 155 | "rand_core 0.3.1", 156 | ] 157 | 158 | [[package]] 159 | name = "winapi" 160 | version = "0.3.9" 161 | source = "registry+https://github.com/rust-lang/crates.io-index" 162 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 163 | dependencies = [ 164 | "winapi-i686-pc-windows-gnu", 165 | "winapi-x86_64-pc-windows-gnu", 166 | ] 167 | 168 | [[package]] 169 | name = "winapi-i686-pc-windows-gnu" 170 | version = "0.4.0" 171 | source = "registry+https://github.com/rust-lang/crates.io-index" 172 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 173 | 174 | [[package]] 175 | name = "winapi-x86_64-pc-windows-gnu" 176 | version = "0.4.0" 177 | source = "registry+https://github.com/rust-lang/crates.io-index" 178 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 179 | -------------------------------------------------------------------------------- /exercises/guessing_game/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "guessing_game" 3 | version = "0.1.0" 4 | authors = ["oreqizer "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | rand = "0.6.0" 11 | -------------------------------------------------------------------------------- /exercises/guessing_game/src/main.rs: -------------------------------------------------------------------------------- 1 | use rand::Rng; 2 | use std::cmp::Ordering; 3 | use std::io; 4 | 5 | fn main() { 6 | println!("Guess the number!"); 7 | 8 | let secret_number = rand::thread_rng().gen_range(1, 101); 9 | 10 | loop { 11 | println!("Please input your guess."); 12 | 13 | let mut guess = String::new(); 14 | 15 | io::stdin() 16 | .read_line(&mut guess) 17 | .expect("Failed to read line"); 18 | 19 | let guess: u32 = match guess.trim().parse() { 20 | Ok(num) => num, 21 | Err(_) => continue, 22 | }; 23 | 24 | println!("You guessed: {}", guess); 25 | 26 | match guess.cmp(&secret_number) { 27 | Ordering::Less => println!("Too small!"), 28 | Ordering::Greater => println!("Too big!"), 29 | Ordering::Equal => { 30 | println!("You win!"); 31 | break; 32 | }, 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /exercises/minigrep/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "minigrep" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /exercises/minigrep/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "minigrep" 3 | version = "0.1.0" 4 | authors = ["oreqizer "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /exercises/minigrep/poem.txt: -------------------------------------------------------------------------------- 1 | I'm nobody! Who are you? 2 | Are you nobody, too? 3 | Then there's a pair of us - don't tell! 4 | They'd banish us, you know. 5 | 6 | How dreary to be somebody! 7 | How public, like a frog 8 | To tell your name the livelong day 9 | To an admiring bog! 10 | -------------------------------------------------------------------------------- /exercises/minigrep/src/lib.rs: -------------------------------------------------------------------------------- 1 | use std::error::Error; 2 | use std::fs; 3 | use std::env; 4 | 5 | pub struct Config { 6 | pub query: String, 7 | pub filename: String, 8 | pub case_sensitive: bool, 9 | } 10 | 11 | impl Config { 12 | pub fn new(args: &[String]) -> Result { 13 | if args.len() < 3 { 14 | return Err("not enough arguments"); 15 | } 16 | 17 | let query = args[1].clone(); 18 | let filename = args[2].clone(); 19 | 20 | let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); 21 | 22 | Ok(Config { 23 | query, 24 | filename, 25 | case_sensitive, 26 | }) 27 | } 28 | } 29 | 30 | pub fn run(config: Config) -> Result<(), Box> { 31 | let contents = fs::read_to_string(config.filename)?; 32 | 33 | let results = if config.case_sensitive { 34 | search(&config.query, &contents) 35 | } else { 36 | search_case_insensitive(&config.query, &contents) 37 | }; 38 | 39 | results.iter().for_each(|line| { 40 | println!("{}", line); 41 | }); 42 | 43 | Ok(()) 44 | } 45 | 46 | pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { 47 | contents 48 | .lines() 49 | .filter(|line| line.contains(query)) 50 | .collect() 51 | } 52 | 53 | pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { 54 | let query = &query.to_lowercase(); 55 | 56 | contents 57 | .lines() 58 | .filter(|line| line.to_lowercase().contains(query)) 59 | .collect() 60 | } 61 | 62 | #[cfg(test)] 63 | mod tests { 64 | use super::*; 65 | 66 | #[test] 67 | fn case_sensitive() { 68 | let query = "duct"; 69 | let contents = "\ 70 | Rust: 71 | safe, fast, productive. 72 | Pick three. 73 | Duct tape."; 74 | 75 | assert_eq!(vec!["safe, fast, productive."], search(query, contents)); 76 | } 77 | 78 | #[test] 79 | fn case_insensitive() { 80 | let query = "rUsT"; 81 | let contents = "\ 82 | Rust: 83 | safe, fast, productive. 84 | Pick three. 85 | Trust me."; 86 | 87 | assert_eq!( 88 | vec!["Rust:", "Trust me."], 89 | search_case_insensitive(query, contents) 90 | ); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /exercises/minigrep/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::process; 3 | 4 | use minigrep::Config; 5 | 6 | fn main() { 7 | let args: Vec = env::args().collect(); 8 | 9 | let config = Config::new(&args).unwrap_or_else(|err| { 10 | eprintln!("Problem parsing arguments: {}", err); 11 | process::exit(1); 12 | }); 13 | 14 | if let Err(e) = minigrep::run(config) { 15 | eprintln!("Application error: {}", e); 16 | process::exit(1); 17 | } 18 | } 19 | --------------------------------------------------------------------------------