├── 10 - Advance Techniques ├── 1 - Declarative Macros Basics.txt ├── 10 - Testing your code (Part 3) (System Integration Test).txt ├── 11 - Practice Problems.docx ├── 2 - Capturing Types.txt ├── 3 - Repeating Patterns.txt ├── 4 - Unit Type, Expression vs statements and Partial Move.txt ├── 5 - as_ref and Partial move in option.txt ├── 6 - Take, replace and swap for Avoiding Allocations.txt ├── 7 - Question mark operator.txt ├── 8 - Testing your code (Part 1).txt └── 9 - Testing your code (Part 2).txt ├── 11 - Real Life Application ├── 1 - Search Results using Word Groupings.txt ├── 10 - Efficient Storage and Retrieval of Words.txt ├── 11 - 12 - Most recently used product information .txt ├── 13 - Displaying Participants in an online meeting.txt ├── 2 - Product Popularity .txt ├── 3 - Maximum Product Earning.txt ├── 3 - Product Maximum Earning.txt ├── 4 - Finding an Employ with no meeting .txt ├── 5 - Longest nonstop working hours.txt ├── 6 - Suggesting Items for Special Shopping Card .txt ├── 7- 8 - Items in ranges .txt └── 9 - Fetching Top Products.txt ├── 12 - Deep Dive into Traits ├── 10 - Some useful traits on structs.txt ├── 10 - Static vs dynamic dispatch .txt ├── 11 - Trait Bounds.txt ├── 12 - Associated Type.txt ├── 3 - Trait Items.txt └── 4 - Scope of a trait, Marker and Super traits.txt ├── 13 - Efficient Programming with Rust ├── 1 - Initializing stuct instances .txt ├── 11 - Builder pattern.txt ├── 2 - Fucntion inputs and coercion.txt ├── 3 - Iterating though option .txt ├── 4 - Disabling Mutability for finalized objects.txt ├── 5 - String Concatenation and Ownership.txt ├── 6 - Simplifying Sturctures.txt ├── 7 - Efficient Programming Tips.txt ├── 8 - todo Macro .txt └── 9 - String Literals.txt ├── 14 - Concurrency in RUST ├── 1 - Thread basics.txt ├── 10 - Thread Parking and Yield.txt ├── 11 - Async-Await.txt ├── 12 - Asycn-Await.txt ├── 2 - Multiple Threads and Ownership in Threads .txt ├── 3 - Communication through channels.txt ├── 4 - Multiple producers, threads and functions.txt ├── 5 - Sharing States .txt ├── 6 - Passing Mutexes between Threads.txt ├── 7 - Synchronization through barriers .txt ├── 8- Project- Webscrapping using Threads.txt └── 9 - Scoped Threads.txt ├── 15 - Text Processing, File and directory handlign ├── 1 - Basic File Handling.txt ├── 2 - Directory and path related functions.txt ├── 3 - Regular Expression Basics.txt └── 4 - Regexes- Repeatitions and Quantifiers.txt ├── 16 - Sized and Unsized Types ├── 1 - Unsized Types and References to Them.txt ├── 2 - Possibly Sized Property.txt ├── 3 - Rust Provided Non Sized Types.txt └── 4- Coercion in Unsized Types.txt ├── 17 - BlockChain from Scratch in RUST ├── 3 - Blockchain in Rust (Part 1 Basic Structures and Functions) Finalized.txt └── 4 - Blockchain in Rust (Part 2).txt ├── 18 - Web Programming ├── 1 - Web Programming (Basics).txt ├── 2 - Writting Responces.txt └── 3 - Handling Multiple requests using threads.txt ├── 19 - Measuring and Improving Performance ├── 1. Benchmarking.txt └── 2. Performance lints.txt ├── 2 - Basic Programming ├── 1 - Program Outputs and comments.txt ├── 2 - Variables and Scalar Data Types.txt ├── 3 - More on Variables Shadowing and Constants.txt ├── 4 - Compuond Data Type- Strings.txt ├── 5 - Compund Data Types-Tuples, Arrays, Vectors.txt ├── 6 - Compund Data Types - Vectors .txt ├── 7 - Functions and Inputs.txt └── 8 - Practice Problems.docx ├── 3 - Rust Ownership ├── 1 - Ownership Rules, Premitive, and non-premitive types.txt ├── 2 - Heap and stack .txt ├── 3 - Onwership and Feferences in Functions .txt ├── 4 - Mutable and Immutable References.txt ├── 5 - Dereferencing (the reverse of a reference).txt └── 6 - Practice Problems.docx ├── 4 - Control Structures ├── 1 - Conditional If and its varaints .txt ├── 2 - If let, nested if and the match .txt ├── 3 - Match statement .txt ├── 4 - While and simple loops .txt ├── 5 - For loops and its variants.txt ├── 6 - Break and continue .txt ├── 7 - Practice Problems.docx └── Exercise │ ├── 10 - Practice - Palindrome.txt │ ├── 11 - Practice - Pathagorian Triplet .txt │ ├── 7 - Some Examples of loops.txt │ ├── 8 - Practice- Sum of square difference .txt │ └── 9 - Practice- Sum of Multiples .txt ├── 5 - Project-Stack Implemenation and Applications ├── 1 - Implementation Stacks using Rust .txt ├── 2 - String reversal using Stacks .txt └── 5-6-7 - Expression Evaluation_Implement Rust using Stack.TXT ├── 6 - Structures, Traits, Generics, Enums ├── 1 - Structs Basics .txt ├── 2 - Traits and Default Implementations.txt ├── 3 - Functions within a Trait.txt ├── 4 - Enums .txt ├── 5 - Generics .txt ├── 6 - Option Enum.txt ├── 7 - Result Enum.txt ├── 8 - Hash Maps.txt └── 9 - Practice Problems.docx ├── 7 - Iterators, Lifetimes, Closures ├── 1 - Lifetimes (Part 1) .txt ├── 2 - Lifetimes (Part 2).txt ├── 3 - Eliding Lifetimes.txt ├── 4 - Closures (Part 1).txt ├── 5 - Closures (Part 2).txt ├── 6 - Function types.txt ├── 7 - Iterators (Part 1).txt ├── 8 - Iterators (Part 2).txt ├── 9 - Practice Problems.docx └── Exercise │ ├── 7 - Sum of multiples revised with iterators .txt │ └── 8 - Set intersection and Union .txt ├── 8 - Rust Modules ├── 1 - Rust Modules (Part 1) │ ├── file_1.txt │ ├── file_2.txt │ ├── lib.txt │ └── main.txt ├── 2 - Rust Modules (Part 2) │ ├── 1 - Rust Modules (Part 1).txt │ ├── file_1.txt │ ├── file_2.txt │ └── file_3.txt ├── 3 - Cargo tools to Visualize Module Hierarchy │ ├── commands .txt │ ├── method 1 │ │ ├── customer.rs │ │ ├── lib.rs │ │ ├── order.rs │ │ ├── product.rs │ │ └── product │ │ │ └── category.rs │ └── method 2 │ │ ├── customer │ │ └── mod.rs │ │ ├── lib.rs │ │ ├── order │ │ └── mod.rs │ │ └── product │ │ ├── category.rs │ │ └── mod.rs ├── 4 - Re-Exporting using Pub Use.txt ├── 5 - Using External crates.txt ├── 6 - Publishing a crate on crates.io.txt └── 7 - Practice Problems.docx ├── 9 - Smart Pointers in Rust ├── 1 - Basics of Smart Pointers.txt ├── 11 - Reference cycles Leaking Memory.txt ├── 2 - Box Pointers and When they are Useful .txt ├── 3 - Refining Cons List and Custom Smart Pointer.txt ├── 4 - Generics and Deref Coercion in Smart Pointers.txt ├── 5- Rc smart pointer.txt ├── 6 - RefCell smart pointer.txt ├── 7 - Implementing Singly Link list from Scratch (Part 1) .txt ├── 8- Implementing Singly Link list from Scratch (Part 2) .txt └── 9 -10 - Doubly link list (Part 1 and 2) .txt ├── Course Code Bundle - 2022 Edition ├── 2 - Basic Programming │ ├── 1 - Program Outputs and comments.txt │ ├── 2 - Variables and Scalar Data Types.txt │ ├── 3 - More on Variables Shadowing and Constants.txt │ ├── 4 - Compuond Data Type- Strings.txt │ ├── 5 - Compund Data Types-Tuples, Arrays, Vectors.txt │ ├── 6 - Compund Data Types - Vectors .txt │ └── 7 - Functions and Inputs.txt ├── 3 - Rust Ownership │ ├── 1 - Ownership Rules, Premitive, and non-premitive types.txt │ ├── 2 - Heap and stack .txt │ ├── 3 - Onwership and Feferences in Functions .txt │ ├── 4 - Mutable and Immutable References.txt │ └── 5 - String Concatenation and Ownership.txt ├── 4 - Control Structures │ ├── 1 - Conditional If and its varaints .txt │ ├── 2 - If let, nested if and the match .txt │ ├── 3 - Match statement .txt │ ├── 4 - While and simple loops .txt │ ├── 5 - For loops and its variants.txt │ ├── 6 - Break and continue .txt │ └── Exercise │ │ ├── 10 - Practice - Palindrome.txt │ │ ├── 11 - Practice - Pathagorian Triplet .txt │ │ ├── 7 - Some Examples of loops.txt │ │ ├── 8 - Practice- Sum of square difference .txt │ │ └── 9 - Practice- Sum of Multiples .txt ├── 5 - Project Stack Implementation │ ├── 1 - Implementation Stacks using Rust .txt │ ├── 2 - String reversal using Stacks .txt │ └── 5-6-7 Expression Evaluation (Stacks).txt ├── 6 - Structures, Traits, Generics, Enums │ ├── 1 - Structs Basics .txt │ ├── 2 - Traits & Default Implementations.txt │ ├── 3 - Functions within a Trait.txt │ ├── 4 - Enums .txt │ ├── 5 - Generics .txt │ ├── 6 - Option Enum.txt │ ├── 7 - Result Enum.txt │ └── 8 - Hash Maps.txt ├── 7 - Iterators, Lifetimes, Closures │ ├── 1 - Lifetimes (Part 1) .txt │ ├── 2 - Lifetimes (Part 2).txt │ ├── 3 - Closures (Part 1).txt │ ├── 4 - Closures (Part 2).txt │ ├── 5 - Function types .txt │ ├── 6 - Iterators (Part 1) .txt │ ├── 7 - Iterators (Part 2) .txt │ └── Exercise │ │ ├── 7 - Sum of multiples.txt │ │ └── 8 - Set intersection and Union .txt ├── 8 - Rust Modules │ ├── 3 - Using External crates .txt │ ├── 4 - Publishing a crate on crates.io.txt │ ├── Rust Modules (Part 1) │ │ ├── file_1.txt │ │ ├── file_2.txt │ │ ├── lib.txt │ │ └── main.txt │ └── Rust Modules (Part 2) │ │ ├── 1 - Rust Modules (Part 1).txt │ │ ├── file_1.txt │ │ ├── file_2.txt │ │ └── file_3.txt └── 9 - Smart Pointers │ ├── 1 - Basics of Smart Pointers.txt │ ├── 2 - Box Pointers and When they are Useful .txt │ ├── 3 - Refining Cons List and Custom Smart Pointer.txt │ └── 4 - Generics and Deref Coercion in Smart Pointers.txt ├── Course Code Bundle - Mar 2023 Edition ├── 10 - Real Life Application │ ├── 1 - Search Results using Word Groupings.txt │ ├── 10 - Efficient Storage and Retrieval of Words.txt │ ├── 11-12-Most recent product information.txt │ ├── 13 - Display Participants in Online Meet.txt │ ├── 2 - Product Popularity .txt │ ├── 3 - Maximum Product Earning.txt │ ├── 3 - Product Maximum Earning.txt │ ├── 4 - Finding an Employ with no meeting .txt │ ├── 5 - Longest nonstop working hours.txt │ ├── 6 - Suggest Items for Special Shopping Card.txt │ ├── 7- 8 - Items in ranges .txt │ └── 9 - Fetching Top Products.txt ├── 11 - Efficient Programming with Rust │ ├── 1 - Initializing stuct instances .txt │ ├── 10 - Static vs dynamic dispatch .txt │ ├── 11 - Builder pattern.txt │ ├── 2 - Fucntion inputs and coercion.txt │ ├── 3 - Iterating though option .txt │ ├── 4-Disable Mutability for final obj.txt │ ├── 5-String Concatenation & Ownership.txt │ ├── 6 - Simplifying Sturctures.txt │ ├── 7 - Efficient Programming Tips.txt │ ├── 8 - todo Macro .txt │ └── 9 - String Literals.txt ├── 12- Concurrency in RUST │ ├── 1 - Thread basics.txt │ ├── 10 - Thread Parking and Yield.txt │ ├── 11 - Async-Await.txt │ ├── 2 - Multiple Threads and Ownership in Threads .txt │ ├── 3 - Communication through channels.txt │ ├── 4 - Multiple producers, threads and functions.txt │ ├── 5 - Sharing States .txt │ ├── 6 - Passing Mutexes between Threads.txt │ ├── 7 - Synchronization through barriers .txt │ ├── 8- Project- Webscrapping using Threads.txt │ └── 9 - Scoped Threads.txt ├── 13 - Text Processing, File and directory handlign │ ├── 1-Basic File Handling.txt │ ├── 2-Directory and Path.txt │ ├── 3-Reg Exp Basics.txt │ └── 4-REPE~1.TXT ├── 14 - BlockChain from Scratch in RUST │ ├── 3 - Blockchain in Rust (Part 1).txt │ └── 4 - Blockchain in Rust (Part 2).txt ├── 2 - Basic Programming │ ├── 1 - Program Outputs and comments.txt │ ├── 2 - Variables and Scalar Data Types.txt │ ├── 3 - More on Variables Shadowing and Constants.txt │ ├── 4 - Compuond Data Type- Strings.txt │ ├── 5 - Compund Data Types-Tuples, Arrays, Vectors.txt │ ├── 6 - Compund Data Types - Vectors .txt │ └── 7 - Functions and Inputs.txt ├── 3 - Rust Ownership │ ├── 1 - Ownership Rules and Types.txt │ ├── 2 - Heap and stack .txt │ ├── 3 - Onwership and Feferences in Functions .txt │ └── 4 - Mutable and Immutable References.txt ├── 4 - Control Structures │ ├── 1 - Conditional If and its varaints .txt │ ├── 2 - If let, nested if and the match .txt │ ├── 3 - Match statement .txt │ ├── 4 - While and simple loops .txt │ ├── 5 - For loops and its variants.txt │ ├── 6 - Break and continue .txt │ └── Exercise │ │ ├── 10 - Practice - Palindrome.txt │ │ ├── 11 - Practice - Pathagorian Triplet .txt │ │ ├── 7 - Some Examples of loops.txt │ │ ├── 8 - Practice- Sum of square difference .txt │ │ └── 9 - Practice- Sum of Multiples .txt ├── 4-1 Project-Stack Implemenation and Applications │ ├── 1 - Stacks using Rust.txt │ ├── 2 - String reversal.txt │ └── 5-6-7 Expr. Evaluation.txt ├── 5 - Structures, Traits, Generics, Enums │ ├── 1 - Structs Basics .txt │ ├── 2-Traits & Default Implements.txt │ ├── 3 - Functions within a Trait.txt │ ├── 4 - Enums .txt │ ├── 5 - Generics .txt │ ├── 6 - Option Enum.txt │ ├── 7 - Result Enum.txt │ └── 8 - Hash Maps.txt ├── 6 - Iterators, Lifetimes, Closures │ ├── 1 - Lifetimes (Part 1) .txt │ ├── 2 - Lifetimes (Part 2).txt │ ├── 3 - Closures (Part 1).txt │ ├── 4 - Closures (Part 2).txt │ ├── 5 - Function types .txt │ ├── 6 - Iterators (Part 1) .txt │ ├── 7 - Iterators (Part 2) .txt │ └── Exercise │ │ ├── 7-Sum of multiples.txt │ │ └── 8 - Set intersect & Union.txt ├── 7 - Rust Modules │ ├── 3 - Using External crates .txt │ ├── 4 - Publishing a crate on crates.io.txt │ ├── Rust Modules (Part 1) │ │ ├── file_1.txt │ │ ├── file_2.txt │ │ ├── lib.txt │ │ └── main.txt │ └── Rust Modules (Part 2) │ │ ├── 1 - Rust Modules (Part 1).txt │ │ ├── file_1.txt │ │ ├── file_2.txt │ │ └── file_3.txt ├── 8 - Advance Concepts │ ├── 1 - Declarative Macros Basics.txt │ ├── 10 - Some useful traits on structs.txt │ ├── 11 - Trait Bounds.txt │ ├── 12 - Associated Type.txt │ ├── 2 - Capturing Types.txt │ ├── 3 - Repeating Patterns.txt │ ├── 4-Unit Type Expr vs stmnts & Partial Move.txt │ ├── 5 - as_ref and Partial move in option.txt │ ├── 6 - Take, replace and swap for Avoiding Allocations.txt │ ├── 7 - Question mark operator.txt │ ├── 8 - Testing your code (Part 1).txt │ └── 9 - Testing your code (Part 2).txt └── 9 - Smart Pointers in Rust │ ├── 1 - Basics of Smart Pointers.txt │ ├── 11 - Reference cycles Leaking Memory.txt │ ├── 2 - Box Pointers and When they are Useful .txt │ ├── 3 - Refine Cons List & Custom Smart Pnter.txt │ ├── 4-Generics & Deref Coerc in Smart Pnters.txt │ ├── 5- Rc smart pointer.txt │ ├── 6 - RefCell smart pointer.txt │ ├── 7-Singly Link list (Part 1).txt │ ├── 8-Singly Link list (Part 2).txt │ └── 9 -10 - Doubly link list (Part 1 and 2) .txt ├── LICENSE ├── Practice Questions ├── Section 2 │ ├── Practice Exercise on Functions and Inputs.docx │ ├── Practice Exercise on Tuples and Arrays and Scalars.docx │ └── Practice Exercise on Variables.docx ├── Section 3 │ └── Practice Exercise on Ownership.docx ├── Section 4 │ └── Practice Exercise on Basic Programming.docx └── Section 7 │ └── Practice Exercise on Iterators, Lifetimes, and Closures.docx └── README.md /10 - Advance Techniques/1 - Declarative Macros Basics.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------------- 2 | // Declarative Macros 3 | // ------------------------------------------------- 4 | 5 | /* General Syntax 6 | 7 | macro_rules! macro_name { 8 | // |--- Match rules 9 | (...) => { ... }; 10 | (...) => { ... }; 11 | (...) => { ... }; // the semicolon at the last rule is optional 12 | } 13 | */ 14 | 15 | 16 | macro_rules! our_macro { 17 | () => { 1+1; 18 | }; 19 | 20 | (something 4 u dear u32 @_@) => { 21 | println!("You found nonsense here") 22 | }; 23 | 24 | ($e1:expr, $e2:expr) => { 25 | $e1 + $e2 26 | }; 27 | 28 | ($a:expr, $b:expr; $c:expr) => { 29 | $a * ($b + $c) 30 | } 31 | } 32 | fn main() { 33 | 34 | 35 | println!("{}",our_macro!()); 36 | our_macro!(); 37 | println!("{}", our_macro!(2,2)); 38 | println!("{}", our_macro!(5,6;3)); 39 | // println!("{}", our_macro!("something",2;"nothing")); 40 | 41 | our_macro!(); 42 | our_macro![]; 43 | 44 | our_macro!{}; 45 | 46 | 47 | 48 | // 1. cargo install cargo-expand 49 | // 2. rustup install nightly 50 | // 3. rustup component add rustfmt 51 | // 4. rustup component add rustfmt --toolchain nightly 52 | 53 | 54 | } -------------------------------------------------------------------------------- /10 - Advance Techniques/10 - Testing your code (Part 3) (System Integration Test).txt: -------------------------------------------------------------------------------- 1 | use testing::{Category, Customer, Order, Product}; 2 | mod helpers; 3 | #[test] 4 | fn test_total_bill_without_discount() { 5 | helpers::common_setup(); 6 | let product = Product::new(1, String::from("Book"), 19.9, Category::Books); 7 | let customer = Customer::new(1, String::from("Bob"), String::from("bob@example.com")); 8 | let order = Order::new(2, product, customer, 3); 9 | 10 | assert_eq!(format!("{:.2}", order.total_bill()), "65.67"); 11 | } 12 | 13 | #[test] 14 | fn test_total_bill_with_discount() { 15 | let product = Product::new(1, String::from("Book"), 19.99, Category::Books); 16 | let customer = Customer::new(1, String::from("Bob"), String::from("bob@example.com")); 17 | let order = Order::new(2, product, customer, 10); // change to 10 later on 18 | assert_eq!(format!("{:.2}", order.total_bill()), "197.90"); // change to 197.90 19 | } 20 | 21 | 22 | // store in a separate file inside the tests/helpers/mod.rs 23 | pub fn common_setup(); -------------------------------------------------------------------------------- /10 - Advance Techniques/11 - Practice Problems.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Programming-Master-Class-from-Beginner-to-Expert/7a219af138cce6793e3e5f1fb22bb50a4cac1b40/10 - Advance Techniques/11 - Practice Problems.docx -------------------------------------------------------------------------------- /10 - Advance Techniques/2 - Capturing Types.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------------- 2 | // Capturing Types 3 | // ------------------------------------------------- 4 | /* 5 | macro_rules! input { 6 | ($t: ty) => {{ 7 | let mut n = String::new(); 8 | std::io::stdin() 9 | .read_line(&mut n) 10 | .expect("failed to read input"); 11 | 12 | let n: $t = n.trim().parse().expect("invalid input"); 13 | n 14 | 15 | } 16 | }; 17 | } 18 | 19 | macro_rules! add_as { 20 | ($a: expr, $b: expr, $typ: ty) => { $a as $typ + $b as $typ } 21 | } 22 | 23 | macro_rules! some_macro { 24 | ($var: ident) => { 25 | $var = $var + 1; 26 | 27 | }; 28 | } 29 | fn main(){ 30 | /* 31 | println!("Please enter a floating point number"); 32 | let some_input_0 = input!(f32); 33 | */ 34 | 35 | 36 | // println!("{}", add_as!(15,2.3,f32)); 37 | let mut x = 4; 38 | some_macro!(x); 39 | 40 | } 41 | */ 42 | 43 | macro_rules! create_function { 44 | ($func_name:ident, $input: ident, $type_input: ty, $type_output: ty) => { 45 | 46 | fn $func_name($input:$type_input) -> $type_output { 47 | println!("You called {:?}() with the input of {:?}", stringify!($func_name), stringify!($input1)); 48 | $input 49 | } 50 | 51 | }; 52 | } 53 | 54 | create_function!(f1,x,i32, i32); 55 | fn main() { 56 | //f1(15); 57 | let y = f1(15); 58 | } -------------------------------------------------------------------------------- /10 - Advance Techniques/3 - Repeating Patterns.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------------- 2 | // Declarative Macros 3 | // - Repeating Patterns 4 | // ------------------------------------------------- 5 | 6 | 7 | macro_rules! string_concat { 8 | /* 9 | () => { 10 | String::new(); 11 | }; 12 | 13 | ($some_str: expr) => {{ 14 | let mut temp_str = String::new(); 15 | temp_str.push_str($some_str); 16 | temp_str 17 | } 18 | }; 19 | 20 | ($some_s1: expr, $some_s2:expr) => {{ 21 | let mut temp_str = String::new(); 22 | temp_str.push_str($some_s1); 23 | temp_str.push_str($some_s2); 24 | 25 | temp_str 26 | } 27 | }; 28 | 29 | */ 30 | 31 | ($($some_str:expr,) *) => {{ 32 | let mut temp_str = String::new(); 33 | $(temp_str.push_str($some_str);)* 34 | temp_str 35 | } 36 | }; 37 | 38 | 39 | } 40 | 41 | macro_rules! vec_mac { 42 | ( $($element: expr),*) => {{ 43 | let mut some_vec = Vec::new(); 44 | $(some_vec.push($element);)* 45 | some_vec 46 | } 47 | }; 48 | } 49 | fn main(){ 50 | let str_null = string_concat!(); 51 | let str_single = string_concat!("First",); 52 | 53 | let str_double = string_concat!("First","Second",); 54 | 55 | let string_vec = vec_mac!("Nouman", "Azam"); 56 | } -------------------------------------------------------------------------------- /10 - Advance Techniques/5 - as_ref and Partial move in option.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------------- 2 | // Partial move in option and result 3 | // ------------------------------------------------- 4 | 5 | /* 6 | fn main() { 7 | let some_option =Some("Alice".to_owned()); 8 | 9 | // match some_option { 10 | match &some_option { // an implication is that we &option 11 | Some(inner_value)=> println!("Name is {}", inner_value), 12 | 13 | 14 | // Some(ref inner_value)=> println!("Name is {}", inner_value), 15 | None => println!("No name provided"), 16 | } 17 | println!("{:?}", some_option); 18 | } 19 | */ 20 | 21 | 22 | 23 | fn try_me (option_name: Option<&String>) { 24 | match option_name { 25 | Some(inner_value) => println!("Name is {} ", inner_value), 26 | None => println! ("No name provided"), 27 | } 28 | } 29 | 30 | fn main(){ 31 | let some_option = Some("Alice".to_owned()); 32 | 33 | let some_1 = &some_option; 34 | let some_2 = some_option.as_ref(); 35 | 36 | 37 | //try_me(&some_option); // issue with this one 38 | try_me(some_option.as_ref()); 39 | println!("{:?}", some_option); 40 | } 41 | 42 | -------------------------------------------------------------------------------- /10 - Advance Techniques/6 - Take, replace and swap for Avoiding Allocations.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // - Avoiding Allocations 3 | // ------------------------------------------- 4 | 5 | 6 | use std::mem; 7 | /* 8 | #[derive(Debug)] 9 | enum Customer { 10 | new { name: String }, 11 | loyal { name: String }, 12 | rich { name: String }, 13 | } 14 | 15 | fn promote(user: &mut Customer) { 16 | use Customer::*; 17 | 18 | *user = match user { 19 | //Customer::new { name } => Customer::loyal { name: name.clone() }, 20 | Customer::new { name } => Customer::loyal {name: mem::take(name)}, 21 | //Customer::new { name } => Customer::loyal {name: mem::replace(name, String::new())}, 22 | 23 | //Customer::loyal { name } => Customer::rich { name: name.clone() }, 24 | Customer::loyal { name } => Customer::rich {name: mem::take(name)}, 25 | //Customer::loyal { name } => Customer::rich {name: mem::replace(name, String::new())}, 26 | 27 | Customer::rich { name } => return, 28 | } 29 | } 30 | 31 | fn main() { 32 | let mut customer_1 = Customer::new { name: "micheal".to_string() }; 33 | 34 | promote(&mut customer_1); 35 | 36 | println!("Cutomer 1 {:?}", customer_1); 37 | } 38 | 39 | */ 40 | 41 | 42 | use std::mem::swap; 43 | fn main() { 44 | let mut s1 = "Nouman".to_string(); 45 | let mut s2 = "Azam".to_string(); 46 | 47 | //Swapping of variables 48 | let temp = s1; 49 | s1 = s2; 50 | s2 = temp; 51 | println!("s1: {:?} s2: {:?}",s1,s2); 52 | 53 | 54 | //The idiomatic way is the one given below 55 | swap(&mut s1, &mut s2); 56 | println!("s1: {:?} s2: {:?}",s1,s2); 57 | } 58 | 59 | -------------------------------------------------------------------------------- /11 - Real Life Application/1 - Search Results using Word Groupings.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Correct Search Results Using Word Grouping 3 | // - Description 4 | // - Given a list of words, group the words that are anagrams 5 | 6 | // - Tools 7 | // - Hashmaps, Nested Loops 8 | // ------------------------------------------- 9 | 10 | use std::collections::HashMap; 11 | fn word_grouping(words_list: Vec) -> Vec> 12 | { 13 | let mut word_hash = HashMap::new(); 14 | let mut char_freq = vec![0; 26]; 15 | 16 | for current_word in words_list { 17 | for c in current_word.to_lowercase().chars() { 18 | 19 | char_freq[(c as u32 - 'a' as u32) as usize] += 1; 20 | } 21 | 22 | let key: String = char_freq.into_iter().map(|i| i.to_string()).collect::(); 23 | word_hash.entry(key).or_insert(Vec::new()).push(current_word); 24 | 25 | char_freq=vec![0;26]; 26 | } 27 | 28 | // Just for hte sake of output and confirming the (key, value) pairs 29 | for (key,value) in &word_hash{ 30 | println!("key # {:?} value {:?}",key,value); 31 | } 32 | 33 | 34 | word_hash.into_iter().map(|(_, v)| v).collect() 35 | 36 | } 37 | 38 | fn main() { 39 | let words = vec!["The".to_string(),"teh".to_string(), 40 | "het".to_string(),"stupid".to_string(),"studpi".to_string(),"apple".to_string(), 41 | "appel".to_string()]; 42 | 43 | 44 | let grouping = word_grouping(words); 45 | println!("{:?}\n\n\n", grouping); 46 | 47 | let input_word = String::from("teh"); 48 | 49 | for i in grouping.into_iter() { 50 | if i.contains(&input_word) 51 | { 52 | println!("The group of the word is {:?}", i); 53 | } 54 | 55 | } 56 | 57 | } -------------------------------------------------------------------------------- /11 - Real Life Application/2 - Product Popularity .txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | // ------------------------------------------- 4 | // Popularity Scores 5 | // - Description 6 | // - Given some products along with its respectively popularity scores, 7 | // We want to determine if the popularity is fulctuating, increasing or decreasing 8 | 9 | // - Tools 10 | // - Hashmaps, Loops, conditional if 11 | // ------------------------------------------- 12 | 13 | fn popularity_analysis(scores: Vec) -> bool 14 | { 15 | let mut increasing = true; 16 | let mut decreasing = true; 17 | 18 | for i in 0..scores.len()-1 { 19 | if scores[i] > scores[i+1] 20 | { 21 | increasing = false; 22 | } 23 | if scores[i] < scores[i+1] 24 | { 25 | decreasing = false; 26 | } 27 | } 28 | return increasing || decreasing; 29 | } 30 | 31 | use std::collections::HashMap; 32 | 33 | fn main() { 34 | let mut products = HashMap::new(); 35 | 36 | products.insert("Product 1", vec![1,2,2,3]); 37 | products.insert("Product 2", vec![4,5,6,3,4]); 38 | products.insert("Product 3",vec![8,8,7,6,5,4,4,1] ); 39 | 40 | for (product_id, popularity) in products { 41 | if popularity_analysis(popularity) { 42 | println!("{} popularity is increasing or decreasing", product_id); 43 | } 44 | else{ 45 | println!("{} popularity is Fluctuating", product_id); 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /11 - Real Life Application/3 - Maximum Product Earning.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Highest Price Stock 3 | // - Description 4 | // - We have weekwise stock prices. we want to retrieve the highest 5 | // stock price in any in any week in little to no time. 6 | // 7 | // - Tools 8 | // - Maxstacks, Structures, Vectors 9 | // ------------------------------------------- 10 | 11 | 12 | 13 | 14 | struct MaxStack{ 15 | main_stack: Vec, 16 | maximum_stack: Vec 17 | } 18 | impl MaxStack { 19 | fn new() -> Self { 20 | MaxStack { 21 | main_stack: Vec::new(), 22 | maximum_stack: Vec::new(), 23 | } 24 | } 25 | 26 | 27 | fn push(&mut self,value: i32){ 28 | self.main_stack.push(value); 29 | if !self.maximum_stack.is_empty() && self.maximum_stack.last().unwrap() > &value { 30 | self.maximum_stack.push(*self.maximum_stack.last().unwrap()); 31 | } 32 | else { 33 | self.maximum_stack.push(value); 34 | } 35 | } 36 | fn pop(&mut self) { 37 | self.main_stack.pop(); 38 | self.maximum_stack.pop(); 39 | } 40 | 41 | 42 | fn max_value(&self) -> i32 { 43 | *self.maximum_stack.last().unwrap() 44 | } 45 | 46 | } 47 | 48 | 49 | 50 | fn main() { 51 | 52 | let mut stack = MaxStack::new(); 53 | stack.push(55); 54 | stack.push(80); 55 | stack.push(120); 56 | stack.push(99); 57 | stack.push(22); 58 | stack.push(140); 59 | stack.push(145); 60 | 61 | print!("Maximum value of stock: "); 62 | println!("{:}",stack.max_value()); 63 | 64 | 65 | println!("After going one week back"); 66 | print!("Maximum value of stock: "); 67 | stack.pop(); 68 | 69 | println!("{:}",stack.max_value()); 70 | 71 | } 72 | -------------------------------------------------------------------------------- /11 - Real Life Application/3 - Product Maximum Earning.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Highest Price Stock 3 | // - Description 4 | // - We have weekwise stock prices. we want to retrieve the highest 5 | // stock price in any in any week in little to no time. 6 | // 7 | // - Tools 8 | // - Maxstacks, Structures, Vectors 9 | // ------------------------------------------- 10 | 11 | 12 | 13 | 14 | struct MaxStack{ 15 | main_stack: Vec, 16 | maximum_stack: Vec 17 | } 18 | impl MaxStack { 19 | fn new() -> Self { 20 | MaxStack { 21 | main_stack: Vec::new(), 22 | maximum_stack: Vec::new(), 23 | } 24 | } 25 | 26 | 27 | fn push(&mut self,value: i32){ 28 | self.main_stack.push(value); 29 | if !self.maximum_stack.is_empty() && self.maximum_stack.last().unwrap() > &value { 30 | self.maximum_stack.push(*self.maximum_stack.last().unwrap()); 31 | } 32 | else { 33 | self.maximum_stack.push(value); 34 | } 35 | } 36 | fn pop(&mut self) { 37 | self.main_stack.pop(); 38 | self.maximum_stack.pop(); 39 | } 40 | 41 | 42 | fn max_value(&self) -> i32 { 43 | *self.maximum_stack.last().unwrap() 44 | } 45 | 46 | } 47 | 48 | 49 | 50 | fn main() { 51 | 52 | let mut stack = MaxStack::new(); 53 | stack.push(55); 54 | stack.push(80); 55 | stack.push(120); 56 | stack.push(99); 57 | stack.push(22); 58 | stack.push(140); 59 | stack.push(145); 60 | 61 | print!("Maximum value of stock: "); 62 | println!("{:}",stack.max_value()); 63 | 64 | 65 | println!("After going one week back"); 66 | print!("Maximum value of stock: "); 67 | stack.pop(); 68 | 69 | println!("{:}",stack.max_value()); 70 | 71 | } 72 | -------------------------------------------------------------------------------- /11 - Real Life Application/6 - Suggesting Items for Special Shopping Card .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Suggesting Items for Special Shopping Card 3 | // - Description 4 | // - Given a list of prices, return a couple of items with their sum matching the given price 5 | // - Tools 6 | // - Hashsets, Vectors 7 | // ------------------------------------------- 8 | 9 | use std::collections::HashSet; 10 | fn product_suggestions(product_prices:Vec, amount:i32) -> Vec>{ 11 | let mut prices_hash = HashSet::new(); 12 | let mut offers = Vec::new(); 13 | 14 | //ec![11, 30, 55, 34, 45, 10, 19, 20, 60, 5, 23]; 15 | for i in product_prices { 16 | let diff = amount-i; 17 | if prices_hash.get(&diff).is_none() { 18 | prices_hash.insert(i); 19 | } else { 20 | offers.push(vec![i, diff]); 21 | } 22 | 23 | } 24 | 25 | offers 26 | } 27 | 28 | 29 | 30 | 31 | // Driver code 32 | fn main(){ 33 | let product =vec![11, 30, 55, 34, 45, 10, 19, 20, 60, 5, 23]; 34 | 35 | let suggestions = product_suggestions(product, 50); 36 | println!("{:?}",suggestions); 37 | //return 0; 38 | } -------------------------------------------------------------------------------- /12 - Deep Dive into Traits/10 - Some useful traits on structs.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------------- 2 | // Some Useful Traits 3 | // ------------------------------------------------- 4 | use std::cmp::Ordering; 5 | 6 | //#[derive( PartialOrd, PartialEq, Clone)] 7 | #[derive( Clone)] 8 | struct Person { 9 | name: String, 10 | age: u8, 11 | earning: u32, 12 | savings: u32, 13 | } 14 | 15 | 16 | impl PartialEq for Person { 17 | fn eq(&self, other: &Self) -> bool { 18 | self.age == other.age 19 | } 20 | } 21 | 22 | 23 | 24 | impl PartialOrd for Person { 25 | fn partial_cmp(&self, other: &Self) -> Option { 26 | self.earning.partial_cmp(&other.earning) 27 | } 28 | } 29 | 30 | 31 | fn main() { 32 | let bob = Person { 33 | name: "bob".to_owned(), 34 | age: 30, 35 | earning: 30_000, 36 | savings: 50_000, 37 | }; 38 | 39 | 40 | let mut bob_clone = bob.clone(); 41 | 42 | bob_clone.age = 15; 43 | bob_clone.name = "eve".to_owned(); 44 | bob_clone.earning = 40_000; 45 | //bob_clone.savings = 60_000; 46 | 47 | println!("{}", bob == bob_clone); 48 | println!("{}",bob >= bob_clone); 49 | println!("{}",bob <= bob_clone); 50 | 51 | 52 | let alice = Person { 53 | name: "Bob".to_owned(), 54 | age: 25, 55 | earning: 30_000, 56 | savings: 40_000, 57 | 58 | }; 59 | 60 | println!(" {}", alice > bob); 61 | } 62 | 63 | -------------------------------------------------------------------------------- /12 - Deep Dive into Traits/11 - Trait Bounds.txt: -------------------------------------------------------------------------------- 1 | 2 | // ------------------------------------------------- 3 | // - Trait Bounds 4 | // ---------------------------------------------- 5 | 6 | 7 | 8 | fn quadruple(x: i32) -> i32 { 9 | // fn quadruple(x: T) -> T { 10 | // fn quadruple(x: T) -> T { 11 | x.double().double() 12 | } 13 | 14 | trait Double { 15 | fn double(&self) -> Self; 16 | } 17 | impl Double for i32 { 18 | fn double(&self) -> Self { 19 | self * 2 20 | } 21 | } 22 | 23 | // 2.0 24 | /* 25 | impl Double for i64 { 26 | fn double(&self) -> Self { 27 | self * 2 28 | } 29 | } 30 | */ 31 | 32 | fn main() { 33 | println!("quadruple 5_i32 == {}", quadruple(5_i64)); 34 | } 35 | -------------------------------------------------------------------------------- /12 - Deep Dive into Traits/12 - Associated Type.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------------- 2 | // Associated Types 3 | // ------------------------------------------------- 4 | 5 | #[derive(Debug)] 6 | struct Kmh { 7 | value: u32, 8 | } 9 | 10 | #[derive(Debug)] 11 | struct Km { 12 | value: u32, 13 | } 14 | 15 | 16 | #[derive(Debug)] 17 | struct Mph { 18 | value: u32, 19 | } 20 | #[derive(Debug)] 21 | struct Miles { 22 | value: u32, 23 | } 24 | 25 | 26 | impl Kmh { 27 | fn distance_in_three_hours(&self) -> Km { 28 | Km { 29 | value: self.value * 3, 30 | } 31 | } 32 | } 33 | 34 | impl Mph { 35 | fn distance_in_three_hours(&self) -> Miles { 36 | Miles { 37 | value: self.value * 3, 38 | } 39 | } 40 | } 41 | 42 | 43 | 44 | 45 | /* 46 | trait DistanceThreeHours { 47 | type Distance; 48 | fn distance_in_three_hours(&self) -> Self::Distance; 49 | } 50 | 51 | impl DistanceThreeHours for Kmh { 52 | type Distance = Km; 53 | fn distance_in_three_hours(&self) -> Self::Distance{ 54 | Self::Distance { 55 | value: self.value * 3, 56 | } 57 | } 58 | } 59 | 60 | impl DistanceThreeHours for Mph { 61 | type Distance = Miles; 62 | fn distance_in_three_hours(&self) -> Self::Distance { 63 | Self::Distance { 64 | value: self.value * 3, 65 | } 66 | } 67 | } 68 | */ 69 | 70 | fn main() { 71 | let speed = Kmh { value: 90 }; 72 | let distance = speed.distance_in_three_hours(); 73 | println!("At {:?}, you will travel {:?} in 3 hours", speed, distance); 74 | 75 | let speed_mph = Mph { value: 90 }; 76 | let distance_miles = speed_mph.distance_in_three_hours(); 77 | println!("At {:?}, you will travel {:?} in 3 hours",speed_mph, distance_miles); 78 | } 79 | -------------------------------------------------------------------------------- /13 - Efficient Programming with Rust/1 - Initializing stuct instances .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Initializing Struct Instance 3 | // ------------------------------------------- 4 | use project::Student; 5 | fn main() { 6 | /* 7 | let new_student = Student { 8 | id: 11, 9 | name: "joseph".to_string(), 10 | age: 20, 11 | }; 12 | */ 13 | 14 | 15 | 16 | 17 | let new_student = Student::new("joseph".to_string()) 18 | .unwrap_or_default(); // next example, make sure to remove semicolon from the statement above 19 | 20 | println!("{:?}", new_student); 21 | 22 | 23 | 24 | let new_student = Student::default(); 25 | println!("{:?}", new_student); 26 | 27 | let new_student = Student { 28 | age: 12, 29 | .. Default::default() 30 | }; 31 | } 32 | 33 | 34 | 35 | // code for library 36 | #[derive(Debug, Default)] 37 | pub struct Student { 38 | pub id: u8, 39 | 40 | pub name: String, 41 | pub age: u8, 42 | } 43 | 44 | impl Student { 45 | /* 46 | pub fn new(std_name: String) -> Self { 47 | Self { 48 | id: 0, 49 | name: std_name, 50 | age: 20, 51 | } 52 | } 53 | */ 54 | 55 | 56 | pub fn new(std_name: String) -> Result { 57 | if std_name.chars().all(|x| matches!(x, 'a'..='z')) { 58 | Ok(Self { 59 | id: 0, 60 | name: std_name, 61 | age: 20, 62 | }) 63 | } else { 64 | Err("The name is invalid".to_string()) 65 | } 66 | } 67 | } 68 | 69 | /* 70 | impl Default for Student { 71 | fn default() -> Self { 72 | Self { 73 | id: 0, 74 | name: "unknown".to_string(), 75 | age: 20, 76 | } 77 | } 78 | } 79 | 80 | */ 81 | 82 | -------------------------------------------------------------------------------- /13 - Efficient Programming with Rust/2 - Fucntion inputs and coercion.txt: -------------------------------------------------------------------------------- 1 | 2 | // ------------------------------------------- 3 | // Fucntion Inputs and Coercion 4 | // ------------------------------------------- 5 | 6 | // Example 1 7 | /* 8 | 9 | fn vowels(word: &String) -> u8 { 10 | //fn vowels(word: &str) -> u8 { 11 | 12 | 13 | let vowels_count = word_chars. 14 | into_iter(). 15 | filter(|x| (*x == 'a') |(*x == 'e') |(*x == 'i')|(*x == 'o') | (*x == 'u')).count(); 16 | vowels_count as u8 17 | } 18 | 19 | fn main() { 20 | let affan = "affan".to_string(); 21 | println!("{}: {:?}", affan, vowels(&affan)); 22 | 23 | 24 | println!("Ferris: {}", vowels("Ferris")); 25 | 26 | } 27 | 28 | */ 29 | 30 | 31 | // Example 2: &T over &Box becuase it is being coerced to that type 32 | 33 | /* 34 | //fn length_str(x: &Box<&str>) { 35 | fn length_str(x: &str) { 36 | println!("length of the string {} is {} ",x, x.len()); 37 | } 38 | 39 | 40 | fn main() { 41 | length_str("hello rust"); 42 | let box_str = Box::new("Hello"); 43 | length_str(&box_str); 44 | } 45 | 46 | */ 47 | 48 | 49 | 50 | // Example 3: &[T] over &Vec 51 | //fn square_values(num_vec: &Vec) { 52 | fn square_values(num_vec: &[i32]) { 53 | for i in num_vec{ 54 | println!("The square is {}", i*i); 55 | } 56 | } 57 | 58 | fn main() { 59 | let values_vec = vec![1,2,3,6,5]; 60 | let values_array = [1,2,3,4,5,6]; 61 | 62 | square_values(&values_vec); 63 | square_values(&values_array); 64 | } 65 | -------------------------------------------------------------------------------- /13 - Efficient Programming with Rust/4 - Disabling Mutability for finalized objects.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // - Disabling mutability for finalized objects 3 | // ------------------------------------------- 4 | 5 | /* 6 | fn main() { 7 | 8 | // Method 1: using variable rebinding 9 | let mut data = vec![5,6,9,4,3]; 10 | data.sort(); 11 | let data = data; 12 | 13 | 14 | // method 2: using code block 15 | let data = { 16 | let mut data = vec![5,6,9,4 ,3]; 17 | data.sort(); 18 | data 19 | }; 20 | 21 | } 22 | */ 23 | 24 | 25 | // Example 2: Here's a pattern for disabling mutability for "finalized" objects, even in mutable owned copies of a thing, preventing misuse. Done by wrapping it in a newtype with a private 26 | // inner value that implements Deref but not DerefMut: 27 | 28 | #[derive(Debug, Clone)] 29 | pub struct finalized_config(T); 30 | 31 | impl Copy for finalized_config where T: Copy {} 32 | 33 | impl std::ops::Deref for finalized_config { 34 | type Target = T; 35 | 36 | fn deref(&self) -> &T { 37 | &self.0 38 | } 39 | } 40 | 41 | #[derive(Default)] 42 | struct Config { 43 | a: usize, 44 | b: String, 45 | } 46 | 47 | impl Config { 48 | fn new() -> Self { 49 | Self { a: 0, b: String::from("Hello") } 50 | } 51 | 52 | fn build(self) -> finalized_config { 53 | finalized_config(self) 54 | } 55 | } 56 | 57 | 58 | 59 | fn main() { 60 | let mut my_configuration = Config::new(); 61 | my_configuration.a = 6; 62 | 63 | let finalized = my_configuration.build(); 64 | 65 | let mut finalized_copy = finalized; 66 | //finalized_copy.a = 666; 67 | } 68 | 69 | -------------------------------------------------------------------------------- /13 - Efficient Programming with Rust/5 - String Concatenation and Ownership.txt: -------------------------------------------------------------------------------- 1 | fn main() 2 | { 3 | // ------------------------------------------- 4 | // String concatenation and onwership 5 | // ------------------------------------------- 6 | 7 | /* let s1 = String::from("hello"); 8 | let s2: &str = "world"; 9 | 10 | let s3 = s1 + s2; // the ownership changed here 11 | println!("{}", s3); 12 | */ 13 | 14 | /* let s1 = String::from("hello"); 15 | let s2 = String::from("world"); 16 | 17 | let s3 = s1 + &s2; // The ownership of only owned_string1 changed 18 | println!("{} {} ", s3 , s2); 19 | */ 20 | 21 | let s1 = String::from("hello"); 22 | let s2 = String::from("world"); 23 | let s3 = String::from(" from Rust"); 24 | 25 | let s4 = s1 + &s2 + &s3; // The ownership of only s1 changed 26 | println!("{} {} {}", s4,s2,s3); 27 | 28 | } 29 | 30 | -------------------------------------------------------------------------------- /13 - Efficient Programming with Rust/6 - Simplifying Sturctures.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // - Simplifying structures 3 | // ------------------------------------------- 4 | 5 | 6 | struct A { 7 | f1: u32, 8 | f2: u32, 9 | f3: u32, 10 | } 11 | 12 | fn fn1(a: &mut A) -> &u32 { &a.f2 } 13 | fn fn2(a: &mut A) -> u32 { a.f1 + a.f3 } 14 | 15 | fn fn3(a: &mut A) { 16 | let x = fn1(a); 17 | let y = fn2(a); 18 | println!("{}", x); 19 | } 20 | 21 | struct A { 22 | b: B, 23 | c: C, 24 | } 25 | struct B { 26 | f2: u32, 27 | } 28 | struct C { 29 | f1: u32, 30 | f3: u32, 31 | } 32 | 33 | // These functions take a B or C, rather than A. 34 | fn fn1(b: &mut B) -> &u32 { &b.f2 } 35 | fn fn2(c: &mut C) -> u32 { c.f1 + c.f3 } 36 | 37 | fn fn3(a: &mut A) { 38 | let x = fn1(&mut a.b); 39 | let y = fn2(&mut a.c); 40 | println!("{}", x); 41 | } 42 | 43 | fn main() {} 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /13 - Efficient Programming with Rust/8 - todo Macro .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // - ToDo Macro 3 | // ------------------------------------------- 4 | #[derive(Default)] 5 | struct Student { 6 | name_std: String, 7 | age: u8, 8 | sex: char, 9 | country: String, 10 | salary: u32, 11 | nationality: String, 12 | } 13 | 14 | impl Student { 15 | fn some_fn_1(&self) -> String { 16 | // todo!() 17 | "".to_string() 18 | } 19 | 20 | fn some_fn_2(&self) -> u8 { 21 | todo!() 22 | } 23 | } 24 | trait GeneralInfo { 25 | fn info(&self) -> (&str, u8,char); 26 | fn country_info(&self) -> &str; 27 | } 28 | 29 | fn main(){ 30 | let student_1 = Student::default(); 31 | student_1.some_fn_1(); 32 | } -------------------------------------------------------------------------------- /13 - Efficient Programming with Rust/9 - String Literals.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // - String Literal 3 | // ------------------------------------------- 4 | fn main() { 5 | let str = r"The main said _Hello world_ \n \t ' "; 6 | println!("{}", str); 7 | 8 | let jason_str = "{ 9 | \" name \": \"Micheal\", 10 | \"age\": 40, 11 | \"sex\": Male 12 | }"; 13 | 14 | let jason_str1 = r#"{ 15 | " name ": "Micheal", 16 | "age": 40, 17 | "sex": Male 18 | }"#; 19 | 20 | let str = r###"Hello"## World!"###; 21 | 22 | 23 | // Exercise for you 24 | 25 | let string1 = r#"""#; // " 26 | let string2 = r#""""""""#; // """""" 27 | let string3 = r#" He asked,"Is rust awesome?"""#; // He asked,"Is rust awesome?" 28 | println!("{}", string1); 29 | println!("{}", string2); 30 | println!("{}", string3); 31 | } -------------------------------------------------------------------------------- /14 - Concurrency in RUST/1 - Thread basics.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Threads Basics 3 | // ------------------------------------------- 4 | use std::thread; 5 | use std::time::Duration; 6 | 7 | fn main() { 8 | println!("This will be printed"); 9 | println!("This will also be printed"); 10 | println!("The concurrency will start after this line"); 11 | 12 | let t = thread::spawn(|| { 13 | println!("Hello 1 from the thread"); 14 | println!("Hello 2 from the thread"); 15 | println!("Hello 3 from the thread"); 16 | println!("Hello 4 from the thread"); 17 | println!("Hello 5 from the thread"); 18 | println!("Hello 6 from the thread"); 19 | println!("Hello 7 from the thread"); 20 | }); 21 | 22 | 23 | thread::sleep(Duration::from_millis(1)); 24 | println!("Hello 1 from the main"); 25 | println!("Hello 2 from the main"); 26 | t.join(); 27 | } -------------------------------------------------------------------------------- /14 - Concurrency in RUST/10 - Thread Parking and Yield.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Thread Park 3 | // ------------------------------------------- 4 | 5 | use std::thread; 6 | use std::time::Duration; 7 | fn main() { 8 | let job_1 = thread::spawn(|| { 9 | println!("-- Job 1 has started -- "); 10 | println!("Waiting for job 2 to complete"); 11 | //thread::park_timeout(Duration::from_secs(2)); 12 | //thread::sleep(Duration::from_secs(2)); 13 | thread::yield_now(); 14 | 15 | println!("-- Job 1 resumed --"); 16 | println!("-- Job 1 finished"); 17 | }); 18 | 19 | let job_2 = thread::spawn(|| { 20 | println!("-- Job 2 started --"); 21 | println!(" -- Job 2 finished --"); 22 | }); 23 | job_2.join().unwrap(); 24 | println!("Job 2 is now completed"); 25 | println!("Job 1 will now resume"); 26 | job_1.thread().unpark(); 27 | job_1.join().unwrap(); 28 | } 29 | -------------------------------------------------------------------------------- /14 - Concurrency in RUST/11 - Async-Await.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Async Await basics 3 | // tokio = {version = "1.17", features = ["full"]} 4 | // ------------------------------------------- 5 | 6 | async fn printing(){ 7 | println!("I am async function"); 8 | } 9 | 10 | #[tokio::main] 11 | async fn main(){ 12 | let x = printing(); 13 | println!("The has not being polled yet"); 14 | drop(x); 15 | //x.await; 16 | 17 | } -------------------------------------------------------------------------------- /14 - Concurrency in RUST/2 - Multiple Threads and Ownership in Threads .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Multiple Threads 3 | // Ownership and Threads 4 | // ------------------------------------------- 5 | 6 | use std::thread; 7 | fn main(){ 8 | 9 | /* 10 | let mut thread_vec = vec![]; 11 | for i in 0..10 { 12 | thread_vec.push(thread::spawn(move || { 13 | println!("Thread number {}", i); 14 | })); 15 | } 16 | 17 | for i in thread_vec { 18 | i.join(); 19 | } 20 | */ 21 | 22 | let v = vec![1,2,3]; 23 | let x = 5; 24 | let handle = thread::spawn(move || { 25 | println!("Here's a vector: {:?}", v); 26 | println!("Here's a variable : {:?}", x); 27 | }); 28 | 29 | drop(x); 30 | println!("The variable x is still alive {}", x) ; 31 | println!("The variable v is not alive {}", v) ; 32 | handle.join(); 33 | } 34 | -------------------------------------------------------------------------------- /14 - Concurrency in RUST/3 - Communication through channels.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Message Passing through Channels 3 | // ------------------------------------------- 4 | use std::thread; 5 | use std::sync::mpsc; 6 | fn main(){ 7 | let (tx, rx) = mpsc::channel(); 8 | 9 | // let rx1 = rx; 10 | 11 | let t = thread::spawn(move || { 12 | let val = String::from("some data from sender"); 13 | println!("Value sending from the thread"); 14 | tx.send(val).unwrap(); 15 | // println!("This may execute after the statement in the main"); 16 | // println!("Val is {:?}", val); 17 | }); 18 | 19 | //let recieved = rx.recv().unwrap(); 20 | //println!("Recieved: {:?}", recieved); 21 | 22 | t.join(); 23 | let mut recieved_status = false; 24 | while recieved_status != true { 25 | match rx.try_recv() { 26 | Ok(recieved_value) => { 27 | println!("Recieved value is {:?}", recieved_value); 28 | recieved_status = true; 29 | }, 30 | Err(_) => println!("I am doing some other stuff"), 31 | } 32 | } 33 | 34 | } -------------------------------------------------------------------------------- /14 - Concurrency in RUST/5 - Sharing States .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Sharing States 3 | // ------------------------------------------- 4 | use std::sync::Mutex; 5 | fn main() { 6 | let m = Mutex::new(5); 7 | 8 | /* 9 | { 10 | let mut num = m.lock().unwrap(); 11 | *num = 10; 12 | } 13 | 14 | println!("m = {:?}", m); 15 | */ 16 | 17 | let mut num = m.lock().unwrap(); 18 | *num = 10; 19 | drop(num); 20 | 21 | let mut num1 = m.lock().unwrap(); 22 | *num1 = 15; 23 | drop(num1); 24 | 25 | } -------------------------------------------------------------------------------- /14 - Concurrency in RUST/6 - Passing Mutexes between Threads.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Passes Mutexes betwen Threads 3 | // ------------------------------------------- 4 | 5 | /* 6 | use std::sync::Mutex; 7 | use std::thread; 8 | //use std::rc::Rc; 9 | //use std::sync::Arc; // add later on 10 | 11 | fn main() { 12 | let counter = Mutex::new(0); 13 | //let counter = Rc::new(Mutex::new(0)); 14 | //let counter = Arc::new(Mutex::new(0)); 15 | 16 | let mut handles = vec![]; 17 | 18 | for _ in 0..10 { 19 | //let counter = Rc::clone(&counter); 20 | //let counter = Arc::clone(&counter); 21 | let handle = thread::spawn(move || { 22 | let mut num = counter.lock().unwrap(); 23 | 24 | *num += 1; 25 | }); 26 | handles.push(handle); 27 | } 28 | 29 | for handle in handles { 30 | handle.join().unwrap(); 31 | } 32 | 33 | println!("Result: {}", *counter.lock().unwrap()); 34 | } 35 | */ 36 | 37 | 38 | 39 | // Example 2: A nice usecase of the Arc for cloning types which are not clone (does not implement clone) 40 | 41 | use std::thread; 42 | use std::sync::Arc; 43 | 44 | struct MyString(String); 45 | 46 | impl MyString { 47 | fn new(s: &str) -> MyString { 48 | MyString(s.to_string()) 49 | } 50 | } 51 | 52 | fn main() { 53 | let mut threads = Vec::new(); 54 | let name = Arc::new(MyString::new("Rust")); 55 | 56 | for i in 0..5 { 57 | let some_str = name.clone(); 58 | let t = thread::spawn(move || { 59 | println!("hello {} count {}", some_str.0, i); 60 | }); 61 | threads.push(t); 62 | } 63 | 64 | for t in threads { 65 | t.join(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /14 - Concurrency in RUST/9 - Scoped Threads.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Scope Threads 3 | // ------------------------------------------- 4 | 5 | use std::thread; 6 | 7 | fn main() { 8 | let mut vec = vec![1, 2, 3]; 9 | let mut x = 0; 10 | 11 | thread::scope(|some_scope| { 12 | some_scope.spawn(|| { 13 | println!("I am first thread in the scope"); 14 | println!("{:?}", vec); 15 | }); 16 | 17 | some_scope.spawn(|| { 18 | println!("I am second thread in the scope"); 19 | x += 45; 20 | // vec.push(4); 21 | println!("{:?}", vec); 22 | }); 23 | }); 24 | 25 | println!("The threads are now complete"); 26 | vec.push(5); 27 | println!("x: {:?} and vec: {:?}", x, vec); 28 | } 29 | -------------------------------------------------------------------------------- /15 - Text Processing, File and directory handlign/1 - Basic File Handling.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Basic File Handling 3 | // ------------------------------------------- 4 | use std::fs::*; 5 | use std::io::{BufRead, BufReader, Read, Write}; 6 | use std::path::Path; 7 | 8 | fn basic_file_handling() -> std::io::Result<()> { 9 | let path_loc = r"D:\my_text.txt"; 10 | let path = Path::new(path_loc); 11 | // let mut file = File::create(path)?; 12 | 13 | //file.write(b"let's put this in the file")?; 14 | // file.write("let's put this in the file".as_bytes())?; 15 | 16 | 17 | // let mut file = OpenOptions::new().append(true).open(path)?; 18 | // file.write("\n www.includehelp.com\n".as_bytes())?; 19 | 20 | // let str1 = "nouman"; 21 | // file.write(str1.as_bytes())?; 22 | 23 | 24 | // let some_vec = vec![1,2,3,4,5,6]; 25 | // let str_from_vec = some_vec 26 | // .into_iter() 27 | // .map(|a| format!("{} \n", a.to_string())) 28 | // .collect::(); 29 | 30 | // file.write(str_from_vec.as_bytes())?; 31 | 32 | // let (name, age) = ("Joseph", 40); 33 | // let formatted_str = format!("I am {} and my name is {}", name, age); 34 | // file.write(formatted_str.as_bytes())?; 35 | 36 | // let mut file = File::open(path)?; 37 | // let mut contents = String::new(); 38 | // file.read_to_string(&mut contents)?; 39 | // println!("The file contains {:?}", contents); 40 | 41 | 42 | let mut file = File::open(path)?; 43 | let file_buffer = BufReader::new(file); 44 | for lines in file_buffer.lines(){ 45 | println!("{:?}", lines?); 46 | } 47 | Ok(()) 48 | 49 | } 50 | fn main(){ 51 | basic_file_handling(); 52 | } -------------------------------------------------------------------------------- /15 - Text Processing, File and directory handlign/4 - Regexes- Repeatitions and Quantifiers.txt: -------------------------------------------------------------------------------- 1 | 2 | // ------------------------------------------- 3 | // Regexes- Repeatitions and Quantifiers 4 | // ------------------------------------------- 5 | 6 | extern crate regex; 7 | use regex::Regex; 8 | 9 | fn main(){ 10 | //let re = Regex::new(r"a?aa").unwrap(); 11 | //let text = "aa aaa"; 12 | 13 | // let re = Regex::new(r"ba?").unwrap(); 14 | // let text = "a ba b ba"; 15 | 16 | // let re = Regex::new(r"\w?\w?\w?.rs").unwrap(); 17 | // let text = "fil.rs t1.rs file.rs"; 18 | 19 | // for cap in re.captures_iter(text) { 20 | // println!("Match: {} ", &cap[0]); 21 | // } 22 | 23 | // let re = Regex::new(r"a+").unwrap(); 24 | // let text = "a aa aaa baab bab"; 25 | 26 | // let re = Regex::new(r"\w+\.gif").unwrap(); 27 | // let text = "image1.gif and background.gif"; 28 | 29 | // let re = Regex::new(r"ab*").unwrap(); 30 | // let text = "a ab abbbbb"; 31 | 32 | // for cap in re.captures_iter(text) { 33 | // println!("Match: {} ", &cap[0]); 34 | // } 35 | 36 | // let re = Regex::new(r"\b\w{3,5}\b").unwrap(); 37 | // let text = "Hello i think you are happy becuase i have a gift for you"; 38 | 39 | // let re = Regex::new(r"\b\d{1,3}\.\d{1,3}\b").unwrap(); 40 | // let text = "921.583 0.0 1456.25"; 41 | 42 | // let re = Regex::new(r"\d{3,}").unwrap(); 43 | // let text = "5321 500 5698 12"; 44 | 45 | // for cap in re.captures_iter(text) { 46 | // println!("Match: {} ", &cap[0]); 47 | // } 48 | 49 | 50 | let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap(); 51 | let text = "2012-03-14, 2013-01-01 and 2014-07-05"; 52 | 53 | for cap in re.captures_iter(text) { 54 | println!("Month: {} Day: {} Year: {}, the whole: {}", &cap[2], &cap[3], &cap[1], &cap[0]); 55 | } 56 | 57 | } -------------------------------------------------------------------------------- /16 - Sized and Unsized Types/2 - Possibly Sized Property.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // - Sized Trait 3 | // - Optionally Sized Trait 4 | // ------------------------------------------- 5 | 6 | 7 | // include as dependency in the cargo.toml file negative-impl = "0.1.4" 8 | 9 | use negative_impl::negative_impl; 10 | struct ABC; 11 | 12 | #[negative_impl] 13 | impl !Send for ABC {} 14 | 15 | #[negative_impl] 16 | impl !Sync for ABC {} 17 | 18 | // #[negative_impl] 19 | // impl !Sized for ABC {} 20 | 21 | //fn some_fn(t: T) {} 22 | //fn some_fn(t: T) {} 23 | fn some_fn(t: &T) {} 24 | 25 | 26 | fn main() { 27 | let x: i32 = Default::default(); 28 | let y = Clone::clone(&x); 29 | } 30 | 31 | 32 | 33 | // ------------------------------------------- 34 | // - ?Sized and Generic Parameters 35 | // ------------------------------------------- 36 | 37 | use std::fmt::Debug; 38 | 39 | // 1. Must have a single unsized field. 40 | // 2. The unsized field must be the last field. 41 | struct UnSizedStruct { 42 | sized_field_1: i32, 43 | unsized_field: T, 44 | } 45 | 46 | // fn print_fn(t: T) 47 | fn print_fn(t: &T) { 48 | println!("{:?}", t); 49 | } 50 | 51 | fn main() { 52 | let x = UnSizedStruct { 53 | sized_field_1: 3, 54 | unsized_field: [3], 55 | }; 56 | 57 | let x = "my name"; 58 | print_fn(&x); 59 | 60 | // /* 61 | // Parameter type T &T &T 62 | // Function call Input &str &str &&str 63 | // Resolves to T = &str T = str T = &str 64 | // */ 65 | } 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /16 - Sized and Unsized Types/4- Coercion in Unsized Types.txt: -------------------------------------------------------------------------------- 1 | 2 | // ------------------------------------------- 3 | // - Unsized Coercion 4 | // ------------------------------------------- 5 | 6 | fn str_slice_fn(s: &str) {} 7 | 8 | fn array_slice_fn(s: &[T]) {} 9 | 10 | trait Some_Trait { 11 | fn method(&self); 12 | } 13 | 14 | impl Some_Trait for [T] { 15 | fn method(&self) {} 16 | // can now call "method" on 17 | // 1) any &[T] 18 | // 2) Vec 19 | // 3) [T; N] 20 | } 21 | fn main() { 22 | let some_string = String::from("String"); 23 | str_slice_fn(&some_string); 24 | 25 | let slice: &[i32] = &[1]; 26 | let vec = vec![1]; 27 | let array = [1, 2, 3]; 28 | 29 | array_slice_fn(slice); 30 | array_slice_fn(&vec); // deref coercion 31 | array_slice_fn(&array); // Unsized coercion 32 | 33 | slice.method(); 34 | vec.method(); // deref coercion 35 | array.method(); // Unsized coercion 36 | } 37 | -------------------------------------------------------------------------------- /18 - Web Programming/1 - Web Programming (Basics).txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Web Programming Basics 3 | // ------------------------------------------- 4 | 5 | 6 | use std::net::{TcpListener, TcpStream}; 7 | use std::io::{BufReader, BufRead}; 8 | use std::io::prelude; 9 | fn main(){ 10 | let listener = TcpListener::bind("127.0.0.1:8000").unwrap(); 11 | //let stream = listener.accept(); 12 | 13 | //println!("The stream {:?} \n The socket {:?}", stream.as_ref().unwrap().1, stream.as_ref().unwrap().0); 14 | // for i in 0..10 { 15 | // match listener.accept() { 16 | // Ok((socket, addr)) => println!("The client info: {:?}", addr), 17 | // Err(e) => println!("Couldn't get cliet: {:?}", e), 18 | // } 19 | // } 20 | 21 | for stream in listener.incoming() { 22 | let stream = stream.unwrap(); 23 | handle_connection(stream); 24 | } 25 | } 26 | 27 | fn handle_connection(mut stream: TcpStream) { 28 | let buf_reader = BufReader::new(&mut stream); 29 | 30 | let http_request = buf_reader 31 | .lines() 32 | .map(|result| result.unwrap()) 33 | .take_while(|lines| !lines.is_empty()) 34 | .collect::>(); 35 | 36 | println!("Request: {:#?}", http_request); 37 | 38 | 39 | } -------------------------------------------------------------------------------- /19 - Measuring and Improving Performance/1. Benchmarking.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Benchmarking using Criterion 3 | // ------------------------------------------- 4 | 5 | // add the following to cargo.toml file 6 | /* 7 | [dev-dependencies] 8 | criterion = "0.4.0" 9 | 10 | 11 | [[bench]] 12 | name = "sorting_benchmark" 13 | harness = false 14 | */ 15 | 16 | 17 | // code for sorting_benchmark.rs file 18 | 19 | use learning_rust::{sort_algo_1, sort_algo_2}; 20 | 21 | use criterion::{criterion_group, criterion_main, Criterion}; 22 | 23 | fn sort_benchmark(c: &mut Criterion) { 24 | let mut numbers: Vec = vec![ 25 | 1, 2, 3, 6, 5, 4, 8, 52, 2, 1, 5, 4, 4, 5, 8, 54, 2, 0, 55, 5, 2, 0, 5, 5, 5, 21, 26 | ]; 27 | 28 | // This creates a benchmark 29 | c.bench_function("Sorting Algorithm", |b| { 30 | b.iter(|| sort_algo_2(&mut numbers)) 31 | }); 32 | } 33 | 34 | criterion_group!(benches, sort_benchmark); 35 | criterion_main!(benches); 36 | 37 | 38 | // Code for lib.rs 39 | pub fn sort_algo_1(arr: &mut Vec) { 40 | let mut swapped = false; 41 | for i in 0..(arr.len() - 1) { 42 | if arr[i] > arr[i + 1] { 43 | arr.swap(i, i + 1); 44 | swapped = true; 45 | } 46 | } 47 | if swapped { 48 | sort_algo_1(arr); 49 | } 50 | } 51 | 52 | 53 | 54 | pub fn sort_algo_2(arr: &mut Vec) { 55 | let len = arr.len(); 56 | for left in 0..len { 57 | let mut smallest = left; 58 | for right in (left + 1)..len { 59 | if arr[right] < arr[smallest] { 60 | smallest = right; 61 | } 62 | } 63 | arr.swap(smallest, left); 64 | } 65 | } 66 | 67 | 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /19 - Measuring and Improving Performance/2. Performance lints.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Performance Lints 3 | // ------------------------------------------- 4 | 5 | // struct A { 6 | // values: Vec, 7 | // } 8 | 9 | enum B { 10 | variant_1(i32), 11 | variant_2(Box<[i32; 10_000]>), 12 | } 13 | fn main() { 14 | // let x = Box::new(32u32); 15 | let x: Box = Box::default(); 16 | 17 | let x = String::from("Nouman"); 18 | let y = "Nouman"; 19 | if x == y { 20 | println!("Values are equal"); 21 | } 22 | 23 | let mut a = vec![1, 2, 3]; 24 | let mut b = vec![4, 5, 6]; 25 | a.extend(b.drain(..)); 26 | 27 | a.append(&mut b); 28 | 29 | let hello = "hesuo worpd" 30 | .replace("s", "l") 31 | .replace("u", "l") 32 | .replace("p", "l"); 33 | 34 | let hello = "hesuo worpd".replace(['s', 'u', 'p'], "l"); 35 | 36 | //https://github.com/rust-lang/rust-clippy 37 | } 38 | -------------------------------------------------------------------------------- /2 - Basic Programming/8 - Practice Problems.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Programming-Master-Class-from-Beginner-to-Expert/7a219af138cce6793e3e5f1fb22bb50a4cac1b40/2 - Basic Programming/8 - Practice Problems.docx -------------------------------------------------------------------------------- /3 - Rust Ownership/1 - Ownership Rules, Premitive, and non-premitive types.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Rust Ownership 3 | // - Each value in Rust has a variable that’s called its owner. 4 | // - There can be only one owner at a time. 5 | // - When the owner goes out of scope, the value will be dropped. 6 | // ------------------------------------------- 7 | 8 | fn main() { 9 | /*let mut x = 32.6; 10 | let mut y = x; 11 | 12 | let s1 = String::from("abc"); 13 | let s2 = &s1; 14 | println!("The value of s1 = {} and s2 = {}",s1,s2); 15 | */ 16 | 17 | /* 18 | let num_vec1: Vec = vec![5,6,9,8,7]; 19 | //let num_vec2 = num_vec1; //move, Ownership change 20 | // println!("The first vector is {:?} {:?}",num_vec1,num_vec2); 21 | 22 | 23 | let num_vec2 = &num_vec1; // Referencing or borrowing 24 | println!("The first vector is {:?} {:?}",num_vec1,num_vec2); 25 | 26 | let num_vec2 = num_vec1.clone(); 27 | println!("The first vector is {:?} {:?}",num_vec1,num_vec2); 28 | */ 29 | 30 | { 31 | let my_name = String::from("Nouman Azam"); 32 | } 33 | println!("My name is {}", my_name); 34 | 35 | 36 | } 37 | 38 | -------------------------------------------------------------------------------- /3 - Rust Ownership/2 - Heap and stack .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Heap and Stack 3 | // ------------------------------------------- 4 | 5 | const MAX_VALUE:i32 = 40_000; 6 | /* 7 | fn main() { 8 | 9 | let (x,y) = (2,4); 10 | let sum_value = square_sum(x,y); 11 | println!("The value of Square of Sum = {}",sum_value); 12 | } 13 | 14 | fn square_sum(num1:i32, num2:i32) -> i32 { 15 | let result = square(num1+num2); 16 | result 17 | } 18 | 19 | fn square(num:i32) -> i32 { 20 | num * num 21 | } 22 | */ 23 | 24 | fn main() 25 | { 26 | let x: i32 = 5; 27 | 28 | let s1 = String::from("some string"); 29 | let s2 = s1; 30 | let s3 = &s2; 31 | let s4 = s2.clone(); 32 | 33 | 34 | } -------------------------------------------------------------------------------- /3 - Rust Ownership/4 - Mutable and Immutable References.txt: -------------------------------------------------------------------------------- 1 | 2 | fn main() 3 | { 4 | 5 | // ------------------------------------------- 6 | // References Rules 7 | // - One mutable reference in a scope 8 | // - Many immutable references 9 | // - Mutable and immutable can not coexist 10 | // - Scope of a reference 11 | // - Data should not change when immutable references are in scope 12 | // ------------------------------------------- 13 | 14 | /* 15 | 16 | let mut heap_num = vec![4, 5, 6]; 17 | let ref1 = &mut heap_num; 18 | let ref2 = &mut heap_num; 19 | 20 | println!("The first reference is {:?} and the second one is {:?}",ref1,ref2); 21 | 22 | 23 | let mut heap_num = vec![4, 5, 6]; 24 | let ref1 = &heap_num; 25 | let ref2 = &heap_num; 26 | println!("The first reference is {:?} and the second one is {:?}",ref1,ref2); 27 | 28 | 29 | 30 | 31 | let mut heap_num = vec![4, 5, 6]; 32 | let ref1 = &heap_num; 33 | let ref2 = &heap_num; 34 | let ref3 = &mut heap_num; 35 | println!("Immutable references are {:?} and {:?} and the mutable reference is {:?}",ref1,ref2,ref3); 36 | 37 | 38 | let mut heap_num = vec![4, 5, 6]; 39 | let ref1 = &heap_num; 40 | let ref2 = &heap_num; 41 | println!("Immutable references are {:?} and {:?}",ref1,ref2); 42 | let ref3 = &mut heap_num; 43 | */ 44 | 45 | 46 | let mut heap_num = vec![4, 5, 6]; 47 | heap_num.push(68); 48 | 49 | let ref1 = &heap_num; 50 | let ref2 = &heap_num; 51 | println!("Immutable references are {:?} and {:?}",ref1,ref2); 52 | heap_num.push(86); 53 | 54 | 55 | 56 | } 57 | 58 | 59 | -------------------------------------------------------------------------------- /3 - Rust Ownership/5 - Dereferencing (the reverse of a reference).txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Dereferencing 3 | // ------------------------------------------- 4 | fn main() { 5 | let mut some_data = 42; 6 | let ref_1 = &mut some_data; 7 | let deref_copy = *ref_1; 8 | *ref_1 = 13; 9 | println!("some_data is: {some_data}, deref_copy is: {deref_copy}"); 10 | 11 | let mut heap_data = vec![5, 6, 7]; 12 | let ref_1 = &heap_data; 13 | let ref_2 = ref_1; 14 | let ref_3 = ref_1; 15 | let deref_copy = ref_1.clone(); 16 | 17 | let move_out = ref_1; 18 | // let move_out_again = ref_1; 19 | } 20 | -------------------------------------------------------------------------------- /3 - Rust Ownership/6 - Practice Problems.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Programming-Master-Class-from-Beginner-to-Expert/7a219af138cce6793e3e5f1fb22bb50a4cac1b40/3 - Rust Ownership/6 - Practice Problems.docx -------------------------------------------------------------------------------- /4 - Control Structures/3 - Match statement .txt: -------------------------------------------------------------------------------- 1 | fn main() 2 | { 3 | // ------------------------------------------- 4 | // Match 5 | // - Simple match 6 | // - If else ladder into a match 7 | // - If let syntax style match 8 | // ------------------------------------------- 9 | /* General syntax 10 | 11 | match value { 12 | 13 | possible_value(s) => {Statements to execute}, 14 | possible_value(s) => {Statements to execute}, 15 | possible_value(s) => {Statements to execute}, 16 | 17 | _ = { default_execution_statements }, 18 | }; 19 | */ 20 | /* 21 | let some_number = 100; 22 | match some_number { 23 | 1 | 2 => println!("The number is -1"), 24 | 2 | 3 => println!("The number either 2 or 3"), // please note a single pipe here for the conditional OR 25 | 4..=100 => println!("The number is between 4 and 100 inclusive"), 26 | //_ => println!("The number is greater than 100"), 27 | } 28 | */ 29 | 30 | 31 | /* 32 | let marks = 50; 33 | let mut grade = 'N'; 34 | 35 | match marks { 36 | 90..=100 => grade = 'A', 37 | 80..=89 => grade = 'B', 38 | 70..=79 => grade = 'C', 39 | 60..=69 => grade = 'D', 40 | _ => grade = 'F', 41 | } 42 | println!("The grade achieved is {}",grade); 43 | */ 44 | 45 | 46 | /* 47 | let variable = match value { 48 | possible_value(s) = {Statements to execute}, 49 | possible_value(s) = {Statements to execute}, 50 | possible_value(s) = {Statements to execute}, 51 | 52 | _ = { default_execution_statements } 53 | }; 54 | */ 55 | 56 | let marks = 98; 57 | let grade = match marks { 58 | 90..=100 => 'A', 59 | 80..=89 => 'B', 60 | 70..=79 => 'C', 61 | 60..=69 => 'D', 62 | _ => 'F', 63 | }; 64 | println!("The grade achieved is {}",grade); 65 | 66 | } -------------------------------------------------------------------------------- /4 - Control Structures/5 - For loops and its variants.txt: -------------------------------------------------------------------------------- 1 | 2 | fn main() 3 | { 4 | // ------------------------------------------- 5 | // Loops 6 | // - For loop 7 | // - Looping through elements using an immutable reference 8 | // - Looping through elements using a mutable reference 9 | // ------------------------------------------- 10 | 11 | /* 12 | let mut some_vec = vec![45, 30, 85, 90, 41,39]; 13 | 14 | for i in 0..=5 { // 0..=5 15 | println!("The {}th value in the vector is {}", i, some_vec[i]); 16 | } 17 | */ 18 | 19 | /* 20 | let some_vec = vec![45, 30, 85, 90, 41,39]; 21 | for i in some_vec { 22 | println!("{}", i); 23 | } 24 | println!("{:?}", some_vec); 25 | */ 26 | 27 | /* 28 | let some_vec = vec![45, 30, 85, 90, 41,39]; 29 | for i in some_vec.iter() { // &some_vec 30 | println!("{}", i); 31 | } 32 | println!("{:?}", some_vec); 33 | 34 | */ 35 | 36 | let mut some_vec = vec![45, 30, 85, 90, 41,39]; 37 | for i in &mut some_vec.iter_mut() { // or &mut some_vec 38 | *i += 5; 39 | println!("{}", i); 40 | } 41 | println!("{:?}", some_vec); 42 | 43 | } 44 | 45 | -------------------------------------------------------------------------------- /4 - Control Structures/7 - Practice Problems.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Programming-Master-Class-from-Beginner-to-Expert/7a219af138cce6793e3e5f1fb22bb50a4cac1b40/4 - Control Structures/7 - Practice Problems.docx -------------------------------------------------------------------------------- /4 - Control Structures/Exercise/10 - Practice - Palindrome.txt: -------------------------------------------------------------------------------- 1 | fn main() { 2 | 3 | let input = String::from("abbbbaa"); 4 | let mut is_palindrome = true; 5 | if input.len() == 0 { is_palindrome = true; 6 | println!("\n\n The input is palindrome {:?}",is_palindrome); 7 | return} 8 | 9 | let mut last = input.len() - 1; 10 | let mut first = 0; 11 | 12 | let my_vec = input.as_bytes(); 13 | 14 | while first < last { 15 | if my_vec[first] != my_vec[last] { 16 | is_palindrome = false; 17 | break; // what will happen if we insert a return here 18 | } 19 | 20 | first +=1; 21 | last -=1; 22 | } 23 | 24 | println!("\n\n The input is palindrome {:?}",is_palindrome); 25 | } 26 | -------------------------------------------------------------------------------- /4 - Control Structures/Exercise/11 - Practice - Pathagorian Triplet .txt: -------------------------------------------------------------------------------- 1 | /*fn main() 2 | { 3 | let mut flag = true; 4 | for a in 1..=1000{ 5 | for b in a+1..1000 { 6 | for c in b+1..1000{ 7 | if a*a + b*b == c*c && a + b+c == 1000 8 | { 9 | println!("\n\n The required pathagorian triplet are ({}, {}, {}) \n\n", a,b,c); 10 | flag = false; 11 | break 12 | } 13 | } 14 | if flag == false {break} 15 | } 16 | if flag == false {break} 17 | } 18 | 19 | } 20 | */ 21 | 22 | // alternate way using the return statement 23 | fn main() 24 | { 25 | for a in 1..=1000{ 26 | for b in a+1..1000 { 27 | for c in b+1..1000{ 28 | if a*a + b*b == c*c && a + b+c == 1000 29 | { 30 | println!("\n\n The required pathagorian triplet are ({}, {}, {}) \n\n", a,b,c); 31 | 32 | return; 33 | } 34 | } 35 | 36 | } 37 | 38 | } 39 | 40 | 41 | } -------------------------------------------------------------------------------- /4 - Control Structures/Exercise/7 - Some Examples of loops.txt: -------------------------------------------------------------------------------- 1 | 2 | fn main() 3 | { 4 | 5 | let mut condition = true; 6 | println!("Please enter the marks in percentage for the students\n"); 7 | 8 | let mut grades = vec![]; 9 | while condition { 10 | println!("'Please enter the student marks"); 11 | 12 | let mut marks_input = String::new(); 13 | std::io::stdin() 14 | .read_line(&mut marks_input) 15 | .expect("failed to read input."); 16 | 17 | let marks_input: i32 = marks_input.trim().parse().expect("invalid input"); 18 | grades.push(marks_input); 19 | println!("Do you want to enter another student data [Y/N]"); 20 | 21 | let choice: char = { 22 | let mut choice_input = String::new(); 23 | 24 | std::io::stdin() 25 | .read_line(&mut choice_input) 26 | .expect("failed to read input."); 27 | 28 | choice_input.trim().parse().expect("invalid input") 29 | }; 30 | 31 | 32 | // Try using the break instead of this logic 33 | if choice_input == 'Y'{ 34 | condition = true; 35 | } else { condition = false; } 36 | 37 | 38 | } 39 | 40 | println!("The students grades are = {:?}", grades); 41 | } 42 | 43 | -------------------------------------------------------------------------------- /4 - Control Structures/Exercise/8 - Practice- Sum of square difference .txt: -------------------------------------------------------------------------------- 1 | fn main() { 2 | 3 | let mut n = String::new(); 4 | std::io::stdin() 5 | .read_line(&mut n) 6 | .expect("failed to read input."); 7 | let n: i32 = n.trim().parse().expect("invalid input"); 8 | 9 | let mut square_of_sum =0 ; 10 | let mut sum_of_squares = 0; 11 | for i in 1..=n { 12 | square_of_sum = square_of_sum + i; 13 | sum_of_squares = sum_of_squares + i.pow(2); 14 | } 15 | 16 | let difference = square_of_sum.pow(2) - sum_of_squares; 17 | // println!("The square of sum is {} and the sum of square is {}", square_of_sum.pow(2), sum_of_squares); 18 | println!("The difference of the square_of_sum and sum of Squares for N = {} is {}",n, difference); 19 | 20 | 21 | 22 | } 23 | 24 | 25 | -------------------------------------------------------------------------------- /4 - Control Structures/Exercise/9 - Practice- Sum of Multiples .txt: -------------------------------------------------------------------------------- 1 | // take help from the video and script in matlab course 2 | fn main() { 3 | 4 | let mut n = String::new(); 5 | std::io::stdin() 6 | .read_line(&mut n) 7 | .expect("failed to read input."); 8 | let n: i32 = n.trim().parse().expect("invalid input"); 9 | 10 | let numbers = 1..n; 11 | let mut multiples_of_3 = vec![0]; // please note that we can not use arrays in this example becuase the length of the array needs to be known at compile time 12 | let mut multiples_of_5 = vec![0]; 13 | 14 | for i in 1..n { 15 | if i%3 == 0 { multiples_of_3.push(1); } else {multiples_of_3.push(0);} 16 | if i%5 == 0 { multiples_of_5.push(1); } else {multiples_of_5.push(0);} 17 | } 18 | 19 | //println!("\n\n Multiple of 3 = {:?}", multiples_of_3); 20 | 21 | 22 | let mut combined_list = vec![0]; 23 | for i in 1..n as usize { 24 | if multiples_of_3[i] == 1 || multiples_of_5[i] == 1 {combined_list.push(1)} else {combined_list.push(0);} 25 | } 26 | 27 | // println!("{:?}",combined_list); 28 | 29 | let mut values_of_multiples:Vec = vec![0]; 30 | for i in 1..=n { 31 | values_of_multiples.push(combined_list[i as usize] * i); 32 | } 33 | // values_of_multiples.iter().sum(); 34 | 35 | println!("\n\n Multiple of 3 and 5 are = {:?}", values_of_multiples); 36 | 37 | println!("\n\n The sum of the multiples are = {:?}\n\n", values_of_multiples.iter().sum::()); // it is having difficutly in inferring the types so i explicilty provide that 38 | 39 | 40 | } 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /5 - Project-Stack Implemenation and Applications/2 - String reversal using Stacks .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Stack 3 | // - Stack using vec 4 | // - Application of Stacks (String Reversal) 5 | // ------------------------------------------- 6 | 7 | fn new_stack(maxsize: usize) -> Vec { 8 | let vec: Vec = Vec::with_capacity(maxsize); 9 | vec 10 | } 11 | 12 | fn pop(stack: &mut Vec) -> Option { 13 | let poped_val = stack.pop(); 14 | // println!("The poped value is {:?}",poped_val); 15 | poped_val 16 | } 17 | 18 | fn push(stack: &mut Vec, item: char, maxsize: usize) { 19 | if stack.len() == maxsize { 20 | // println!("Can not add more") 21 | } else { 22 | stack.push(item); 23 | // println!("Stack: {:?}", stack); 24 | } 25 | } 26 | 27 | fn size(stack: &Vec) -> usize { 28 | stack.len() 29 | } 30 | 31 | fn main() { 32 | let input_string = String::from("Welcome to rust"); 33 | let size_stack = input_string.len(); 34 | let mut stack = new_stack(size_stack); 35 | let mut rev_string = String::new(); 36 | 37 | 38 | for i in input_string.chars() { 39 | push(&mut stack, i, size_stack); 40 | } 41 | 42 | 43 | for i in 0..size(&stack) { 44 | rev_string.push(pop(&mut stack).unwrap()); 45 | } 46 | println!("The input string is {:?}", input_string); 47 | println!("The reverse of the string is {:?} ",rev_string); 48 | 49 | } 50 | -------------------------------------------------------------------------------- /6 - Structures, Traits, Generics, Enums/3 - Functions within a Trait.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Traits 3 | // - General explaination 4 | // - Default function implementation 5 | // - Functions within a trait implementation 6 | // ------------------------------------------- 7 | 8 | 9 | struct Data{ 10 | some_data: Vec, 11 | } 12 | 13 | trait BasicStats { 14 | fn mean(&self) -> f32; 15 | fn variance(&self) -> f32; 16 | } 17 | 18 | impl BasicStats for Data { 19 | fn mean(&self) -> f32 { 20 | let mut sum = 0; 21 | for i in self.some_data.iter(){ 22 | sum += *i; 23 | } 24 | //println!("{:?}",sum); 25 | sum as f32 / self.some_data.len() as f32 26 | 27 | } 28 | 29 | fn variance(&self) ->f32 { 30 | let mu = self.mean(); 31 | let mut sum_sqauared_diff:f32 = 0.0; 32 | for i in self.some_data.iter(){ 33 | sum_sqauared_diff += (*i as f32 - mu) * (*i as f32 - mu); 34 | } 35 | sum_sqauared_diff / self.some_data.len() as f32 36 | 37 | } 38 | } 39 | 40 | 41 | 42 | fn main() 43 | { 44 | let my_data = Data { 45 | some_data: vec![5, 6, 9, 8, 7, 4, 8], 46 | }; 47 | println!("the mean of the data is {}",my_data.mean()); 48 | println!("The standard deviation of the data is {}",my_data.variance()); 49 | 50 | 51 | } 52 | 53 | -------------------------------------------------------------------------------- /6 - Structures, Traits, Generics, Enums/7 - Result Enum.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Result enum 3 | // - Basic Syntax and usage 4 | // ------------------------------------------- 5 | 6 | /* 7 | enum Result { 8 | Ok(T), 9 | Err(E), 10 | } 11 | */ 12 | 13 | // Example 1 14 | /* 15 | fn division(dividend: f64, divisor: f64) -> Result { 16 | 17 | /*if divisor == 0.0 { 18 | Err(String::from("Error: Division by zero")) 19 | } else { 20 | Ok(dividend / divisor) 21 | } 22 | */ 23 | 24 | match divisor { 25 | 0. => Err(String::from("Error: Division By Zero")), 26 | _ => Ok(dividend / divisor), 27 | } 28 | 29 | } 30 | 31 | 32 | fn main() { 33 | 34 | println!("\n\n{:?}", division(9.0, 3.0)); 35 | println!("{:?}", division(4.0, 0.0)); 36 | println!("{:?} \n\n", division(0.0, 2.0)); 37 | } 38 | 39 | */ 40 | 41 | 42 | // Example 2 43 | 44 | fn main() { 45 | let some_vec:Vec = vec![5,5,2,1,5,9]; 46 | 47 | let result1 = match some_vec.get(15) { 48 | Some(a) => Ok(a), 49 | None => Err("The value does not exist"), 50 | }; 51 | 52 | println!("The value of Result is {:?}", result1); 53 | 54 | 55 | 56 | } 57 | -------------------------------------------------------------------------------- /6 - Structures, Traits, Generics, Enums/9 - Practice Problems.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Programming-Master-Class-from-Beginner-to-Expert/7a219af138cce6793e3e5f1fb22bb50a4cac1b40/6 - Structures, Traits, Generics, Enums/9 - Practice Problems.docx -------------------------------------------------------------------------------- /7 - Iterators, Lifetimes, Closures/1 - Lifetimes (Part 1) .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Lifetimes 3 | // - Dangling Reference 4 | // - Undetermined Lifetimes 5 | // ------------------------------------------- 6 | 7 | // use std::vec; 8 | 9 | /* 10 | fn main(){ 11 | let i:&i32; 12 | { 13 | 14 | let j = 5; 15 | i = &j; 16 | } 17 | println!("The value of i = {}", i); 18 | } 19 | */ 20 | 21 | 22 | /* 23 | fn main() { 24 | 25 | let some_int = 10; 26 | let additional_int = some_fn(some_int); 27 | println!("{}", additional_int); 28 | 29 | } 30 | 31 | fn some_fn(i: i32) -> &i32{ 32 | &i 33 | } 34 | */ 35 | 36 | 37 | /* 38 | fn main(){ 39 | let int1 = 5; 40 | let int2 = 10; 41 | let result = greater(&int1,&int2); 42 | 43 | } 44 | 45 | fn greater(i:&i32,j:&i32) -> &i32 { 46 | if i> j { 47 | i 48 | } else {j 49 | } 50 | 51 | } 52 | */ 53 | 54 | 55 | 56 | 57 | fn main(){ 58 | let s_1 = "Hello"; 59 | 60 | 61 | let v; 62 | { 63 | let s_2 = String::from("World"); 64 | v = some_fn(s_1, s_2.as_str()); 65 | } 66 | println!("\n\n{} \n\n", v); 67 | } 68 | 69 | fn some_fn(first_str: &str, second_str: &str) -> &str { 70 | first_str 71 | 72 | } 73 | 74 | -------------------------------------------------------------------------------- /7 - Iterators, Lifetimes, Closures/3 - Eliding Lifetimes.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Lifetime Elision 3 | // ------------------------------------------- 4 | 5 | /* 6 | 1. Each parameter that is a reference, gets its own lifetime parameter. 7 | 2. If there is exactly one input lifetime parameter, that lifetime is assigned to 8 | all output lifetime parameters. 9 | 3. If there are multiple input lifetime parameters, but one of them is &self or &mut self, 10 | the lifetime of self is assigned to all output lifetime parameters. 11 | */ 12 | 13 | //Example 1: 14 | fn main() { 15 | let str_1 = "some str"; 16 | 17 | let recieved_str = return_str(&str_1); 18 | } 19 | // Code with Lifetime Elision 20 | // fn return_str(s_1: &str) -> &str { 21 | // s_1 22 | // } 23 | 24 | // Code without Lifetime Elision 25 | fn return_str<'a>(s_1: &'a str) -> &'a str { 26 | s_1 27 | } 28 | 29 | // Example 2: 30 | /* fn main() { 31 | let str_1 = "some str"; 32 | let str_2 = "other str"; 33 | let recieved_str = return_str(&str_1, &str_2); 34 | } 35 | 36 | fn return_str<'a, 'b>(s_1: &'a str, s_2: &'b str) -> &'a str { 37 | s_1 38 | } 39 | */ 40 | -------------------------------------------------------------------------------- /7 - Iterators, Lifetimes, Closures/5 - Closures (Part 2).txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Closures 3 | // - A quick recap 4 | // - Borrow by immutable reference 5 | // - Borrow by a mutable reference 6 | // - Moving of a value into a closure 7 | // ------------------------------------------- 8 | 9 | 10 | 11 | /* 12 | fn main(){ 13 | 14 | let some_closure_1 = |x: u32| -> u32 { x + 1 }; 15 | let some_closure_2 = |x| { x + 1 }; 16 | let some_closure_3 = |x| x + 1 ; 17 | } 18 | */ 19 | 20 | 21 | 22 | /* 23 | fn main(){ 24 | let mut vec_1 = vec![1, 2,3]; 25 | let some_closure = || { 26 | // vec_1 is being used by reference. 27 | println!("Vec 1 : {:?}", vec_1); 28 | }; 29 | 30 | println!("Vec_1: {:?}",vec_1); 31 | some_closure(); 32 | 33 | vec_1[1] = 15; 34 | } 35 | */ 36 | 37 | 38 | /* 39 | fn main(){ 40 | let mut vec_1 = vec![4,5,6]; 41 | let mut some_closure = || { 42 | 43 | vec_1.push(35); 44 | 45 | }; 46 | 47 | //println!("vec_2 {:?}", vec_2); 48 | //vec_1[1] = 15; 49 | some_closure(); 50 | 51 | 52 | // vec_1[2] = 15; 53 | 54 | } 55 | 56 | */ 57 | 58 | fn main(){ 59 | let mut vec_1 = vec![1,2,3]; 60 | let some_closure = || { 61 | 62 | let vec_2 = vec_1; 63 | }; 64 | 65 | 66 | some_closure(); 67 | println!("vec 1 = {:?} ", vec_1); 68 | println!("vec 2 = {:?} ", vec_2); 69 | 70 | } 71 | -------------------------------------------------------------------------------- /7 - Iterators, Lifetimes, Closures/6 - Function types.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Function Types 3 | // - Basic syntax and use 4 | // - Function types as parameters to function 5 | // ------------------------------------------- 6 | 7 | /* 8 | fn max(x: i32, y: i32) -> i32 { 9 | if x > y { 10 | x 11 | } else { 12 | y 13 | } 14 | } 15 | 16 | fn min(x: i32, y: i32) -> i32 { 17 | if x < y { 18 | x 19 | } else { 20 | y 21 | } 22 | } 23 | 24 | fn main(){ 25 | let mut f = max; 26 | println!("The minimum of the two values is {}",f(2,3)); 27 | } 28 | */ 29 | 30 | 31 | /* 32 | 33 | fn prints_name(name: &str) { 34 | print!("The name is {}",name); 35 | } 36 | 37 | fn prints_full_info(f: fn(&str), some_one: &str, age: i32) { 38 | f(some_one); 39 | println!(" and my age is {}", age); 40 | } 41 | 42 | fn main() { 43 | let (my_name, my_age) = (String::from("Nouman"), 40); 44 | prints_full_info(prints_name, &my_name, my_age) ; 45 | } 46 | */ 47 | 48 | 49 | 50 | fn add_one(x: i32) -> i32 { 51 | x + 1 52 | } 53 | 54 | fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 { 55 | f(arg) + f(arg) 56 | } 57 | 58 | fn main() { 59 | let answer = do_twice(add_one, 5); 60 | println!("The answer is: {}", answer); 61 | } 62 | -------------------------------------------------------------------------------- /7 - Iterators, Lifetimes, Closures/8 - Iterators (Part 2).txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Iterators 3 | // - Basics 4 | // - Some useful functions for iterators 5 | // - Common statistics 6 | // - Modifying and collecting values 7 | // ------------------------------------------- 8 | 9 | fn main() 10 | { 11 | let a = vec![0, 1, 2, 3,4,5,6,7]; 12 | 13 | 14 | let filtered_values = a.iter().filter(|&x| *x >= 5).collect::>(); 15 | println!(" {:?}", filtered_values); 16 | 17 | 18 | let b = a.clone(); 19 | let filtered_values= a.into_iter().filter(|x| *x >= 5).collect::>(); 20 | println!(" {:?}", filtered_values); 21 | 22 | // println!(" {:?}", a); 23 | 24 | 25 | let mut mapped_values = b.iter().map(|x| 2 * *x).collect::>(); 26 | println!(" {:?}", mapped_values); 27 | 28 | 29 | 30 | let mut mapped_values = b.iter().map(|x| 2 * x).filter(|x| *x > 10).collect::>(); 31 | 32 | println!(" {:?}", mapped_values); 33 | 34 | // https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map 35 | 36 | } 37 | 38 | -------------------------------------------------------------------------------- /7 - Iterators, Lifetimes, Closures/9 - Practice Problems.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Programming-Master-Class-from-Beginner-to-Expert/7a219af138cce6793e3e5f1fb22bb50a4cac1b40/7 - Iterators, Lifetimes, Closures/9 - Practice Problems.docx -------------------------------------------------------------------------------- /7 - Iterators, Lifetimes, Closures/Exercise/7 - Sum of multiples revised with iterators .txt: -------------------------------------------------------------------------------- 1 | // Example: Sum of multiples of 3 and 5 -> refined and reduced version of the code with iterators 2 | 3 | /* 4 | fn main() { 5 | 6 | let mut n = String::new(); 7 | std::io::stdin() 8 | .read_line(&mut n) 9 | .expect("failed to read input."); 10 | let n: u32 = n.trim().parse().expect("invalid input"); 11 | 12 | let divisible_by_3_5 = (1..n).into_iter().filter(|&x| x % 3 == 0 || x % 5 ==0 ).collect::>(); 13 | println!("{:?}", divisible_by_3_5); 14 | println!("{:?}", divisible_by_3_5.iter().sum::()); 15 | 16 | 17 | } 18 | 19 | -------------------------------------------------------------------------------- /8 - Rust Modules/1 - Rust Modules (Part 1)/file_1.txt: -------------------------------------------------------------------------------- 1 | pub fn printing() { 2 | println!("Hello from first crate"); 3 | } -------------------------------------------------------------------------------- /8 - Rust Modules/1 - Rust Modules (Part 1)/file_2.txt: -------------------------------------------------------------------------------- 1 | pub fn printing() { 2 | println!("Hello from second crate"); 3 | } -------------------------------------------------------------------------------- /8 - Rust Modules/1 - Rust Modules (Part 1)/lib.txt: -------------------------------------------------------------------------------- 1 | pub mod file_1; 2 | pub mod file_2; -------------------------------------------------------------------------------- /8 - Rust Modules/1 - Rust Modules (Part 1)/main.txt: -------------------------------------------------------------------------------- 1 | use new_project::file_1; 2 | use new_project::file_2; 3 | 4 | fn main() { 5 | new_project::file_1::printing(); 6 | new_project::file_2::printing(); 7 | } 8 | -------------------------------------------------------------------------------- /8 - Rust Modules/2 - Rust Modules (Part 2)/1 - Rust Modules (Part 1).txt: -------------------------------------------------------------------------------- 1 | /*mod file_1; 2 | fn main(){ 3 | 4 | let rect1 = Rectangle{ 5 | length: 5, 6 | width:10, 7 | }; 8 | let area_rect1 = rect_area(&rect1.length, &rect1.width); // also del the file_1:: if you are including the code in the same script 9 | } 10 | 11 | struct Rectangle{ 12 | length: i32, 13 | width:i32, 14 | } 15 | */ 16 | 17 | /* 18 | fn some_fn() { 19 | println!("This is the function of the file_1 crate"); 20 | } 21 | 22 | mod maths { 23 | pub mod basic_math { 24 | pub fn multiplication(num1:&i32, num2:&i32) -> i32{ 25 | let result = num1 * num2; 26 | printing(&result); 27 | result 28 | } 29 | fn printing(num: &i32) { 30 | println!("The result is {}", num); 31 | crate::some_fn(); 32 | } 33 | 34 | } 35 | } 36 | 37 | 38 | fn rect_area(length:&i32, width:&i32) -> i32 { 39 | // absolute path 40 | use maths::basic_math::multiplication; 41 | multiplication(length, width) // parents can not see child modules but childs can see parents modules by default 42 | } 43 | */ 44 | 45 | 46 | /* 47 | mod file_2; 48 | fn main() { 49 | file_2::some_person(); 50 | } 51 | */ 52 | 53 | mod file_3; 54 | 55 | fn main() 56 | { 57 | file_3::allowance(); 58 | } 59 | -------------------------------------------------------------------------------- /8 - Rust Modules/2 - Rust Modules (Part 2)/file_1.txt: -------------------------------------------------------------------------------- 1 | fn some_fn() { 2 | println!("This is the function of the file_1 crate"); 3 | } 4 | 5 | mod maths { 6 | pub mod basic_math { 7 | pub fn multiplication(num1:&i32, num2:&i32) -> i32{ 8 | let result = num1 * num2; 9 | printing(&result); 10 | result 11 | } 12 | fn printing(num: &i32) { 13 | println!("The result is {}", num); 14 | crate::file_1::some_fn(); 15 | } 16 | 17 | } 18 | } 19 | 20 | 21 | // Point: The program will not compile if we remove the pub word 22 | pub fn rect_area(length:&i32, width:&i32) -> i32 { 23 | // absolute path 24 | use maths::basic_math::multiplication; 25 | multiplication(length, width) // parents can not see child modules but childs can see parents modules by default 26 | } 27 | 28 | /* 29 | file_1 30 | - math 31 | - basic maths 32 | rect_area() 33 | some_fn() 34 | 35 | */ 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /8 - Rust Modules/2 - Rust Modules (Part 2)/file_2.txt: -------------------------------------------------------------------------------- 1 | mod person { 2 | pub struct personal_info { 3 | pub age: u8, 4 | pub education: String, 5 | } 6 | 7 | impl personal_info{ 8 | pub fn new(new_edu: &str) -> Self { 9 | Self { 10 | education: String::from(new_edu), 11 | age: 20, 12 | } 13 | } 14 | } 15 | } 16 | 17 | pub fn some_person() { 18 | let mut person1 = person::personal_info::new("bachelors"); 19 | person1.education = String::from("Masters"); 20 | 21 | 22 | let person2 = person::personal_info { 23 | age: 42, 24 | education: String::from("Masters"), 25 | }; 26 | 27 | } 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /8 - Rust Modules/2 - Rust Modules (Part 2)/file_3.txt: -------------------------------------------------------------------------------- 1 | 2 | mod travel_history { 3 | enum Conveyance { 4 | Car, 5 | Train, 6 | Air, 7 | } 8 | } 9 | 10 | 11 | pub fn allowance() { 12 | let travel_1 = travel_history::Conveyance::Car; 13 | let travel_2 = travel_history::Conveyance::Train; 14 | } 15 | -------------------------------------------------------------------------------- /8 - Rust Modules/3 - Cargo tools to Visualize Module Hierarchy/commands .txt: -------------------------------------------------------------------------------- 1 | // cargo install cargo-modules 2 | // cargo modules generate tree 3 | //cargo modules generate tree --lib (only modules) 4 | // cargo modules generate tree --lib --types --fns (details) -------------------------------------------------------------------------------- /8 - Rust Modules/3 - Cargo tools to Visualize Module Hierarchy/method 1/customer.rs: -------------------------------------------------------------------------------- 1 | pub struct Customer { 2 | id: u64, // this can be made private 3 | name: String, 4 | email: String, // this can be made private 5 | } 6 | -------------------------------------------------------------------------------- /8 - Rust Modules/3 - Cargo tools to Visualize Module Hierarchy/method 1/order.rs: -------------------------------------------------------------------------------- 1 | use crate::customer::Customer; 2 | use crate::product::Product; 3 | pub struct Order { 4 | id: u64, // private 5 | product: Product, 6 | customer: Customer, 7 | quantity: u32, 8 | } 9 | 10 | impl Order { 11 | // Private 12 | fn calculate_discount(&self) -> f64 { 13 | if self.quantity > 5 { 14 | 0.1 15 | } else { 16 | 0.0 17 | } 18 | } 19 | 20 | // Public 21 | fn total_bill(&self) -> f64 { 22 | let discount = self.calculate_discount(); 23 | let total_before_discount = self.product.product_price() * self.quantity as f64; 24 | total_before_discount - (total_before_discount * discount) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /8 - Rust Modules/3 - Cargo tools to Visualize Module Hierarchy/method 1/product.rs: -------------------------------------------------------------------------------- 1 | pub use category::Category; 2 | pub struct Product { 3 | id: u64, // this can be made private 4 | name: String, 5 | price: f64, 6 | category: Category, // this can be made private 7 | } 8 | mod category; 9 | impl Product { 10 | // private 11 | fn calculate_tax(&self) -> f64 { 12 | self.price * 0.1 13 | } 14 | 15 | // public function 16 | pub fn product_price(&self) -> f64 { 17 | self.price + self.calculate_tax() 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /8 - Rust Modules/3 - Cargo tools to Visualize Module Hierarchy/method 1/product/category.rs: -------------------------------------------------------------------------------- 1 | pub enum Category { 2 | Electronics, 3 | Clothing, 4 | Books, 5 | } 6 | -------------------------------------------------------------------------------- /8 - Rust Modules/3 - Cargo tools to Visualize Module Hierarchy/method 2/customer/mod.rs: -------------------------------------------------------------------------------- 1 | pub struct Customer { 2 | id: u64, // this can be made private 3 | name: String, 4 | email: String, // this can be made private 5 | } 6 | -------------------------------------------------------------------------------- /8 - Rust Modules/3 - Cargo tools to Visualize Module Hierarchy/method 2/lib.rs: -------------------------------------------------------------------------------- 1 | mod customer; 2 | mod order; 3 | mod product; 4 | -------------------------------------------------------------------------------- /8 - Rust Modules/3 - Cargo tools to Visualize Module Hierarchy/method 2/order/mod.rs: -------------------------------------------------------------------------------- 1 | use crate::customer::Customer; 2 | use crate::product::Product; 3 | pub struct Order { 4 | id: u64, // private 5 | product: Product, 6 | customer: Customer, 7 | quantity: u32, 8 | } 9 | 10 | impl Order { 11 | // Private 12 | fn calculate_discount(&self) -> f64 { 13 | if self.quantity > 5 { 14 | 0.1 15 | } else { 16 | 0.0 17 | } 18 | } 19 | 20 | // Public 21 | fn total_bill(&self) -> f64 { 22 | let discount = self.calculate_discount(); 23 | let total_before_discount = self.product.product_price() * self.quantity as f64; 24 | total_before_discount - (total_before_discount * discount) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /8 - Rust Modules/3 - Cargo tools to Visualize Module Hierarchy/method 2/product/category.rs: -------------------------------------------------------------------------------- 1 | pub enum Category { 2 | Electronics, 3 | Clothing, 4 | Books, 5 | } 6 | -------------------------------------------------------------------------------- /8 - Rust Modules/3 - Cargo tools to Visualize Module Hierarchy/method 2/product/mod.rs: -------------------------------------------------------------------------------- 1 | pub use category::Category; 2 | pub struct Product { 3 | id: u64, // this can be made private 4 | name: String, 5 | price: f64, 6 | category: Category, // this can be made private 7 | } 8 | mod category; 9 | impl Product { 10 | // private 11 | fn calculate_tax(&self) -> f64 { 12 | self.price * 0.1 13 | } 14 | 15 | // public function 16 | pub fn product_price(&self) -> f64 { 17 | self.price + self.calculate_tax() 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /8 - Rust Modules/5 - Using External crates.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // External Crates 3 | // - Add to cargo.toml under dependency array_tool = "1.0.3" 4 | // ------------------------------------------- 5 | 6 | use array_tool::vec::*; 7 | fn main() { 8 | let vec_1 = vec![1,1,3,5,6,7]; 9 | let vec_2 = vec![1,2,3]; 10 | let intesection = vec_1.intersect(vec_2.clone()); 11 | println!("The intersection = {:?}",intesection); 12 | 13 | 14 | let union_set = vec_1.union(vec_2.clone()); 15 | println!("The union = {:?}",union_set); 16 | println!("Vec 1 three times displayed = {:?}",vec_2.times(3)); 17 | 18 | } -------------------------------------------------------------------------------- /8 - Rust Modules/7 - Practice Problems.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Programming-Master-Class-from-Beginner-to-Expert/7a219af138cce6793e3e5f1fb22bb50a4cac1b40/8 - Rust Modules/7 - Practice Problems.docx -------------------------------------------------------------------------------- /9 - Smart Pointers in Rust/1 - Basics of Smart Pointers.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Smart Pointers 3 | // - Box Pointers 4 | // ------------------------------------------- 5 | 6 | 7 | fn main() { 8 | let single_value = Box::new(0.625); 9 | let x = 0.625; 10 | println!("Are the values being equal {}", x == *single_value); // deref is needed when box contains a single value 11 | 12 | 13 | let mut stack_var = 4; 14 | let stack_ref = &stack_var; 15 | let heap_var = Box::new(stack_var); // what happens when we write stack_var inside the (stack_ref) 16 | 17 | 18 | stack_var = 5; 19 | println!("The value of stack_var = {} and heap_var = {}", stack_var, heap_var); 20 | 21 | 22 | let point = Box::new((100, 125)); 23 | println!("{} {}", 100 == point.0, point.1); 24 | 25 | let x = point; // 26 | } -------------------------------------------------------------------------------- /9 - Smart Pointers in Rust/2 - Box Pointers and When they are Useful .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Smart Pointers 3 | // - Box Pointers 4 | // - Use Case of Box Pointers 5 | // ------------------------------------------- 6 | 7 | 8 | /* 9 | #[derive(Debug)] 10 | enum List { 11 | Cons(i32, List), 12 | Nil, 13 | } 14 | use List::{Cons, Nil}; 15 | 16 | 17 | /* 18 | enum Conveyance { 19 | Car(i32), 20 | Train(i32), 21 | Air(i32), 22 | Walk 23 | } 24 | */ 25 | fn main() { 26 | let list = Cons(1, Cons(2, Cons(3, Nil))); 27 | // let list = List::Cons(1, List::Cons(2, List::Cons(3, List::Nil))); 28 | println!("{:?}",list); 29 | } 30 | */ 31 | 32 | 33 | #[derive(Debug)] 34 | enum List { 35 | Cons(i32, Box), 36 | Nil, 37 | } 38 | 39 | fn main() { 40 | let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Cons(3, Box::new(List::Nil)))))); 41 | println!("{:?}",list); 42 | } 43 | 44 | -------------------------------------------------------------------------------- /9 - Smart Pointers in Rust/4 - Generics and Deref Coercion in Smart Pointers.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Smart Pointers 3 | // - Custom Defined Smart pointers 4 | // - Deref Coercion 5 | // ------------------------------------------- 6 | 7 | struct MySmartPointer{value: T, 8 | name: String} // add it at the end 9 | 10 | 11 | impl MySmartPointer { 12 | fn new(x:T)-> MySmartPointer { 13 | MySmartPointer{value: x, name:String::from("Hello")} 14 | 15 | } 16 | } 17 | 18 | use std::ops::Deref; 19 | impl Deref for MySmartPointer { 20 | type Target = T; 21 | fn deref(&self) -> &T { 22 | &self.value 23 | } 24 | } 25 | 26 | 27 | 28 | impl Drop for MySmartPointer{ 29 | fn drop(&mut self){ 30 | println!("dropping MySmartPointer object from memory {:?}", self.value); 31 | } 32 | } 33 | 34 | 35 | fn my_fn(str: &str) 36 | 37 | { 38 | println!("The string recieved from teh main is \"{}\"", str); 39 | } 40 | 41 | 42 | #[derive(Debug)] 43 | struct Person{ 44 | name: String, 45 | 46 | } 47 | 48 | 49 | fn main() { 50 | let sptr_p1 = MySmartPointer::new("Nouman Azam"); 51 | my_fn(&sptr_p1); 52 | 53 | let some_vec = MySmartPointer::new(vec![1,2,3]); 54 | 55 | for z in &*some_vec { 56 | println!("The value is {}", z); 57 | 58 | } 59 | 60 | } 61 | 62 | 63 | -------------------------------------------------------------------------------- /9 - Smart Pointers in Rust/5- Rc smart pointer.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Reference Counting Pointers 3 | // ------------------------------------------- 4 | /* 5 | use std::rc::Rc; 6 | enum List{ 7 | //Cons(i32, Box), 8 | Cons(i32, Rc), 9 | Nil, 10 | } 11 | 12 | use crate::List::{Cons, Nil}; 13 | fn main(){ 14 | /* 15 | let a = Cons(1, Box::new(Cons(2, Box::new(Nil)))); 16 | let b = Cons(3, Box::new(a)); 17 | let c = Cons(4, Box::new(a)); 18 | */ 19 | 20 | let a = Rc::new(Cons(1, Rc::new(Cons(2, Rc::new(Nil))))); 21 | println!("Count after creating a = {}", Rc::strong_count(&a)); 22 | 23 | { 24 | let b = Rc::new(Cons(3, Rc::clone(&a))); 25 | println!("Count after creating b = {}", Rc::strong_count(&a)); 26 | 27 | let c = Rc::new(Cons(4, Rc::clone(&a))); 28 | println!("Count after creating c = {}", Rc::strong_count(&a)); 29 | } 30 | println!("Count after code block = {}", Rc::strong_count(&a)); 31 | } 32 | */ 33 | 34 | 35 | use std::rc::Rc; 36 | 37 | fn make_rc() -> Rc { 38 | 39 | let s1 = Rc::new(String::from("Hello")); 40 | println!("Count when the pointer is created {}", Rc::strong_count(&s1)); 41 | 42 | let s2 = s1.clone(); 43 | println!("Count after the clone is created for the pointer {}", Rc::strong_count(&s1)); 44 | s2 45 | 46 | } 47 | 48 | fn main(){ 49 | let s2 = make_rc(); 50 | println!("Count after function call {}", Rc::strong_count(&s2)); 51 | }s -------------------------------------------------------------------------------- /9 - Smart Pointers in Rust/6 - RefCell smart pointer.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // RefCell 3 | // - Borrowing rules checked at run time 4 | // - Interior Mutablity 5 | // - Rc with RefCell 6 | 7 | // ------------------------------------------- 8 | 9 | 10 | /* 11 | use std::cell::RefCell; 12 | 13 | fn main() 14 | { 15 | 16 | /* 17 | let mut x = 50; 18 | let x1 = &x; 19 | let x2 = &x; 20 | let x3 = &mut x; 21 | 22 | println!("{} {} ", x1,x2); 23 | */ 24 | 25 | /* 26 | let a = RefCell::new(10); 27 | 28 | { 29 | let b = a.borrow(); 30 | let c = a.borrow(); 31 | } 32 | 33 | //drop(b); 34 | //drop(c); 35 | 36 | let d = a.borrow_mut(); 37 | drop(d); 38 | println!("Value of a is : {:?}",a); 39 | 40 | */ 41 | 42 | /* 43 | let x = 32; 44 | let x1 = &mut x; 45 | */ 46 | 47 | 48 | /* 49 | let a = RefCell::new(10); 50 | // *a.borrow_mut() = 15; 51 | let mut b = a.borrow_mut(); 52 | *b = 15; 53 | 54 | //drop(b); 55 | println!("{:?}",a); 56 | 57 | 58 | 59 | */ 60 | //} 61 | 62 | */ 63 | 64 | 65 | 66 | 67 | use std::cell::RefCell; 68 | use std::rc::Rc; 69 | 70 | 71 | 72 | fn main() 73 | { 74 | 75 | 76 | let a = Rc::new(RefCell::new(String::from("java"))); 77 | let b = Rc::clone(&a); 78 | 79 | *b.borrow_mut() = String::from("c++"); 80 | println!("{:?}",a); 81 | 82 | 83 | 84 | } 85 | 86 | -------------------------------------------------------------------------------- /9 - Smart Pointers in Rust/7 - Implementing Singly Link list from Scratch (Part 1) .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Link List (Part 1) 3 | // ------------------------------------------- 4 | 5 | #[derive(Debug)] 6 | struct linklist{ 7 | head: pointer, 8 | } 9 | #[derive(Debug)] 10 | struct Node{ 11 | element: i32, 12 | next: pointer, 13 | } 14 | 15 | type pointer = Option>; 16 | 17 | fn main(){ 18 | /* 19 | 20 | let list = Node{element: 1, next: None}; 21 | 22 | let list = Node{element: 1, next: Some(Box::new(Node { 23 | element: 2, next: Some(Box::new(Node { 24 | element:3, next: None 25 | })) 26 | }))}; 27 | 28 | let list = linklist {head: Node{element: 1, next: None}}; 29 | 30 | let list = linklist {head: Node { element: 1, next: Some(Box::new(Node { 31 | element: 2, next: Some(Box::new(Node { 32 | element: 3, next: None 33 | })) 34 | })) }}; 35 | */ 36 | 37 | let list = linklist{head: None}; 38 | 39 | let list = linklist{head: Some(Box::new(Node {element: 100, next: ( 40 | Some(Box::new(Node { 41 | element: 200, next: None 42 | })) 43 | )}))}; 44 | 45 | //println!("{:?}", list.head.unwrap().element); 46 | 47 | 48 | //println!("{:?}", list.head.unwrap().next.unwrap().element); 49 | 50 | println!("{:?}", list.head); 51 | 52 | 53 | 54 | } 55 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/3 - Rust Ownership/1 - Ownership Rules, Premitive, and non-premitive types.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Rust Ownership 3 | // - Each value in Rust has a variable that’s called its owner. 4 | // - There can be only one owner at a time. 5 | // - When the owner goes out of scope, the value will be dropped. 6 | // ------------------------------------------- 7 | 8 | fn main() { 9 | /*let mut x = 32.6; 10 | let mut y = x; 11 | 12 | let s1 = String::from("abc"); 13 | let s2 = &s1; 14 | println!("The value of s1 = {} and s2 = {}",s1,s2); 15 | */ 16 | 17 | /* 18 | let num_vec1: Vec = vec![5,6,9,8,7]; 19 | //let num_vec2 = num_vec1; //move, Ownership change 20 | // println!("The first vector is {:?} {:?}",num_vec1,num_vec2); 21 | 22 | 23 | let num_vec2 = &num_vec1; // Referencing or borrowing 24 | println!("The first vector is {:?} {:?}",num_vec1,num_vec2); 25 | 26 | let num_vec2 = num_vec1.clone(); 27 | println!("The first vector is {:?} {:?}",num_vec1,num_vec2); 28 | */ 29 | 30 | { 31 | let my_name = String::from("Nouman Azam"); 32 | } 33 | println!("My name is {}", my_name); 34 | 35 | 36 | } 37 | 38 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/3 - Rust Ownership/2 - Heap and stack .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Heap and Stack 3 | // ------------------------------------------- 4 | 5 | const MAX_VALUE:i32 = 40_000; 6 | /* 7 | fn main() { 8 | 9 | let (x,y) = (2,4); 10 | let sum_value = square_sum(x,y); 11 | println!("The value of Square of Sum = {}",sum_value); 12 | } 13 | 14 | fn square_sum(num1:i32, num2:i32) -> i32 { 15 | let result = square(num1+num2); 16 | result 17 | } 18 | 19 | fn square(num:i32) -> i32 { 20 | num * num 21 | } 22 | */ 23 | 24 | fn main() 25 | { 26 | let x: i32 = 5; 27 | 28 | let s1 = String::from("some string"); 29 | let s2 = s1; 30 | let s3 = &s2; 31 | let s4 = s2.clone(); 32 | 33 | 34 | } -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/3 - Rust Ownership/4 - Mutable and Immutable References.txt: -------------------------------------------------------------------------------- 1 | 2 | fn main() 3 | { 4 | 5 | // ------------------------------------------- 6 | // References Rules 7 | // - One mutable reference in a scope 8 | // - Many immutable references 9 | // - Mutable and immutable can not coexist 10 | // - Scope of a reference 11 | // - Data should not change when immutable references are in scope 12 | // ------------------------------------------- 13 | 14 | /* 15 | 16 | let mut heap_num = vec![4, 5, 6]; 17 | let ref1 = &mut heap_num; 18 | let ref2 = &mut heap_num; 19 | 20 | println!("The first reference is {:?} and the second one is {:?}",ref1,ref2); 21 | 22 | 23 | let mut heap_num = vec![4, 5, 6]; 24 | let ref1 = &heap_num; 25 | let ref2 = &heap_num; 26 | println!("The first reference is {:?} and the second one is {:?}",ref1,ref2); 27 | 28 | 29 | 30 | 31 | let mut heap_num = vec![4, 5, 6]; 32 | let ref1 = &heap_num; 33 | let ref2 = &heap_num; 34 | let ref3 = &mut heap_num; 35 | println!("Immutable references are {:?} and {:?} and the mutable reference is {:?}",ref1,ref2,ref3); 36 | 37 | 38 | let mut heap_num = vec![4, 5, 6]; 39 | let ref1 = &heap_num; 40 | let ref2 = &heap_num; 41 | println!("Immutable references are {:?} and {:?}",ref1,ref2); 42 | let ref3 = &mut heap_num; 43 | */ 44 | 45 | 46 | let mut heap_num = vec![4, 5, 6]; 47 | heap_num.push(68); 48 | 49 | let ref1 = &heap_num; 50 | let ref2 = &heap_num; 51 | println!("Immutable references are {:?} and {:?}",ref1,ref2); 52 | heap_num.push(86); 53 | 54 | 55 | 56 | } 57 | 58 | 59 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/3 - Rust Ownership/5 - String Concatenation and Ownership.txt: -------------------------------------------------------------------------------- 1 | fn main() 2 | { 3 | // ------------------------------------------- 4 | // String concatenation and onwership 5 | // ------------------------------------------- 6 | 7 | /* let s1 = String::from("hello"); 8 | let s2: &str = "world"; 9 | 10 | let s3 = s1 + s2; // the ownership changed here 11 | println!("{}", s3); 12 | */ 13 | 14 | /* let s1 = String::from("hello"); 15 | let s2 = String::from("world"); 16 | 17 | let s3 = s1 + &s2; // The ownership of only owned_string1 changed 18 | println!("{} {} ", s3 , s2); 19 | */ 20 | 21 | let s1 = String::from("hello"); 22 | let s2 = String::from("world"); 23 | let s3 = String::from(" from Rust"); 24 | 25 | let s4 = s1 + &s2 + &s3; // The ownership of only s1 changed 26 | println!("{} {} {}", s4,s2,s3); 27 | 28 | } 29 | 30 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/4 - Control Structures/5 - For loops and its variants.txt: -------------------------------------------------------------------------------- 1 | 2 | fn main() 3 | { 4 | // ------------------------------------------- 5 | // Loops 6 | // - For loop 7 | // - Looping through elements using an immutable reference 8 | // - Looping through elements using a mutable reference 9 | // ------------------------------------------- 10 | 11 | /* 12 | let mut some_vec = vec![45, 30, 85, 90, 41,39]; 13 | 14 | for i in 0..=5 { // 0..=5 15 | println!("The {}th value in the vector is {}", i, some_vec[i]); 16 | } 17 | */ 18 | 19 | /* 20 | let some_vec = vec![45, 30, 85, 90, 41,39]; 21 | for i in some_vec { 22 | println!("{}", i); 23 | } 24 | println!("{:?}", some_vec); 25 | */ 26 | 27 | /* 28 | let some_vec = vec![45, 30, 85, 90, 41,39]; 29 | for i in some_vec.iter() { // &some_vec 30 | println!("{}", i); 31 | } 32 | println!("{:?}", some_vec); 33 | 34 | */ 35 | 36 | let mut some_vec = vec![45, 30, 85, 90, 41,39]; 37 | for i in &mut some_vec.iter_mut() { // or &mut some_vec 38 | *i += 5; 39 | println!("{}", i); 40 | } 41 | println!("{:?}", some_vec); 42 | 43 | } 44 | 45 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/4 - Control Structures/Exercise/10 - Practice - Palindrome.txt: -------------------------------------------------------------------------------- 1 | fn main() { 2 | 3 | let input = String::from("abbbbaa"); 4 | let mut is_palindrome = true; 5 | if input.len() == 0 { is_palindrome = true; 6 | println!("\n\n The input is palindrome {:?}",is_palindrome); 7 | return} 8 | 9 | let mut last = input.len() - 1; 10 | let mut first = 0; 11 | 12 | let my_vec = input.as_bytes(); 13 | 14 | while first < last { 15 | if my_vec[first] != my_vec[last] { 16 | is_palindrome = false; 17 | break; // what will happen if we insert a return here 18 | } 19 | 20 | first +=1; 21 | last -=1; 22 | } 23 | 24 | println!("\n\n The input is palindrome {:?}",is_palindrome); 25 | } 26 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/4 - Control Structures/Exercise/11 - Practice - Pathagorian Triplet .txt: -------------------------------------------------------------------------------- 1 | /*fn main() 2 | { 3 | let mut flag = true; 4 | for a in 1..=1000{ 5 | for b in a+1..1000 { 6 | for c in b+1..1000{ 7 | if a*a + b*b == c*c && a + b+c == 1000 8 | { 9 | println!("\n\n The required pathagorian triplet are ({}, {}, {}) \n\n", a,b,c); 10 | flag = false; 11 | break 12 | } 13 | } 14 | if flag == false {break} 15 | } 16 | if flag == false {break} 17 | } 18 | 19 | } 20 | */ 21 | 22 | // alternate way using the return statement 23 | fn main() 24 | { 25 | for a in 1..=1000{ 26 | for b in a+1..1000 { 27 | for c in b+1..1000{ 28 | if a*a + b*b == c*c && a + b+c == 1000 29 | { 30 | println!("\n\n The required pathagorian triplet are ({}, {}, {}) \n\n", a,b,c); 31 | 32 | return; 33 | } 34 | } 35 | 36 | } 37 | 38 | } 39 | 40 | 41 | } -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/4 - Control Structures/Exercise/7 - Some Examples of loops.txt: -------------------------------------------------------------------------------- 1 | 2 | fn main() 3 | { 4 | 5 | let mut condition = true; 6 | println!("Please enter the marks in percentage for the students\n"); 7 | 8 | let mut grades = vec![]; 9 | while condition { 10 | println!("'Please enter the student marks"); 11 | 12 | let mut marks_input = String::new(); 13 | std::io::stdin() 14 | .read_line(&mut marks_input) 15 | .expect("failed to read input."); 16 | 17 | let marks_input: i32 = marks_input.trim().parse().expect("invalid input"); 18 | grades.push(marks_input); 19 | println!("Do you want to enter another student data [Y/N]"); 20 | 21 | let choice: char = { 22 | let mut choice_input = String::new(); 23 | 24 | std::io::stdin() 25 | .read_line(&mut choice_input) 26 | .expect("failed to read input."); 27 | 28 | choice_input.trim().parse().expect("invalid input") 29 | }; 30 | 31 | 32 | // Try using the break instead of this logic 33 | if choice_input == 'Y'{ 34 | condition = true; 35 | } else { condition = false; } 36 | 37 | 38 | } 39 | 40 | println!("The students grades are = {:?}", grades); 41 | } 42 | 43 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/4 - Control Structures/Exercise/8 - Practice- Sum of square difference .txt: -------------------------------------------------------------------------------- 1 | fn main() { 2 | 3 | let mut n = String::new(); 4 | std::io::stdin() 5 | .read_line(&mut n) 6 | .expect("failed to read input."); 7 | let n: i32 = n.trim().parse().expect("invalid input"); 8 | 9 | let mut square_of_sum =0 ; 10 | let mut sum_of_squares = 0; 11 | for i in 1..=n { 12 | square_of_sum = square_of_sum + i; 13 | sum_of_squares = sum_of_squares + i.pow(2); 14 | } 15 | 16 | let difference = square_of_sum.pow(2) - sum_of_squares; 17 | // println!("The square of sum is {} and the sum of square is {}", square_of_sum.pow(2), sum_of_squares); 18 | println!("The difference of the square_of_sum and sum of Squares for N = {} is {}",n, difference); 19 | 20 | 21 | 22 | } 23 | 24 | 25 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/4 - Control Structures/Exercise/9 - Practice- Sum of Multiples .txt: -------------------------------------------------------------------------------- 1 | // take help from the video and script in matlab course 2 | fn main() { 3 | 4 | let mut n = String::new(); 5 | std::io::stdin() 6 | .read_line(&mut n) 7 | .expect("failed to read input."); 8 | let n: i32 = n.trim().parse().expect("invalid input"); 9 | 10 | let numbers = 1..n; 11 | let mut multiples_of_3 = vec![0]; // please note that we can not use arrays in this example becuase the length of the array needs to be known at compile time 12 | let mut multiples_of_5 = vec![0]; 13 | 14 | for i in 1..n { 15 | if i%3 == 0 { multiples_of_3.push(1); } else {multiples_of_3.push(0);} 16 | if i%5 == 0 { multiples_of_5.push(1); } else {multiples_of_5.push(0);} 17 | } 18 | 19 | //println!("\n\n Multiple of 3 = {:?}", multiples_of_3); 20 | 21 | 22 | let mut combined_list = vec![0]; 23 | for i in 1..n as usize { 24 | if multiples_of_3[i] == 1 || multiples_of_5[i] == 1 {combined_list.push(1)} else {combined_list.push(0);} 25 | } 26 | 27 | // println!("{:?}",combined_list); 28 | 29 | let mut values_of_multiples:Vec = vec![0]; 30 | for i in 1..=n { 31 | values_of_multiples.push(combined_list[i as usize] * i); 32 | } 33 | // values_of_multiples.iter().sum(); 34 | 35 | println!("\n\n Multiple of 3 and 5 are = {:?}", values_of_multiples); 36 | 37 | println!("\n\n The sum of the multiples are = {:?}\n\n", values_of_multiples.iter().sum::()); // it is having difficutly in inferring the types so i explicilty provide that 38 | 39 | 40 | } 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/5 - Project Stack Implementation/2 - String reversal using Stacks .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Stack 3 | // - Stack using vec 4 | // - Application of Stacks (String Reversal) 5 | // ------------------------------------------- 6 | 7 | fn new_stack(maxsize: usize) -> Vec { 8 | let vec: Vec = Vec::with_capacity(maxsize); 9 | vec 10 | } 11 | 12 | fn pop(stack: &mut Vec) -> Option { 13 | let poped_val = stack.pop(); 14 | // println!("The poped value is {:?}",poped_val); 15 | poped_val 16 | } 17 | 18 | fn push(stack: &mut Vec, item: char, maxsize: usize) { 19 | if stack.len() == maxsize { 20 | // println!("Can not add more") 21 | } else { 22 | stack.push(item); 23 | // println!("Stack: {:?}", stack); 24 | } 25 | } 26 | 27 | fn size(stack: &Vec) -> usize { 28 | stack.len() 29 | } 30 | 31 | fn main() { 32 | let input_string = String::from("Welcome to rust"); 33 | let size_stack = input_string.len(); 34 | let mut stack = new_stack(size_stack); 35 | let mut rev_string = String::new(); 36 | 37 | 38 | for i in input_string.chars() { 39 | push(&mut stack, i, size_stack); 40 | } 41 | 42 | 43 | for i in 0..size(&stack) { 44 | rev_string.push(pop(&mut stack).unwrap()); 45 | } 46 | println!("The input string is {:?}", input_string); 47 | println!("The reverse of the string is {:?} ",rev_string); 48 | 49 | } 50 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/5 - Project Stack Implementation/5-6-7 Expression Evaluation (Stacks).txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Programming-Master-Class-from-Beginner-to-Expert/7a219af138cce6793e3e5f1fb22bb50a4cac1b40/Course Code Bundle - 2022 Edition/5 - Project Stack Implementation/5-6-7 Expression Evaluation (Stacks).txt -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/6 - Structures, Traits, Generics, Enums/3 - Functions within a Trait.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Traits 3 | // - General explaination 4 | // - Default function implementation 5 | // - Functions within a trait implementation 6 | // ------------------------------------------- 7 | 8 | 9 | struct Data{ 10 | some_data: Vec, 11 | } 12 | 13 | trait BasicStats { 14 | fn mean(&self) -> f32; 15 | fn variance(&self) -> f32; 16 | } 17 | 18 | impl BasicStats for Data { 19 | fn mean(&self) -> f32 { 20 | let mut sum = 0; 21 | for i in self.some_data.iter(){ 22 | sum += *i; 23 | } 24 | //println!("{:?}",sum); 25 | sum as f32 / self.some_data.len() as f32 26 | 27 | } 28 | 29 | fn variance(&self) ->f32 { 30 | let mu = self.mean(); 31 | let mut sum_sqauared_diff:f32 = 0.0; 32 | for i in self.some_data.iter(){ 33 | sum_sqauared_diff += (*i as f32 - mu) * (*i as f32 - mu); 34 | } 35 | sum_sqauared_diff / self.some_data.len() as f32 36 | 37 | } 38 | } 39 | 40 | 41 | 42 | fn main() 43 | { 44 | let my_data = Data { 45 | some_data: vec![5, 6, 9, 8, 7, 4, 8], 46 | }; 47 | println!("the mean of the data is {}",my_data.mean()); 48 | println!("The standard deviation of the data is {}",my_data.variance()); 49 | 50 | 51 | } 52 | 53 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/6 - Structures, Traits, Generics, Enums/7 - Result Enum.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Result enum 3 | // - Basic Syntax and usage 4 | // ------------------------------------------- 5 | 6 | /* 7 | enum Result { 8 | Ok(T), 9 | Err(E), 10 | } 11 | */ 12 | 13 | // Example 1 14 | /* 15 | fn division(dividend: f64, divisor: f64) -> Result { 16 | 17 | /*if divisor == 0.0 { 18 | Err(String::from("Error: Division by zero")) 19 | } else { 20 | Ok(dividend / divisor) 21 | } 22 | */ 23 | 24 | match divisor { 25 | 0. => Err(String::from("Error: Division By Zero")), 26 | _ => Ok(dividend / divisor), 27 | } 28 | 29 | } 30 | 31 | 32 | fn main() { 33 | 34 | println!("\n\n{:?}", division(9.0, 3.0)); 35 | println!("{:?}", division(4.0, 0.0)); 36 | println!("{:?} \n\n", division(0.0, 2.0)); 37 | } 38 | 39 | */ 40 | 41 | 42 | // Example 2 43 | 44 | fn main() { 45 | let some_vec:Vec = vec![5,5,2,1,5,9]; 46 | 47 | let result1 = match some_vec.get(15) { 48 | Some(a) => Ok(a), 49 | None => Err("The value does not exist"), 50 | }; 51 | 52 | println!("The value of Result is {:?}", result1); 53 | 54 | 55 | 56 | } 57 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/7 - Iterators, Lifetimes, Closures/1 - Lifetimes (Part 1) .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Lifetimes 3 | // - Dangling Reference 4 | // - Undetermined Lifetimes 5 | // ------------------------------------------- 6 | 7 | // use std::vec; 8 | 9 | /* 10 | fn main(){ 11 | let i:&i32; 12 | { 13 | 14 | let j = 5; 15 | i = &j; 16 | } 17 | println!("The value of i = {}", i); 18 | } 19 | */ 20 | 21 | 22 | /* 23 | fn main() { 24 | 25 | let some_int = 10; 26 | let additional_int = some_fn(some_int); 27 | println!("{}", additional_int); 28 | 29 | } 30 | 31 | fn some_fn(i: i32) -> &i32{ 32 | &i 33 | } 34 | */ 35 | 36 | 37 | /* 38 | fn main(){ 39 | let int1 = 5; 40 | let int2 = 10; 41 | let result = greater(&int1,&int2); 42 | 43 | } 44 | 45 | fn greater(i:&i32,j:&i32) -> &i32 { 46 | if i> j { 47 | i 48 | } else {j 49 | } 50 | 51 | } 52 | */ 53 | 54 | 55 | 56 | 57 | fn main(){ 58 | let s_1 = "Hello"; 59 | 60 | 61 | let v; 62 | { 63 | let s_2 = String::from("World"); 64 | v = some_fn(s_1, s_2.as_str()); 65 | } 66 | println!("\n\n{} \n\n", v); 67 | } 68 | 69 | fn some_fn(first_str: &str, second_str: &str) -> &str { 70 | first_str 71 | 72 | } 73 | 74 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/7 - Iterators, Lifetimes, Closures/4 - Closures (Part 2).txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Closures 3 | // - A quick recap 4 | // - Borrow by immutable reference 5 | // - Borrow by a mutable reference 6 | // - Moving of a value into a closure 7 | // ------------------------------------------- 8 | 9 | 10 | 11 | /* 12 | fn main(){ 13 | 14 | let some_closure_1 = |x: u32| -> u32 { x + 1 }; 15 | let some_closure_2 = |x| { x + 1 }; 16 | let some_closure_3 = |x| x + 1 ; 17 | } 18 | */ 19 | 20 | 21 | 22 | /* 23 | fn main(){ 24 | let mut vec_1 = vec![1, 2,3]; 25 | let some_closure = || { 26 | // vec_1 is being used by reference. 27 | println!("Vec 1 : {:?}", vec_1); 28 | }; 29 | 30 | println!("Vec_1: {:?}",vec_1); 31 | some_closure(); 32 | 33 | vec_1[1] = 15; 34 | } 35 | */ 36 | 37 | 38 | /* 39 | fn main(){ 40 | let mut vec_1 = vec![4,5,6]; 41 | let mut some_closure = || { 42 | 43 | vec_1.push(35); 44 | 45 | }; 46 | 47 | //println!("vec_2 {:?}", vec_2); 48 | //vec_1[1] = 15; 49 | some_closure(); 50 | 51 | 52 | // vec_1[2] = 15; 53 | 54 | } 55 | 56 | */ 57 | 58 | fn main(){ 59 | let mut vec_1 = vec![1,2,3]; 60 | let some_closure = || { 61 | 62 | let vec_2 = vec_1; 63 | }; 64 | 65 | 66 | some_closure(); 67 | println!("vec 1 = {:?} ", vec_1); 68 | println!("vec 2 = {:?} ", vec_2); 69 | 70 | } 71 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/7 - Iterators, Lifetimes, Closures/5 - Function types .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Function Types 3 | // - Basic syntax and use 4 | // - Function types as parameters to function 5 | // ------------------------------------------- 6 | 7 | /* 8 | fn max(x: i32, y: i32) -> i32 { 9 | if x > y { 10 | x 11 | } else { 12 | y 13 | } 14 | } 15 | 16 | fn min(x: i32, y: i32) -> i32 { 17 | if x < y { 18 | x 19 | } else { 20 | y 21 | } 22 | } 23 | 24 | fn main(){ 25 | let mut f = max; 26 | println!("The minimum of the two values is {}",f(2,3)); 27 | } 28 | */ 29 | 30 | 31 | /* 32 | 33 | fn prints_name(name: &str) { 34 | print!("The name is {}",name); 35 | } 36 | 37 | fn prints_full_info(f: fn(&str), some_one: &str, age: i32) { 38 | f(some_one); 39 | println!(" and my age is {}", age); 40 | } 41 | 42 | fn main() { 43 | let (my_name, my_age) = (String::from("Nouman"), 40); 44 | prints_full_info(prints_name, &my_name, my_age) ; 45 | } 46 | */ 47 | 48 | 49 | 50 | fn add_one(x: i32) -> i32 { 51 | x + 1 52 | } 53 | 54 | fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 { 55 | f(arg) + f(arg) 56 | } 57 | 58 | fn main() { 59 | let answer = do_twice(add_one, 5); 60 | println!("The answer is: {}", answer); 61 | } 62 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/7 - Iterators, Lifetimes, Closures/7 - Iterators (Part 2) .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Iterators 3 | // - Basics 4 | // - Some useful functions for iterators 5 | // - Common statistics 6 | // - Modifying and collecting values 7 | // ------------------------------------------- 8 | 9 | fn main() 10 | { 11 | let a = vec![0, 1, 2, 3,4,5,6,7]; 12 | 13 | 14 | let filtered_values = a.iter().filter(|&x| *x >= 5).collect::>(); 15 | println!(" {:?}", filtered_values); 16 | 17 | 18 | let b = a.clone(); 19 | let filtered_values= a.into_iter().filter(|x| *x >= 5).collect::>(); 20 | println!(" {:?}", filtered_values); 21 | 22 | // println!(" {:?}", a); 23 | 24 | 25 | let mut mapped_values = b.iter().map(|x| 2 * *x).collect::>(); 26 | println!(" {:?}", mapped_values); 27 | 28 | 29 | 30 | let mut mapped_values = b.iter().map(|x| 2 * x).filter(|x| *x > 10).collect::>(); 31 | 32 | println!(" {:?}", mapped_values); 33 | 34 | // https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map 35 | 36 | } 37 | 38 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/7 - Iterators, Lifetimes, Closures/Exercise/7 - Sum of multiples.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Programming-Master-Class-from-Beginner-to-Expert/7a219af138cce6793e3e5f1fb22bb50a4cac1b40/Course Code Bundle - 2022 Edition/7 - Iterators, Lifetimes, Closures/Exercise/7 - Sum of multiples.txt -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/8 - Rust Modules/3 - Using External crates .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // External Crates 3 | // - Add to cargo.toml under dependency array_tool = "1.0.3" 4 | // ------------------------------------------- 5 | 6 | use array_tool::vec::*; 7 | fn main() { 8 | let vec_1 = vec![1,1,3,5,6,7]; 9 | let vec_2 = vec![1,2,3]; 10 | let intesection = vec_1.intersect(vec_2.clone()); 11 | println!("The intersection = {:?}",intesection); 12 | 13 | 14 | let union_set = vec_1.union(vec_2.clone()); 15 | println!("The union = {:?}",union_set); 16 | println!("Vec 1 three times displayed = {:?}",vec_2.times(3)); 17 | 18 | } -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/8 - Rust Modules/Rust Modules (Part 1)/file_1.txt: -------------------------------------------------------------------------------- 1 | pub fn printing() { 2 | println!("Hello from first crate"); 3 | } -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/8 - Rust Modules/Rust Modules (Part 1)/file_2.txt: -------------------------------------------------------------------------------- 1 | pub fn printing() { 2 | println!("Hello from second crate"); 3 | } -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/8 - Rust Modules/Rust Modules (Part 1)/lib.txt: -------------------------------------------------------------------------------- 1 | pub mod file_1; 2 | pub mod file_2; -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/8 - Rust Modules/Rust Modules (Part 1)/main.txt: -------------------------------------------------------------------------------- 1 | use new_project::file_1; 2 | use new_project::file_2; 3 | 4 | fn main() { 5 | new_project::file_1::printing(); 6 | new_project::file_2::printing(); 7 | } 8 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/8 - Rust Modules/Rust Modules (Part 2)/1 - Rust Modules (Part 1).txt: -------------------------------------------------------------------------------- 1 | /*mod file_1; 2 | fn main(){ 3 | 4 | let rect1 = Rectangle{ 5 | length: 5, 6 | width:10, 7 | }; 8 | let area_rect1 = rect_area(&rect1.length, &rect1.width); // also del the file_1:: if you are including the code in the same script 9 | } 10 | 11 | struct Rectangle{ 12 | length: i32, 13 | width:i32, 14 | } 15 | */ 16 | 17 | /* 18 | fn some_fn() { 19 | println!("This is the function of the file_1 crate"); 20 | } 21 | 22 | mod maths { 23 | pub mod basic_math { 24 | pub fn multiplication(num1:&i32, num2:&i32) -> i32{ 25 | let result = num1 * num2; 26 | printing(&result); 27 | result 28 | } 29 | fn printing(num: &i32) { 30 | println!("The result is {}", num); 31 | crate::some_fn(); 32 | } 33 | 34 | } 35 | } 36 | 37 | 38 | fn rect_area(length:&i32, width:&i32) -> i32 { 39 | // absolute path 40 | use maths::basic_math::multiplication; 41 | multiplication(length, width) // parents can not see child modules but childs can see parents modules by default 42 | } 43 | */ 44 | 45 | 46 | /* 47 | mod file_2; 48 | fn main() { 49 | file_2::some_person(); 50 | } 51 | */ 52 | 53 | mod file_3; 54 | 55 | fn main() 56 | { 57 | file_3::allowance(); 58 | } 59 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/8 - Rust Modules/Rust Modules (Part 2)/file_1.txt: -------------------------------------------------------------------------------- 1 | fn some_fn() { 2 | println!("This is the function of the file_1 crate"); 3 | } 4 | 5 | mod maths { 6 | pub mod basic_math { 7 | pub fn multiplication(num1:&i32, num2:&i32) -> i32{ 8 | let result = num1 * num2; 9 | printing(&result); 10 | result 11 | } 12 | fn printing(num: &i32) { 13 | println!("The result is {}", num); 14 | crate::file_1::some_fn(); 15 | } 16 | 17 | } 18 | } 19 | 20 | 21 | // Point: The program will not compile if we remove the pub word 22 | pub fn rect_area(length:&i32, width:&i32) -> i32 { 23 | // absolute path 24 | use maths::basic_math::multiplication; 25 | multiplication(length, width) // parents can not see child modules but childs can see parents modules by default 26 | } 27 | 28 | /* 29 | file_1 30 | - math 31 | - basic maths 32 | rect_area() 33 | some_fn() 34 | 35 | */ 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/8 - Rust Modules/Rust Modules (Part 2)/file_2.txt: -------------------------------------------------------------------------------- 1 | mod person { 2 | pub struct personal_info { 3 | pub age: u8, 4 | pub education: String, 5 | } 6 | 7 | impl personal_info{ 8 | pub fn new(new_edu: &str) -> Self { 9 | Self { 10 | education: String::from(new_edu), 11 | age: 20, 12 | } 13 | } 14 | } 15 | } 16 | 17 | pub fn some_person() { 18 | let mut person1 = person::personal_info::new("bachelors"); 19 | person1.education = String::from("Masters"); 20 | 21 | 22 | let person2 = person::personal_info { 23 | age: 42, 24 | education: String::from("Masters"), 25 | }; 26 | 27 | } 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/8 - Rust Modules/Rust Modules (Part 2)/file_3.txt: -------------------------------------------------------------------------------- 1 | 2 | mod travel_history { 3 | enum Conveyance { 4 | Car, 5 | Train, 6 | Air, 7 | } 8 | } 9 | 10 | 11 | pub fn allowance() { 12 | let travel_1 = travel_history::Conveyance::Car; 13 | let travel_2 = travel_history::Conveyance::Train; 14 | } 15 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/9 - Smart Pointers/1 - Basics of Smart Pointers.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Smart Pointers 3 | // - Box Pointers 4 | // ------------------------------------------- 5 | 6 | 7 | fn main() { 8 | let single_value = Box::new(0.625); 9 | let x = 0.625; 10 | println!("Are the values being equal {}", x == *single_value); // deref is needed when box contains a single value 11 | 12 | 13 | let mut stack_var = 4; 14 | let stack_ref = &stack_var; 15 | let heap_var = Box::new(stack_var); // what happens when we write stack_var inside the (stack_ref) 16 | 17 | 18 | stack_var = 5; 19 | println!("The value of stack_var = {} and heap_var = {}", stack_var, heap_var); 20 | 21 | 22 | let point = Box::new((100, 125)); 23 | println!("{} {}", 100 == point.0, point.1); 24 | 25 | let x = point; // 26 | } -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/9 - Smart Pointers/2 - Box Pointers and When they are Useful .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Smart Pointers 3 | // - Box Pointers 4 | // - Use Case of Box Pointers 5 | // ------------------------------------------- 6 | 7 | 8 | /* 9 | #[derive(Debug)] 10 | enum List { 11 | Cons(i32, List), 12 | Nil, 13 | } 14 | use List::{Cons, Nil}; 15 | 16 | 17 | /* 18 | enum Conveyance { 19 | Car(i32), 20 | Train(i32), 21 | Air(i32), 22 | Walk 23 | } 24 | */ 25 | fn main() { 26 | let list = Cons(1, Cons(2, Cons(3, Nil))); 27 | // let list = List::Cons(1, List::Cons(2, List::Cons(3, List::Nil))); 28 | println!("{:?}",list); 29 | } 30 | */ 31 | 32 | 33 | #[derive(Debug)] 34 | enum List { 35 | Cons(i32, Box), 36 | Nil, 37 | } 38 | 39 | fn main() { 40 | let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Cons(3, Box::new(List::Nil)))))); 41 | println!("{:?}",list); 42 | } 43 | 44 | -------------------------------------------------------------------------------- /Course Code Bundle - 2022 Edition/9 - Smart Pointers/4 - Generics and Deref Coercion in Smart Pointers.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Smart Pointers 3 | // - Custom Defined Smart pointers 4 | // - Deref Coercion 5 | // ------------------------------------------- 6 | 7 | struct MySmartPointer{value: T, 8 | name: String} // add it at the end 9 | 10 | 11 | impl MySmartPointer { 12 | fn new(x:T)-> MySmartPointer { 13 | MySmartPointer{value: x, name:String::from("Hello")} 14 | 15 | } 16 | } 17 | 18 | use std::ops::Deref; 19 | impl Deref for MySmartPointer { 20 | type Target = T; 21 | fn deref(&self) -> &T { 22 | &self.value 23 | } 24 | } 25 | 26 | 27 | 28 | impl Drop for MySmartPointer{ 29 | fn drop(&mut self){ 30 | println!("dropping MySmartPointer object from memory {:?}", self.value); 31 | } 32 | } 33 | 34 | 35 | fn my_fn(str: &str) 36 | 37 | { 38 | println!("The string recieved from teh main is \"{}\"", str); 39 | } 40 | 41 | 42 | #[derive(Debug)] 43 | struct Person{ 44 | name: String, 45 | 46 | } 47 | q 48 | 49 | fn main() { 50 | let sptr_p1 = MySmartPointer::new("Nouman Azam"); 51 | my_fn(&sptr_p1); 52 | 53 | let some_vec = MySmartPointer::new(vec![1,2,3]); 54 | 55 | for z in &*some_vec.value { 56 | println!("The value is {}", z); 57 | 58 | } 59 | 60 | } 61 | 62 | 63 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/10 - Real Life Application/1 - Search Results using Word Groupings.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Correct Search Results Using Word Grouping 3 | // - Description 4 | // - Given a list of words, group the words that are anagrams 5 | 6 | // - Tools 7 | // - Hashmaps, Nested Loops 8 | // ------------------------------------------- 9 | 10 | use std::collections::HashMap; 11 | fn word_grouping(words_list: Vec) -> Vec> 12 | { 13 | let mut word_hash = HashMap::new(); 14 | let mut char_freq = vec![0; 26]; 15 | 16 | for current_word in words_list { 17 | for c in current_word.to_lowercase().chars() { 18 | 19 | char_freq[(c as u32 - 'a' as u32) as usize] += 1; 20 | } 21 | 22 | let key: String = char_freq.into_iter().map(|i| i.to_string()).collect::(); 23 | word_hash.entry(key).or_insert(Vec::new()).push(current_word); 24 | 25 | char_freq=vec![0;26]; 26 | } 27 | 28 | // Just for hte sake of output and confirming the (key, value) pairs 29 | for (key,value) in &word_hash{ 30 | println!("key # {:?} value {:?}",key,value); 31 | } 32 | 33 | 34 | word_hash.into_iter().map(|(_, v)| v).collect() 35 | 36 | } 37 | 38 | fn main() { 39 | let words = vec!["The".to_string(),"teh".to_string(), 40 | "het".to_string(),"stupid".to_string(),"studpi".to_string(),"apple".to_string(), 41 | "appel".to_string()]; 42 | 43 | 44 | let grouping = word_grouping(words); 45 | println!("{:?}\n\n\n", grouping); 46 | 47 | let input_word = String::from("teh"); 48 | 49 | for i in grouping.into_iter() { 50 | if i.contains(&input_word) 51 | { 52 | println!("The group of the word is {:?}", i); 53 | } 54 | 55 | } 56 | 57 | } -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/10 - Real Life Application/2 - Product Popularity .txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | // ------------------------------------------- 4 | // Popularity Scores 5 | // - Description 6 | // - Given some products along with its respectively popularity scores, 7 | // We want to determine if the popularity is fulctuating, increasing or decreasing 8 | 9 | // - Tools 10 | // - Hashmaps, Loops, conditional if 11 | // ------------------------------------------- 12 | 13 | fn popularity_analysis(scores: Vec) -> bool 14 | { 15 | let mut increasing = true; 16 | let mut decreasing = true; 17 | 18 | for i in 0..scores.len()-1 { 19 | if scores[i] > scores[i+1] 20 | { 21 | increasing = false; 22 | } 23 | if scores[i] < scores[i+1] 24 | { 25 | decreasing = false; 26 | } 27 | } 28 | return increasing || decreasing; 29 | } 30 | 31 | use std::collections::HashMap; 32 | 33 | fn main() { 34 | let mut products = HashMap::new(); 35 | 36 | products.insert("Product 1", vec![1,2,2,3]); 37 | products.insert("Product 2", vec![4,5,6,3,4]); 38 | products.insert("Product 3",vec![8,8,7,6,5,4,4,1] ); 39 | 40 | for (product_id, popularity) in products { 41 | if popularity_analysis(popularity) { 42 | println!("{} popularity is increasing or decreasing", product_id); 43 | } 44 | else{ 45 | println!("{} popularity is Fluctuating", product_id); 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/10 - Real Life Application/3 - Maximum Product Earning.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Highest Price Stock 3 | // - Description 4 | // - We have weekwise stock prices. we want to retrieve the highest 5 | // stock price in any in any week in little to no time. 6 | // 7 | // - Tools 8 | // - Maxstacks, Structures, Vectors 9 | // ------------------------------------------- 10 | 11 | 12 | 13 | 14 | struct MaxStack{ 15 | main_stack: Vec, 16 | maximum_stack: Vec 17 | } 18 | impl MaxStack { 19 | fn new() -> Self { 20 | MaxStack { 21 | main_stack: Vec::new(), 22 | maximum_stack: Vec::new(), 23 | } 24 | } 25 | 26 | 27 | fn push(&mut self,value: i32){ 28 | self.main_stack.push(value); 29 | if !self.maximum_stack.is_empty() && self.maximum_stack.last().unwrap() > &value { 30 | self.maximum_stack.push(*self.maximum_stack.last().unwrap()); 31 | } 32 | else { 33 | self.maximum_stack.push(value); 34 | } 35 | } 36 | fn pop(&mut self) { 37 | self.main_stack.pop(); 38 | self.maximum_stack.pop(); 39 | } 40 | 41 | 42 | fn max_value(&self) -> i32 { 43 | *self.maximum_stack.last().unwrap() 44 | } 45 | 46 | } 47 | 48 | 49 | 50 | fn main() { 51 | 52 | let mut stack = MaxStack::new(); 53 | stack.push(55); 54 | stack.push(80); 55 | stack.push(120); 56 | stack.push(99); 57 | stack.push(22); 58 | stack.push(140); 59 | stack.push(145); 60 | 61 | print!("Maximum value of stock: "); 62 | println!("{:}",stack.max_value()); 63 | 64 | 65 | println!("After going one week back"); 66 | print!("Maximum value of stock: "); 67 | stack.pop(); 68 | 69 | println!("{:}",stack.max_value()); 70 | 71 | } 72 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/10 - Real Life Application/6 - Suggest Items for Special Shopping Card.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Suggesting Items for Special Shopping Card 3 | // - Description 4 | // - Given a list of prices, return a couple of items with their sum matching the given price 5 | // - Tools 6 | // - Hashsets, Vectors 7 | // ------------------------------------------- 8 | 9 | use std::collections::HashSet; 10 | fn product_suggestions(product_prices:Vec, amount:i32) -> Vec>{ 11 | let mut prices_hash = HashSet::new(); 12 | let mut offers = Vec::new(); 13 | 14 | //ec![11, 30, 55, 34, 45, 10, 19, 20, 60, 5, 23]; 15 | for i in product_prices { 16 | let diff = amount-i; 17 | if prices_hash.get(&diff).is_none() { 18 | prices_hash.insert(i); 19 | } else { 20 | offers.push(vec![i, diff]); 21 | } 22 | 23 | } 24 | 25 | offers 26 | } 27 | 28 | 29 | 30 | 31 | // Driver code 32 | fn main(){ 33 | let product =vec![11, 30, 55, 34, 45, 10, 19, 20, 60, 5, 23]; 34 | 35 | let suggestions = product_suggestions(product, 50); 36 | println!("{:?}",suggestions); 37 | //return 0; 38 | } -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/11 - Efficient Programming with Rust/1 - Initializing stuct instances .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Initializing Struct Instance 3 | // ------------------------------------------- 4 | use project::Student; 5 | fn main() { 6 | /* 7 | let new_student = Student { 8 | id: 11, 9 | name: "joseph".to_string(), 10 | age: 20, 11 | }; 12 | */ 13 | 14 | 15 | 16 | 17 | let new_student = Student::new("joseph".to_string()) 18 | .unwrap_or_default(); // next example, make sure to remove semicolon from the statement above 19 | 20 | println!("{:?}", new_student); 21 | 22 | 23 | 24 | let new_student = Student::default(); 25 | println!("{:?}", new_student); 26 | 27 | let new_student = Student { 28 | age: 12, 29 | .. Default::default() 30 | }; 31 | } 32 | 33 | 34 | 35 | // code for library 36 | #[derive(Debug, Default)] 37 | pub struct Student { 38 | pub id: u8, 39 | 40 | pub name: String, 41 | pub age: u8, 42 | } 43 | 44 | impl Student { 45 | /* 46 | pub fn new(std_name: String) -> Self { 47 | Self { 48 | id: 0, 49 | name: std_name, 50 | age: 20, 51 | } 52 | } 53 | */ 54 | 55 | 56 | pub fn new(std_name: String) -> Result { 57 | if std_name.chars().all(|x| matches!(x, 'a'..='z')) { 58 | Ok(Self { 59 | id: 0, 60 | name: std_name, 61 | age: 20, 62 | }) 63 | } else { 64 | Err("The name is invalid".to_string()) 65 | } 66 | } 67 | } 68 | 69 | /* 70 | impl Default for Student { 71 | fn default() -> Self { 72 | Self { 73 | id: 0, 74 | name: "unknown".to_string(), 75 | age: 20, 76 | } 77 | } 78 | } 79 | 80 | */ 81 | 82 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/11 - Efficient Programming with Rust/2 - Fucntion inputs and coercion.txt: -------------------------------------------------------------------------------- 1 | 2 | // ------------------------------------------- 3 | // Fucntion Inputs and Coercion 4 | // ------------------------------------------- 5 | 6 | // Example 1 7 | /* 8 | 9 | fn vowels(word: &String) -> u8 { 10 | //fn vowels(word: &str) -> u8 { 11 | 12 | 13 | let vowels_count = word_chars. 14 | into_iter(). 15 | filter(|x| (*x == 'a') |(*x == 'e') |(*x == 'i')|(*x == 'o') | (*x == 'u')).count(); 16 | vowels_count as u8 17 | } 18 | 19 | fn main() { 20 | let affan = "affan".to_string(); 21 | println!("{}: {:?}", affan, vowels(&affan)); 22 | 23 | 24 | println!("Ferris: {}", vowels("Ferris")); 25 | 26 | } 27 | 28 | */ 29 | 30 | 31 | // Example 2: &T over &Box becuase it is being coerced to that type 32 | 33 | /* 34 | //fn length_str(x: &Box<&str>) { 35 | fn length_str(x: &str) { 36 | println!("length of the string {} is {} ",x, x.len()); 37 | } 38 | 39 | 40 | fn main() { 41 | length_str("hello rust"); 42 | let box_str = Box::new("Hello"); 43 | length_str(&box_str); 44 | } 45 | 46 | */ 47 | 48 | 49 | 50 | // Example 3: &[T] over &Vec 51 | //fn square_values(num_vec: &Vec) { 52 | fn square_values(num_vec: &[i32]) { 53 | for i in num_vec{ 54 | println!("The square is {}", i*i); 55 | } 56 | } 57 | 58 | fn main() { 59 | let values_vec = vec![1,2,3,6,5]; 60 | let values_array = [1,2,3,4,5,6]; 61 | 62 | square_values(&values_vec); 63 | square_values(&values_array); 64 | } 65 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/11 - Efficient Programming with Rust/4-Disable Mutability for final obj.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // - Disabling mutability for finalized objects 3 | // ------------------------------------------- 4 | 5 | /* 6 | fn main() { 7 | 8 | // Method 1: using variable rebinding 9 | let mut data = vec![5,6,9,4,3]; 10 | data.sort(); 11 | let data = data; 12 | 13 | 14 | // method 2: using code block 15 | let data = { 16 | let mut data = vec![5,6,9,4 ,3]; 17 | data.sort(); 18 | data 19 | }; 20 | 21 | } 22 | */ 23 | 24 | 25 | // Example 2: Here's a pattern for disabling mutability for "finalized" objects, even in mutable owned copies of a thing, preventing misuse. Done by wrapping it in a newtype with a private 26 | // inner value that implements Deref but not DerefMut: 27 | 28 | #[derive(Debug, Clone)] 29 | pub struct finalized_config(T); 30 | 31 | impl Copy for finalized_config where T: Copy {} 32 | 33 | impl std::ops::Deref for finalized_config { 34 | type Target = T; 35 | 36 | fn deref(&self) -> &T { 37 | &self.0 38 | } 39 | } 40 | 41 | #[derive(Default)] 42 | struct Config { 43 | a: usize, 44 | b: String, 45 | } 46 | 47 | impl Config { 48 | fn new() -> Self { 49 | Self { a: 0, b: String::from("Hello") } 50 | } 51 | 52 | fn build(self) -> finalized_config { 53 | finalized_config(self) 54 | } 55 | } 56 | 57 | 58 | 59 | fn main() { 60 | let mut my_configuration = Config::new(); 61 | my_configuration.a = 6; 62 | 63 | let finalized = my_configuration.build(); 64 | 65 | let mut finalized_copy = finalized; 66 | //finalized_copy.a = 666; 67 | } 68 | 69 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/11 - Efficient Programming with Rust/5-String Concatenation & Ownership.txt: -------------------------------------------------------------------------------- 1 | fn main() 2 | { 3 | // ------------------------------------------- 4 | // String concatenation and onwership 5 | // ------------------------------------------- 6 | 7 | /* let s1 = String::from("hello"); 8 | let s2: &str = "world"; 9 | 10 | let s3 = s1 + s2; // the ownership changed here 11 | println!("{}", s3); 12 | */ 13 | 14 | /* let s1 = String::from("hello"); 15 | let s2 = String::from("world"); 16 | 17 | let s3 = s1 + &s2; // The ownership of only owned_string1 changed 18 | println!("{} {} ", s3 , s2); 19 | */ 20 | 21 | let s1 = String::from("hello"); 22 | let s2 = String::from("world"); 23 | let s3 = String::from(" from Rust"); 24 | 25 | let s4 = s1 + &s2 + &s3; // The ownership of only s1 changed 26 | println!("{} {} {}", s4,s2,s3); 27 | 28 | } 29 | 30 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/11 - Efficient Programming with Rust/6 - Simplifying Sturctures.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // - Simplifying structures 3 | // ------------------------------------------- 4 | 5 | 6 | struct A { 7 | f1: u32, 8 | f2: u32, 9 | f3: u32, 10 | } 11 | 12 | fn fn1(a: &mut A) -> &u32 { &a.f2 } 13 | fn fn2(a: &mut A) -> u32 { a.f1 + a.f3 } 14 | 15 | fn fn3(a: &mut A) { 16 | let x = fn1(a); 17 | let y = fn2(a); 18 | println!("{}", x); 19 | } 20 | 21 | struct A { 22 | b: B, 23 | c: C, 24 | } 25 | struct B { 26 | f2: u32, 27 | } 28 | struct C { 29 | f1: u32, 30 | f3: u32, 31 | } 32 | 33 | // These functions take a B or C, rather than A. 34 | fn fn1(b: &mut B) -> &u32 { &b.f2 } 35 | fn fn2(c: &mut C) -> u32 { c.f1 + c.f3 } 36 | 37 | fn fn3(a: &mut A) { 38 | let x = fn1(&mut a.b); 39 | let y = fn2(&mut a.c); 40 | println!("{}", x); 41 | } 42 | 43 | fn main() {} 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/11 - Efficient Programming with Rust/8 - todo Macro .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // - ToDo Macro 3 | // ------------------------------------------- 4 | #[derive(Default)] 5 | struct Student { 6 | name_std: String, 7 | age: u8, 8 | sex: char, 9 | country: String, 10 | salary: u32, 11 | nationality: String, 12 | } 13 | 14 | impl Student { 15 | fn some_fn_1(&self) -> String { 16 | // todo!() 17 | "".to_string() 18 | } 19 | 20 | fn some_fn_2(&self) -> u8 { 21 | todo!() 22 | } 23 | } 24 | trait GeneralInfo { 25 | fn info(&self) -> (&str, u8,char); 26 | fn country_info(&self) -> &str; 27 | } 28 | 29 | fn main(){ 30 | let student_1 = Student::default(); 31 | student_1.some_fn_1(); 32 | } -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/11 - Efficient Programming with Rust/9 - String Literals.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // - String Literal 3 | // ------------------------------------------- 4 | fn main() { 5 | let str = r"The main said _Hello world_ \n \t ' "; 6 | println!("{}", str); 7 | 8 | let jason_str = "{ 9 | \" name \": \"Micheal\", 10 | \"age\": 40, 11 | \"sex\": Male 12 | }"; 13 | 14 | let jason_str1 = r#"{ 15 | " name ": "Micheal", 16 | "age": 40, 17 | "sex": Male 18 | }"#; 19 | 20 | let str = r###"Hello"## World!"###; 21 | 22 | 23 | // Exercise for you 24 | 25 | let string1 = r#"""#; // " 26 | let string2 = r#""""""""#; // """""" 27 | let string3 = r#" He asked,"Is rust awesome?"""#; // He asked,"Is rust awesome?" 28 | println!("{}", string1); 29 | println!("{}", string2); 30 | println!("{}", string3); 31 | } -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/12- Concurrency in RUST/1 - Thread basics.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Threads Basics 3 | // ------------------------------------------- 4 | use std::thread; 5 | use std::time::Duration; 6 | 7 | fn main() { 8 | println!("This will be printed"); 9 | println!("This will also be printed"); 10 | println!("The concurrency will start after this line"); 11 | 12 | let t = thread::spawn(|| { 13 | println!("Hello 1 from the thread"); 14 | println!("Hello 2 from the thread"); 15 | println!("Hello 3 from the thread"); 16 | println!("Hello 4 from the thread"); 17 | println!("Hello 5 from the thread"); 18 | println!("Hello 6 from the thread"); 19 | println!("Hello 7 from the thread"); 20 | }); 21 | 22 | 23 | thread::sleep(Duration::from_millis(1)); 24 | println!("Hello 1 from the main"); 25 | println!("Hello 2 from the main"); 26 | t.join(); 27 | } -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/12- Concurrency in RUST/10 - Thread Parking and Yield.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Thread Park 3 | // ------------------------------------------- 4 | 5 | use std::thread; 6 | use std::time::Duration; 7 | fn main() { 8 | let job_1 = thread::spawn(|| { 9 | println!("-- Job 1 has started -- "); 10 | println!("Waiting for job 2 to complete"); 11 | //thread::park_timeout(Duration::from_secs(2)); 12 | //thread::sleep(Duration::from_secs(2)); 13 | thread::yield_now(); 14 | 15 | println!("-- Job 1 resumed --"); 16 | println!("-- Job 1 finished"); 17 | }); 18 | 19 | let job_2 = thread::spawn(|| { 20 | println!("-- Job 2 started --"); 21 | println!(" -- Job 2 finished --"); 22 | }); 23 | job_2.join().unwrap(); 24 | println!("Job 2 is now completed"); 25 | println!("Job 1 will now resume"); 26 | job_1.thread().unpark(); 27 | job_1.join().unwrap(); 28 | } 29 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/12- Concurrency in RUST/11 - Async-Await.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Async Await basics 3 | // tokio = {version = "1.17", features = ["full"]} 4 | // ------------------------------------------- 5 | 6 | async fn printing(){ 7 | println!("I am async function"); 8 | } 9 | 10 | #[tokio::main] 11 | async fn main(){ 12 | let x = printing(); 13 | println!("The has not being polled yet"); 14 | drop(x); 15 | //x.await; 16 | 17 | } -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/12- Concurrency in RUST/2 - Multiple Threads and Ownership in Threads .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Multiple Threads 3 | // Ownership and Threads 4 | // ------------------------------------------- 5 | 6 | use std::thread; 7 | fn main(){ 8 | 9 | /* 10 | let mut thread_vec = vec![]; 11 | for i in 0..10 { 12 | thread_vec.push(thread::spawn(move || { 13 | println!("Thread number {}", i); 14 | })); 15 | } 16 | 17 | for i in thread_vec { 18 | i.join(); 19 | } 20 | */ 21 | 22 | let v = vec![1,2,3]; 23 | let x = 5; 24 | let handle = thread::spawn(move || { 25 | println!("Here's a vector: {:?}", v); 26 | println!("Here's a variable : {:?}", x); 27 | }); 28 | 29 | drop(x); 30 | println!("The variable x is still alive {}", x) ; 31 | println!("The variable v is not alive {}", v) ; 32 | handle.join(); 33 | } 34 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/12- Concurrency in RUST/3 - Communication through channels.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Message Passing through Channels 3 | // ------------------------------------------- 4 | use std::thread; 5 | use std::sync::mpsc; 6 | fn main(){ 7 | let (tx, rx) = mpsc::channel(); 8 | 9 | // let rx1 = rx; 10 | 11 | let t = thread::spawn(move || { 12 | let val = String::from("some data from sender"); 13 | println!("Value sending from the thread"); 14 | tx.send(val).unwrap(); 15 | // println!("This may execute after the statement in the main"); 16 | // println!("Val is {:?}", val); 17 | }); 18 | 19 | //let recieved = rx.recv().unwrap(); 20 | //println!("Recieved: {:?}", recieved); 21 | 22 | t.join(); 23 | let mut recieved_status = false; 24 | while recieved_status != true { 25 | match rx.try_recv() { 26 | Ok(recieved_value) => { 27 | println!("Recieved value is {:?}", recieved_value); 28 | recieved_status = true; 29 | }, 30 | Err(_) => println!("I am doing some other stuff"), 31 | } 32 | } 33 | 34 | } -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/12- Concurrency in RUST/5 - Sharing States .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Sharing States 3 | // ------------------------------------------- 4 | use std::sync::Mutex; 5 | fn main() { 6 | let m = Mutex::new(5); 7 | 8 | /* 9 | { 10 | let mut num = m.lock().unwrap(); 11 | *num = 10; 12 | } 13 | 14 | println!("m = {:?}", m); 15 | */ 16 | 17 | let mut num = m.lock().unwrap(); 18 | *num = 10; 19 | drop(num); 20 | 21 | let mut num1 = m.lock().unwrap(); 22 | *num1 = 15; 23 | drop(num1); 24 | 25 | } -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/12- Concurrency in RUST/6 - Passing Mutexes between Threads.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Passes Mutexes betwen Threads 3 | // ------------------------------------------- 4 | 5 | /* 6 | use std::sync::Mutex; 7 | use std::thread; 8 | //use std::rc::Rc; 9 | //use std::sync::Arc; // add later on 10 | 11 | fn main() { 12 | let counter = Mutex::new(0); 13 | //let counter = Rc::new(Mutex::new(0)); 14 | //let counter = Arc::new(Mutex::new(0)); 15 | 16 | let mut handles = vec![]; 17 | 18 | for _ in 0..10 { 19 | //let counter = Rc::clone(&counter); 20 | //let counter = Arc::clone(&counter); 21 | let handle = thread::spawn(move || { 22 | let mut num = counter.lock().unwrap(); 23 | 24 | *num += 1; 25 | }); 26 | handles.push(handle); 27 | } 28 | 29 | for handle in handles { 30 | handle.join().unwrap(); 31 | } 32 | 33 | println!("Result: {}", *counter.lock().unwrap()); 34 | } 35 | */ 36 | 37 | 38 | 39 | // Example 2: A nice usecase of the Arc for cloning types which are not clone (does not implement clone) 40 | 41 | use std::thread; 42 | use std::sync::Arc; 43 | 44 | struct MyString(String); 45 | 46 | impl MyString { 47 | fn new(s: &str) -> MyString { 48 | MyString(s.to_string()) 49 | } 50 | } 51 | 52 | fn main() { 53 | let mut threads = Vec::new(); 54 | let name = Arc::new(MyString::new("Rust")); 55 | 56 | for i in 0..5 { 57 | let some_str = name.clone(); 58 | let t = thread::spawn(move || { 59 | println!("hello {} count {}", some_str.0, i); 60 | }); 61 | threads.push(t); 62 | } 63 | 64 | for t in threads { 65 | t.join(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/12- Concurrency in RUST/9 - Scoped Threads.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Scope Threads 3 | // ------------------------------------------- 4 | 5 | use std::thread; 6 | 7 | fn main() { 8 | let mut vec = vec![1, 2, 3]; 9 | let mut x = 0; 10 | 11 | thread::scope(|some_scope| { 12 | some_scope.spawn(|| { 13 | println!("I am first thread in the scope"); 14 | println!("{:?}", vec); 15 | }); 16 | 17 | some_scope.spawn(|| { 18 | println!("I am second thread in the scope"); 19 | x += 45; 20 | // vec.push(4); 21 | println!("{:?}", vec); 22 | }); 23 | }); 24 | 25 | println!("The threads are now complete"); 26 | vec.push(5); 27 | println!("x: {:?} and vec: {:?}", x, vec); 28 | } 29 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/13 - Text Processing, File and directory handlign/1-Basic File Handling.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Basic File Handling 3 | // ------------------------------------------- 4 | use std::fs::*; 5 | use std::io::{BufRead, BufReader, Read, Write}; 6 | use std::path::Path; 7 | 8 | fn basic_file_handling() -> std::io::Result<()> { 9 | let path_loc = r"D:\my_text.txt"; 10 | let path = Path::new(path_loc); 11 | // let mut file = File::create(path)?; 12 | 13 | //file.write(b"let's put this in the file")?; 14 | // file.write("let's put this in the file".as_bytes())?; 15 | 16 | 17 | // let mut file = OpenOptions::new().append(true).open(path)?; 18 | // file.write("\n www.includehelp.com\n".as_bytes())?; 19 | 20 | // let str1 = "nouman"; 21 | // file.write(str1.as_bytes())?; 22 | 23 | 24 | // let some_vec = vec![1,2,3,4,5,6]; 25 | // let str_from_vec = some_vec 26 | // .into_iter() 27 | // .map(|a| format!("{} \n", a.to_string())) 28 | // .collect::(); 29 | 30 | // file.write(str_from_vec.as_bytes())?; 31 | 32 | // let (name, age) = ("Joseph", 40); 33 | // let formatted_str = format!("I am {} and my name is {}", name, age); 34 | // file.write(formatted_str.as_bytes())?; 35 | 36 | // let mut file = File::open(path)?; 37 | // let mut contents = String::new(); 38 | // file.read_to_string(&mut contents)?; 39 | // println!("The file contains {:?}", contents); 40 | 41 | 42 | let mut file = File::open(path)?; 43 | let file_buffer = BufReader::new(file); 44 | for lines in file_buffer.lines(){ 45 | println!("{:?}", lines?); 46 | } 47 | Ok(()) 48 | 49 | } 50 | fn main(){ 51 | basic_file_handling(); 52 | } -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/13 - Text Processing, File and directory handlign/4-REPE~1.TXT: -------------------------------------------------------------------------------- 1 | 2 | // ------------------------------------------- 3 | // Regexes- Repeatitions and Quantifiers 4 | // ------------------------------------------- 5 | 6 | extern crate regex; 7 | use regex::Regex; 8 | 9 | fn main(){ 10 | //let re = Regex::new(r"a?aa").unwrap(); 11 | //let text = "aa aaa"; 12 | 13 | // let re = Regex::new(r"ba?").unwrap(); 14 | // let text = "a ba b ba"; 15 | 16 | // let re = Regex::new(r"\w?\w?\w?.rs").unwrap(); 17 | // let text = "fil.rs t1.rs file.rs"; 18 | 19 | // for cap in re.captures_iter(text) { 20 | // println!("Match: {} ", &cap[0]); 21 | // } 22 | 23 | // let re = Regex::new(r"a+").unwrap(); 24 | // let text = "a aa aaa baab bab"; 25 | 26 | // let re = Regex::new(r"\w+\.gif").unwrap(); 27 | // let text = "image1.gif and background.gif"; 28 | 29 | // let re = Regex::new(r"ab*").unwrap(); 30 | // let text = "a ab abbbbb"; 31 | 32 | // for cap in re.captures_iter(text) { 33 | // println!("Match: {} ", &cap[0]); 34 | // } 35 | 36 | // let re = Regex::new(r"\b\w{3,5}\b").unwrap(); 37 | // let text = "Hello i think you are happy becuase i have a gift for you"; 38 | 39 | // let re = Regex::new(r"\b\d{1,3}\.\d{1,3}\b").unwrap(); 40 | // let text = "921.583 0.0 1456.25"; 41 | 42 | // let re = Regex::new(r"\d{3,}").unwrap(); 43 | // let text = "5321 500 5698 12"; 44 | 45 | // for cap in re.captures_iter(text) { 46 | // println!("Match: {} ", &cap[0]); 47 | // } 48 | 49 | 50 | let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap(); 51 | let text = "2012-03-14, 2013-01-01 and 2014-07-05"; 52 | 53 | for cap in re.captures_iter(text) { 54 | println!("Month: {} Day: {} Year: {}, the whole: {}", &cap[2], &cap[3], &cap[1], &cap[0]); 55 | } 56 | 57 | } -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/3 - Rust Ownership/1 - Ownership Rules and Types.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Rust Ownership 3 | // - Each value in Rust has a variable that’s called its owner. 4 | // - There can be only one owner at a time. 5 | // - When the owner goes out of scope, the value will be dropped. 6 | // ------------------------------------------- 7 | 8 | fn main() { 9 | /*let mut x = 32.6; 10 | let mut y = x; 11 | 12 | let s1 = String::from("abc"); 13 | let s2 = &s1; 14 | println!("The value of s1 = {} and s2 = {}",s1,s2); 15 | */ 16 | 17 | /* 18 | let num_vec1: Vec = vec![5,6,9,8,7]; 19 | //let num_vec2 = num_vec1; //move, Ownership change 20 | // println!("The first vector is {:?} {:?}",num_vec1,num_vec2); 21 | 22 | 23 | let num_vec2 = &num_vec1; // Referencing or borrowing 24 | println!("The first vector is {:?} {:?}",num_vec1,num_vec2); 25 | 26 | let num_vec2 = num_vec1.clone(); 27 | println!("The first vector is {:?} {:?}",num_vec1,num_vec2); 28 | */ 29 | 30 | { 31 | let my_name = String::from("Nouman Azam"); 32 | } 33 | println!("My name is {}", my_name); 34 | 35 | 36 | } 37 | 38 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/3 - Rust Ownership/2 - Heap and stack .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Heap and Stack 3 | // ------------------------------------------- 4 | 5 | const MAX_VALUE:i32 = 40_000; 6 | /* 7 | fn main() { 8 | 9 | let (x,y) = (2,4); 10 | let sum_value = square_sum(x,y); 11 | println!("The value of Square of Sum = {}",sum_value); 12 | } 13 | 14 | fn square_sum(num1:i32, num2:i32) -> i32 { 15 | let result = square(num1+num2); 16 | result 17 | } 18 | 19 | fn square(num:i32) -> i32 { 20 | num * num 21 | } 22 | */ 23 | 24 | fn main() 25 | { 26 | let x: i32 = 5; 27 | 28 | let s1 = String::from("some string"); 29 | let s2 = s1; 30 | let s3 = &s2; 31 | let s4 = s2.clone(); 32 | 33 | 34 | } -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/3 - Rust Ownership/4 - Mutable and Immutable References.txt: -------------------------------------------------------------------------------- 1 | 2 | fn main() 3 | { 4 | 5 | // ------------------------------------------- 6 | // References Rules 7 | // - One mutable reference in a scope 8 | // - Many immutable references 9 | // - Mutable and immutable can not coexist 10 | // - Scope of a reference 11 | // - Data should not change when immutable references are in scope 12 | // ------------------------------------------- 13 | 14 | /* 15 | 16 | let mut heap_num = vec![4, 5, 6]; 17 | let ref1 = &mut heap_num; 18 | let ref2 = &mut heap_num; 19 | 20 | println!("The first reference is {:?} and the second one is {:?}",ref1,ref2); 21 | 22 | 23 | let mut heap_num = vec![4, 5, 6]; 24 | let ref1 = &heap_num; 25 | let ref2 = &heap_num; 26 | println!("The first reference is {:?} and the second one is {:?}",ref1,ref2); 27 | 28 | 29 | 30 | 31 | let mut heap_num = vec![4, 5, 6]; 32 | let ref1 = &heap_num; 33 | let ref2 = &heap_num; 34 | let ref3 = &mut heap_num; 35 | println!("Immutable references are {:?} and {:?} and the mutable reference is {:?}",ref1,ref2,ref3); 36 | 37 | 38 | let mut heap_num = vec![4, 5, 6]; 39 | let ref1 = &heap_num; 40 | let ref2 = &heap_num; 41 | println!("Immutable references are {:?} and {:?}",ref1,ref2); 42 | let ref3 = &mut heap_num; 43 | */ 44 | 45 | 46 | let mut heap_num = vec![4, 5, 6]; 47 | heap_num.push(68); 48 | 49 | let ref1 = &heap_num; 50 | let ref2 = &heap_num; 51 | println!("Immutable references are {:?} and {:?}",ref1,ref2); 52 | heap_num.push(86); 53 | 54 | 55 | 56 | } 57 | 58 | 59 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/4 - Control Structures/3 - Match statement .txt: -------------------------------------------------------------------------------- 1 | fn main() 2 | { 3 | // ------------------------------------------- 4 | // Match 5 | // - Simple match 6 | // - If else ladder into a match 7 | // - If let syntax style match 8 | // ------------------------------------------- 9 | /* General syntax 10 | 11 | match value { 12 | 13 | possible_value(s) => {Statements to execute}, 14 | possible_value(s) => {Statements to execute}, 15 | possible_value(s) => {Statements to execute}, 16 | 17 | _ = { default_execution_statements }, 18 | }; 19 | */ 20 | /* 21 | let some_number = 100; 22 | match some_number { 23 | 1 | 2 => println!("The number is -1"), 24 | 2 | 3 => println!("The number either 2 or 3"), // please note a single pipe here for the conditional OR 25 | 4..=100 => println!("The number is between 4 and 100 inclusive"), 26 | //_ => println!("The number is greater than 100"), 27 | } 28 | */ 29 | 30 | 31 | /* 32 | let marks = 50; 33 | let mut grade = 'N'; 34 | 35 | match marks { 36 | 90..=100 => grade = 'A', 37 | 80..=89 => grade = 'B', 38 | 70..=79 => grade = 'C', 39 | 60..=69 => grade = 'D', 40 | _ => grade = 'F', 41 | } 42 | println!("The grade achieved is {}",grade); 43 | */ 44 | 45 | 46 | /* 47 | let variable = match value { 48 | possible_value(s) = {Statements to execute}, 49 | possible_value(s) = {Statements to execute}, 50 | possible_value(s) = {Statements to execute}, 51 | 52 | _ = { default_execution_statements } 53 | }; 54 | */ 55 | 56 | let marks = 98; 57 | let grade = match marks { 58 | 90..=100 => 'A', 59 | 80..=89 => 'B', 60 | 70..=79 => 'C', 61 | 60..=69 => 'D', 62 | _ => 'F', 63 | }; 64 | println!("The grade achieved is {}",grade); 65 | 66 | } -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/4 - Control Structures/5 - For loops and its variants.txt: -------------------------------------------------------------------------------- 1 | 2 | fn main() 3 | { 4 | // ------------------------------------------- 5 | // Loops 6 | // - For loop 7 | // - Looping through elements using an immutable reference 8 | // - Looping through elements using a mutable reference 9 | // ------------------------------------------- 10 | 11 | /* 12 | let mut some_vec = vec![45, 30, 85, 90, 41,39]; 13 | 14 | for i in 0..=5 { // 0..=5 15 | println!("The {}th value in the vector is {}", i, some_vec[i]); 16 | } 17 | */ 18 | 19 | /* 20 | let some_vec = vec![45, 30, 85, 90, 41,39]; 21 | for i in some_vec { 22 | println!("{}", i); 23 | } 24 | println!("{:?}", some_vec); 25 | */ 26 | 27 | /* 28 | let some_vec = vec![45, 30, 85, 90, 41,39]; 29 | for i in some_vec.iter() { // &some_vec 30 | println!("{}", i); 31 | } 32 | println!("{:?}", some_vec); 33 | 34 | */ 35 | 36 | let mut some_vec = vec![45, 30, 85, 90, 41,39]; 37 | for i in &mut some_vec.iter_mut() { // or &mut some_vec 38 | *i += 5; 39 | println!("{}", i); 40 | } 41 | println!("{:?}", some_vec); 42 | 43 | } 44 | 45 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/4 - Control Structures/Exercise/10 - Practice - Palindrome.txt: -------------------------------------------------------------------------------- 1 | fn main() { 2 | 3 | let input = String::from("abbbbaa"); 4 | let mut is_palindrome = true; 5 | if input.len() == 0 { is_palindrome = true; 6 | println!("\n\n The input is palindrome {:?}",is_palindrome); 7 | return} 8 | 9 | let mut last = input.len() - 1; 10 | let mut first = 0; 11 | 12 | let my_vec = input.as_bytes(); 13 | 14 | while first < last { 15 | if my_vec[first] != my_vec[last] { 16 | is_palindrome = false; 17 | break; // what will happen if we insert a return here 18 | } 19 | 20 | first +=1; 21 | last -=1; 22 | } 23 | 24 | println!("\n\n The input is palindrome {:?}",is_palindrome); 25 | } 26 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/4 - Control Structures/Exercise/11 - Practice - Pathagorian Triplet .txt: -------------------------------------------------------------------------------- 1 | /*fn main() 2 | { 3 | let mut flag = true; 4 | for a in 1..=1000{ 5 | for b in a+1..1000 { 6 | for c in b+1..1000{ 7 | if a*a + b*b == c*c && a + b+c == 1000 8 | { 9 | println!("\n\n The required pathagorian triplet are ({}, {}, {}) \n\n", a,b,c); 10 | flag = false; 11 | break 12 | } 13 | } 14 | if flag == false {break} 15 | } 16 | if flag == false {break} 17 | } 18 | 19 | } 20 | */ 21 | 22 | // alternate way using the return statement 23 | fn main() 24 | { 25 | for a in 1..=1000{ 26 | for b in a+1..1000 { 27 | for c in b+1..1000{ 28 | if a*a + b*b == c*c && a + b+c == 1000 29 | { 30 | println!("\n\n The required pathagorian triplet are ({}, {}, {}) \n\n", a,b,c); 31 | 32 | return; 33 | } 34 | } 35 | 36 | } 37 | 38 | } 39 | 40 | 41 | } -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/4 - Control Structures/Exercise/7 - Some Examples of loops.txt: -------------------------------------------------------------------------------- 1 | 2 | fn main() 3 | { 4 | 5 | let mut condition = true; 6 | println!("Please enter the marks in percentage for the students\n"); 7 | 8 | let mut grades = vec![]; 9 | while condition { 10 | println!("'Please enter the student marks"); 11 | 12 | let mut marks_input = String::new(); 13 | std::io::stdin() 14 | .read_line(&mut marks_input) 15 | .expect("failed to read input."); 16 | 17 | let marks_input: i32 = marks_input.trim().parse().expect("invalid input"); 18 | grades.push(marks_input); 19 | println!("Do you want to enter another student data [Y/N]"); 20 | 21 | let choice: char = { 22 | let mut choice_input = String::new(); 23 | 24 | std::io::stdin() 25 | .read_line(&mut choice_input) 26 | .expect("failed to read input."); 27 | 28 | choice_input.trim().parse().expect("invalid input") 29 | }; 30 | 31 | 32 | // Try using the break instead of this logic 33 | if choice_input == 'Y'{ 34 | condition = true; 35 | } else { condition = false; } 36 | 37 | 38 | } 39 | 40 | println!("The students grades are = {:?}", grades); 41 | } 42 | 43 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/4 - Control Structures/Exercise/8 - Practice- Sum of square difference .txt: -------------------------------------------------------------------------------- 1 | fn main() { 2 | 3 | let mut n = String::new(); 4 | std::io::stdin() 5 | .read_line(&mut n) 6 | .expect("failed to read input."); 7 | let n: i32 = n.trim().parse().expect("invalid input"); 8 | 9 | let mut square_of_sum =0 ; 10 | let mut sum_of_squares = 0; 11 | for i in 1..=n { 12 | square_of_sum = square_of_sum + i; 13 | sum_of_squares = sum_of_squares + i.pow(2); 14 | } 15 | 16 | let difference = square_of_sum.pow(2) - sum_of_squares; 17 | // println!("The square of sum is {} and the sum of square is {}", square_of_sum.pow(2), sum_of_squares); 18 | println!("The difference of the square_of_sum and sum of Squares for N = {} is {}",n, difference); 19 | 20 | 21 | 22 | } 23 | 24 | 25 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/4 - Control Structures/Exercise/9 - Practice- Sum of Multiples .txt: -------------------------------------------------------------------------------- 1 | // take help from the video and script in matlab course 2 | fn main() { 3 | 4 | let mut n = String::new(); 5 | std::io::stdin() 6 | .read_line(&mut n) 7 | .expect("failed to read input."); 8 | let n: i32 = n.trim().parse().expect("invalid input"); 9 | 10 | let numbers = 1..n; 11 | let mut multiples_of_3 = vec![0]; // please note that we can not use arrays in this example becuase the length of the array needs to be known at compile time 12 | let mut multiples_of_5 = vec![0]; 13 | 14 | for i in 1..n { 15 | if i%3 == 0 { multiples_of_3.push(1); } else {multiples_of_3.push(0);} 16 | if i%5 == 0 { multiples_of_5.push(1); } else {multiples_of_5.push(0);} 17 | } 18 | 19 | //println!("\n\n Multiple of 3 = {:?}", multiples_of_3); 20 | 21 | 22 | let mut combined_list = vec![0]; 23 | for i in 1..n as usize { 24 | if multiples_of_3[i] == 1 || multiples_of_5[i] == 1 {combined_list.push(1)} else {combined_list.push(0);} 25 | } 26 | 27 | // println!("{:?}",combined_list); 28 | 29 | let mut values_of_multiples:Vec = vec![0]; 30 | for i in 1..=n { 31 | values_of_multiples.push(combined_list[i as usize] * i); 32 | } 33 | // values_of_multiples.iter().sum(); 34 | 35 | println!("\n\n Multiple of 3 and 5 are = {:?}", values_of_multiples); 36 | 37 | println!("\n\n The sum of the multiples are = {:?}\n\n", values_of_multiples.iter().sum::()); // it is having difficutly in inferring the types so i explicilty provide that 38 | 39 | 40 | } 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/4-1 Project-Stack Implemenation and Applications/2 - String reversal.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Stack 3 | // - Stack using vec 4 | // - Application of Stacks (String Reversal) 5 | // ------------------------------------------- 6 | 7 | fn new_stack(maxsize: usize) -> Vec { 8 | let vec: Vec = Vec::with_capacity(maxsize); 9 | vec 10 | } 11 | 12 | fn pop(stack: &mut Vec) -> Option { 13 | let poped_val = stack.pop(); 14 | // println!("The poped value is {:?}",poped_val); 15 | poped_val 16 | } 17 | 18 | fn push(stack: &mut Vec, item: char, maxsize: usize) { 19 | if stack.len() == maxsize { 20 | // println!("Can not add more") 21 | } else { 22 | stack.push(item); 23 | // println!("Stack: {:?}", stack); 24 | } 25 | } 26 | 27 | fn size(stack: &Vec) -> usize { 28 | stack.len() 29 | } 30 | 31 | fn main() { 32 | let input_string = String::from("Welcome to rust"); 33 | let size_stack = input_string.len(); 34 | let mut stack = new_stack(size_stack); 35 | let mut rev_string = String::new(); 36 | 37 | 38 | for i in input_string.chars() { 39 | push(&mut stack, i, size_stack); 40 | } 41 | 42 | 43 | for i in 0..size(&stack) { 44 | rev_string.push(pop(&mut stack).unwrap()); 45 | } 46 | println!("The input string is {:?}", input_string); 47 | println!("The reverse of the string is {:?} ",rev_string); 48 | 49 | } 50 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/5 - Structures, Traits, Generics, Enums/3 - Functions within a Trait.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Traits 3 | // - General explaination 4 | // - Default function implementation 5 | // - Functions within a trait implementation 6 | // ------------------------------------------- 7 | 8 | 9 | struct Data{ 10 | some_data: Vec, 11 | } 12 | 13 | trait BasicStats { 14 | fn mean(&self) -> f32; 15 | fn variance(&self) -> f32; 16 | } 17 | 18 | impl BasicStats for Data { 19 | fn mean(&self) -> f32 { 20 | let mut sum = 0; 21 | for i in self.some_data.iter(){ 22 | sum += *i; 23 | } 24 | //println!("{:?}",sum); 25 | sum as f32 / self.some_data.len() as f32 26 | 27 | } 28 | 29 | fn variance(&self) ->f32 { 30 | let mu = self.mean(); 31 | let mut sum_sqauared_diff:f32 = 0.0; 32 | for i in self.some_data.iter(){ 33 | sum_sqauared_diff += (*i as f32 - mu) * (*i as f32 - mu); 34 | } 35 | sum_sqauared_diff / self.some_data.len() as f32 36 | 37 | } 38 | } 39 | 40 | 41 | 42 | fn main() 43 | { 44 | let my_data = Data { 45 | some_data: vec![5, 6, 9, 8, 7, 4, 8], 46 | }; 47 | println!("the mean of the data is {}",my_data.mean()); 48 | println!("The standard deviation of the data is {}",my_data.variance()); 49 | 50 | 51 | } 52 | 53 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/5 - Structures, Traits, Generics, Enums/7 - Result Enum.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Result enum 3 | // - Basic Syntax and usage 4 | // ------------------------------------------- 5 | 6 | /* 7 | enum Result { 8 | Ok(T), 9 | Err(E), 10 | } 11 | */ 12 | 13 | // Example 1 14 | /* 15 | fn division(dividend: f64, divisor: f64) -> Result { 16 | 17 | /*if divisor == 0.0 { 18 | Err(String::from("Error: Division by zero")) 19 | } else { 20 | Ok(dividend / divisor) 21 | } 22 | */ 23 | 24 | match divisor { 25 | 0. => Err(String::from("Error: Division By Zero")), 26 | _ => Ok(dividend / divisor), 27 | } 28 | 29 | } 30 | 31 | 32 | fn main() { 33 | 34 | println!("\n\n{:?}", division(9.0, 3.0)); 35 | println!("{:?}", division(4.0, 0.0)); 36 | println!("{:?} \n\n", division(0.0, 2.0)); 37 | } 38 | 39 | */ 40 | 41 | 42 | // Example 2 43 | 44 | fn main() { 45 | let some_vec:Vec = vec![5,5,2,1,5,9]; 46 | 47 | let result1 = match some_vec.get(15) { 48 | Some(a) => Ok(a), 49 | None => Err("The value does not exist"), 50 | }; 51 | 52 | println!("The value of Result is {:?}", result1); 53 | 54 | 55 | 56 | } 57 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/6 - Iterators, Lifetimes, Closures/1 - Lifetimes (Part 1) .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Lifetimes 3 | // - Dangling Reference 4 | // - Undetermined Lifetimes 5 | // ------------------------------------------- 6 | 7 | // use std::vec; 8 | 9 | /* 10 | fn main(){ 11 | let i:&i32; 12 | { 13 | 14 | let j = 5; 15 | i = &j; 16 | } 17 | println!("The value of i = {}", i); 18 | } 19 | */ 20 | 21 | 22 | /* 23 | fn main() { 24 | 25 | let some_int = 10; 26 | let additional_int = some_fn(some_int); 27 | println!("{}", additional_int); 28 | 29 | } 30 | 31 | fn some_fn(i: i32) -> &i32{ 32 | &i 33 | } 34 | */ 35 | 36 | 37 | /* 38 | fn main(){ 39 | let int1 = 5; 40 | let int2 = 10; 41 | let result = greater(&int1,&int2); 42 | 43 | } 44 | 45 | fn greater(i:&i32,j:&i32) -> &i32 { 46 | if i> j { 47 | i 48 | } else {j 49 | } 50 | 51 | } 52 | */ 53 | 54 | 55 | 56 | 57 | fn main(){ 58 | let s_1 = "Hello"; 59 | 60 | 61 | let v; 62 | { 63 | let s_2 = String::from("World"); 64 | v = some_fn(s_1, s_2.as_str()); 65 | } 66 | println!("\n\n{} \n\n", v); 67 | } 68 | 69 | fn some_fn(first_str: &str, second_str: &str) -> &str { 70 | first_str 71 | 72 | } 73 | 74 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/6 - Iterators, Lifetimes, Closures/4 - Closures (Part 2).txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Closures 3 | // - A quick recap 4 | // - Borrow by immutable reference 5 | // - Borrow by a mutable reference 6 | // - Moving of a value into a closure 7 | // ------------------------------------------- 8 | 9 | 10 | 11 | /* 12 | fn main(){ 13 | 14 | let some_closure_1 = |x: u32| -> u32 { x + 1 }; 15 | let some_closure_2 = |x| { x + 1 }; 16 | let some_closure_3 = |x| x + 1 ; 17 | } 18 | */ 19 | 20 | 21 | 22 | /* 23 | fn main(){ 24 | let mut vec_1 = vec![1, 2,3]; 25 | let some_closure = || { 26 | // vec_1 is being used by reference. 27 | println!("Vec 1 : {:?}", vec_1); 28 | }; 29 | 30 | println!("Vec_1: {:?}",vec_1); 31 | some_closure(); 32 | 33 | vec_1[1] = 15; 34 | } 35 | */ 36 | 37 | 38 | /* 39 | fn main(){ 40 | let mut vec_1 = vec![4,5,6]; 41 | let mut some_closure = || { 42 | 43 | vec_1.push(35); 44 | 45 | }; 46 | 47 | //println!("vec_2 {:?}", vec_2); 48 | //vec_1[1] = 15; 49 | some_closure(); 50 | 51 | 52 | // vec_1[2] = 15; 53 | 54 | } 55 | 56 | */ 57 | 58 | fn main(){ 59 | let mut vec_1 = vec![1,2,3]; 60 | let some_closure = || { 61 | 62 | let vec_2 = vec_1; 63 | }; 64 | 65 | 66 | some_closure(); 67 | println!("vec 1 = {:?} ", vec_1); 68 | println!("vec 2 = {:?} ", vec_2); 69 | 70 | } 71 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/6 - Iterators, Lifetimes, Closures/5 - Function types .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Function Types 3 | // - Basic syntax and use 4 | // - Function types as parameters to function 5 | // ------------------------------------------- 6 | 7 | /* 8 | fn max(x: i32, y: i32) -> i32 { 9 | if x > y { 10 | x 11 | } else { 12 | y 13 | } 14 | } 15 | 16 | fn min(x: i32, y: i32) -> i32 { 17 | if x < y { 18 | x 19 | } else { 20 | y 21 | } 22 | } 23 | 24 | fn main(){ 25 | let mut f = max; 26 | println!("The minimum of the two values is {}",f(2,3)); 27 | } 28 | */ 29 | 30 | 31 | /* 32 | 33 | fn prints_name(name: &str) { 34 | print!("The name is {}",name); 35 | } 36 | 37 | fn prints_full_info(f: fn(&str), some_one: &str, age: i32) { 38 | f(some_one); 39 | println!(" and my age is {}", age); 40 | } 41 | 42 | fn main() { 43 | let (my_name, my_age) = (String::from("Nouman"), 40); 44 | prints_full_info(prints_name, &my_name, my_age) ; 45 | } 46 | */ 47 | 48 | 49 | 50 | fn add_one(x: i32) -> i32 { 51 | x + 1 52 | } 53 | 54 | fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 { 55 | f(arg) + f(arg) 56 | } 57 | 58 | fn main() { 59 | let answer = do_twice(add_one, 5); 60 | println!("The answer is: {}", answer); 61 | } 62 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/6 - Iterators, Lifetimes, Closures/7 - Iterators (Part 2) .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Iterators 3 | // - Basics 4 | // - Some useful functions for iterators 5 | // - Common statistics 6 | // - Modifying and collecting values 7 | // ------------------------------------------- 8 | 9 | fn main() 10 | { 11 | let a = vec![0, 1, 2, 3,4,5,6,7]; 12 | 13 | 14 | let filtered_values = a.iter().filter(|&x| *x >= 5).collect::>(); 15 | println!(" {:?}", filtered_values); 16 | 17 | 18 | let b = a.clone(); 19 | let filtered_values= a.into_iter().filter(|x| *x >= 5).collect::>(); 20 | println!(" {:?}", filtered_values); 21 | 22 | // println!(" {:?}", a); 23 | 24 | 25 | let mut mapped_values = b.iter().map(|x| 2 * *x).collect::>(); 26 | println!(" {:?}", mapped_values); 27 | 28 | 29 | 30 | let mut mapped_values = b.iter().map(|x| 2 * x).filter(|x| *x > 10).collect::>(); 31 | 32 | println!(" {:?}", mapped_values); 33 | 34 | // https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map 35 | 36 | } 37 | 38 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/6 - Iterators, Lifetimes, Closures/Exercise/7-Sum of multiples.txt: -------------------------------------------------------------------------------- 1 | // Example: Sum of multiples of 3 and 5 -> refined and reduced version of the code with iterators 2 | 3 | /* 4 | fn main() { 5 | 6 | let mut n = String::new(); 7 | std::io::stdin() 8 | .read_line(&mut n) 9 | .expect("failed to read input."); 10 | let n: u32 = n.trim().parse().expect("invalid input"); 11 | 12 | let divisible_by_3_5 = (1..n).into_iter().filter(|&x| x % 3 == 0 || x % 5 ==0 ).collect::>(); 13 | println!("{:?}", divisible_by_3_5); 14 | println!("{:?}", divisible_by_3_5.iter().sum::()); 15 | 16 | 17 | } 18 | 19 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/7 - Rust Modules/3 - Using External crates .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // External Crates 3 | // - Add to cargo.toml under dependency array_tool = "1.0.3" 4 | // ------------------------------------------- 5 | 6 | use array_tool::vec::*; 7 | fn main() { 8 | let vec_1 = vec![1,1,3,5,6,7]; 9 | let vec_2 = vec![1,2,3]; 10 | let intesection = vec_1.intersect(vec_2.clone()); 11 | println!("The intersection = {:?}",intesection); 12 | 13 | 14 | let union_set = vec_1.union(vec_2.clone()); 15 | println!("The union = {:?}",union_set); 16 | println!("Vec 1 three times displayed = {:?}",vec_2.times(3)); 17 | 18 | } -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/7 - Rust Modules/Rust Modules (Part 1)/file_1.txt: -------------------------------------------------------------------------------- 1 | pub fn printing() { 2 | println!("Hello from first crate"); 3 | } -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/7 - Rust Modules/Rust Modules (Part 1)/file_2.txt: -------------------------------------------------------------------------------- 1 | pub fn printing() { 2 | println!("Hello from second crate"); 3 | } -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/7 - Rust Modules/Rust Modules (Part 1)/lib.txt: -------------------------------------------------------------------------------- 1 | pub mod file_1; 2 | pub mod file_2; -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/7 - Rust Modules/Rust Modules (Part 1)/main.txt: -------------------------------------------------------------------------------- 1 | use new_project::file_1; 2 | use new_project::file_2; 3 | 4 | fn main() { 5 | new_project::file_1::printing(); 6 | new_project::file_2::printing(); 7 | } 8 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/7 - Rust Modules/Rust Modules (Part 2)/1 - Rust Modules (Part 1).txt: -------------------------------------------------------------------------------- 1 | /*mod file_1; 2 | fn main(){ 3 | 4 | let rect1 = Rectangle{ 5 | length: 5, 6 | width:10, 7 | }; 8 | let area_rect1 = rect_area(&rect1.length, &rect1.width); // also del the file_1:: if you are including the code in the same script 9 | } 10 | 11 | struct Rectangle{ 12 | length: i32, 13 | width:i32, 14 | } 15 | */ 16 | 17 | /* 18 | fn some_fn() { 19 | println!("This is the function of the file_1 crate"); 20 | } 21 | 22 | mod maths { 23 | pub mod basic_math { 24 | pub fn multiplication(num1:&i32, num2:&i32) -> i32{ 25 | let result = num1 * num2; 26 | printing(&result); 27 | result 28 | } 29 | fn printing(num: &i32) { 30 | println!("The result is {}", num); 31 | crate::some_fn(); 32 | } 33 | 34 | } 35 | } 36 | 37 | 38 | fn rect_area(length:&i32, width:&i32) -> i32 { 39 | // absolute path 40 | use maths::basic_math::multiplication; 41 | multiplication(length, width) // parents can not see child modules but childs can see parents modules by default 42 | } 43 | */ 44 | 45 | 46 | /* 47 | mod file_2; 48 | fn main() { 49 | file_2::some_person(); 50 | } 51 | */ 52 | 53 | mod file_3; 54 | 55 | fn main() 56 | { 57 | file_3::allowance(); 58 | } 59 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/7 - Rust Modules/Rust Modules (Part 2)/file_1.txt: -------------------------------------------------------------------------------- 1 | fn some_fn() { 2 | println!("This is the function of the file_1 crate"); 3 | } 4 | 5 | mod maths { 6 | pub mod basic_math { 7 | pub fn multiplication(num1:&i32, num2:&i32) -> i32{ 8 | let result = num1 * num2; 9 | printing(&result); 10 | result 11 | } 12 | fn printing(num: &i32) { 13 | println!("The result is {}", num); 14 | crate::file_1::some_fn(); 15 | } 16 | 17 | } 18 | } 19 | 20 | 21 | // Point: The program will not compile if we remove the pub word 22 | pub fn rect_area(length:&i32, width:&i32) -> i32 { 23 | // absolute path 24 | use maths::basic_math::multiplication; 25 | multiplication(length, width) // parents can not see child modules but childs can see parents modules by default 26 | } 27 | 28 | /* 29 | file_1 30 | - math 31 | - basic maths 32 | rect_area() 33 | some_fn() 34 | 35 | */ 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/7 - Rust Modules/Rust Modules (Part 2)/file_2.txt: -------------------------------------------------------------------------------- 1 | mod person { 2 | pub struct personal_info { 3 | pub age: u8, 4 | pub education: String, 5 | } 6 | 7 | impl personal_info{ 8 | pub fn new(new_edu: &str) -> Self { 9 | Self { 10 | education: String::from(new_edu), 11 | age: 20, 12 | } 13 | } 14 | } 15 | } 16 | 17 | pub fn some_person() { 18 | let mut person1 = person::personal_info::new("bachelors"); 19 | person1.education = String::from("Masters"); 20 | 21 | 22 | let person2 = person::personal_info { 23 | age: 42, 24 | education: String::from("Masters"), 25 | }; 26 | 27 | } 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/7 - Rust Modules/Rust Modules (Part 2)/file_3.txt: -------------------------------------------------------------------------------- 1 | 2 | mod travel_history { 3 | enum Conveyance { 4 | Car, 5 | Train, 6 | Air, 7 | } 8 | } 9 | 10 | 11 | pub fn allowance() { 12 | let travel_1 = travel_history::Conveyance::Car; 13 | let travel_2 = travel_history::Conveyance::Train; 14 | } 15 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/8 - Advance Concepts/1 - Declarative Macros Basics.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------------- 2 | // Declarative Macros 3 | // ------------------------------------------------- 4 | 5 | /* General Syntax 6 | 7 | macro_rules! macro_name { 8 | // |--- Match rules 9 | (...) => { ... }; 10 | (...) => { ... }; 11 | (...) => { ... }; // the semicolon at the last rule is optional 12 | } 13 | */ 14 | 15 | 16 | macro_rules! our_macro { 17 | () => { 1+1; 18 | }; 19 | 20 | (something 4 u dear u32 @_@) => { 21 | println!("You found nonsense here") 22 | }; 23 | 24 | ($e1:expr, $e2:expr) => { 25 | $e1 + $e2 26 | }; 27 | 28 | ($a:expr, $b:expr; $c:expr) => { 29 | $a * ($b + $c) 30 | } 31 | } 32 | fn main() { 33 | 34 | 35 | println!("{}",our_macro!()); 36 | our_macro!(); 37 | println!("{}", our_macro!(2,2)); 38 | println!("{}", our_macro!(5,6;3)); 39 | // println!("{}", our_macro!("something",2;"nothing")); 40 | 41 | our_macro!(); 42 | our_macro![]; 43 | 44 | our_macro!{}; 45 | 46 | 47 | 48 | // 1. cargo install cargo-expand 49 | // 2. rustup install nightly 50 | // 3. rustup component add rustfmt 51 | // 4. rustup component add rustfmt --toolchain nightly 52 | 53 | 54 | } -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/8 - Advance Concepts/10 - Some useful traits on structs.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------------- 2 | // Some Useful Traits 3 | // ------------------------------------------------- 4 | use std::cmp::Ordering; 5 | 6 | //#[derive( PartialOrd, PartialEq, Clone)] 7 | #[derive( Clone)] 8 | struct Person { 9 | name: String, 10 | age: u8, 11 | earning: u32, 12 | savings: u32, 13 | } 14 | 15 | 16 | impl PartialEq for Person { 17 | fn eq(&self, other: &Self) -> bool { 18 | self.age == other.age 19 | } 20 | } 21 | 22 | 23 | 24 | impl PartialOrd for Person { 25 | fn partial_cmp(&self, other: &Self) -> Option { 26 | self.earning.partial_cmp(&other.earning) 27 | } 28 | } 29 | 30 | 31 | fn main() { 32 | let bob = Person { 33 | name: "bob".to_owned(), 34 | age: 30, 35 | earning: 30_000, 36 | savings: 50_000, 37 | }; 38 | 39 | 40 | let mut bob_clone = bob.clone(); 41 | 42 | bob_clone.age = 15; 43 | bob_clone.name = "eve".to_owned(); 44 | bob_clone.earning = 40_000; 45 | //bob_clone.savings = 60_000; 46 | 47 | println!("{}", bob == bob_clone); 48 | println!("{}",bob >= bob_clone); 49 | println!("{}",bob <= bob_clone); 50 | 51 | 52 | let alice = Person { 53 | name: "Bob".to_owned(), 54 | age: 25, 55 | earning: 30_000, 56 | savings: 40_000, 57 | 58 | }; 59 | 60 | println!(" {}", alice > bob); 61 | } 62 | 63 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/8 - Advance Concepts/11 - Trait Bounds.txt: -------------------------------------------------------------------------------- 1 | 2 | // ------------------------------------------------- 3 | // - Trait Bounds 4 | // ---------------------------------------------- 5 | 6 | 7 | 8 | fn quadruple(x: i32) -> i32 { 9 | // fn quadruple(x: T) -> T { 10 | // fn quadruple(x: T) -> T { 11 | x.double().double() 12 | } 13 | 14 | trait Double { 15 | fn double(&self) -> Self; 16 | } 17 | impl Double for i32 { 18 | fn double(&self) -> Self { 19 | self * 2 20 | } 21 | } 22 | 23 | // 2.0 24 | /* 25 | impl Double for i64 { 26 | fn double(&self) -> Self { 27 | self * 2 28 | } 29 | } 30 | */ 31 | 32 | fn main() { 33 | println!("quadruple 5_i32 == {}", quadruple(5_i64)); 34 | } 35 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/8 - Advance Concepts/12 - Associated Type.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------------- 2 | // Associated Types 3 | // ------------------------------------------------- 4 | 5 | #[derive(Debug)] 6 | struct Kmh { 7 | value: u32, 8 | } 9 | 10 | #[derive(Debug)] 11 | struct Km { 12 | value: u32, 13 | } 14 | 15 | 16 | #[derive(Debug)] 17 | struct Mph { 18 | value: u32, 19 | } 20 | #[derive(Debug)] 21 | struct Miles { 22 | value: u32, 23 | } 24 | 25 | 26 | impl Kmh { 27 | fn distance_in_three_hours(&self) -> Km { 28 | Km { 29 | value: self.value * 3, 30 | } 31 | } 32 | } 33 | 34 | impl Mph { 35 | fn distance_in_three_hours(&self) -> Miles { 36 | Miles { 37 | value: self.value * 3, 38 | } 39 | } 40 | } 41 | 42 | 43 | 44 | 45 | /* 46 | trait DistanceThreeHours { 47 | type Distance; 48 | fn distance_in_three_hours(&self) -> Self::Distance; 49 | } 50 | 51 | impl DistanceThreeHours for Kmh { 52 | type Distance = Km; 53 | fn distance_in_three_hours(&self) -> Self::Distance{ 54 | Self::Distance { 55 | value: self.value * 3, 56 | } 57 | } 58 | } 59 | 60 | impl DistanceThreeHours for Mph { 61 | type Distance = Miles; 62 | fn distance_in_three_hours(&self) -> Self::Distance { 63 | Self::Distance { 64 | value: self.value * 3, 65 | } 66 | } 67 | } 68 | */ 69 | 70 | fn main() { 71 | let speed = Kmh { value: 90 }; 72 | let distance = speed.distance_in_three_hours(); 73 | println!("At {:?}, you will travel {:?} in 3 hours", speed, distance); 74 | 75 | let speed_mph = Mph { value: 90 }; 76 | let distance_miles = speed_mph.distance_in_three_hours(); 77 | println!("At {:?}, you will travel {:?} in 3 hours",speed_mph, distance_miles); 78 | } 79 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/8 - Advance Concepts/2 - Capturing Types.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------------- 2 | // Capturing Types 3 | // ------------------------------------------------- 4 | /* 5 | macro_rules! input { 6 | ($t: ty) => {{ 7 | let mut n = String::new(); 8 | std::io::stdin() 9 | .read_line(&mut n) 10 | .expect("failed to read input"); 11 | 12 | let n: $t = n.trim().parse().expect("invalid input"); 13 | n 14 | 15 | } 16 | }; 17 | } 18 | 19 | macro_rules! add_as { 20 | ($a: expr, $b: expr, $typ: ty) => { $a as $typ + $b as $typ } 21 | } 22 | 23 | macro_rules! some_macro { 24 | ($var: ident) => { 25 | $var = $var + 1; 26 | 27 | }; 28 | } 29 | fn main(){ 30 | /* 31 | println!("Please enter a floating point number"); 32 | let some_input_0 = input!(f32); 33 | */ 34 | 35 | 36 | // println!("{}", add_as!(15,2.3,f32)); 37 | let mut x = 4; 38 | some_macro!(x); 39 | 40 | } 41 | */ 42 | 43 | macro_rules! create_function { 44 | ($func_name:ident, $input: ident, $type_input: ty, $type_output: ty) => { 45 | 46 | fn $func_name($input:$type_input) -> $type_output { 47 | println!("You called {:?}() with the input of {:?}", stringify!($func_name), stringify!($input1)); 48 | $input 49 | } 50 | 51 | }; 52 | } 53 | 54 | create_function!(f1,x,i32, i32); 55 | fn main() { 56 | //f1(15); 57 | let y = f1(15); 58 | } -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/8 - Advance Concepts/3 - Repeating Patterns.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------------- 2 | // Declarative Macros 3 | // - Repeating Patterns 4 | // ------------------------------------------------- 5 | 6 | 7 | macro_rules! string_concat { 8 | /* 9 | () => { 10 | String::new(); 11 | }; 12 | 13 | ($some_str: expr) => {{ 14 | let mut temp_str = String::new(); 15 | temp_str.push_str($some_str); 16 | temp_str 17 | } 18 | }; 19 | 20 | ($some_s1: expr, $some_s2:expr) => {{ 21 | let mut temp_str = String::new(); 22 | temp_str.push_str($some_s1); 23 | temp_str.push_str($some_s2); 24 | 25 | temp_str 26 | } 27 | }; 28 | 29 | */ 30 | 31 | ($($some_str:expr,) *) => {{ 32 | let mut temp_str = String::new(); 33 | $(temp_str.push_str($some_str);)* 34 | temp_str 35 | } 36 | }; 37 | 38 | 39 | } 40 | 41 | macro_rules! vec_mac { 42 | ( $($element: expr),*) => {{ 43 | let mut some_vec = Vec::new(); 44 | $(some_vec.push($element);)* 45 | some_vec 46 | } 47 | }; 48 | } 49 | fn main(){ 50 | let str_null = string_concat!(); 51 | let str_single = string_concat!("First",); 52 | 53 | let str_double = string_concat!("First","Second",); 54 | 55 | let string_vec = vec_mac!("Nouman", "Azam"); 56 | } -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/8 - Advance Concepts/5 - as_ref and Partial move in option.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------------- 2 | // Partial move in option and result 3 | // ------------------------------------------------- 4 | 5 | /* 6 | fn main() { 7 | let some_option =Some("Alice".to_owned()); 8 | 9 | // match some_option { 10 | match &some_option { // an implication is that we &option 11 | Some(inner_value)=> println!("Name is {}", inner_value), 12 | 13 | 14 | // Some(ref inner_value)=> println!("Name is {}", inner_value), 15 | None => println!("No name provided"), 16 | } 17 | println!("{:?}", some_option); 18 | } 19 | */ 20 | 21 | 22 | 23 | fn try_me (option_name: Option<&String>) { 24 | match option_name { 25 | Some(inner_value) => println!("Name is {} ", inner_value), 26 | None => println! ("No name provided"), 27 | } 28 | } 29 | 30 | fn main(){ 31 | let some_option = Some("Alice".to_owned()); 32 | 33 | let some_1 = &some_option; 34 | let some_2 = some_option.as_ref(); 35 | 36 | 37 | //try_me(&some_option); // issue with this one 38 | try_me(some_option.as_ref()); 39 | println!("{:?}", some_option); 40 | } 41 | 42 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/8 - Advance Concepts/6 - Take, replace and swap for Avoiding Allocations.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // - Avoiding Allocations 3 | // ------------------------------------------- 4 | 5 | 6 | use std::mem; 7 | /* 8 | #[derive(Debug)] 9 | enum Customer { 10 | new { name: String }, 11 | loyal { name: String }, 12 | rich { name: String }, 13 | } 14 | 15 | fn promote(user: &mut Customer) { 16 | use Customer::*; 17 | 18 | *user = match user { 19 | //Customer::new { name } => Customer::loyal { name: name.clone() }, 20 | Customer::new { name } => Customer::loyal {name: mem::take(name)}, 21 | //Customer::new { name } => Customer::loyal {name: mem::replace(name, String::new())}, 22 | 23 | //Customer::loyal { name } => Customer::rich { name: name.clone() }, 24 | Customer::loyal { name } => Customer::rich {name: mem::take(name)}, 25 | //Customer::loyal { name } => Customer::rich {name: mem::replace(name, String::new())}, 26 | 27 | Customer::rich { name } => return, 28 | } 29 | } 30 | 31 | fn main() { 32 | let mut customer_1 = Customer::new { name: "micheal".to_string() }; 33 | 34 | promote(&mut customer_1); 35 | 36 | println!("Cutomer 1 {:?}", customer_1); 37 | } 38 | 39 | */ 40 | 41 | 42 | use std::mem::swap; 43 | fn main() { 44 | let mut s1 = "Nouman".to_string(); 45 | let mut s2 = "Azam".to_string(); 46 | 47 | //Swapping of variables 48 | let temp = s1; 49 | s1 = s2; 50 | s2 = temp; 51 | println!("s1: {:?} s2: {:?}",s1,s2); 52 | 53 | 54 | //The idiomatic way is the one given below 55 | swap(&mut s1, &mut s2); 56 | println!("s1: {:?} s2: {:?}",s1,s2); 57 | } 58 | 59 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/9 - Smart Pointers in Rust/1 - Basics of Smart Pointers.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Smart Pointers 3 | // - Box Pointers 4 | // ------------------------------------------- 5 | 6 | 7 | fn main() { 8 | let single_value = Box::new(0.625); 9 | let x = 0.625; 10 | println!("Are the values being equal {}", x == *single_value); // deref is needed when box contains a single value 11 | 12 | 13 | let mut stack_var = 4; 14 | let stack_ref = &stack_var; 15 | let heap_var = Box::new(stack_var); // what happens when we write stack_var inside the (stack_ref) 16 | 17 | 18 | stack_var = 5; 19 | println!("The value of stack_var = {} and heap_var = {}", stack_var, heap_var); 20 | 21 | 22 | let point = Box::new((100, 125)); 23 | println!("{} {}", 100 == point.0, point.1); 24 | 25 | let x = point; // 26 | } -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/9 - Smart Pointers in Rust/2 - Box Pointers and When they are Useful .txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Smart Pointers 3 | // - Box Pointers 4 | // - Use Case of Box Pointers 5 | // ------------------------------------------- 6 | 7 | 8 | /* 9 | #[derive(Debug)] 10 | enum List { 11 | Cons(i32, List), 12 | Nil, 13 | } 14 | use List::{Cons, Nil}; 15 | 16 | 17 | /* 18 | enum Conveyance { 19 | Car(i32), 20 | Train(i32), 21 | Air(i32), 22 | Walk 23 | } 24 | */ 25 | fn main() { 26 | let list = Cons(1, Cons(2, Cons(3, Nil))); 27 | // let list = List::Cons(1, List::Cons(2, List::Cons(3, List::Nil))); 28 | println!("{:?}",list); 29 | } 30 | */ 31 | 32 | 33 | #[derive(Debug)] 34 | enum List { 35 | Cons(i32, Box), 36 | Nil, 37 | } 38 | 39 | fn main() { 40 | let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Cons(3, Box::new(List::Nil)))))); 41 | println!("{:?}",list); 42 | } 43 | 44 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/9 - Smart Pointers in Rust/4-Generics & Deref Coerc in Smart Pnters.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Smart Pointers 3 | // - Custom Defined Smart pointers 4 | // - Deref Coercion 5 | // ------------------------------------------- 6 | 7 | struct MySmartPointer{value: T, 8 | name: String} // add it at the end 9 | 10 | 11 | impl MySmartPointer { 12 | fn new(x:T)-> MySmartPointer { 13 | MySmartPointer{value: x, name:String::from("Hello")} 14 | 15 | } 16 | } 17 | 18 | use std::ops::Deref; 19 | impl Deref for MySmartPointer { 20 | type Target = T; 21 | fn deref(&self) -> &T { 22 | &self.value 23 | } 24 | } 25 | 26 | 27 | 28 | impl Drop for MySmartPointer{ 29 | fn drop(&mut self){ 30 | println!("dropping MySmartPointer object from memory {:?}", self.value); 31 | } 32 | } 33 | 34 | 35 | fn my_fn(str: &str) 36 | 37 | { 38 | println!("The string recieved from teh main is \"{}\"", str); 39 | } 40 | 41 | 42 | #[derive(Debug)] 43 | struct Person{ 44 | name: String, 45 | 46 | } 47 | 48 | 49 | fn main() { 50 | let sptr_p1 = MySmartPointer::new("Nouman Azam"); 51 | my_fn(&sptr_p1); 52 | 53 | let some_vec = MySmartPointer::new(vec![1,2,3]); 54 | 55 | for z in &*some_vec { 56 | println!("The value is {}", z); 57 | 58 | } 59 | 60 | } 61 | 62 | 63 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/9 - Smart Pointers in Rust/5- Rc smart pointer.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Reference Counting Pointers 3 | // ------------------------------------------- 4 | /* 5 | use std::rc::Rc; 6 | enum List{ 7 | //Cons(i32, Box), 8 | Cons(i32, Rc), 9 | Nil, 10 | } 11 | 12 | use crate::List::{Cons, Nil}; 13 | fn main(){ 14 | /* 15 | let a = Cons(1, Box::new(Cons(2, Box::new(Nil)))); 16 | let b = Cons(3, Box::new(a)); 17 | let c = Cons(4, Box::new(a)); 18 | */ 19 | 20 | let a = Rc::new(Cons(1, Rc::new(Cons(2, Rc::new(Nil))))); 21 | println!("Count after creating a = {}", Rc::strong_count(&a)); 22 | 23 | { 24 | let b = Rc::new(Cons(3, Rc::clone(&a))); 25 | println!("Count after creating b = {}", Rc::strong_count(&a)); 26 | 27 | let c = Rc::new(Cons(4, Rc::clone(&a))); 28 | println!("Count after creating c = {}", Rc::strong_count(&a)); 29 | } 30 | println!("Count after code block = {}", Rc::strong_count(&a)); 31 | } 32 | */ 33 | 34 | 35 | use std::rc::Rc; 36 | 37 | fn make_rc() -> Rc { 38 | 39 | let s1 = Rc::new(String::from("Hello")); 40 | println!("Count when the pointer is created {}", Rc::strong_count(&s1)); 41 | 42 | let s2 = s1.clone(); 43 | println!("Count after the clone is created for the pointer {}", Rc::strong_count(&s1)); 44 | s2 45 | 46 | } 47 | 48 | fn main(){ 49 | let s2 = make_rc(); 50 | println!("Count after function call {}", Rc::strong_count(&s2)); 51 | }s -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/9 - Smart Pointers in Rust/6 - RefCell smart pointer.txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // RefCell 3 | // - Borrowing rules checked at run time 4 | // - Interior Mutablity 5 | // - Rc with RefCell 6 | 7 | // ------------------------------------------- 8 | 9 | 10 | /* 11 | use std::cell::RefCell; 12 | 13 | fn main() 14 | { 15 | 16 | /* 17 | let mut x = 50; 18 | let x1 = &x; 19 | let x2 = &x; 20 | let x3 = &mut x; 21 | 22 | println!("{} {} ", x1,x2); 23 | */ 24 | 25 | /* 26 | let a = RefCell::new(10); 27 | 28 | { 29 | let b = a.borrow(); 30 | let c = a.borrow(); 31 | } 32 | 33 | //drop(b); 34 | //drop(c); 35 | 36 | let d = a.borrow_mut(); 37 | drop(d); 38 | println!("Value of a is : {:?}",a); 39 | 40 | */ 41 | 42 | /* 43 | let x = 32; 44 | let x1 = &mut x; 45 | */ 46 | 47 | 48 | /* 49 | let a = RefCell::new(10); 50 | // *a.borrow_mut() = 15; 51 | let mut b = a.borrow_mut(); 52 | *b = 15; 53 | 54 | //drop(b); 55 | println!("{:?}",a); 56 | 57 | 58 | 59 | */ 60 | //} 61 | 62 | */ 63 | 64 | 65 | 66 | 67 | use std::cell::RefCell; 68 | use std::rc::Rc; 69 | 70 | 71 | 72 | fn main() 73 | { 74 | 75 | 76 | let a = Rc::new(RefCell::new(String::from("java"))); 77 | let b = Rc::clone(&a); 78 | 79 | *b.borrow_mut() = String::from("c++"); 80 | println!("{:?}",a); 81 | 82 | 83 | 84 | } 85 | 86 | -------------------------------------------------------------------------------- /Course Code Bundle - Mar 2023 Edition/9 - Smart Pointers in Rust/7-Singly Link list (Part 1).txt: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // Link List (Part 1) 3 | // ------------------------------------------- 4 | 5 | #[derive(Debug)] 6 | struct linklist{ 7 | head: pointer, 8 | } 9 | #[derive(Debug)] 10 | struct Node{ 11 | element: i32, 12 | next: pointer, 13 | } 14 | 15 | type pointer = Option>; 16 | 17 | fn main(){ 18 | /* 19 | 20 | let list = Node{element: 1, next: None}; 21 | 22 | let list = Node{element: 1, next: Some(Box::new(Node { 23 | element: 2, next: Some(Box::new(Node { 24 | element:3, next: None 25 | })) 26 | }))}; 27 | 28 | let list = linklist {head: Node{element: 1, next: None}}; 29 | 30 | let list = linklist {head: Node { element: 1, next: Some(Box::new(Node { 31 | element: 2, next: Some(Box::new(Node { 32 | element: 3, next: None 33 | })) 34 | })) }}; 35 | */ 36 | 37 | let list = linklist{head: None}; 38 | 39 | let list = linklist{head: Some(Box::new(Node {element: 100, next: ( 40 | Some(Box::new(Node { 41 | element: 200, next: None 42 | })) 43 | )}))}; 44 | 45 | //println!("{:?}", list.head.unwrap().element); 46 | 47 | 48 | //println!("{:?}", list.head.unwrap().next.unwrap().element); 49 | 50 | println!("{:?}", list.head); 51 | 52 | 53 | 54 | } 55 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Packt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Practice Questions/Section 2/Practice Exercise on Functions and Inputs.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Programming-Master-Class-from-Beginner-to-Expert/7a219af138cce6793e3e5f1fb22bb50a4cac1b40/Practice Questions/Section 2/Practice Exercise on Functions and Inputs.docx -------------------------------------------------------------------------------- /Practice Questions/Section 2/Practice Exercise on Tuples and Arrays and Scalars.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Programming-Master-Class-from-Beginner-to-Expert/7a219af138cce6793e3e5f1fb22bb50a4cac1b40/Practice Questions/Section 2/Practice Exercise on Tuples and Arrays and Scalars.docx -------------------------------------------------------------------------------- /Practice Questions/Section 2/Practice Exercise on Variables.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Programming-Master-Class-from-Beginner-to-Expert/7a219af138cce6793e3e5f1fb22bb50a4cac1b40/Practice Questions/Section 2/Practice Exercise on Variables.docx -------------------------------------------------------------------------------- /Practice Questions/Section 3/Practice Exercise on Ownership.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Programming-Master-Class-from-Beginner-to-Expert/7a219af138cce6793e3e5f1fb22bb50a4cac1b40/Practice Questions/Section 3/Practice Exercise on Ownership.docx -------------------------------------------------------------------------------- /Practice Questions/Section 4/Practice Exercise on Basic Programming.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Programming-Master-Class-from-Beginner-to-Expert/7a219af138cce6793e3e5f1fb22bb50a4cac1b40/Practice Questions/Section 4/Practice Exercise on Basic Programming.docx -------------------------------------------------------------------------------- /Practice Questions/Section 7/Practice Exercise on Iterators, Lifetimes, and Closures.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Rust-Programming-Master-Class-from-Beginner-to-Expert/7a219af138cce6793e3e5f1fb22bb50a4cac1b40/Practice Questions/Section 7/Practice Exercise on Iterators, Lifetimes, and Closures.docx -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # Rust-Programming-Master-Class-from-Beginner-to-Expert --------------------------------------------------------------------------------