{"id":20452345,"url":"https://github.com/zakharb/rustguide","last_synced_at":"2026-04-04T06:12:28.333Z","repository":{"id":142500008,"uuid":"603994807","full_name":"zakharb/RustGuide","owner":"zakharb","description":"Rust docs","archived":false,"fork":false,"pushed_at":"2023-03-03T22:59:41.000Z","size":1216,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-06T19:11:15.206Z","etag":null,"topics":["cheatsheet","learning","rust","rust-examples","rust-learning"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/zakharb.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-02-20T05:25:40.000Z","updated_at":"2024-08-22T02:44:13.000Z","dependencies_parsed_at":null,"dependency_job_id":"769304b0-14d8-47c4-a8f8-7046815a6ade","html_url":"https://github.com/zakharb/RustGuide","commit_stats":null,"previous_names":["zakharb/rustguide"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/zakharb/RustGuide","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zakharb%2FRustGuide","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zakharb%2FRustGuide/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zakharb%2FRustGuide/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zakharb%2FRustGuide/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/zakharb","download_url":"https://codeload.github.com/zakharb/RustGuide/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zakharb%2FRustGuide/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":276801522,"owners_count":25707312,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-24T02:00:09.776Z","response_time":97,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cheatsheet","learning","rust","rust-examples","rust-learning"],"created_at":"2024-11-15T11:09:04.710Z","updated_at":"2025-09-24T18:31:04.966Z","avatar_url":"https://github.com/zakharb.png","language":"Rust","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Content  \n- [1 Getting Started](#1-getting-started)  \n- [2 Programming a Guessing Game](#2-programming-a-guessing-game)  \n- [3 Comming Programming Concepts](#3-comming-programming-concepts)  \n- [4 Ownership](#4-ownership)  \n- [5 Using Structs](#5-using-structs)  \n- [6 Enums and Pattern Matching](#6-enums-and-pattern-matching)  \n- [7 Packages Crates and Modules](#7-packages-crates-and-modules)  \n- [8 Common Collections](#8-common-collections)  \n- [9 Error Handling](#9-error-handling)  \n- [10 Generic Types Traits Lifetimes](#10-generic-types-traits-lifetimes)  \n- [11 How to Write Tests](#11-how-to-write-tests)  \n- [12 Building a Command Line Program](#12-building-a-command-line-program)  \n- [13 Functional Language Features](#13-functional-fanguage-features)  \n- [14 More About Cargo](#14-more-about-cargo)  \n- [15 Smart Pointers](#15-smart-pointers)  \n\n# 1 Getting Started\n\n## Installation\nInstall\n```sh\ncurl --proto '=https' --tlsv1.3 https://sh.rustup.rs -sSf | sh\n```\n\nCheck, update, uninstall\n```sh\nrustc --version\nrustup update\nrustup self uninstall\n```\n\n## Hello, World!\nIt’s traditional when learning a new language to write a little program that prints the text `Hello, world!` to the screen, so we’ll do the same here!\n\n### Creating a Project Directory\nWe suggest making a `projects directory` in your home directory and keeping all your projects there\n```sh\nmkdir ~/projects\ncd ~/projects\nmkdir hello_world\ncd hello_world\n```\n\n### Writing and Running a Rust Program\nNext, make a new source file and call it main.rs. \n```rust\nfn main() {\n    println!(\"Hello, world!\");\n}\n```\n\nCompile\n```sh\nrustc main.rs\n./main\n```\n\n### Anatomy of a Rust Program\nThese lines define a function named `main`. The function body is wrapped in `{}`\n```rust\nfn main() {\n\n}\n```\n\n\u003e If you want to stick to a standard style across Rust projects, you can use an automatic formatter tool called `rustfmt`\n\n- Rust style is to indent with `four spaces`, not a tab\n- println! calls a `Rust macro`\n- we pass string as an argument to `println!`\n- we end the line with a semicolon `(;)`\n\n### Compiling and Running Are Separate Steps\nBefore running a Rust program, you must compile it using `rustc`\n```sh\nrustc main.rs\n```\n## Hello, Cargo!\n`Cargo` is Rust’s build system and `package manager`. \n\n### Creating a Project with Cargo\nLet’s create a new project using Cargo\n```sh\ncargo new hello_cargo\ncd hello_cargo\n```\n\nFilename: Cargo.toml - Cargo’s configuration file.\n```tm\n[package]\nname = \"hello_cargo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\n```\n\n### Building and Running a Cargo Project\nBuild project \n```sh\ncargo build\n```\nBecause the default build is a debug build, Cargo puts the binary in a directory named debug. You can run the executable with this command:\n```sh\n./target/debug/hello_cargo\n```\n\nWe can also use cargo run to compile the code and then `run` the resultant executable `all in one` command:\n```sh\ncargo run\n```\n\nThis command quickly `checks` your code to make sure it compiles but doesn’t produce an executable\n```sh\ncargo check\n```\n\n### Building for Release\nWhen your project is finally ready for release, you can use command to compile it with optimizations.\n```sh\ncargo --build release\n```\n\n# 2 Programming a Guessing Game\nWe’ll implement a classic beginner programming problem: a guessing game. Here’s how it works: the program will generate a random integer between 1 and 100. It will then prompt the player to enter a guess. After a guess is entered, the program will indicate whether the guess is too low or too high. If the guess is correct, the game will print a congratulatory message and exit.\n\n## Setting Up a New Project\nGo to the projects directory and make a `new project` using `Cargo`\n```sh\ncargo new guessing_game\ncd guessing_game\n```\n\n## Processing a Guess\nThe first part of the guessing game program will ask for user input, process that input, and check that the input is in the expected form.\n```rust\nuse std::io; //standard library, known as std\n\nfn main() { //the entry point\n    println!(\"Guess the number!\"); //macro that prints a string to the screen\n    println!(\"Please input your guess.\"); // macro println!\n    let mut guess = String::new();\n    io::stdin()\n        .read_line(\u0026mut guess)\n        .expect(\"Failed to read line\");\n    println!(\"You guessed: {guess}\");\n}\n```\n\n### Storing Values with Variables\nNext, we’ll create a variable to store the user input, like this:\n```rust\n    let mut guess = String::new();\n```\n\nTo make a variable mutable, we add mut before the variable name:\n```rust\nlet apples = 5; // immutable\nlet mut bananas = 5; // mutable\n```\n\nIn full, the let mut guess = String::new(); line has created a mutable variable that is currently bound to a new, empty instance of a String:  \n- `let mut guess` will introduce a `mutable variable` named `guess`  \n- equal sign `(=)` tells Rust we want to `bind` something to the variable  \n- `::` syntax in the `::new` line indicates that new is an associated function of the `String` type  \n\n### Receiving User Input\nCall the `stdin` function from the `io` module, which will allow us to handle user `input`:\n```rust\n    io::stdin()\n        .read_line(\u0026mut guess)\n```\n\u003e If we hadn’t `imported` the io library with `use std::io`; at the beginning of the program, we could still use the function by writing this function call as `std::io::stdin`.\n\nNext, the line `.read_line(\u0026mut guess)` calls the `read_line` method on the standard input handle to get `input` from the user\n\nThe `\u0026` indicates that this argument is a `reference`, which gives you a way to let multiple parts of your code access one piece of data without needing to copy that data into memory multiple times.\n\n### Handling Potential Failure with Result\n`One long line` is difficult to read, so it’s best to `divide` it\nThe next part is this method\n```rust\n        .expect(\"Failed to read line\");\n```\nAs mentioned earlier, `read_line` puts whatever the user enters into the string we pass to it, but it also returns a `Result` value - `enum`.\nResult’s variants are `Ok` and `Err`.\nAn instance of `Result` has an `expect` method:\n- if `Err` value, expect will cause the program to crash and display message  \n- if `Ok` value, expect will take the return value and return just it  \n\u003e If you don’t call `expect`, the program will compile, but you’ll get a `warning`\n\n### Printing Values with println! Placeholders\nThere’s only one more line to discuss in the code so far:\n ```rust\n     println!(\"You guessed: {guess}\");\n```\n\u003e The `{}` set of curly brackets is a `placeholder`: think of {} as little crab pincers that hold a value in place.\n\nPrinting a variable and the result of an expression in one call to println! would look like this:\n```rust\nlet x = 5;\nlet y = 10;\n\nprintln!(\"x = {x} and y + 2 = {}\", y + 2); // \"x = 5 and y = 12\"\n```\n### Testing the First Part\nLet’s test the first part of the guessing game.\n```sh\ncargo run\n```\n\n## Generating a Secret Number\nNext, we need to generate a secret number that the user will try to guess.\n\n### Using a Crate to Get More Functionality\nThe `rand` crate is a library crate, which contains code that is intended\n```sh\n[dependencies]\nrand = \"0.8.5\"\n```\n\u003e The specifier 0.8.5 is actually shorthand for ^0.8.5, which means any version that is at least 0.8.5 but below 0.9.0.\n\n### Ensuring Reproducible Builds with the Cargo.lock File\nWhen you `build` a project for the `first time`, Cargo figures out all the versions of the dependencies that fit the criteria and then writes them to the `Cargo.lock` file. \n\n### Updating a Crate to Get a New Version\nWhen you do want to update a crate, Cargo provides the `command update`, which will ignore the `Cargo.lock` file and figure out all the latest versions that fit your specifications in Cargo.toml. \n```sh\ncargo update\n```\n\n### Generating a Random Number\nLet’s start using rand to generate a number to guess.\n```rust\nuse std::io;\nuse rand::Rng; //trait defines methods that random number generators implement\n\nfn main() {\n    println!(\"Guess the number!\");\n\n    let secret_number = rand::thread_rng().gen_range(1..=100);\n\n    println!(\"The secret number is: {secret_number}\");\n\n    println!(\"Please input your guess.\");\n\n    let mut guess = String::new();\n\n    io::stdin()\n        .read_line(\u0026mut guess)\n        .expect(\"Failed to read line\");\n\n    println!(\"You guessed: {guess}\");\n}\n```\n\u003e Another neat feature of Cargo is that running the `cargo doc --open` command will build documentation provided by all your dependencies locally and open it in your browser\n\nWe call the `rand::thread_rng` function that gives us the particular random number generator we’re going to use: one that is local to the current thread of execution and is seeded by the operating system. Then we call the `gen_range` method on the random number generator. This method is defined by the `Rng trait` that we brought into scope with the `use rand::Rng;` statement. \n\n## Comparing the Guess to the Secret Number\nNow that we have user input and a random number, we can compare them. \n```rust\nuse rand::Rng;\nuse std::cmp::Ordering; \nuse std::io;\n\nfn main() {\n    // --snip--\n\n    println!(\"You guessed: {guess}\");\n\n    match guess.cmp(\u0026secret_number) {\n        Ordering::Less =\u003e println!(\"Too small!\"),\n        Ordering::Greater =\u003e println!(\"Too big!\"),\n        Ordering::Equal =\u003e println!(\"You win!\"),\n    }\n}\n```\nFirst we add another use statement, bringing a type called `std::cmp::Ordering` into scope from the standard library. The Ordering type is another `enum` and has the variants `Less, Greater, and Equal`.\n\nThe `cmp` method compares two values and can be called on anything that can be compared. It takes a `reference` to whatever you want to compare with: here it’s comparing `guess` to `secret_number`. \n\nWe use a `match` expression to decide what to do next based on which variant of `Ordering` was returned from the call to `cmp` with the values in `guess` and `secret_number`.\n\n\u003e The core of the error states that there are `mismatched types`. Rust has a strong, static type system. However, it also has type inference. When we wrote `let mut guess = String::new()`, Rust was able to infer that guess should be a `String` and didn’t make us write the type.\n\nUltimately, we want to `convert` the `String` the program reads as input into a `real number type` so we can compare it numerically to the secret number:\n```rust\n    // --snip--\n    let mut guess = String::new();\n    io::stdin()\n        .read_line(\u0026mut guess)\n        .expect(\"Failed to read line\");\n    let guess: u32 = guess.trim().parse().expect(\"Please type a number!\"); //convert str to u32\n    println!(\"You guessed: {guess}\");\n    match guess.cmp(\u0026secret_number) {\n        Ordering::Less =\u003e println!(\"Too small!\"),\n        Ordering::Greater =\u003e println!(\"Too big!\"),\n        Ordering::Equal =\u003e println!(\"You win!\"),\n    }\n```\n\u003e Rust allows us to `shadow` the previous value of guess with a new one. `Shadowing` lets us `reuse` the guess variable name rather than forcing us to create two unique variables, such as `guess_str` and `guess`\n\nThe `parse` method on strings converts a string to `another type`. Here, we use it to convert from a string to a `number`. We need to tell Rust the exact number type we want by using `let guess: u32`.\n\n## Allowing Multiple Guesses with Looping\nThe loop keyword creates an infinite loop.\n```rust\n    // --snip--\n    println!(\"The secret number is: {secret_number}\");\n    loop {\n        println!(\"Please input your guess.\");\n        // --snip--\n        match guess.cmp(\u0026secret_number) {\n            Ordering::Less =\u003e println!(\"Too small!\"),\n            Ordering::Greater =\u003e println!(\"Too big!\"),\n            Ordering::Equal =\u003e println!(\"You win!\"),\n        }\n    }\n}\n```\n### Handling Invalid Input\nWe switch from an expect call to a match expression to move from crashing on an error to handling the error.\n```rust\n        // --snip--\n        io::stdin()\n            .read_line(\u0026mut guess)\n            .expect(\"Failed to read line\");\n        let guess: u32 = match guess.trim().parse() {\n            Ok(num) =\u003e num,\n            Err(_) =\u003e continue,\n        };\n        println!(\"You guessed: {guess}\");\n        // --snip--\n```\n\n## Summary\nThis project was a hands-on way to introduce you to many new Rust concepts: let, match, functions, the use of external crates, and more.\n\n# 3 Common Programming Concepts\nThis chapter covers concepts that appear in almost every programming language and how they work in Rust.\n\n## Variables and Mutability\nBy default, variables are `immutable`\nWhen a variable is immutable, once a value is bound to a name, you `can’t change` that value.\n```rust\nfn main() {\n    let x = 5;\n    println!(\"The value of x is: {x}\");\n    x = 6;\n    println!(\"The value of x is: {x}\");\n}\n```\nAlthough variables are immutable by default, you can make them mutable by adding `mut` in front of the variable name \n```rust\nfn main() {\n    let mut x = 5;\n    println!(\"The value of x is: {x}\");\n    x = 6;\n    println!(\"The value of x is: {x}\");\n}\n```\n\n### Constants\nLike `immutable variables`, constants are values that are bound to a name and `are not allowed to change`, but there are a few `differences` between constants and variables.\n- `aren’t allowed to use mut` with constants.\n- may be set only to a `constant expression`, not the result of a value that could only be computed at runtime.\n```rust\nconst THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;\n```\nRust’s naming convention for constants is to use `all uppercase with underscores` between words\n\n### Shadowing\nYou can declare a new variable with `the same name` as a previous variable - the first variable is `shadowed` by the second\nWe can shadow a variable by using the same variable’s name and repeating the use of the `let` keyword as follows\n```rust\nfn main() {\n    let x = 5;\n    let x = x + 1;\n    {\n        let x = x * 2;\n        println!(\"The value of x in the inner scope is: {x}\");\n    }\n    println!(\"The value of x is: {x}\");\n}\n```\n\nShadowing is `different` from marking a variable as `mut` because\n- we’ll get a compile-time error if we accidentally try to reassign to this variable without using the `let` keyword\n- we’re effectively creating a new variable when we use the `let` keyword again, we can change the type of the value but reuse the same name\n```rust\n    let spaces = \"   \"; // str\n    let spaces = spaces.len(); // int\n```\n\n## Data Types\nEvery value in Rust is of a certain `data type`, which tells Rust what kind of data is being specified so it knows how to work with that data. \nKeep in mind that Rust is a `statically typed language`\n```rust\nlet guess: u32 = \"42\".parse().expect(\"Not a number!\");\n```\n\n### Scalar Types\nA scalar type represents a single value. Rust has four primary scalar types: \n- integers  \n- floating point numbers  \n- booleans  \n- characters  \n\n### Integer Types\nAn integer is a number without a fractional component `i8 i16 i32 i64 i128`, `u8 u16 u32 u64 u128`\nthe `isize` and `usize` types depend on the architecture of the computer \n\n### Floating-Point Types\nRust also has two primitive types for floating-point numbers, which are numbers with decimal points. Rust’s floating-point types are `f32` and `f64`\n```rust\nfn main() {\n    let x = 2.0; // f64\n    let y: f32 = 3.0; // f32\n}\n```\n\n### Numeric Operations\n```rust\nfn main() {\n    // addition\n    let sum = 5 + 10;\n    // subtraction\n    let difference = 95.5 - 4.3;\n    // multiplication\n    let product = 4 * 30;\n    // division\n    let quotient = 56.7 / 32.2;\n    let truncated = -5 / 3; // Results in -1\n    // remainder\n    let remainder = 43 % 5;\n}\n```\n\n### The Boolean Type\nAs in most other programming languages, a Boolean type in Rust has two possible values: `true` and `false`.\n```rust\nfn main() {\n    let t = true;\n    let f: bool = false; // with explicit type annotation\n}\n```\n\n### The Character Type\nRust’s `char` type is the language’s most primitive alphabetic type.\n```rust\nfn main() {\n    let c = 'z';\n    let z: char = 'ℤ'; // with explicit type annotation\n    let heart_eyed_cat = '😻';\n}\n```\n\n### Compound Types\nCompound types can group multiple values into one type. Rust has two primitive compound types: `tuples` and `arrays`.\n\n### The Tuple Type\nA `tuple` is a general way of grouping together a number of values with a variety of types into `one` compound type. \n```rust\nfn main() {\n    let tup: (i32, f64, u8) = (500, 6.4, 1);\n}\n```\nThe variable tup binds to the entire tuple because a tuple is considered a single compound element. To get the individual values out of a tuple, we can use pattern matching to destructure a tuple value, like this:\n```rust\nfn main() {\n    let tup = (500, 6.4, 1);\n    let (x, y, z) = tup;\n    println!(\"The value of y is: {y}\");\n}\n```\nWe can also access a tuple element directly by using a period `(.)` followed by the index of the value we want to access\n```rust\nfn main() {\n    let x: (i32, f64, u8) = (500, 6.4, 1);\n    let five_hundred = x.0;\n    let six_point_four = x.1;\n    let one = x.2;\n}\n```\nThe tuple without any values has a special name, `unit`.\n\n### The Array Type\nUnlike a tuple, every element of an array must have the `same type`. Unlike arrays in some other languages, arrays in Rust have a `fixed length`.\n```rust\nfn main() {\n    let a = [1, 2, 3, 4, 5];\n    let a: [i32; 5];\n    let a = [3; 5];\n}\n```\nA `vector` is a similar collection type provided by the standard library that is allowed to `grow or shrink` in size\n\n### Accessing Array Elements\nAn array is a single chunk of memory of a known, `fixed` size that can be `allocated` on the `stack`. You can access elements of an array using `indexing`\n```rust\nfn main() {\n    let a = [1, 2, 3, 4, 5];\n    let first = a[0];\n    let second = a[1];\n}\n```\n\n### Invalid Array Element Access\nRust will `check` that the index you’ve specified is `less than` the array `length`. If the index is greater than or equal to the length, Rust will `panic`. \nThis is an example of Rust’s memory `safety principles` in action. In many low-level languages, this kind of check is not done, and when you provide an `incorrect` index, invalid memory `can be accessed`. \n\n## Functions\n`main` function, which is the `entry point` of many programs. You’ve also seen the `fn` keyword, which allows you to declare new functions.\nRust code uses `snake case` as the conventional `style` for function and variable names, in which all letters are lowercase and underscores separate words\n```rust\nfn main() {\n    println!(\"Hello, world!\");\n    another_function();\n}\nfn another_function() {\n    println!(\"Another function.\");\n}\n```\n\n### Parameters\nWe can define functions to have `parameters`\n```rust\nfn main() {\n    another_function(5);\n}\nfn another_function(x: i32) { //The type of x is specified as i32\n    println!(\"The value of x is: {x}\");\n}\n```\nIn function signatures, you must declare the `type` of each `parameter`\nWhen defining `multiple parameters`, separate the parameter declarations with `commas`\n\n### Statements and Expressions\nRust is an `expression-based` language\n- Statements are instructions that perform some action and do not return a value  \n- Expressions evaluate to a resultant value  \n\nCreating a variable and assigning a value to it with the let keyword is a statement\n```rust\nfn main() {\n    let y = 6;\n}\n```\n\nStatements do not return values. Therefore, you `can’t assign a let` statement to another variable, as the following code tries to do; you’ll get an `error`\n```rust\nfn main() {\n    let x = (let y = 6);\n}\n```\nThe `let y = 6` statement does `not return` a value, so there isn’t anything for `x` to bind to\n`Expressions` evaluate to a value and make up most of the `rest of the code` that you’ll write in Rust. Calling a function is an expression. Calling a macro is an expression. A new scope block created with curly brackets is an expression\n\n\n`Expressions` do not include `ending semicolons`. If you `add a semicolon` to the end of an expression, you `turn` it into a `statement`, and it will then not return a value.\n```rust\n{\n    let x = 3;\n    x + 1\n}\n```\n\n### Functions with Return Values\nWe `don’t name` return values, but we must `declare` their `type` after an arrow `(-\u003e)`.\nIn Rust, the `return value` of the function is synonymous with the value of the `final expression` in the block of the body of a function.\nYou can return `early` from a function by using the `return`\n```rust\nfn five() -\u003e i32 { // declare only return Type\n    5 // no ; or return word\n}\n```\n\nBut if we place a `semicolon` at the end of the line containing x + 1, `changing` it from an `expression` to a `statement` - wll be error statements don’t evaluate to a value, which is expressed by (), the unit type\n```rust\nfn plus_one(x: i32) -\u003e i32 {\n    x + 1; // error here, return unit type - ()\n}\n```\n\n## Comments\n```rust\n// So we’re doing something complicated here, long enough that we need\n// multiple lines of comments to do it! Whew! Hopefully, this comment will\n// explain what’s going on.\n\nfn main() {\n    // I’m feeling lucky today\n    let lucky_number = 7;\n}\n```\n\n## Control Flow\nThe most common constructs that let you control the flow of execution of Rust code are `if` expressions and `loops`.\n\n### if Expressions\n```rust\nfn main() {\n    let number = 3;\n    if number \u003c 5 {\n        println!(\"condition was true\");\n    } else {\n        println!(\"condition was false\");\n    }\n}\n```\n Unlike languages such as Ruby and JavaScript, Rust will `not automatically` try to `convert` `non-Boolean` types `to a Boolean`. You must be `explicit` and always provide if with a `Boolean as its condition`.\n ```rust\n fn main() {\n    let number = 3;\n    if number != 0 {\n        println!(\"number was something other than zero\");\n    }\n}\n``` \n\n### Handling Multiple Conditions with else if\nUsing `too many else if` expressions can `clutter` your code, so if you have more than one - use `match`\n\n### Using if in a let Statement\nBecause `if` is an `expression`, we can use it on the `right side` of a `let` statement to assign the outcome to a variable\n```rust\nfn main() {\n    let condition = true;\n    let number = if condition { 5 } else { 6 };\n    println!(\"The value of number is: {number}\");\n}\n```\n\n## Repetition with Loops\n\nRust has three kinds of loops: `loop`, `while`, and `for`. Let’s try each one.\n\n### Repeating Code with loop\nYou can place the `break` keyword within the loop to tell the program when to stop \nWe also used `continue` in the guessing game, which in a loop tells the program to skip over any remaining code in this iteration of the loop and go to the next iteration.\n\n### Returning Values from Loops\nYou can `add the value` you want returned `after the break` expression you use to stop the loop\n```rust\nfn main() {\n    let mut counter = 0;\n    let result = loop {\n        counter += 1;\n        if counter == 10 {\n            break counter * 2;\n        }\n    };\n    println!(\"The result is {result}\");\n}\n```\n\n### Loop Labels to Disambiguate Between Multiple Loops\nYou can optionally specify a loop `label` on a loop that you can then use with `break` or `continue`\n```rust\nfn main() {\n    let mut count = 0;\n    'counting_up: loop {\n        println!(\"count = {count}\");\n        let mut remaining = 10;\n        loop {\n            println!(\"remaining = {remaining}\");\n            if remaining == 9 {\n                break; // break internal loop\n            }\n            if count == 2 {\n                break 'counting_up; // break external loop\n            }\n            remaining -= 1;\n        }\n        count += 1;\n    }\n    println!(\"End count = {count}\");\n}\n```\n\n### Conditional Loops with while\nA program will `often need` to evaluate a `condition` within a loop. While the condition is true, the loop runs.\n```rust\nfn main() {\n    let mut number = 3;\n    while number != 0 {\n        println!(\"{number}!\");\n        number -= 1;\n    }\n    println!(\"LIFTOFF!!!\");\n}\n```\n\n### Looping Through a Collection with for\nYou can use a `for` loop and execute some code for `each item` in a `collection`.\n```rust\nfn main() {\n    let a = [10, 20, 30, 40, 50];\n    for element in a {\n        println!(\"the value is: {element}\");\n    }\n}\n```\n\n# 4 Ownership  \n\n## What is Ownership  \nOwnership is a set of rules that govern how a Rust program `manages` memory.\n\n### The Stack and the Heap  \nThe `stack` stores values in the order it gets them and removes the values in the opposite order - `last in, first out`.\nLike plates. Adding or removing plates from the middle or bottom wouldn’t work as well! Adding data is called pushing onto the stack, and removing data is called popping off the stack.\n\nThe `heap` is less organized: when you put data on the heap, you request a certain amount of space. The memory allocator finds an empty spot in the heap that is big enough, marks it as being in use, and returns a pointer, which is the address of that location - `allocating`\nLike Restaurant. When you enter, you state the number of people in your group, and the host finds an empty table that fits everyone and leads you there. If someone in your group comes late, they can ask where you’ve been seated to find you.\n\n### Ownership Rules  \n- Each value in Rust has an owner  \n- There can only be one owner at a time  \n- When the owner goes out of scope, the value will be dropped  \n\n### Variable Scope\n```rust\nfn main() {\n    {                      // s is not valid here, it’s not yet declared\n        let s = \"hello\";   // s is valid from this point forward\n        // do stuff with s\n    }                      // this scope is now over, and s is no longer valid\n}\n```\n\n### The String Type\nRust has a second string type `String`  \nThis type manages data allocated on the heap and as such is able to store an amount of text that is unknown to us at compile time.  \n```rust\nfn main() {\n    let mut s = String::from(\"hello\");\n\n    s.push_str(\", world!\"); // push_str() appends a literal to a String\n\n    println!(\"{}\", s); // This will print `hello, world!`\n}\n```\n\n### Memory and Allocation\nWith the String type, in order to support a mutable, growable piece of text, we need to allocate an amount of memory on the heap, unknown at compile time, to hold the contents. This means:  \n- The memory must be requested from the memory allocator at runtime.  \n- We need a way of returning this memory to the allocator when we’re done with our String.  \n\nThe memory is automatically returned `drop` once the variable that owns it goes `out of scope`. \n```rust\nfn main() {\n    {\n        let s = String::from(\"hello\"); // s is valid from this point forward\n        // do stuff with s\n    }                                  // this scope is now over, and s is no\n                                       // longer valid\n}\n```\n\n### Variables and Data Interacting with Move\nTo ensure memory safety, after the line `let s2 = s1;`, Rust considers `s1` as no longer valid. Therefore, Rust doesn’t need to `free anything` when s1 goes out of scope. \n```rust\nfn main() {\n    let s1 = String::from(\"hello\");\n    let s2 = s1;\n\n    println!(\"{}, world!\", s1);\n}\n```\nInstead of being called a shallow copy, it’s known as a `move`. In this example, we would say that `s1 was moved into s2`.\n\n### Variables and Data Interacting with Clone\nIf we do want to `deeply copy` the heap data of the String, not just the stack data, we can use a common method called `clone`.\n```rust\nfn main() {\n    let s1 = String::from(\"hello\");\n    let s2 = s1.clone();\n\n    println!(\"s1 = {}, s2 = {}\", s1, s2);\n}\n```\n\n### Stack-Only Data: Copy\nIntegers that `have a known size at compile time` are stored entirely on the `stack`, so copies of the actual values are quick to make.\n```rust\nfn main() {\n    let x = 5;\n    let y = x;\n\n    println!(\"x = {}, y = {}\", x, y);\n}\n```\n\nTypes implement the `Copy`   \n- All the integer types, such as u32.  \n- The Boolean type, bool, with values true and false.  \n- All the floating-point types, such as f64.  \n- The character type, char.  \n- Tuples, if they only contain types that also implement Copy. For example, (i32, i32) implements Copy, but (i32, String) does not.  \n\n### Ownership and Functions\nThe mechanics of passing a value to a function `are similar to those when assigning a value to a variable`. Passing a variable to a function will `move or copy`, just as assignment does.  \n```rust\nfn main() {\n    let s = String::from(\"hello\");  // s comes into scope\n\n    takes_ownership(s);             // s's value moves into the function...\n                                    // ... and so is no longer valid here\n\n    let x = 5;                      // x comes into scope\n\n    makes_copy(x);                  // x would move into the function,\n                                    // but i32 is Copy, so it's okay to still\n                                    // use x afterward\n\n} // Here, x goes out of scope, then s. But because s's value was moved, nothing\n  // special happens.\n\nfn takes_ownership(some_string: String) { // some_string comes into scope\n    println!(\"{}\", some_string);\n} // Here, some_string goes out of scope and `drop` is called. The backing\n  // memory is freed.\n\nfn makes_copy(some_integer: i32) { // some_integer comes into scope\n    println!(\"{}\", some_integer);\n} // Here, some_integer goes out of scope. Nothing special happens.\n```\n\n### Return Values and Scope\nReturning values can also `transfer ownership`.\n```rust\nfn main() {\n    let s1 = gives_ownership();         // gives_ownership moves its return\n                                        // value into s1\n\n    let s2 = String::from(\"hello\");     // s2 comes into scope\n\n    let s3 = takes_and_gives_back(s2);  // s2 is moved into\n                                        // takes_and_gives_back, which also\n                                        // moves its return value into s3\n} // Here, s3 goes out of scope and is dropped. s2 was moved, so nothing\n  // happens. s1 goes out of scope and is dropped.\n\nfn gives_ownership() -\u003e String {             // gives_ownership will move its\n                                             // return value into the function\n                                             // that calls it\n\n    let some_string = String::from(\"yours\"); // some_string comes into scope\n\n    some_string                              // some_string is returned and\n                                             // moves out to the calling\n                                             // function\n}\n\n// This function takes a String and returns one\nfn takes_and_gives_back(a_string: String) -\u003e String { // a_string comes into\n                                                      // scope\n\n    a_string  // a_string is returned and moves out to the calling function\n}\n```\n\n## References and Borrowing\n\nA `reference` is like a `pointer` in that it’s an address we can follow to access the data stored at that address.\nFunction that has a `reference to an object as a parameter instead` of taking ownership of the value\n```rust\nfn main() {\n    let s1 = String::from(\"hello\");\n\n    let len = calculate_length(\u0026s1);\n\n    println!(\"The length of '{}' is {}.\", s1, len);\n}\n\nfn calculate_length(s: \u0026String) -\u003e usize {\n    s.len()\n}\n```\n\nPass `\u0026s1` into `calculate_length` and, in its definition, we take `\u0026String` rather than `String`.\n\u003eThe opposite of referencing by using `\u0026` is dereferencing, which is accomplished with the dereference operator, `*`.  \n\nWe call the action of creating a reference `borrowing`. As in real life, if a person owns something, you can borrow it from them. When you’re done, you have to give it back. `You don’t own it`.  \n\nJust as variables are immutable by default, so are references. We’re not allowed to modify something we have a reference to.\n\n### Mutable References\nFirst we change `s` to be `mut`. Then we create a mutable reference with `\u0026mut` s where we call the change function, and update the function signature to accept a mutable reference with `some_string: \u0026mut String`. This makes it very clear that the change function will `mutate the value it borrows`.\n```rust\nfn main() {\n    let mut s = String::from(\"hello\");\n\n    change(\u0026mut s);\n}\n\nfn change(some_string: \u0026mut String) {\n    some_string.push_str(\", world\");\n}\n```\n\u003e Mutable references have one big restriction: if you have a mutable reference to a value, you `can have no other references to that value` - `data races`\n\nRust enforces a similar rule for combining mutable and immutable references. \n```rust\nfn main() {\n    let mut s = String::from(\"hello\");\n\n    let r1 = \u0026s; // no problem\n    let r2 = \u0026s; // no problem\n    let r3 = \u0026mut s; // BIG PROBLEM\n\n    println!(\"{}, {}, and {}\", r1, r2, r3);\n}\n```\n\nThe scopes of the immutable references `r1` and `r2` end after the `println!` where they are last used, which is before the mutable reference `r3` is created.\n```rust\nfn main() {\n    let mut s = String::from(\"hello\");\n\n    let r1 = \u0026s; // no problem\n    let r2 = \u0026s; // no problem\n    println!(\"{} and {}\", r1, r2);\n    // variables r1 and r2 will not be used after this point\n\n    let r3 = \u0026mut s; // no problem\n    println!(\"{}\", r3);\n}\n```\n\n### Dangling References\nIn languages with pointers, it’s easy to erroneously create a `dangling pointer` — a pointer that references a location in memory that may `have been given to someone else` — by freeing some memory while preserving a pointer to that memory.\n```rust\nfn main() {\n    let reference_to_nothing = dangle();\n}\n\nfn dangle() -\u003e \u0026String { // dangle returns a reference to a String\n\n    let s = String::from(\"hello\"); // s is a new String\n\n    \u0026s // we return a reference to the String, s\n} // Here, s goes out of scope, and is dropped. Its memory goes away.\n  // Danger!\n```\n\nThe solution here is to return the `String` directly:\n```rust\nfn main() {\n    let string = no_dangle();\n}\n\nfn no_dangle() -\u003e String {\n    let s = String::from(\"hello\");\n\n    s\n}\n```\n\n### The Rules of References  \nLet’s recap what we’ve discussed about references:  \n- At any given time, you can have either one mutable reference or any number of immutable references.  \n- References must always be valid.  \n\n### The Slice Type\nSlices let you reference a contiguous sequence of elements in a collection rather than the whole collection. A slice is a kind of `reference`, so it does not have `ownership`.\n\nThe problem: Having to worry about the index in word getting out of sync with the data in s is tedious and error prone!\n```rust\nfn first_word(s: \u0026String) -\u003e usize {\n    let bytes = s.as_bytes();\n\n    for (i, \u0026item) in bytes.iter().enumerate() {\n        if item == b' ' {\n            return i;\n        }\n    }\n\n    s.len()\n}\n\nfn main() {\n    let mut s = String::from(\"hello world\");\n\n    let word = first_word(\u0026s); // word will get the value 5\n\n    s.clear(); // this empties the String, making it equal to \"\"\n\n    // word still has the value 5 here, but there's no more string that\n    // we could meaningfully use the value 5 with. word is now totally invalid!\n}\n```\n \n ### String Slices\n A string slice is a `reference to part of a String`, and it looks like this:\n```rust\n fn main() {\n    let s = String::from(\"hello world\");\n\n    let hello = \u0026s[0..5];\n    let world = \u0026s[6..11];\n\tlet slice = \u0026s[..2]; //if you want to start at index 0\n\tlet slice = \u0026s[3..]; //if your slice includes the last byte\n\tlet slice = \u0026s[..]; //entire slice\n\n}\n```\n\nRecall from the borrowing rules that if we have an immutable reference to something, we cannot also take a `mutable reference`. Because `clear` needs to truncate the `String`, it needs to get a `mutable reference`. The `println!` after the call to clear uses the reference in word, so the `immutable reference must still be active at that point`. Rust disallows the mutable reference in clear and the immutable reference in word from `existing at the same time`, and compilation fails.\n```rust\nfn first_word(s: \u0026String) -\u003e \u0026str {\n    let bytes = s.as_bytes();\n\n    for (i, \u0026item) in bytes.iter().enumerate() {\n        if item == b' ' {\n            return \u0026s[0..i];\n        }\n    }\n\n    \u0026s[..]\n}\n\nfn main() {\n    let mut s = String::from(\"hello world\");\n\n    let word = first_word(\u0026s);\n\n    s.clear(); // error!\n\n    println!(\"the first word is: {}\", word);\n}\n```\n\n### String Slices as Parameters\nKnowing that you can take slices of literals and String values leads us to one more improvement on first_word, and that’s its signature:\n```rust\nfn first_word(s: \u0026String) -\u003e \u0026str {\n```\nA more experienced Rustacean would write the signature shown in Listing 4-9 instead because it allows us to use the same function on both \u0026String values and \u0026str values.\n```rust\nfn first_word(s: \u0026str) -\u003e \u0026str {\n```\n\n### Other Slices\nJust as we might want to refer to part of a string, we might want to refer to part of an array\n```rust\n#![allow(unused)]\nfn main() {\nlet a = [1, 2, 3, 4, 5];\n\nlet slice = \u0026a[1..3];\n\nassert_eq!(slice, \u0026[2, 3]);\n}\n```\n\n## Summary\nThe concepts of ownership, borrowing, and slices ensure memory safety in Rust programs at compile time. The Rust language gives you control over your memory usage in the same way as other systems programming languages, but having the owner of data automatically clean up that data when the owner goes out of scope means you don’t have to write and debug extra code to get this control.\n\n\n# 5 Using Structs\n\n## Defining and Instantiating Structs\n\nA `struct, or structure`, is a custom data type that lets you package together and name multiple related values that make up a meaningful group. \n```rust\nstruct User {\n    active: bool,\n    username: String,\n    email: String,\n    sign_in_count: u64,\n}\n\nfn main() {}\n```\n\nTo get a specific value from a struct, we use dot notation.\n```rust\nfn main() {\n    let mut user1 = User {\n        active: true,\n        username: String::from(\"someusername123\"),\n        email: String::from(\"someone@example.com\"),\n        sign_in_count: 1,\n    };\n\n    user1.email = String::from(\"anotheremail@example.com\");\n}\n```\n\n### Using the Field Init Shorthand\n\nBecause the parameter names and the struct field names are exactly the same in we can use the field init shorthand syntax\n```rust\nfn build_user(email: String, username: String) -\u003e User {\n    User {\n        active: true,\n        username,\n        email,\n        sign_in_count: 1,\n    }\n}\n```\n\n### Creating Instances from Other Instances with Struct Update Syntax\n\nIt’s often useful to create a new instance of a struct that includes most of the values from another instance, but changes some. You can do this using `struct update syntax`. The syntax `..` specifies that the remaining fields not explicitly set should have the same value as the fields in the given instance.\n```rust\nfn main() {\n    // --snip--\n\n    let user2 = User {\n        email: String::from(\"another@example.com\"),\n        ..user1\n    };\n}\n```\n\n### Using Tuple Structs Without Named Fields to Create Different Types\nRust also supports structs that look similar to tuples, called `tuple structs`.\n```rust\nstruct Color(i32, i32, i32);\nstruct Point(i32, i32, i32);\n\nfn main() {\n    let black = Color(0, 0, 0);\n    let origin = Point(0, 0, 0);\n}\n```\n\n### Unit-Like Structs Without Any Fields\nYou can also define structs that don’t have any fields! \n```rust\nstruct AlwaysEqual;\n\nfn main() {\n    let subject = AlwaysEqual;\n}\n```\n\n### Ownership of Struct Data\n\n\u003e In the User struct definition in Listing 5-1, we used the owned String type rather than the \u0026str string slice type. This is a deliberate choice because we want each instance of this struct to own all of its data and for that data to be valid for as long as the entire struct is valid.  \n\n## An Example Program Using Structs\nTo understand when we might want to use structs, let’s write a program that calculates the area of a rectangle. We’ll start by using single variables, and then refactor the program until we’re using structs instead.\n```rust\nfn main() {\n    let width1 = 30;\n    let height1 = 50;\n\n    println!(\n        \"The area of the rectangle is {} square pixels.\",\n        area(width1, height1)\n    );\n}\n\nfn area(width: u32, height: u32) -\u003e u32 {\n    width * height\n}\n```\n\n### Refactoring with Tuples\nIn one way, this program is better. Tuples let us add a bit of structure, and we’re now passing just one argument. But in another way, this version is less clear: tuples don’t name their elements, so we have to index into the parts of the tuple, making our calculation less obvious.\n```rust\nfn main() {\n    let rect1 = (30, 50);\n\n    println!(\n        \"The area of the rectangle is {} square pixels.\",\n        area(rect1)\n    );\n}\n\nfn area(dimensions: (u32, u32)) -\u003e u32 {\n    dimensions.0 * dimensions.1\n}\n```\n\n### Refactoring with Structs: Adding More Meaning\nWe use structs to add meaning by labeling the data. We can transform the tuple we’re using into a struct with a name for the whole as well as names for the parts\n```rust\nstruct Rectangle {\n    width: u32,\n    height: u32,\n}\n\nfn main() {\n    let rect1 = Rectangle {\n        width: 30,\n        height: 50,\n    };\n\n    println!(\n        \"The area of the rectangle is {} square pixels.\",\n        area(\u0026rect1)\n    );\n}\n\nfn area(rectangle: \u0026Rectangle) -\u003e u32 {\n    rectangle.width * rectangle.height\n}\n```\n\n### Adding Useful Functionality with Derived Traits\nRust does include functionality to print out debugging information, but we have to explicitly opt in to make that functionality available for our struct. To do that, we add the outer attribute `#[derive(Debug)]` just before the struct definition\n```rust\n#[derive(Debug)]\nstruct Rectangle {\n    width: u32,\n    height: u32,\n}\n\nfn main() {\n    let rect1 = Rectangle {\n        width: 30,\n        height: 50,\n    };\n\n    println!(\"rect1 is {:?}\", rect1); // {:?} used for print debug info\n}\n```\n\nAnother way to print out a value using the `Debug` format is to use the `dbg! macro`\n```rust\n#[derive(Debug)]\nstruct Rectangle {\n    width: u32,\n    height: u32,\n}\n\nfn main() {\n    let scale = 2;\n    let rect1 = Rectangle {\n        width: dbg!(30 * scale),\n        height: 50,\n    };\n\n    dbg!(\u0026rect1);\n}\n```\n\n## Method Syntax\n`Methods` are similar to functions: we declare them with the fn keyword and a name, they can have parameters and a return value, and they contain some code that’s run when the method is called from somewhere else. \n\n### Defining Methods\nLet’s change the area function that has a `Rectangle` instance as a parameter and instead make an `area` method defined on the `Rectangle struct`.\nTo define the function within the context of `Rectangle`, we start an `impl` (implementation) block for Rectangle. Everything within this impl block will be `associated` with the Rectangle type\n```rust\n#[derive(Debug)]\nstruct Rectangle {\n    width: u32,\n    height: u32,\n}\n\nimpl Rectangle {\n    fn area(\u0026self) -\u003e u32 {\n        self.width * self.height\n    }\n}\n\nfn main() {\n    let rect1 = Rectangle {\n        width: 30,\n        height: 50,\n    };\n\n    println!(\n        \"The area of the rectangle is {} square pixels.\",\n        rect1.area()\n    );\n}\n```\nIn the signature for area, we use `\u0026self` instead of `rectangle: \u0026Rectangle`. The `\u0026self` is actually short for `self: \u0026Self`. Within an `impl` block, the type Self is an `alias` for the type that the impl block is for. \n\nMethods like this are called `getters`, and Rust does not implement them automatically for struct fields as some other languages do.\n```rust\nimpl Rectangle {\n    fn width(\u0026self) -\u003e bool {\n        self.width \u003e 0\n    }\n}\n\nfn main() {\n    let rect1 = Rectangle {\n        width: 30,\n        height: 50,\n    };\n\n    if rect1.width() {\n        println!(\"The rectangle has a nonzero width; it is {}\", rect1.width);\n    }\n}\n```\n\n### Where’s the -\u003e Operator?\n\u003e In C and C++, two different operators are used for calling methods: you use `.` if you’re calling a method on the object directly and `-\u003e` if you’re calling the method on a pointer to the object and need to dereference the pointer first. In other words, if `object` is a pointer, `object-\u003esomething()` is similar to `(*object).something()`.\nRust doesn’t have an equivalent to the `-\u003e operator;` instead, Rust has a feature called `automatic referencing and dereferencing`. Calling methods is one of the few places in Rust that has this behavior.\n\n### Methods with More Parameters\nLet’s practice using methods by implementing a second method on the `Rectangle` struct. This time we want an instance of Rectangle to take another instance of Rectangle and return `true` if the second Rectangle can fit completely within `self` (the first Rectangle); otherwise, it should return `false`.\n```rust\n#[derive(Debug)]\nstruct Rectangle {\n    width: u32,\n    height: u32,\n}\n\nimpl Rectangle {\n    fn area(\u0026self) -\u003e u32 {\n        self.width * self.height\n    }\n\n    fn can_hold(\u0026self, other: \u0026Rectangle) -\u003e bool {\n        self.width \u003e other.width \u0026\u0026 self.height \u003e other.height\n    }\n}\n\nfn main() {\n    let rect1 = Rectangle {\n        width: 30,\n        height: 50,\n    };\n    let rect2 = Rectangle {\n        width: 10,\n        height: 40,\n    };\n    let rect3 = Rectangle {\n        width: 60,\n        height: 45,\n    };\n\n    println!(\"Can rect1 hold rect2? {}\", rect1.can_hold(\u0026rect2));\n    println!(\"Can rect1 hold rect3? {}\", rect1.can_hold(\u0026rect3));\n}\n```\n\n### Associated Functions\nAll functions defined within an `impl` block are called `associated functions because` they’re associated with the type named after the impl. We can define associated functions that `don’t have self` as their first parameter (and thus are not methods) because they `don’t need an instance` of the type to work with. We’ve already used one function like this: the `String::from` function that’s defined on the String type.\n```rust\n#[derive(Debug)]\nstruct Rectangle {\n    width: u32,\n    height: u32,\n}\n\nimpl Rectangle {\n    fn square(size: u32) -\u003e Self {\n        Self {\n            width: size,\n            height: size,\n        }\n    }\n}\n\nfn main() {\n    let sq = Rectangle::square(3); // call this associated function\n}\n```\n\n### Multiple impl Blocks\nEach struct is allowed to have `multiple impl` blocks. \n```rust\nimpl Rectangle {\n    fn area(\u0026self) -\u003e u32 {\n        self.width * self.height\n    }\n}\n\nimpl Rectangle {\n    fn can_hold(\u0026self, other: \u0026Rectangle) -\u003e bool {\n        self.width \u003e other.width \u0026\u0026 self.height \u003e other.height\n    }\n}\n```\n\n## Summary\nStructs let you create custom types that are meaningful for your domain. By using structs, you can keep associated pieces of data connected to each other and name each piece to make your code clear. In impl blocks, you can define functions that are associated with your type, and methods are a kind of associated function that let you specify the behavior that instances of your structs have.\n\n\n# 6 Enums and Pattern Matching\nIn this chapter, we’ll look at `enumerations`, also referred to as `enums`. Enums allow you to define a type by enumerating its possible `variants`. \n\n### Defining an Enum\nWhere structs give you a way of grouping together related fields and data, like a `Rectangle` with its width and height, `enums` give you a way of saying a value is one of a `possible set of values`. For example, we may want to say that `Rectangle` is one of a set of possible shapes that also includes `Circle` and `Triangle`\n\n### Enum Values\nWe can express this concept in code by defining an IpAddrKind enumeration and listing the possible kinds an IP address can be, `V4` and `V6`.\n```rust\nenum IpAddrKind {\n    V4,\n    V6,\n}\n\nfn main() {\n    let four = IpAddrKind::V4; // We can create instances of each \n    let six = IpAddrKind::V6;  // of the two variants of `IpAddrKind`\n\n    route(IpAddrKind::V4); // we can call this function \n    route(IpAddrKind::V6); // with either variant: V4, V6\n}\n\nfn route(ip_kind: IpAddrKind) {} // for instance we can define a function that takes any IpAddrKind\n```\n\nRepresenting the same concept using just an enum is more concise: rather than an enum inside a struct, we can put data directly into each enum variant.\n```rust\nfn main() {\n    enum IpAddr {\n        V4(String),\n        V6(String),\n    }\n\n    let home = IpAddr::V4(String::from(\"127.0.0.1\")); // one liners to difine\n    let loopback = IpAddr::V6(String::from(\"::1\"));   // home and loopback\n}\n```\n\nThere’s another advantage to using an enum rather than a struct: `each variant can have different types and amounts of associated data`. Version four IP addresses will always have `four numeric components` that will have values between 0 and 255. If we wanted to store V4 addresses as four u8 values but still express V6 addresses as one String value, we `wouldn’t be able to with a struct`.\n```rust\n    enum IpAddr {\n        V4(u8, u8, u8, u8),\n        V6(String),\n    }\n\n    let home = IpAddr::V4(127, 0, 0, 1);\n\n    let loopback = IpAddr::V6(String::from(\"::1\"));\n```\n\nLet’s look at how the `standard library` defines `IpAddr`: it has the exact `enum` and `variants` that we’ve defined and used, but it embeds the address data inside the variants in the form of `two different structs`\n```rust\nstruct Ipv4Addr {\n    // --snip--\n}\n\nstruct Ipv6Addr {\n    // --snip--\n}\n\nenum IpAddr {\n    V4(Ipv4Addr),\n    V6(Ipv6Addr),\n}\n```\n\nLet’s look at another example of an enum: this one has a wide `variety of types` embedded in its variants.\n```rust\nenum Message {\n    Quit,\n    Move { x: i32, y: i32 },\n    Write(String),\n    ChangeColor(i32, i32, i32),\n}\n```\n\nThere is one more similarity between enums and structs: just as we’re able to define methods on structs using `impl`, we’re also able to define `methods` on enums. Here’s a method named `call` that we could define on our Message enum:\n```rust\nfn main() {\n    enum Message {\n        Quit,\n        Move { x: i32, y: i32 },\n        Write(String),\n        ChangeColor(i32, i32, i32),\n    }\n\n    impl Message {\n        fn call(\u0026self) {\n            // method body would be defined here\n        }\n    }\n\n    let m = Message::Write(String::from(\"hello\"));\n    m.call();\n}\n```\n\n### The Option Enum and Its Advantages Over Null Values\nThis section explores a case study of `Option`, which is another `enum` defined by the standard library. The Option type encodes the very common scenario in which a value could be `something` or it could be `nothing`.\nRust doesn’t have the `null` feature that many other languages have.\n```rust\nenum Option\u003cT\u003e {\n    None,\n    Some(T),\n}\n```\n\n`\u003cT\u003e` means that the `Some` variant of the `Option` enum can hold `one` piece of data of any type\n```rust\nlet some_number = Some(5);\nlet some_char = Some('e');\n\nlet absent_number: Option\u003ci32\u003e = None;\n```\n\n`Option\u003cT\u003e` and `T` (where T can be any type) are `different types`, the compiler won’t let us use an `Option\u003cT\u003e` value as if it were definitely a valid value\n```rust\nlet x: i8 = 5;\nlet y: Option\u003ci8\u003e = Some(5);\n\nlet sum = x + y;\n```\n\n## The match Control Flow Construct\nRust has an extremely powerful control flow construct called `match` that allows you to compare a value against a series of patterns and then execute code based on which pattern matches.\n\nFunction that takes an unknown US coin and, in a similar way as the counting machine, determines which coin it is and returns its value in cents\n```rust\nenum Coin {\n    Penny,\n    Nickel,\n    Dime,\n    Quarter,\n}\n\nfn value_in_cents(coin: Coin) -\u003e u8 {\n    match coin {\n        Coin::Penny =\u003e 1,\n        Coin::Nickel =\u003e 5,\n        Coin::Dime =\u003e 10,\n        Coin::Quarter =\u003e 25,\n    }\n}\n```\n\nIf you want to run `multiple lines` of code in a match arm, you must use curly brackets, and the comma following the arm is then optional\n```rust\nfn value_in_cents(coin: Coin) -\u003e u8 {\n    match coin {\n        Coin::Penny =\u003e {\n            println!(\"Lucky penny!\");\n            1\n        }\n        Coin::Nickel =\u003e 5,\n        Coin::Dime =\u003e 10,\n        Coin::Quarter =\u003e 25,\n    }\n}\n```\n\n### Patterns That Bind to Values\nAnother useful feature of `match` arms is that they can bind to the `parts of the values` that match the pattern. In the match expression for this code, we add a variable called `state` to the pattern that matches values of the variant `Coin::Quarter`\n```rust\n#[derive(Debug)]\nenum UsState {\n    Alabama,\n    Alaska,\n    // --snip--\n}\n\nenum Coin {\n    Penny,\n    Nickel,\n    Dime,\n    Quarter(UsState),\n}\n\nfn value_in_cents(coin: Coin) -\u003e u8 {\n    match coin {\n        Coin::Penny =\u003e 1,\n        Coin::Nickel =\u003e 5,\n        Coin::Dime =\u003e 10,\n        Coin::Quarter(state) =\u003e {\n            println!(\"State quarter from {:?}!\", state); //{:?} debug\n            25\n        }\n    }\n}\n\nfn main() {\n    value_in_cents(Coin::Quarter(UsState::Alaska));\n}\n```\n\n### Matching with Option\u003cT\u003e\nWe can also handle `Option\u003cT\u003e` using `match`\n```rust\n    fn plus_one(x: Option\u003ci32\u003e) -\u003e Option\u003ci32\u003e {\n        match x {\n            None =\u003e None,\n            Some(i) =\u003e Some(i + 1),\n        }\n    }\n\n    let five = Some(5);\n    let six = plus_one(five);\n    let none = plus_one(None);\n```\n\n### Matches Are Exhaustive\nThere’s one other aspect of match we need to discuss: the `arms patterns` must cover `all possibilities`. This will `NOT` work\n```rust\n    fn plus_one(x: Option\u003ci32\u003e) -\u003e Option\u003ci32\u003e {\n        match x {\n            Some(i) =\u003e Some(i + 1),\n        }\n    }\n```\n\n### Catch-all Patterns and the _ Placeholder\nUsing enums, we can also take special actions for a few particular values, but for `all other` values take one `default action`.\n```rust\n    let dice_roll = 9;\n    match dice_roll {\n        3 =\u003e add_fancy_hat(), // if 3 add fancy\n        7 =\u003e remove_fancy_hat(), // if 7 remove fancy\n        other =\u003e move_player(other), // default for all other \n    }\n\n    fn add_fancy_hat() {}\n    fn remove_fancy_hat() {}\n    fn move_player(num_spaces: u8) {}\n```\n\nLet’s change the rules of the game: now, if you roll `anything other than a 3 or a 7`, you must `roll again`. We no longer need to use the catch-all value, so we can change our code to use `_` instead of the variable named `other`\n```rust\n    let dice_roll = 9;\n    match dice_roll {\n        3 =\u003e add_fancy_hat(),\n        7 =\u003e remove_fancy_hat(),\n        _ =\u003e reroll(), // reroll if not 7 or 3\n    }\n\n    fn add_fancy_hat() {}\n    fn remove_fancy_hat() {}\n    fn reroll() {}\n```\n\nFinally, we’ll change the rules of the game one more time so that `nothing` else happens on your turn `if you roll anything` other than a 3 or a 7.\n```rust\n    let dice_roll = 9;\n    match dice_roll {\n        3 =\u003e add_fancy_hat(),\n        7 =\u003e remove_fancy_hat(),\n        _ =\u003e (), // do nothing if not 3 or 7\n    }\n\n    fn add_fancy_hat() {}\n    fn remove_fancy_hat() {}\n```\n\n### Concise Control Flow with if let\nThe `if let` syntax lets you combine if and let into a `less verbose` way to handle values that match `one` pattern while ignoring the rest.\n```rust\n    let config_max = Some(3u8);\n    match config_max {\n        Some(max) =\u003e println!(\"The maximum is configured to be {}\", max),\n        _ =\u003e (),\n    }\n```\n\n`Instead`, we could write this in a shorter way using `if let`.\n```rust\n    let config_max = Some(3u8);\n    if let Some(max) = config_max {\n        println!(\"The maximum is configured to be {}\", max);\n    }\n```\n\nIf we wanted to `count` all `non-quarter coins` we see while also announcing the state of the quarters, we could do that with a `match` expression, like this\n```rust\n    let mut count = 0;\n    match coin {\n        Coin::Quarter(state) =\u003e println!(\"State quarter from {:?}!\", state),\n        _ =\u003e count += 1,\n    }\n```\n\nOr we could use an `if let` and `else` expression\n```rust\n    let mut count = 0;\n    if let Coin::Quarter(state) = coin {\n        println!(\"State quarter from {:?}!\", state);\n    } else {\n        count += 1;\n    }\n```\n\n## Summary\nWe’ve now covered how to use enums to create custom types that can be one of a set of enumerated values. We’ve shown how the standard library’s `Option\u003cT\u003e` type helps you use the type system to prevent errors. When enum values have data inside them, you can use `match` or `if let` to extract and use those values, depending on how many cases you need to handle.\n\n# 7 Packages Crates and Modules\nRust has a number of `features` that allow you to `manage` your code’s organization, including which details are exposed, which details are private, and what names are in each scope in your programs. These features, sometimes collectively referred to as the `module system`, include:\n\n- `Packages`: A Cargo feature that lets you build, test, and share crates\n- `Crates`: A tree of modules that produces a library or executable\n- `Modules and use`: Let you control the organization, scope, and privacy of paths\n- `Paths`: A way of naming an item, such as a struct, function, or module\n\n### Packages and Crates\nA `crate` is the smallest amount of code that the Rust compiler `considers at a time`.\nA crate can come in one of two forms: a `binary crate` or a `library crate`.\n`Binary crates` are programs you can compile to an `executable` that you can run, such as a command-line program or a server - have function `main`\n`Library crates` don’t have `main` and define functionality intended to be shared with multiple projects\n```rust\n$ cargo new my-project\n     Created binary (application) `my-project` package\n$ ls my-project\nCargo.toml\nsrc\n$ ls my-project/src\nmain.rs\n```\n\n## Defining Modules to Control Scope and Privacy\n\n### Modules Cheat Sheet\n\n- `Start from the crate root`: When compiling a crate, the compiler first looks in the crate root file (usually `src/lib.rs` for a library crate or `src/main.rs` for a binary crate) for code to compile.\n\n- `Declaring modules`: In the crate root file, you can declare new modules; say, you declare a “garden” module with `mod garden;`. The compiler will look for the module’s code in these places:  \n-- Inline, within curly brackets that replace the semicolon following `mod garden`  \n-- In the file `src/garden.rs`  \n-- In the file `src/garden/mod.rs`  \n\n- `Declaring submodules`: In any file other than the crate root, you can declare submodules. For example, you might declare `mod vegetables;` in src/garden.rs. The compiler will look for the submodule’s code within the directory named for the parent module in these places:  \n-- Inline, directly following `mod vegetables`, within curly brackets instead of the semicolon  \n-- In the file `src/garden/vegetables.rs`  \n-- In the file `src/garden/vegetables/mod.rs`  \n\n- `Paths to code in modules`: Once a module is part of your crate, you can refer to code in that module from anywhere else in that same crate, as long as the privacy rules allow, using the path to the code. For example, an Asparagus type in the garden vegetables module would be found at `crate::garden::vegetables::Asparagus`.\n\n- `Private vs public`: Code within a module is private from its parent modules by default. To make a module public, declare it with `pub mod` instead of `mod`. To make items within a public module public as well, use pub before their declarations.\n\n- The `use` keyword: Within a scope, the use keyword creates shortcuts to items to reduce repetition of long paths. In any scope that can refer to `crate::garden::vegetables::Asparagus`, you can create a shortcut with use `crate::garden::vegetables::Asparagus;` and from then on you only need to write `Asparagus` to make use of that type in the scope.\n\nHere we create a binary crate named `backyard` that illustrates these rules. The crate’s directory, also named `backyard`, contains these files and directories:\n```rust\nbackyard\n├── Cargo.lock\n├── Cargo.toml\n└── src\n    ├── garden\n    │   └── vegetables.rs\n    ├── garden.rs\n    └── main.rs\n```\n\nThe crate root file in this case is `src/main.rs`, and it contains:\n```rust\nuse crate::garden::vegetables::Asparagus;\n\npub mod garden;\n\nfn main() {\n    let plant = Asparagus {};\n    println!(\"I'm growing {:?}!\", plant);\n}\n```\n\nThe `pub mod garden;` line tells the compiler to include the code it finds in `src/garden.rs`, which is:\n```rust\npub mod vegetables;\n```\nHere, `pub mod vegetables;` means the code in `src/garden/vegetables.rs` is included too. That code is:\n```rust\n#[derive(Debug)]\npub struct Asparagus {}\n```\n\n### Grouping Related Code in Modules\n`Modules` let us organize code within a crate for readability and easy reuse. Modules also allow us to control the `privacy` of items, because code within a module is `private by default`. \n\nIn the `restaurant industry`, some parts of a restaurant are referred to as `front of house` and others as `back of house`. Front of house is where customers are; this encompasses where the hosts seat customers, servers take orders and payment, and bartenders make drinks. Back of house is where the chefs and cooks work in the kitchen, dishwashers clean up, and managers do administrative work.\n\nCreate a `new library` named restaurant by running `cargo new restaurant --lib`.\nFilename: `src/lib.rs`:\n```rust\nmod front_of_house {\n    mod hosting {\n        fn add_to_waitlist() {}\n\n        fn seat_at_table() {}\n    }\n\n    mod serving {\n        fn take_order() {}\n\n        fn serve_order() {}\n\n        fn take_payment() {}\n    }\n}\n```\nWe define a module with the `mod keyword` followed by the name of the module (in this case, `front_of_house`).\n\n`src/main.rs` and `src/lib.rs` are called `crate roots`. The reason for their name is that the contents of either of these two files form a module named `crate` at the root of the crate’s module structure, known as the `module tree`.\n```rust\ncrate\n └── front_of_house\n     ├── hosting\n     │   ├── add_to_waitlist\n     │   └── seat_at_table\n     └── serving\n         ├── take_order\n         ├── serve_order\n         └── take_payment\n\n```\nThe module tree might remind you of the `filesystem’s directory tree` on your computer; this is a very `apt` comparison!\n\n### Paths for Referring to an Item in the Module Tree\nA path can take two forms:\n\n- An `absolute path` is the full path starting from a crate root; for code from an external crate, the absolute path begins with the crate name, and for code from the current crate, it starts with the literal crate.\n- A `relative path` starts from the current module and uses `self`, `super`, or an identifier in the current module.\n\u003e Our preference in general is to specify absolute paths because it’s more likely we’ll want to move code definitions and item calls independently of each other.\n\nBoth absolute and relative paths are followed by one or more identifiers separated by double colons `(::)`.\n```rust\nmod front_of_house {\n    mod hosting {\n        fn add_to_waitlist() {}\n    }\n}\n\npub fn eat_at_restaurant() {\n    // Absolute path\n    crate::front_of_house::hosting::add_to_waitlist();\n\n    // Relative path\n    front_of_house::hosting::add_to_waitlist();\n}\n```\n\u003e We have the correct `paths` for the hosting `module` and the `add_to_waitlist` function, but Rust won’t let us use them because it `doesn’t have access` to the private sections. \n\n### Exposing Paths with the pub Keyword\nWe want the `eat_at_restaurant` function in the parent module to have access to the `add_to_waitlist` function in the child module, so we mark the hosting module with the `pub` keyword\n```rust\nmod front_of_house {\n    pub mod hosting {\n        fn add_to_waitlist() {}\n    }\n}\n\npub fn eat_at_restaurant() {\n    // Absolute path\n    crate::front_of_house::hosting::add_to_waitlist();\n\n    // Relative path\n    front_of_house::hosting::add_to_waitlist();\n}\n```\n\u003e The `pub` keyword on a module only lets code in its `ancestor modules` refer to it, not access its `inner code`\n\nLet’s also make the `add_to_waitlist` function `public` by adding the `pub` keyword before its definition\n```rust\nmod front_of_house {\n    pub mod hosting {\n        pub fn add_to_waitlist() {}\n    }\n}\n\npub fn eat_at_restaurant() {\n    // Absolute path\n    crate::front_of_house::hosting::add_to_waitlist();\n\n    // Relative path\n    front_of_house::hosting::add_to_waitlist();\n}\n```\n\u003e The module tree should be defined in src/lib.rs. Then, any public items can be used in the binary crate by starting paths with the name of the package. The binary crate becomes a user of the library crate just like a completely external crate would use the library crate: it can only use the public API. This helps you design a good API; not only are you the author, you’re also a client!\n\n### Starting Relative Paths with super\nWe can construct relative paths that begin in the parent module, rather than the current module or the crate root, by using `super` at the start of the path.\n```rust\nfn deliver_order() {}\n\nmod back_of_house {\n    fn fix_incorrect_order() {\n        cook_order();\n        super::deliver_order();\n    }\n\n    fn cook_order() {}\n}\n```\n\n### Making Structs and Enums Public\nWe can also use `pub` to designate `structs` and `enums` as `public`, but there are a few details extra to the usage of pub with structs and enums. \nWe’ve defined a `public` `back_of_house::Breakfast` struct with a `public` `toast` field but a `private` `seasonal_fruit` field\n```rust\nmod back_of_house {\n    pub struct Breakfast {\n        pub toast: String,\n        seasonal_fruit: String,\n    }\n\n    impl Breakfast {\n        pub fn summer(toast: \u0026str) -\u003e Breakfast {\n            Breakfast {\n                toast: String::from(toast),\n                seasonal_fruit: String::from(\"peaches\"),\n            }\n        }\n    }\n}\n\npub fn eat_at_restaurant() {\n    // Order a breakfast in the summer with Rye toast\n    let mut meal = back_of_house::Breakfast::summer(\"Rye\");\n    // Change our mind about what bread we'd like\n    meal.toast = String::from(\"Wheat\");\n    println!(\"I'd like {} toast please\", meal.toast);\n\n    // The next line won't compile if we uncomment it; we're not allowed\n    // to see or modify the seasonal fruit that comes with the meal\n    // meal.seasonal_fruit = String::from(\"blueberries\");\n}\n```\n\nIn contrast, if we make an `enum` `public`, all of its variants are then `public`. We only need the `pub` before the enum keyword\n```rust\nmod back_of_house {\n    pub enum Appetizer {\n        Soup,\n        Salad,\n    }\n}\n\npub fn eat_at_restaurant() {\n    let order1 = back_of_house::Appetizer::Soup;\n    let order2 = back_of_house::Appetizer::Salad;\n}\n```\n\n### Bringing Paths into Scope with the use Keyword\nWe bring the `crate::front_of_house::hosting` module into the scope of the `eat_at_restaurant` function so we only have to specify `hosting::add_to_waitlist` to call the `add_to_waitlist` function in eat_at_restaurant\n** Note that use only creates the shortcut for the `particular scope` in which the `use` occurs.**\n```rust\nmod front_of_house {\n    pub mod hosting {\n        pub fn add_to_waitlist() {}\n    }\n}\n\nuse crate::front_of_house::hosting;\n\npub fn eat_at_restaurant() {\n    hosting::add_to_waitlist();\n}\n```\n\u003e Adding `use` and a `path` in a scope is similar to creating a `symbolic link` in the filesystem.\n\n### Creating Idiomatic use Paths\nSpecifying the `parent module` when calling the function makes it clear that the function isn’t `locally defined` while still minimizing repetition of the full path. \n\nOn the other hand, when bringing in `structs, enums, and other items` with `use`, it’s idiomatic to specify the `full path`.\n```rust\nuse std::collections::HashMap;\n\nfn main() {\n    let mut map = HashMap::new();\n    map.insert(1, 2);\n}\n```\n\u003e The exception to this idiom is if we’re bringing two items with the same name into scope with use statements, because Rust doesn’t allow that.\n\n### Providing New Names with the as Keyword\nThere’s another solution to the problem of bringing two types of the same name into the same scope with `use`: after the path, we can specify `as` and a new local name, or alias, for the type. \n```rust\nuse std::fmt::Result;\nuse std::io::Result as IoResult;\n\nfn function1() -\u003e Result {\n    // --snip--\n}\n\nfn function2() -\u003e IoResult\u003c()\u003e {\n    // --snip--\n}\n```\n\n### Re-exporting Names with pub use\nWe can combine `pub` and `use`. This technique is called `re-exporting` because we’re bringing an item into scope but also making that item available for others to bring into their scope.\n```rust\nmod front_of_house {\n    pub mod hosting {\n        pub fn add_to_waitlist() {}\n    }\n}\n\npub use crate::front_of_house::hosting;\n\npub fn eat_at_restaurant() {\n    hosting::add_to_waitlist();\n}\n```\n\n### Using External Packages\nTo bring `rand` definitions into the scope of our package, we added a use line starting with the name of the crate\n```rust\nuse rand::Rng;\n\nfn main() {\n    let secret_number = rand::thread_rng().gen_range(1..=100);\n}\n```\n\nwith `HashMap` we would use this line:\n```rust\nuse std::collections::HashMap;\n```\n\n### Using Nested Paths to Clean Up Large use Lists\nWe can use nested paths to bring items into scope `in one line`\n```rust\nuse std::{cmp::Ordering, io};\nuse std::io::{self, Write};\n```\n\n### The Glob Operator\nIf we want to bring `all` public items\n```rust\nuse std::collections::*;\n```\n\n## Separating Modules into Different Files\nWe’ll extract `modules` into `files` instead of having all the modules defined in the crate root file. \n\nFilename: src/lib.rs\n```rust\nmod front_of_house;\n\npub use crate::front_of_house::hosting;\n\npub fn eat_at_restaurant() {\n    hosting::add_to_waitlist();\n}\n```\n\nFilename: src/front_of_house.rs\n```rust\npub mod hosting;\n```\n\nFilename: src/front_of_house/hosting.rs\n```rust\npub fn add_to_waitlist() {}\n```\n\n## Summary\nRust lets you split a `package` into multiple `crates` and a crate into `modules` so you can refer to items defined in one module from another module. You can do this by specifying `absolute` or `relative` paths. These paths can be brought into scope with a `use` statement so you can use a shorter path for multiple uses of the item in that scope. Module code is `private by default`, but you can make definitions public by adding the `pub` keyword.\n\n\n# 8 Common Collections\nMost other data types represent one specific value, but collections can contain multiple values. Unlike the built-in array and tuple types, the data these collections point to is stored on the heap, which means the amount of data does not need to be known at compile time and can grow or shrink as the program runs.  \n- A `vector` allows you to store a variable number of values next to each other.\n- A `string` is a collection of characters. We’ve mentioned the String type previously, but in this chapter we’ll talk about it in depth.\n- A `hash map` allows you to associate a value with a particular key. It’s a particular implementation of the more general data structure called a map.\n\n## Storing Lists of Values with Vectors\nThe first collection type we’ll look at is `Vec\u003cT\u003e`, also known as a `vector`.\nTo create a new empty vector, we call the `Vec::new` function,\n```rust\n    let v: Vec\u003ci32\u003e = Vec::new();\n    let v = vec![1, 2, 3];\n```\n\n### Updating a Vector\nTo create a vector and then add elements to it, we can use the `push` method,\n```rust\n    let mut v = Vec::new();\n    v.push(5);\n    v.push(6);\n```\n\n### Reading Elements of Vectors\nThere are `two` ways `to reference` a value stored in a vector: via `indexing` or using the `get`\n```rust\n    let v = vec![1, 2, 3, 4, 5];\n\n    let third: \u0026i32 = \u0026v[2]; // using index\n    println!(\"The third element is {third}\");\n\n    let third: Option\u003c\u0026i32\u003e = v.get(2); // using get\n    match third {\n        Some(third) =\u003e println!(\"The third element is {third}\"),\n        None =\u003e println!(\"There is no third element.\"),\n    }\n```\n`Indexing` - this method is best used when you want your program to crash if there’s an attempt to access an element past the end of the vector.\nWhen the `get` method is passed an index that is outside the vector, it returns None `without panicking`.\n\n### Iterating over the Values in a Vector\nTo `access each element` in a vector in turn, we would iterate through all of the elements rather than use indices to access one at a time with `for loop`\n```rust\n    let v = vec![100, 32, 57];\n    for i in \u0026v {\n        println!(\"{i}\");\n    }\n```\n\nWe can also `iterate` over `mutable` references\n```rust\n    let mut v = vec![100, 32, 57];\n    for i in \u0026mut v {\n        *i += 50;\n    }\n\n```\n\n### Using an Enum to Store Multiple Types\nWhen we need `one type` to represent `elements of different types`, we can define and use an `enum`\n```rust\n    enum SpreadsheetCell {\n        Int(i32),\n        Float(f64),\n        Text(String),\n    }\n\n    let row = vec![\n        SpreadsheetCell::Int(3),\n        SpreadsheetCell::Text(String::from(\"blue\")),\n        SpreadsheetCell::Float(10.12),\n    ];\n```\n\n### Dropping a Vector Drops Its Elements\nLike any other struct, a vector is freed when it goes out of scope\n```rust\n    {\n        let v = vec![1, 2, 3, 4];\n\n        // do stuff with v\n    } // \u003c- v goes out of scope and is freed here\n```\n\n## Storing UTF-8 Encoded Text with Strings\nNew Rustaceans commonly get stuck on strings for a combination of three reasons: \n- Rust’s propensity for exposing possible errors  \n- strings being a more complicated data structure than many programmers give them credit for  \n- and UTF-8  \n\n### What Is a String?\nRust has only one string type in the core language, which is the string slice `str` that is usually seen in its borrowed form `\u0026str`\nThe `String` type, which is provided by Rust’s `standard library` rather than coded into the core language, is a `growable`, `mutable`, `owned`, `UTF-8` encoded string type. \n\n### Creating a New String\nMany of the `same operations` available with `Vec\u003cT\u003e` are available with `String` as well, because String is actually implemented as a `wrapper around a vector` of bytes with some extra guarantees, restrictions, and capabilities.\n```rust\n    let mut s = String::new();\n```\n\nOften, we’ll have some `initial data` that we want to start the string with. For that, we `use` the `to_string` method, which is available on any type that implements the `Display` trait\n```rust\n    let data = \"initial contents\";\n\n    let s = data.to_string();\n\n    // the method also works on a literal directly:\n    let s = \"initial contents\".to_string();\n```\n\nWe `can also` use the function `String::from` to create a String from a string literal.\n```rust\n    let s = String::from(\"initial contents\");\n```\n\u003e In this case, `String::from` and `to_string` do the `same` thing, so which you choose is a matter of style and readability.\n\n### Updating a String\nA String `can grow` in size and its contents can change, just like the contents of a `Vec\u003cT\u003e`, if you `push` more data into it. In addition, you can conveniently use the `+` operator or the `format!` macro to concatenate String values.\n\nWe can `grow` a String by using the `push_str` method to\n```rust\n    let mut s = String::from(\"foo\");\n    s.push_str(\"bar\");\n```\n\u003e The push_str method takes a string slice and `don’t take ownership` of the parameter\n\nThe `push` method takes a `single character` as a parameter and adds it to the String.\n```rust\n    let mut s = String::from(\"lo\");\n    s.push('l');\n```\n\nOften, you’ll want to `combine two` existing strings. One way to do so is to `use` the `+` operator\n```rust\n    let s1 = String::from(\"Hello, \");\n    let s2 = String::from(\"world!\");\n    let s3 = s1 + \u0026s2; // note s1 has been moved here and can no longer be used\n```\n\u003e The string s3 will contain Hello, world!. The reason `s1` is `no longer valid` after the addition, and the reason we used a `reference to s2`, has to do with the signature of the `method` that’s called when we use the + operator. The `+` operator `uses` the `add` method\n\nIf we need to concatenate multiple strings, the behavior of the + operator gets unwieldy. \nFor more `complicated string` combining, we can instead `use` the `format!` macro:\n```rust\n    let s1 = String::from(\"tic\");\n    let s2 = String::from(\"tac\");\n    let s3 = String::from(\"toe\");\n\n    let s = format!(\"{s1}-{s2}-{s3}\");\n```\n\n### Indexing into Strings\nRust strings `don’t support indexing`\nA `String` is a wrapper over a `Vec\u003cu8\u003e`.\nSometimes `UTF-8` stores as `1 byte`, sometimes with Unicode scalar value as `2 bytes`.\nTo avoid `returning an unexpected value` and causing `bugs` that might not be discovered immediately, Rust doesn’t compile this code at all and prevents misunderstandings early in the development process.\n\n### Bytes and Scalar Values and Grapheme Clusters! Oh My!\nAnother point about `UTF-8` is that there are actually `three` relevant `ways to look` at strings from Rust’s perspective: `as bytes`, `scalar values`, and `grapheme clusters`\n\u003e A final reason Rust `doesn’t allow us to index` into a String to get a character is that indexing operations are expected to always take constant time (O(1)). But it isn’t possible to guarantee that performance with a String, because `Rust would have to walk through the contents from the beginning to the index` to determine `how many valid` characters there were.\n\n### Slicing Strings\n`Indexing` into a string is `often a bad idea` because it’s `not clear` what the return type of the string-indexing `operation should be`: a byte value, a character, a grapheme cluster, or a string slice.\n\n### Methods for Iterating Over Strings\nThe `best way` to operate on pieces of strings is to be `explicit` about whether you want `characters or bytes`. For individual Unicode scalar values, use the `chars` method.\n```rust\nfor c in \"Зд\".chars() {\n    println!(\"{c}\");\n}\n```\nAlternatively, the `bytes` method returns each `raw byte`\n```rust\nfor b in \"Зд\".bytes() {\n    println!(\"{b}\");\n}\n```\n\n### Strings Are Not So Simple\nTo summarize, `strings are complicated`. Different programming languages make different choices about how to present this complexity to the programmer. Rust has chosen to make the `correct handling of String data the default` behavior for all Rust programs, which means programmers have to put more thought into `handling UTF-8` data upfront\n\n## Storing Keys with Associated Values in Hash Maps\nThe type `HashMap\u003cK, V\u003e` stores a mapping of `keys` of type K to `values` of type V using a hashing function, which determines how it places these keys and values into memory. \nHash maps are `useful` when you want to look up data `not by using an index`, as you can with vectors, but `by using a key` that can be of any type. \n\n### Creating a New Hash Map\nOne way to create an empty hash map is using new and adding elements with insert. Just like vectors, hash maps store their data on the heap. \n```rust\n    use std::collections::HashMap;\n    let mut scores = HashMap::new();\n    scores.insert(String::from(\"Blue\"), 10);\n    scores.insert(String::from(\"Yellow\"), 50);\n```\n\u003e we need to first `use the HashMap from the collections` portion of the standard library.\n\n### Accessing Values in a Hash Map\nWe `can get a value` out of the hash map by providing its key to the `get` method\n```rust\n    use std::collections::HashMap;\n\n    let mut scores = HashMap::new();\n\n    scores.insert(String::from(\"Blue\"), 10);\n    scores.insert(String::from(\"Yellow\"), 50);\n\n    let team_name = String::from(\"Blue\");\n    let score = scores.get(\u0026team_name).copied().unwrap_or(0);\n```\n\u003e Here, `score` will have the value that’s associated with the `Blue` team, and the result will be `10`. The `get` method returns an `Option\u003c\u0026V\u003e`; if there’s `no value` for that key in the hash map, get will return `None`. This program handles the `Option` by calling `copied` to get an `Option\u003ci32\u003e` rather than an `Option\u003c\u0026i32\u003e`, then `unwrap_or` to set score to zero if scores doesn't have an entry for the key.\n\nWe can `iterate` over each key/value pair in a `hash map` in a similar manner as we do with vectors, using a `for loop`\n```rust\n    use std::collections::HashMap;\n\n    let mut scores = HashMap::new();\n\n    scores.insert(String::from(\"Blue\"), 10);\n    scores.insert(String::from(\"Yellow\"), 50);\n\n    for (key, value) in \u0026scores {\n        println!(\"{key}: {value}\");\n    }\n```\n\n### Hash Maps and Ownership\nFor types that implement the `Copy trait, like i32`, the values are `copied into the hash` map. `For owned` values like `String`, the values will be `moved` and the hash map will be the `owner` of those values\n```rust\n    use std::collections::HashMap;\n\n    let field_name = String::from(\"Favorite color\");\n    let field_value = String::from(\"Blue\");\n\n    let mut map = HashMap::new();\n    map.insert(field_name, field_value);\n    // field_name and field_value are invalid at this point, try using them and\n    // see what compiler error you get!\n```\n\u003e We `aren’t able to use` the variables `field_name` and `field_value` after they’ve been moved into the hash map with the call to insert.\n\n### Updating a Hash Map\nWhen you want to change the data in a hash map, you have to decide how to handle the case when a key already has a value assigned.\n\nOverwriting a Value\n```rust\n    use std::collections::HashMap;\n\n    let mut scores = HashMap::new();\n\n    scores.insert(String::from(\"Blue\"), 10);\n    scores.insert(String::from(\"Blue\"), 25);\n\n    println!(\"{:?}\", scores);\n```\n\u003e If we insert a key and a value into a hash map and then insert that same key with a different value, the value associated with that key will be replaced\n\nAdding a Key and Value Only If a Key Isn’t Present\n```rust\n    use std::collections::HashMap;\n\n    let mut scores = HashMap::new();\n    scores.insert(String::from(\"Blue\"), 10);\n\n    scores.entry(String::from(\"Yellow\")).or_insert(50);\n    scores.entry(String::from(\"Blue\")).or_insert(50);\n\n    println!(\"{:?}\", scores);\n```\n\u003e if the key does exist in the hash map, the existing value should remain the way it is. If the key doesn’t exist, insert it and a value for it.\n\nUpdating a Value Based on the Old Value\n```rust\n    use std::collections::HashMap;\n\n    let text = \"hello world wonderful world\";\n\n    let mut map = HashMap::new();\n\n    for word in text.split_whitespace() {\n        let count = map.entry(word).or_insert(0);\n        *count += 1;\n    }\n\n    println!(\"{:?}\", map);\n```\n\u003e We use a hash map with the words as keys and increment the value to keep track of how many times we’ve seen that word\n\n### Hashing Functions\nBy default, HashMap uses a hashing function called `SipHash` \n\n# Error Handling\nRust groups errors into `two` major categories: `recoverable` and `unrecoverable errors`. For a recoverable error, such as a `file not found` error, we most likely just `want to report` the problem to the user and retry the operation. Unrecoverable errors are always symptoms of `bugs`, like `trying to access a location beyond the end of an array`, and so we want to immediately `stop` the program.\nRust `doesn’t have exceptions`. Instead, it has the type `Result\u003cT, E\u003e` for `recoverable` errors and the `panic!` macro that stops execution when the program encounters an `unrecoverable error`.\n\n## Unrecoverable Errors with panic!\nBy default, when a panic occurs, the program starts unwinding, which means Rust walks back up the stack and cleans up the data from each function it encounters. However, this walking back and cleanup is a lot of work. Rust, therefore, allows you to choose the alternative of immediately aborting, which ends the program without cleaning up.\n```\n//Cargo.toml file\n[profile.release]\npanic = 'abort'\n```\nSometimes, bad things happen in your code, and there’s nothing you can do about it. In these cases, Rust has the `panic!` macro\n```rust\nfn main() {\n    panic!(\"crash and burn\");\n}\n```\n\n### Using a panic! Backtrace\nWe can set the `RUST_BACKTRACE` environment variable to get a backtrace of exactly what happened to cause the error. A backtrace is a list of all the functions that `have been called to get to this point`.\n```sh\nRUST_BACKTRACE=1 cargo run\n```\n\u003e Debug symbols are `enabled by default` when using cargo build or cargo run without the `--release` flag, as we have here.\n\n### Recoverable Errors with Result\nMost errors aren’t serious enough to require the program to stop entirely.\n```rust\nenum Result\u003cT, E\u003e {\n    Ok(T),\n    Err(E),\n}\n```\n\nWe need to `add` to the code to take `different actions depending` on the `value` File::open `returns`\n```rust\nuse std::fs::File;\nfn main() {\n    let greeting_file_result = File::open(\"hello.txt\");\n    let greeting_file = match greeting_file_result {\n        Ok(file) =\u003e file, // return inner file\n        Err(error) =\u003e panic!(\"Problem opening the file: {:?}\", error), // panic\n    };\n}\n```\n\n### Matching on Different Errors\nWe want to take `different actions` for different failure reasons: `if File::open failed` because the file doesn’t exist, `we want to create` the file and return the handle to the new file\n```rust\nuse std::fs::File;\nuse std::io::ErrorKind;\n\nfn main() {\n    let greeting_file_result = File::open(\"hello.txt\");\n\n    let greeting_file = match greeting_file_result {\n        Ok(file) =\u003e file,\n        Err(error) =\u003e match error.kind() { // different kinds of errors\n            ErrorKind::NotFound =\u003e match File::create(\"hello.txt\") { // if not found try to create file\n                Ok(fc) =\u003e fc,\n                Err(e) =\u003e panic!(\"Problem creating the file: {:?}\", e), // panic if failed\n            },\n            other_error =\u003e {\n                panic!(\"Problem opening the file: {:?}\", other_error); // in other kind panic\n            }\n        },\n    };\n}\n```\n\nThe `match` expression is very useful but also very much a `primitive`. Here’s `another way` to write the same logic this time using `closures` and the `unwrap_or_else` method\n```rust\nuse std::fs::File;\nuse std::io::ErrorKind;\nfn main() {\n    let greeting_file = File::open(\"hello.txt\").unwrap_or_else(|error| {\n        if error.kind() == ErrorKind::NotFound {\n            File::create(\"hello.txt\").unwrap_or_else(|error| {\n                panic!(\"Problem creating the file: {:?}\", error);\n            })\n        } else {\n            panic!(\"Problem opening the file: {:?}\", error);\n        }\n    });\n}\n```\n\n### Shortcuts for Panic on Error: unwrap and expect\nIf the `Result` value is the `Ok` variant, `unwrap` will `return` the value inside the `Ok`. If the Result is the `Err` variant, unwrap will call the `panic!` macro for us.\n```rust\nuse std::fs::File;\nfn main() {\n    let greeting_file = File::open(\"hello.txt\").unwrap();\n}\n```\n\nSimilarly, the `expect` method lets us also `choose` the `panic!` error message. Using `expect instead of unwrap` and providing good error messages can convey your intent and `make tracking` down the source of a `panic easier`. \n```rust\nuse std::fs::File;\nfn main() {\n    let greeting_file = File::open(\"hello.txt\")\n        .expect(\"hello.txt should be included in this project\");\n}\n```\n\u003e In production-quality code, most Rustaceans choose `expect rather than unwrap`\n\n### Propagating Errors\nWhen a function’s implementation calls something `that might fail`, instead of handling the error within the function itself, you can `return the error` to the `calling code` so that it can decide what to do. This is known as `propagating`\n```rust\nuse std::fs::File;\nuse std::io::{self, Read};\nfn read_username_from_file() -\u003e Result\u003cString, io::Error\u003e {\n    let username_file_result = File::open(\"hello.txt\");\n    let mut username_file = match username_file_result {\n        Ok(file) =\u003e file,\n        Err(e) =\u003e return Err(e),\n    };\n    let mut username = String::new();\n    match username_file.read_to_string(\u0026mut username) {\n        Ok(_) =\u003e Ok(username), // return String if all ok\n        Err(e) =\u003e Err(e), // return Error if cant read\n    }\n}\n```\n\u003e It’s up to the calling code to decide what to do with those values. If the calling code gets an Err value, it could call panic! and crash the program, use a default username, or look up the username from somewhere other than a file, for example.\n\n### A Shortcut for Propagating Errors: the ? Operator\nThis pattern of `propagating` errors is so `common in Rust` that Rust provides the question mark operator `?` to make this easier.\n```rust\nfn read_username_from_file() -\u003e Result\u003cString, io::Error\u003e {\n    let mut username_file = File::open(\"hello.txt\")?;\n    let mut username = String::new();\n    username_file.read_to_string(\u0026mut username)?;\n    Ok(username)\n}\n```\n\u003e `error type` received is `converted` into the error type defined in the `return type` of the `current function` - function returns `one error type` to represent all the ways a function might fail\n\nThe `?` operator eliminates a lot of boilerplate and `makes` this function’s `implementation simpler`.\n```rust\nfn read_username_from_file() -\u003e Result\u003cString, io::Error\u003e {\n    let mut username = String::new();\n    File::open(\"hello.txt\")?.read_to_string(\u0026mut username)?;\n    Ok(username)\n}\n```\n\u003e If the value is an `Err`, the Err will be `returned` from the `whole function` as if we had used the `return` keyword so the error value gets propagated to the calling code.\n\n`Reading a file` into a string is a fairly `common operation`, so the standard library provides the convenient `fs::read_to_string`\n```rust\nfn read_username_from_file() -\u003e Result\u003cString, io::Error\u003e {\n    fs::read_to_string(\"hello.txt\")\n}\n```\n\n### Where The ? Operator Can Be Used\nThe `?` operator can only be `used` in functions whose `return` type is `compatible` with the value the ? is used on.\nThe `error message` also mentioned that ? `can be used` with `Option\u003cT\u003e` values as well.\n```rust\nfn last_char_of_first_line(text: \u0026str) -\u003e Option\u003cchar\u003e {\n    text.lines().next()?.chars().last()\n}\n```\n\u003e As with using ? on Result, you can only `use ?` on `Option` in a function that `returns an Option`\n\nLuckily, `main can also return a Result\u003c(), E\u003e`\n``` rust\nuse std::error::Error;\nuse std::fs::File;\nfn main() -\u003e Result\u003c(), Box\u003cdyn Error\u003e\u003e {\n    let greeting_file = File::open(\"hello.txt\")?;\n    Ok(())\n}\n```\n\u003e you can read `Box\u003cdyn Error\u003e` to mean `any kind of error`\n\nWhen a `main` function `returns` a `Result\u003c(), E\u003e`, the executable will exit with a value of `0` if main returns `Ok(())` and will exit with a `nonzero` value if main returns an `Err` value. \n\n## To panic! or Not to panic!\nYou could call `panic!` for `any error` situation, whether there’s a possible way to recover or not, but then you’re `making` the decision that a `situation` is `unrecoverable` on behalf of the calling code. When you choose to return a `Result` value, you `give` the calling code `options`. \n\n### Examples, Prototype Code, and Tests\nWhen you’re writing an `example` to illustrate some concept, also including robust `error-handling code` can make the example `less clear`. \nSimilarly, the `unwrap and expect` methods are very `handy` when `prototyping`, before you’re ready to decide how to handle errors.\nIf a method call fails in a `test`, you’d want the `whole test to fail`, even if that method isn’t the functionality under test.\n\n### Cases in Which You Have More Information Than the Compiler\nIf you can ensure by manually inspecting the code that you’ll `never have an Err variant`, it’s perfectly acceptable to call unwrap, and even `better to document the reason` you think you’ll never have an Err variant in the `expect` text\n```rust\n    let home: IpAddr = \"127.0.0.1\"\n        .parse()\n        .expect(\"Hardcoded IP address should be valid\");\n```\n\n### Guidelines for Error Handling\nIn cases where continuing could be `insecure or harmful`, the `best choice` might be to `call panic!` and alert the person using your library to the bug in their code so they can fix it during development.\nHowever, when `failure is expected`, it’s more appropriate to `return a Result` than to make a panic! call.\nWhen your code performs an operation that `could put a user at risk` if it’s called using `invalid values`, your code should `verify the values are valid first` and `panic` if the values aren’t valid. \n\u003e you can use `Rust’s type system` (and thus the type checking done by the compiler) to do `many of the checks` for you.\n\n### Creating Custom Types for Validation\nLet’s take the idea of using `Rust’s type system` to ensure we have a `valid value` one step further and look at creating a custom type for validation.\n`One way` to do this would be to parse the guess as an i32 instead of only a u32 to allow potentially negative numbers, and then `add a check everywhere` for the number being in range\n`Instead`, we can `make a new type` and put the validations in a function to create an instance of the type rather than repeating the validations everywhere.\n```rust\npub struct Guess { //define a struct that has a field named value that holds an i32\n    value: i32,\n}\nimpl Guess {\n    pub fn new(value: i32) -\u003e Guess { // creates instances of Guess values\n        if value \u003c 1 || value \u003e 100 { // check if value correct\n            panic!(\"Guess value must be between 1 and 100, got {}.\", value); // panic if not\n        }\n        Guess { value } // return if all ok\n    }\n    pub fn value(\u0026self) -\u003e i32 { // getter, because value is private\n        self.value\n    }\n}\n```\n\u003e A function that has a parameter or returns only numbers between 1 and 100 could then declare in its signature that it takes or returns a `Guess rather than an i32` and wouldn’t need to do any `additional checks` in its body.\n\n## Summary\nRust’s error handling features are designed to help you write more robust code. The panic! macro signals that your program is in a state it can’t handle and lets you tell the process to stop instead of trying to proceed with invalid or incorrect values. The Result enum uses Rust’s type system to indicate that operations might fail in a way that your code could recover from. You can use Result to tell code that calls your code that it needs to handle potential success or failure as well. Using panic! and Result in the appropriate situations will make your code more reliable in the face of inevitable problems.\n\n# Generic Types Traits Lifetimes\nEvery programming language has tools for effectively handling the duplication of concepts. In Rust, one such tool is `generics`: abstract stand-ins for concrete types or other properties. \n\n## Removing Duplication by Extracting a Function\nTo eliminate this duplication, we’ll create an `abstraction` by defining a `function` that operates on any list of integers passed in a parameter. \n```rust\nfn largest(list: \u0026[i32]) -\u003e \u0026i32 {\n    let mut largest = \u0026list[0];\n\n    for item in list {\n        if item \u003e largest {\n            largest = item;\n        }\n    }\n\n    largest\n}\n\nfn main() {\n    let number_list = vec![34, 50, 25, 100, 65];\n\n    let result = largest(\u0026number_list);\n    println!(\"The largest number is {}\", result);\n    assert_eq!(*result, 100);\n\n    let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];\n\n    let result = largest(\u0026number_list);\n    println!(\"The largest number is {}\", result);\n    assert_eq!(*result, 6000);\n}\n```\n\nIn summary, here are the steps we took to change the code:\n- Identify duplicate code.  \n- Extract the duplicate code into the body of the function and specify the inputs and return values of that code in the function signature.  \n- Update the two instances of duplicated code to call the function instead.  \n\n## Generic Data Types\nWe use `generics` to create definitions for items `like function` signatures or structs, which we can then use with many different concrete data types. \n\n### In Function Definitions\nWhen we use a `parameter` in the body of the function, we have to `declare` the parameter name in the `signature` so the compiler knows what that name means.\n```rust\nfn largest\u003cT\u003e(list: \u0026[T]) -\u003e \u0026T {\n```\n\n### In Struct Definitions\nWe can also define `structs` to use a generic type parameter in one or more fields using the `\u003c\u003e` syntax.\n```rust\nstruct Point\u003cT\u003e {\n    x: T,\n    y: T,\n}\n\nfn main() {\n    let integer = Point { x: 5, y: 10 };\n    let float = Point { x: 1.0, y: 4.0 };\n}\n```\n\u003e Note that because we’ve used only `one generic` type to define `Point\u003cT\u003e`, this definition says that the Point\u003cT\u003e struct is generic over `some type T`, and the fields x and y are `both that same type`, whatever that type may be.\n\nTo define a Point struct where x and y are both `generics` but could have `different types`, we can use `multiple generic type` parameters. \n```rust\nstruct Point\u003cT, U\u003e {\n    x: T,\n    y: U,\n}\n\nfn main() {\n    let both_integer = Point { x: 5, y: 10 };\n    let both_float = Point { x: 1.0, y: 4.0 };\n    let integer_and_float = Point { x: 5, y: 4.0 };\n}\n```\n\n### In Enum Definitions\nWe can define enums to hold `generic data` types in their variants.\n```rust\nenum Option\u003cT\u003e {\n    Some(T),\n    None,\n}\n```\n\nEnums can use `multiple generic` types as well. \n```rust\nenum Result\u003cT, E\u003e {\n    Ok(T),\n    Err(E),\n}\n```\n\n### In Method Definitions\nWe can implement methods on structs and enums and use `generic types` in their `definitions`, too.\n```rust\nstruct Point\u003cT\u003e {\n    x: T,\n    y: T,\n}\n\nimpl\u003cT\u003e Point\u003cT\u003e { // using generic data type \u003cT\u003e\n    fn x(\u0026self) -\u003e \u0026T {\n        \u0026self.x\n    }\n}\n\nfn main() {\n    let p = Point { x: 5, y: 10 };\n\n    println!(\"p.x = {}\", p.x());\n}\n```\n\nGeneric type parameters in a struct definition `aren’t always the same` as those you use in that `same struct’s method` signatures.\n```rust\nstruct Point\u003cX1, Y1\u003e {\n    x: X1,\n    y: Y1,\n}\n\nimpl\u003cX1, Y1\u003e Point\u003cX1, Y1\u003e {\n    fn mixup\u003cX2, Y2\u003e(self, other: Point\u003cX2, Y2\u003e) -\u003e Point\u003cX1, Y2\u003e {\n        Point {\n            x: self.x,\n            y: other.y,\n        }\n    }\n}\n\nfn main() {\n    let p1 = Point { x: 5, y: 10.4 };\n    let p2 = Point { x: \"Hello\", y: 'c' };\n\n    let p3 = p1.mixup(p2);\n\n    println!(\"p3.x = {}, p3.y = {}\", p3.x, p3.y);\n}\n```\n\u003e In main, we’ve defined a Point that has an i32 for x (with value 5) and an f64 for y (with value 10.4). The p2 variable is a Point struct that has a string slice for x (with value \"Hello\") and a char for y (with value c). Calling mixup on p1 with the argument p2 gives us p3, which will have an i32 for x, because x came from p1. The p3 variable will have a char for y, because y came from p2. The println! macro call will print p3.x = 5, p3.y = c.\n\n### Performance of Code Using Generics\nRust accomplishes this by performing `monomorphization` of the code using generics at compile time. Monomorphization is the process of `turning generic code` into specific code by `filling` in the `concrete types` that are used when compiled. \n\n## Traits: Defining Shared Behavior\nA `trait defines functionality` a particular type has and can share `with other types`.\n\n### Defining a Trait \nA type’s behavior consists of the `methods` we can call on that `type`. `Different types` share the `same behavior` if we can call the `same methods` on all of those types. `Trait` definitions are a way to `group method` signatures together to define a set of behaviors necessary `to accomplish some purpose`.\n\nWe want to make a media `aggregator library crate` named aggregator that can `display summaries` of data that might be stored in a NewsArticle or Tweet instance. To do this, we need a `summary from each type`, and we’ll request that summary by calling a `summarize method` on an instance. \n```rust\npub trait Summary {\n    fn summarize(\u0026self) -\u003e String;\n}\n```\n\n### Implementing a Trait on a Type\nNow that we’ve defined the desired signatures of the `Summary trait’s methods`, we can implement it on the types in our media aggregator.\n```rust\npub trait Summary {\n    fn summarize(\u0026self) -\u003e String;\n}\n\npub struct NewsArticle {\n    pub headline: String,\n    pub location: String,\n    pub author: String,\n    pub content: String,\n}\n\nimpl Summary for NewsArticle { // trait Summary for NewsArticle\n    fn summarize(\u0026self) -\u003e String {\n        format!(\"{}, by {} ({})\", self.headline, self.author, self.location)\n    }\n}\n\npub struct Tweet {\n    pub username: String,\n    pub content: String,\n    pub reply: bool,\n    pub retweet: bool,\n}\n\nimpl Summary for Tweet { // trait Summary for Tweet\n    fn summarize(\u0026self) -\u003e String {\n        format!(\"{}: {}\", self.username, self.content)\n    }\n}\n`","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzakharb%2Frustguide","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fzakharb%2Frustguide","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzakharb%2Frustguide/lists"}