# Rust tutorial Why Is Rust Different? #### Speed Rust pays no penalty for the abstraction and only pays for the features that are actually used. This improves the code quality and readability without affecting the run time cost. #### Safety Rust does not have a garbage collector. It ensures memory safety using ownership and its borrowing concept. ![](https://i.imgur.com/YWLb14X.png) 1. Safe code 2. In Rust, the objects are managed by the programming language from the beginning to the end. 3. The proper amount of memory required is allocated and automatically deallocated by the system when it is no longer in use. 4. Rust provides a cargo manager that has all the rust libraries. #### Efficient C Binding The Rust language can interoperate with the C language. It provides a foreign function interface to communicate with C API’s. Due to its ownership rules, it can guarantee memory safety. ### Start learing rust ###### All the best to me Basic: ```rust= fn main() ``` **What is a macro?** A macro is an expression that has an exclamation mark (!) before the parenthesis () Now let's start this with hello world as usal. One sec! do u know how to run and where to run this? You can use VS code environment to run this code. 1. Just create a file `hello.rs` 2. run this command in termail `rustc` <file_name> 3. enter ``./hello``. ```rust= fn main(){ println!("{}","Hello rust") } ``` ### Place holders * In Rust, we cannot directly print numbers or variables within the println!() macro, We need a placeholder {}. ```rust= fn main(){ println!("{}",<variable>) println!("{} {}",1,":hello") } ``` Variable may be int or a string. ### Positional Arguments Assign unique value to very variable.Values starts from 0 to (no.of elts in the list -1) . You can use same variable more than one time.And Make sure you use all elements from the list. ```rust= fn main(){ println!("{0}{1} and {1}","Hello","rust"); } ``` ### Named arguments Assign unique name to each elt in the list. ```rust= fn main(){ println!("{Name} and I Like {Name}",Name = "Rust"); } ``` ### Conversions ```rust= fn main(){ println!("Number: 10, Binary:{:b}, hex : {:x}, oct:{:o}",10,20,30); } ``` ### Operators in rust 1. Addition (+) 2. Subtraction (-) 3. Multipication(* ) 4. Integer division (/) 5. Modulo division (%) 4 -> If u want float division then give decimal number in expression. ```rust= println!("{},{},{},{},{},{}",1+1,1-1,1*2,3/2,22.0/7.0,3%1); ``` #### Single place holder for multiple variables. ```rust= fn main() { println!("{:?}", ("hello", 1024)); } ``` #### some macros **print!** - it is used to print every statement in a single line. **println!** - It is used to print each statment in a new line. **eprint!** - Used to print stateme **eprintln!** - It is used to print each statement as an error in new line. ```rust= fn main(){ print!("{}","hello"); print!("{}","rust"); println!("{}","hello"); println!("{}","rust"); eprint!("Rust Programming"); eprint!("Course"); eprintln!("Rust Programming"); eprintln!("Course"); } ``` ![](https://i.imgur.com/3bKmZN4.png) ## Variables The variable associated name is called identifier and data inside the variable is called value. **Note:** Variables are immutable by defalut.(not reassignable). Create a variable using keyword called **let**. WHere `let` is binding followed by the var name. WHat is mean by binding? Rust refers to all declarations as Bindings as they bind a name you create to some type of data. [reference ](https://www.codingame.com/playgrounds/365/getting-started-with-rust/binding-variables) `let` is a binding keyword, which helps in binding a new variable. How to give variable name? 1. Use lower case letters for creating a variable. 2. seperate words using underscore(_). In general they are immutable. If a variable need to be mutable. use `let mut` keyword. **Small note:** 1. You can assign a variable twice using only `let` , only if you have used it previously.If not it will show `warning: unused variable:`. 2. If a variable is kept **un-assigned or unused**, you’ll get a warning. 3. Use ``#[allow(unused_variables, unused_mut)]`` at the starting if the program. to not to get such warnings. Assigning multiple variables using single `let`. ```rust= #[allow(unused_variables, unused_mut)] let (a,b) = ("rust","R"); let mut (a,b) = ("rust","R"); ``` ### Scope and shadowing Scope : The scope of a variable tells about which parts of a program can access that variable. 1. If variable delcared inside amy curly braces{}, then it is restricted within the braces. #### Variables Local variable: Varible inside the block is accessable within braces,but not outside the braces.the variable is freed and memory for the variable is deallocated. #### Gobal variable The variables that are declared outside any block of code and can be accessed within any subsequent blocks are known as global variables. The variables declared using the const keyword can be declared in local as well as global scope. #### Shadowing It is used to use gobal variable inside any scope and using it as local variable.This is also known as masking. This outer variable is said to be shadowed by the inner variable, while the inner variable is said to mask the outer variable. ```rust= fn main(){ let x =10; { let x = 11; let y =12; println!("{}",x); println!("{}",y); } println!("{}",x); } ``` ### Data Types Rust is statistically typed(compiler must know the type of all variables at complie time.) ##### general syntax ```rust= fn main(){ let x = 2; } ``` ##### Explicitly ```rust= fn main(){ let variable:datatype = value; } ``` #### Primitive types: ![](https://i.imgur.com/qtENomB.png) ###### [resource](https://www.educative.io/courses/learn-rust-from-scratch/q2PoBV1BmR3) ###### Scalar Type They store a single value. 1. Integer 2. Float 3. Boolean 4. Character ###### Compound Type They group multiple values in one variable. 1. Array 2. Tuple ##### Numeric types: Variables of integer data type hold whole number values. Integer subtypes are based number of bits occupied by a variable in memory. ###### UNSIGNED #### Fixed Size Types ![](https://i.imgur.com/no4rH6s.png) ``` i8: The 8-bit signed integer type. i16: The 16-bit signed integer type. i32: The 32-bit signed integer type. i64: The 64-bit signed integer type. u8: The 8-bit unsigned integer type. u16: The 16-bit unsigned integer type. u32: The 32-bit unsigned integer type. u64: The 64-bit unsigned integer type. ``` #### Variable Size Types The integer type in which the particular size depends on the underlying machine architecture. * isize: The pointer-sized signed integer type. * usize: The pointer-sized unsigned integer type. ```rust= fn main(){ let a:i32 = -24; let b:u64 = 23; let c:usize = 26; let d:isize = 29; } ``` ##### For floating numbers ``` use **f size** to declare a float variable. **f size** => f32 or 64 ``` This is used for explicit def. #### Boolean The boolean variable can take a value either true or false. ```rust= let is_bool:a = true; //explicitly println!("{}",a); let c = 20<10; println!(c); ``` ##### Character and string Char: The variable is used to store a single char value.The value toa char variable is enclosed in a **single quote(' ')**. In rust character takes 4 bytes rather than a single byte.Here it can take emojis,different language characters. String: A string is any sequence of characters enclosed within double quotes. ```rust= //Character let ch = 'a'; //Imlicit defination let ch1:char = 'e'; //explicitly println!("{}",ch1); //String ``` ```rust= fn main(){ let str_1:&str = "Rust Programming"; let s1 = "rust programming"; } ``` ##### Arrays An array is a collection of same type are stored in a single variable. In Rust, an array can only be of a fixed length. arrays are immutable. Syntax: ``` let var_name: [data_type: size of the array] = [elt1,elt2,elt3]; ``` ###### access array elts ```rust= fn main() { //define an array of size 4 let arr:[i32;4] = [1, 2, 3, 4]; // initialize an array of size 4 with 0 let arr1 = [0 ; 4]; } ``` ###### How to Make an Array Mutable? Use let mut keyword and you can change any elt in that list. ```rust= fn main(){ let mut arr:[i32;4] = [1,2,3,4]; println!("{}",arr[2]); arr[2] = 5; println!("{}",arr[2]); } ``` **Print whole array using debugging trait** use debug trait in `println!({:?})` ###### Lenght of an array Use **`arr.len()`** to get the len of an array. ###### Slicing of an array Slice is basically a portion of an array. It is two worded object which consist of data pointer and slice length. ```Data pointer is a programming language object that points to the memory location of the data, i.e., it stores the memory address of the data.``` Slicing of array starting index is inclusive and ending index is exclusive. ```rust= let ind:&[i32]=&arr[0..2]; ``` ##### Tuples: * It is hetrogenous(it can take different type of datatypes at a time) * Syntax: * let tuple_name = ("value1",'c',1); * let tup_name1 :(&str,char,i32) = ("value",'c',i32); * How to access tuple ? * tup_name1.indexvalue #### Constant Variables: Constant variables can't be changed through out the scope. **Key word** : `const` **syntax** : const var_name : i32 = 001; `identifier` `variable_name` : `variable name` = `variable value` Instructions to create variable name : 1. Use UPPER CASE letters 2. All words should be separated using an underscore ( _ ). Notes: 1. While using `const` , must be define varible with datatype unlike `let`. 2. Unlike let variables, const variables cannot be shadowed. #### Operators ###### Unary operators: The operators that act upon a single operand are unary operators. Types: 1. Borrow Expression 2. Dereference Expression 3. Negation Expression 4. Logical Negation Expression ###### Binary Operators: The operators that deal with two operands are binary operators. 1. Types: 1. Arithmetic Expression 1. Logical Expression 1. Comparison Expression 1. Bitwise Expressions 1. Assignment Expression 1. Compound Assignment Expression 1. Typecast Expression ##### Arithmetic Operators Operations: ``+,-,*,/,%`` ##### Logical Operators Operations: `&&,||,!` ![](https://i.imgur.com/U5E2gsb.png) [Reference](https://www.educative.io/courses/learn-rust-from-scratch/7XzkzpJzW3Q) ##### Comparison Operators Operations: `<,>,<=,>=,==,!=` ![](https://i.imgur.com/sYacpCN.png) [Reference](https://www.educative.io/courses/learn-rust-from-scratch/7XzkzpJzW3Q) ##### Bitwise Operators Operations: ``&,|,^,`` ==> Binary operators Operations: `!,<<,>>` ==> unary operators **Note:** We have two different not operators here. one is from logical and other is from bitwise operators. ![](https://i.imgur.com/HbKG9xO.png) ##### Borrowing and Dereferencing Operators: 1. Shared borrow 2. Nutable borrow ![](https://i.imgur.com/iCOpqO8.png) [referenece](https://www.educative.io/courses/learn-rust-from-scratch/3j1yLqjX7Gp) ```rust= fn main() { let x = 10; let mut y = 13; //immutable reference to a variable let a = &x; println!("Value of a:{}", a); println!("Value of x:{}", x); // x value remains the same since it is immutably borrowed //mutable reference to a variable let b = &mut y; println!("Value of b:{}", b); *b = 11; // derefencing println!("Value of b:{}", b); // updated value of b println!("Value of y:{}", y); // y value can be changed as it is mutuably borrowed } ``` output: ```Value of a:10 Value of x:10 Value of b:13 Value of b:11 Value of y:11``` ``` ###### Precedence Operators are listed below in the order of their precedence from highest to lowest : Unary ``` Logical/Bitwise NOT - ! Derereference - * Borrow - &, &mut Binary Typecast - as Multiplication- *,Division - /, Remainder - % Addition -+, Subtraction - - Left Shift - <<, Right Shift - >> Bitwise AND - & Bitwise XOR - ^ Bitwise OR - | Comparison - == != < > <= >= Logical AND - && Logical OR - || Range - start .. stop Assignment/Compound Assignment - = += -= *= /= %= &= |= ^= <<= >>= ``` Left to Right Associativity Left associativity occurs when an expression is evaluated from left to right. An expression such as a ~ b ~ c, in this case, would be interpreted as (a ~ b) ~ c where ~ can be any operator. The operators below can be chained as left associative. ```as *, /, % +, - << >> & ^ | && || ``` ##### Conditional EXPRESSIONS IF EXPRESSIONS: if condition{ st1; st2; } If ...else expressions: if condition{ } else{ st1; st2; st3; } if ...else if .... else : if cond{ } else if cond{ } else{ } ###### Shorthand if let x=if(condition){statment} else {statemnet};