Variables: let age:u32 = 20; let sum:i32 = 5-15; let mark:isize = 10; let count:usize = 30;

Overflow: let weight:u8 = 256; //overflow value is 0 let height:u8 = 257; //overflow value is 1

Floats: The f32 type is a single-precision float, and f64 has double precision let interest:f32 = 8.35; let cost:f64 = 15000.600; f64 is default

No automatic type casting

That is 50,000 can be written as 50_000 . for ease of read

Bool: let isfun:bool = true;

Character: character data type in Rust supports numbers, alphabets, Unicode and special characters let special_character = ‘@’; //default let alphabet:char = ‘A’; let emoji:char = ‘😁’;

Mutability: By default, variables are immutable − read only in Rust. Error message indicates the cause of the error – you cannot assign values twice to immutable variable fees.

Mutable: let mut variable_name = value;

Constants: ll characters in a constant name are usually in uppercase. const PI:f32 = 3.14; – const keyword Cannot be set to output of function call or any that is computed at runtime

Variable declaration can optionally have a data type but not for constnants

Shadowing: let salary = 100.00; let salary = 1.50 ; The second var hides the first. Only variables can be shadowed

Strings: Literal(&string) and Object(String) String literals (&str) are used when the value of a string is known at compile time; static by default let company:&str=“TutorialsPoint”; String Object for runtime. ::new(), ::from(), to_string(), replace(), as_str() push(), push_str()[push means append here] , len(), trim(), split_whitespace(), split(), chars()etc. are it’s methods.

String Concat using +: let n3 = n1 + &n2; // n2’s reference is passed

Add to strings using format macro: let n3 = format!("{} {}",n1,n2);

Expressions: ++ and – are not supported in Rust

= and ! means equal and not equal comparisons

&& and || are and and or operators respectively. ! is not.

Right shift with zero is also available.

if num > 0 { do things }

if else similarly

else if is written like this.

match statement : if current value is matching from a list of vars: similar as switch

let state_code = “MH”; let state = match state_code { “MH” => {println!(“Found match for MH”); “Maharashtra”}, “KL” => “Kerala”, “KA” => “Karnadaka”, “GA” => “Goa”, _ => “Unknown” };

Loops: for x in 1..11{ do anything }

while x < 10 { do anything } : remember to use mutable variables in loops since they are likely to change

loop : indefinite loop

loop { x+=1; println!(“x={}",x);

if x==15 { break; } }

similarly: continue; statement can be used inside loop

Functions:

Definitions: fn fn_name(param_1, param_n) {}

Invoking: fn_name(params);

Return types: fn get_pi ->f64 {}

fn get\_pi()->f64 {

22.0/7.0 }

In this function, no semicolon means that value is returned

Pass by value: When functs invoked, values are actually copied. e.g. fn mutate_no_to_zero(mut param_no: i32) {} Functions will be similar to this.

Pass by reference: Parameter values can be passed by reference by prefixing the variable name with an & mutate_no_to_zero(&mut no); e.g. fn mutate_no_to_zero(mut param_no: i32) { *param_no = 0;}

  • here is used to de reference the object

Passing strings: fn fn_name(param_name:String){} when used also no need to use * and so on.

Tuples: Tuples have a fixed length - once declared they cannot grow or shrink in size.

Index starts from zero. e.g. let tuple:(i32,f64,u8) = (-325,4.9,22);

To print a tuple: println!(”{:?}", tuple_name)

Getting elements one by one: tuple.0, tuple.1 and so on.

Printing individual elems also require same println!("{:?}",tuple.1);

Passing tuple as param to function: fn_name(x:(i32,bool,f64)) Can be directly used as ‘x’ now.

Tuple values unpacking: e.g. let (age,is_male,cgpa) = x;

Arrays: Variables can have only scalar values and randomly allocated in memory; so diff to read in order of declaration.

Static, sequential memory block, unique by subscript, can be modified but not deleted.

e.g. let arr:[i32;4] = [10,20,30,40]; e.g. let arr = [10,20,30,40]; e.g. let arr:[i32;4] = [-1;4]; // default value -1 for array of size 4

Array Looping: e.g. for val in arr.iter() {}

Mutable array: e.g. let mut arr:[i32;4] = [10,20,30,40]; e.g. arr[2] = 0; //valid now

Arrays as params to functions : pass by value e.g. fn update(mut arr:[i32;3]) // function that accepts array update(arr); //call by value This way passes by value so nothing is changed.

Arrays pass by reference: e.g. fn update(arr:&mut [i32;3]) update(&mut arr); // passing a mutable array so that fn can make changes

Array Declaration: This doesn’t work since the array length must be known at runtime. let N: usize = 20; let arr = [0; N];

Variables can’t be used to define size of array. const N: usize = 20; This now works

Usize: usize is pointer-sized, thus its actual size depends on the architecture you are compiling your program for.

Stack and Heap: Variable of fixed size e.g. i32 –> candidate for stack allocation Strings whose length is known at runtime –> Heap allocated Heap less organized as compared to stack

Ownership: e.g. let age = 30; // age is the owner of 30

Each data can have only one owner at a time.

Two variables so can’t point to same mem location.

Transfer of Ownership: Assigning value to another variable Passing value to function Returning value to function

e.g. let v = vec![1,2,3]; let v2 = v; // ownership transferred here if we try to use v, it returns a error. ‘v’ is destroyed now.

e.g.display(v2); / v2 is moved to display and invalidated println!("{:?}", v2); / here v2 is no longer usable fn display(v:Vec){ println!(“inside display {:?}",v); }

A variable v2 which is in heap once sent to function or closure , it exists no more.

Ownership passed to the function will be invalidated as function execution completes. We can pass back the variable after the function call if we don’t want this to happen.

In case of primitive types, contents from one variable is copied to another. e.g. let u1 = 10; let u2 = u1; // u1 value copied(not moved) to u2

Borrowing:

When a function transfers its control over a variable/value to another function temporarily, for a while, it is called borrowing.

e.g. print_vector(&v); // passing reference

fn print_vector(x:&Vec){ //use x here }

Doing this we can protect ownership of original variable here.

A function can modify a borrowed resource by using a mutable reference to such resource. e.g. passing by reference example of a variable that is mutable

Slice: Pointer to block of memory

Size of slice determined at runtime.

Slices are pointers to the actual data. They are passed by reference to functions, which is also known as borrowing.

e.g let n1 = “Tutorials”.to_string();

let c1 = &n1[4..9]; // this gives part of string 4,5,6,7,8

Passing a slice to function: e.g. fn use_slice(slice:&[i32]) //pass data as use_slice(&data[1..4]);

To mark slice as mutable: e.g. use_slice(&mut data[1..4]); also function needs to accept mutable slice

Structure:

Key value pair: Similar to python dict

e.g. struct Employee { name:String, company:String, age:u32 }

let emp1 = Employee { company:String::from(“TutorialsPoint”), name:String::from(“Mohtashim”), age:50 };

Access elements using emp1.name, emp1.company and so on.

Add mut keyword at front of struct instance to make it mutable e.g. let mut emp1 = Employee{} emp1.age= 20; //this now works

Passing to functions: fn display( emp:Employee){//any code}

Return a struct as output: fn fn_name(params)->Employee {}

Methods in structures:

impl keyword is used to define a method within the context of a structure

The first parameter of a method will be always self

To invoke a method, we need to first instantiate the structure.

e.g. //define dimensions of a rectangle : Do this first struct Rectangle { width:u32, height:u32 }

//logic to calculate area of a rectangle : Then only define methods impl Rectangle { fn area(&self)->u32 { //use the . operator to fetch the value of a field via the self keyword self.width * self.height } }

Static Method in structure:

These methods exist even before the structure is instantiated.

Using structure’s name , no instance to access

Will not take &self as parameter

e.g. impl Structure_Name { //static method that creates objects of the Point structure fn method_name(param1: datatype, param2: datatype) -> return_type { // logic goes here } }

structure_name::method_name(v1,v2) // this is way to invoke static method

Enums:

to select a value from a list of possible variants we use enumeration data types

e.g. #[derive(Debug)] // Used to supress error for not having Debug implemented for GenderCategory enum GenderCategory { Male,Female }

//usage let male = GenderCategory::Male;

Option Enum:

Option is a predefined enum in the Rust standard library

Rust does not support the null keyword. The value None, in the enumOption, can be used by a function to return a null value.

Match can be used with Options

Data Type in Enum and Options:

It is possible to add data type to each variant of an enum

e.g. enum GenderCategory { Name(String),Usr_ID(i32) }

let p1 = GenderCategory::Name(String::from(“LIS”)); let p2 = GenderCategory::Usr_ID(100);

Modules:

Logical group of code

Multiple modules ==> Crate

Binary crate or Library crate

Binary crate has a main method.

Cargo tool used to manage crates in Rust

e.g. networking module, graphics module

Can be public or private modules

Modules private by default

Prefixed with “pub” keyword to make module public

e.g. pub mod movies { pub fn play(name:String) { println!(“Playing movie {}",name); } }

This can be called inside a main function as movies::play()

Use keyword to use a specific module’s function: use public_module_name::function_name;

Use a lib module inside a binary module e.g. extern crate movies_lib; use movies_lib::movies::play;

Collections:

Vectors: e.g. let mut instance_name = Vec::new(); e.g. let vector_name = vec![val1,val2,val3]

vec! is a macro to create a new vector.

functions: new(), push, remove, contains, len

Check an element: if 10 is in the vector if v.contains(&10) { println!(“found 10”); }

HashMap:

insert, len, get, iter, contains_key, remove

Get: Returns a reference to the value corresponding to the key.

Iter: An iterator visiting all key-value pairs in arbitrary order. The iterator element type is (&‘a K, &‘a V).

e.g. using get

match stateCodes.get(&“KL”) { Some(value)=> { println!(“Value for key KL is {}",value); } None => { println!(“nothing found”); } } }

e.g. using iter: for (key, val) in stateCodes.iter() { println!(“key: {} val: {}”, key, val); }

e.g. stateCodes.remove(&“GJ”);

HashSet: set of unique values of type T

Adding and removing values is fast, and

it is fast to ask whether a given value is in the set or not

insert, len, get, iter, contains_key, remove

Error Handling:

Recoverable and unrecoverable errors e.g. FileNotFound error is recoverable

Rust doesn’t have exceptions

Returns enum Result<T, E> for recoverable errors

Panic macro if unrecoverable error occurs

panic!(“Hello”); // this ends the program abruptly

e.g. for array of size 3, if array[10] is called, it invokes a panic

program can invoke panic! if any rules are violated.

e.g. enum Result<T,E> { OK(T), Err(E) }

T ==> type of value to be returned in success case E ==> type of error in failure case within Err variant

e.g. trying to open a file that doesn’t exist

let f = <:open>(“main.jpg”); // main.jpg doesn’t exist match f { Ok(f)=> { println!(“file found {:?}",f); }, Err(e)=> { println!(“file not found \n{:?}",e); //handled error } }

Output: File not found Os { code: 2, kind: NotFound, message: “The system cannot find the file specified.” }

Can make a function to handle stuffs like this: e.g. fn is_even(no:i32)->Result<bool,String> { if no%2==0 { return Ok(true); } else { return Err(“NOT_AN_EVEN”.to_string()); } }

The result then can be used using match and printed for errors.

Unwrap and Expect: When you don’t expect things to fail

In case of success: unwrap to get exact result

e.g. let result = is_even(10).unwrap(); so here we get the number as result

On using unwrap , if the function results in an error, program exits with panic!.

Can use expect() to display custom error message on case of panic. e.g. let f = <:open>(“pqr.txt”).expect(“File not able to open”);

Generic Types: Generics allows to write more concise and clean code by reducing code duplication and providing type-safety.

The syntax known as the type parameter, is used to declare a generic construct.

e.g. struct Data { value:T, }

Now the datatype will be filled by the compiler later.

e.g. let t:Data = Data{value:350}; / generic type of i32 let t2:Data = Data{value:“Tom”.to_string()}; / generic type of string

The main() method when these things will be called will create two instances of Data.

Traits: implement a standard set of behaviors (methods) across multiple structures

Similar to interfaces in OOP.

e.g. struct Book { name:&‘static str, id:u32 }

trait Printable { fn print(&self); }

impl Printable for Book { fn print(&self){ println!(“Printing book with id:{} and name {}",self.id,self.name) } }

Here, first we define a struct data type Book Then, we create a trait called Printable having a Print function ready to be implementd. Now Book struct will impl Printable trait; so it expands the print function from trait to print the book name and id.

Generic Functions: e.g. fn print_pro<T:Display>(t:T){ println!(“Inside print_pro generic function:”); println!(”{}",t); }

Here this function will print any datatype you give.

print_pro(10 as u8); print_pro(20 as u16); print_pro(“Hello TutorialsPoint”);

Every call is valid.

Input/ Output: Read : using stdin, File Similarly for write.

Readers are components that your program can read bytes from read_line() to read lines at a time one by one

e.g. let mut line = String::new(); println!(“Enter your name :”); let b1 = std::io::stdin().read_line(&mut line).unwrap();

Write example: let b1 = std::io::stdout().write(“Tutorials “.as_bytes()).unwrap(); std::io::stdout().write(format!("\nbytes written {}”,(b1+b2)).as_bytes()).unwrap();

Here first one uses sdout to write into the variable Second uses format! macro to generate a string adding two together and writing to var

CommandLine Args:

std::env::args() returns the commandline arguments

e.g. let cmd_line = std::env::args();

now using len() , we can know the number of values passed and can iterate to get all args.

e.g. How to use these args: let mut command_line: std::env::Args = std::env::args(); command_line.next().unwrap(); // this skips file name from the args list

let source = command_line.next().unwrap(); // get the first actual arg passed to a var

File Input and Output:

Methods: open, create, remove_file, append, write_all, read_to_string

std::fs::remove_file(for read), std::fs::OpenOptions(for append), std::io::Writes ( for write_all)

e.g. let mut file = std::fs::<:create>(“data.txt”).expect(“create failed”); file.write_all(“Hello World”.as_bytes()).expect(“write failed”);

e.g. file.read_to_string(&mut contents).unwrap(); // reading from a file to variable

e.g fs::remove_file(“data.txt”).expect(“could not remove file”); //remove a file

e.g. let mut file = OpenOptions::new().append(true).open(“data.txt”).expect(“cannot open file”); // this opens file as to append something to it using write_all method

Iterators:

declare an array, vector and so on. e.g. let mut iter = a.iter(); // where a is any iterable data type

now next() can be used to iterate over the elements

can be used with for loop as well

into_iter() function uses concept of ownership. It moves values in coll to iter object so after doing this, you cannot again use the original collection or vector or whatever.

iter_mut() We can modify elements within the collection. Only mutable collections can use this

Closures:

Closure refers to a function within another function

Anon functions

Also known as inline function

variables in outer function can be accessed by inline functions

e.g. let is_even = |x| { x%2==0 };

similar to lambda function in python

Smart Pointers:

Everything is allocated to stack by default

Can store things on the heap by wrapping them in smart pointers like Box

Vec, String implicitly help heap allocation.

Traits of smart pointers: std::ops::Deref, std::ops::Drop // similar to destructor and immutable deref

Box pointer: stack contains pointer to box, box is stored in heap.

e.g. let var_i32 = 5; //stack let b = Box::new(var_i32);

Now variable b is in addressed from the heap.

To get access to variable’s value, we use dereferencing. * as deref operator.

we can now print variable ‘b’ but to use the value , we need to do *b

Also we can use impl Deref for anyStruct to get the inner variable using *

Concurrency:

Creating a thread:

use std::thread;

thread::spawn(|| { any work });

Spawn Takes closure as parameter

closure defines code that should be executed by the thread

Sleeping a thread:

thread::sleep()

for time duration: use std::time::Duration; Duration::from_millis(1); //eg using ms for time

Join handles:

A spawned thread may not get a chance to run or run completely.

It’s because main thread completes quickly.

handle = thread::spawn(…..) handle.join().unwrap();

The main thread waits for spawned thread to complete because of the call to the join() method.

By joining , the main thread doesn’t immediately close the program but let all other threads finish their work too.

cargo test – –nocapture does the task

cargo test add does this task

cargo test – –ignored will run ignored tests as well.