From 2ed5e4cd4a443c34faaedbaf798b24af8ccaa66e Mon Sep 17 00:00:00 2001 From: Randy8080 Date: Mon, 3 Jan 2022 12:40:31 +0800 Subject: [PATCH] Format Rust cheat sheet --- rust.md | 587 +++++++++++++++++++++++++++----------------------------- 1 file changed, 279 insertions(+), 308 deletions(-) diff --git a/rust.md b/rust.md index 7d35752..decc80e 100644 --- a/rust.md +++ b/rust.md @@ -1,212 +1,203 @@ --- title: Rust date: 2022-01-01 11:51:44 -icon: icon-cpp -background: bg-emerald-600 +icon: icon-rust +background: bg-black tags: categories: - - Programming + - Programming intro: | - Rust quick reference cheat sheet that aims on providing help on writing basic syntax and methods. + The Rust quick reference cheat sheet that aims at providing help on writing basic syntax and methods. --- -# Getting Started +Getting Started {.cols-3} +--------------- -- Hello_World.rs +### Hello_World.rs ```rust - fn main() { - - println!("{}", "Hello, World!"); - +fn main() { + println!("{}", "Hello, World!"); } ``` - -### Compiling and Running - -```bash +#### Compiling and Running +```shell $ rustc Hello_World.rs -o Hello_World $ ./Hello_World Hello, World! ``` -## Formatting +### Primitive types -```rust +| | | +|---------------------------|----------------------------------| +| `bool` | Boolean (`true` _/_ `false`) | +| `char` | character | +| `f32`, `f64` | 32-bits, 64-bits floats | +| `i64`, `i32`, `i16`, `i8` | signed 16- ... integers | +| `u64`, `u32`, `u16`, `u8` | unsigned 16-bits, ... integers | +| `isize` | pointer-sized signed integers | +| `usize` | pointer-sized unsigned integers | -fn main() { - println!("{}", 1); /*Single Placeholder*/ - println!("{} {}", 1, 3); /* Multiple Placeholder */ - println!("{0} is {1} {2}, also {0} is a {3} programming language", "Rust", "cool", "language", "safe"); /*Positional Arguments*/ - println!("{country} is an diverse nation with unity.", country = "India"); /*Named Arguments*/ - println!("Let us print 76 is binary which is {:b} , and hex equivalent is {:0x} and octal equivalent is {:o}", 76, 76, 76); /*Placeholder traits :b for binary, :0x is for hex and :o is octal*/ - println!("Print whatever we want to here using debug trait {:?}", (76, 'A', 90)); /* Debug Trait*/ -} -``` +See: [Rust Types](#rust-types) -## Printing Styles -```rust +### Formatting {.row-span-2} -fn main(){ - print!("Hello World \n"); /* Prints the output to console*/ - println!("Appending a new line after printing"); /* Appends a new line after printing output to the console*/ - eprint!("This is an error\n"); /* Prints as an error*/ - eprintln!("This is an error with new line"); /* Similar to eprint just appends a new line after printing output to the console*/ -} +```rust {.wrap} +// Single Placeholder +println!("{}", 1); + +// Multiple Placeholder +println!("{} {}", 1, 3); + +// Positional Arguments +println!("{0} is {1} {2}, also {0} is a {3} programming language", "Rust", "cool", "language", "safe"); + +// Named Arguments +println!("{country} is an diverse nation with unity.", country = "India"); + +// Placeholder traits :b for binary, :0x is for hex and :o is octal +println!("Let us print 76 is binary which is {:b} , and hex equivalent is {:0x} and octal equivalent is {:o}", 76, 76, 76); + +// Debug Trait +println!("Print whatever we want to here using debug trait {:?}", (76, 'A', 90)); ``` -## Comments +### Printing Styles ```rust +// Prints the output +print!("Hello World\n"); +// Appends a new line after printing +println!("Appending a new line"); + +// Prints as an error +eprint!("This is an error\n"); + +// Prints as an error with new line +eprintln!("This is an error with new line"); +``` + + +### Variables + +```rust +// Initializing and declaring a variable +let some_variable = "This_is_a_variable"; + +// Making a variable mutable +let mut mutable_variable = "Mutable"; + +// Assigning multiple variables +let (name, age) = ("ElementalX", 20); + +// (Global) constant +const SCREAMING_SNAKE_CASE:i64 = 9; +``` + + + +### Comments + +```rust // Line Comments /*.............Block Comments */ /// Outer doc comments //! Inner doc comments ``` +See: [Comment](https://doc.rust-lang.org/reference/comments.html) -## Variables -```rust -fn main(){ - - - let some_variable = "This_is_a_variable"; // Initializing a variable and declaring it. - println!("{}", some_variable); //Printing a variable - let mut mutable_variable = "Mutable Variable"; // Making a variable mutable - println!("{}", mutable_variable); // Printing the mutable variable - let (name, age) = ("ElementalX", 20); //Assigning multiple variables - println!("Hi , Myself {}, and am {}", name, age); // Printing the multiple variables - -/* Shadowing*/ - { - let some_variable = 2; - println!("The value of some variable is : {}", some_variable); // This will print 2 aka the integer. - } - println!("The value of some variable is : {}", some_variable); // This will print the string. - - /* Scope */ - - { - - let just_a_number = 1; /* The scope of thia variable is limited to this braces only*/ - - } - println!("The value of just_a_number is : {}", just_a_number); /* This will produce error as the scope of the variable just a number ends at the braces */ -} - -``` - -## Functions +### Functions ```rust fn test(){ - -println!("This is a function!"); - - + println!("This is a function!"); } fn main(){ - test(); } ``` -# Basic Data Types -## Integer + +Rust Types {.cols-3} +-------------- + + +### Integer ```rust -fn main(){ - let mut a: u32 = 8; - let b: u64 = 877; - let c: i64 = 8999; - let d = -90; - println!("The values of above integers are {:?}", (a, b, c, d)); - -} +let b: u64 = 877; +let c: i64 = 8999; +let d = -90; ``` -## Floating-Point + +### Floating-Point ```rust -fn main(){ - let mut sixty_bit_float: f64 = 89.90; - let thirty_two_bit_float: f32 = 7.90; - let just_a_float = 69.69; - println!("The floats declared above are : {:?}", (sixty_bit_float, thirty_two_bit_float, just_a_float)); -} +let thirty_two_bit_float: f32 = 7.90; +let just_a_float = 69.69; ``` -## Boolean -```rust -fn main(){ +### Boolean - let true_val: bool = true; - let false_val: bool = false; - let just_a_bool = true; - let is_true = 8 < 5; - println!("The booleans declared above are {:?}", (true_val, false_val, just_a_bool, is_true)); -} +```rust {.wrap} +let true_val: bool = true; +let false_val: bool = false; +let just_a_bool = true; +let is_true = 8 < 5; // => false ``` -## Character + +### Character ```rust - let first_letter_of_alphabet = 'a'; - let explicit_char: char = 'F'; - let implicit_char = '8'; - let emoji = "\u{1f600}"; - - println!("The character declared above are : {:?}", (first_letter_of_alphabet, explicit_char, implicit_char, emoji)); +let first_letter_of_alphabet = 'a'; +let explicit_char: char = 'F'; +let implicit_char = '8'; +let emoji = "\u{1f600}"; // => 😀 ``` -## String Literal + +### String Literal + +```rust {.wrap} +let community_name = "AXIAL"; +let no_of_members: &str = "ten"; + +println!("The name of the community is {} and it has {} members", community_name, no_of_members); + ``` + + + +### Arrays ```rust -fn main(){ - - let community_name = "AXIAL"; - let no_of_members: &str = "ten"; - println!("The name of the community is {} and it has {} members", community_name, no_of_members); - } - ``` - - -## Arrays - - -### 1-D Array - -```rust - ┌─────┬─────┬─────┬─────┬─────┬─────┐ | 92 | 97 | 98 | 99 | 98 | 94 | └─────┴─────┴─────┴─────┴─────┴─────┘ 0 1 2 3 4 5 - - ``` +``` +---- ```rust - -fn main(){ - - let array: [i64; 6] = [92,97,98,99,98,94]; -println!("The elements of the array are : {:?}", array); - -} ``` + + ### Multi-Dimensional Array ```rust @@ -216,246 +207,226 @@ i0 | 1 | 2 | 3 | 4 | 5 | 6 | ├────┼────┼────┼────┼────┼────┤ i1 | 6 | 5 | 4 | 3 | 2 | 1 | └────┴────┴────┴────┴────┴────┘ - ``` +``` +---- - ```rust - -fn main(){ - - -let array: [[i64; 6] ;2] = [[1,2,3,4,5,6], [6,5,4,3,2,1]]; -println!("The elements of the array are : {:?}", array); - -} +```rust +let array: [[i64; 6] ;2] = [ + [1,2,3,4,5,6], + [6,5,4,3,2,1]]; ``` ### Mutable Array ```rust -fn main(){ - -let mut array: [i32 ; 3] = [ 2,6,10]; //Arrays are immutable by default, so use the 'mut' keyword to make it mutable. +let mut array: [i32 ; 3] = [2,6,10]; array[1] = 4; array[2] = 6; -println!("The elements of the array are : {:?}", array); - - -} ``` +Use the `mut` keyword to make it mutable. -## Constants + +### Slices ```rust - -const SCREAMING_SNAKE_CASE:i64 = 9; - -fn main() { - println!("The value of the constant variable is : {}", SCREAMING_SNAKE_CASE); -} -``` - -## Slices - -```rust - -fn main(){ - -let mut array: [ i64; 4] = [1,2,3,4]; +let mut array: [ i64; 4] = [1,2,3,4]; let mut slices: &[i64] = &array[0..3] // Lower range is inclusive and upper range is exclusive println!("The elements of the slices are : {:?}", slices); - -} ``` -## Vectors +### Vectors ```rust - -fn main(){ - - -let some_vector = vec![1,2,3,4,5]; // a vector is declared using the "vec!" macro. -println!("The elements of the vector are : {:?}", some_vector); - -} +let some_vector = vec![1,2,3,4,5]; ``` +A vector is declared using the `vec!` macro. -## Tuples + +### Tuples ```rust - -fn main(){ - - -let tuple = ( 1, 'A' , "Cool", 78, true); -println!("The elements of the tuple are : {}", tuple); -} +let tuple = (1, 'A' , "Cool", 78, true); ``` -# Operators +Rust Operators {.cols-3} +----------- -## Arithmetic Operators +### Comparison Operators +| | | +|----------|----------------------------------| +| `e == f` | `e` is equal to `f` | +| `e != f` | `e` is NOT equal to `f` | +| `e < f` | `e` is less than `f` | +| `e > f` | `e` is greater `f` | +| `e <= f` | `e` is less than or equal to `f` | +| `e >= f` | `e` is greater or equal to `f` | -| | | -|---------- |-------------------------------------------------------| -| `a + b` | a is added to b | -| `a - b` | b is substracted from a | -| `a / b` | a is divided by b | -| `a % b` | gets remainder of a by dividing with b | -| `a * b` | a is multiped with b | -|-----------|-------------------------------------------------------| - +--------- ```rust - let (a, b) = (4, 5); - let sum: i32 = a + b; - let subtractions: i32 = a - b; - let multiplication: i32 = a * b; - let division: i32 = a / b; - let modulus: i32 = a % b; +let (e, f) = (1, 100); - println!("The sum of both the numbers is {}, the subtractions is {}, the multiplication is {}, the division is {}, the modulus is {}", sum, subtractions, multiplication, division, modulus); - ``` - - - -## Logical Operators - - -| Example | Meaning | -|----------------|------------------------| -| `C && D` | Both are true _(AND)_ | -| `C OR D` | Either is true _(OR)_ | -| `!C` | `C` is false _(NOT)_ | -|----------------|------------------------| - - -```rust - fn main(){ - - let (c, d) = (true, false); - let AND = c && d; - let OR = c || d; - let NOT = !c; - println!("The result of C && D is : {}, C OR D is : {}, NOT C is : {}", AND, OR, NOT); - } +let greater = f > e; // => true +let less = f < e; // => false +let greater_equal = f >= e; // => true +let less_equal = e <= f; // => true +let equal_to = e == f; // => false +let not_equal_to = e != f; // => true ``` -## Comparision Operators +### Arithmetic Operators -| | | -|----------|------------------------------| -| `e == f` | e is equal to f | -| `e != f` | e is NOT equal to f | -| `e < f` | e is less than f | -| `e > f` | e is greater f | -| `e <= f` | e is less than or equal to f | -| `e >= f` | e is greater or equal to f | +| | | +|----------|--------------------------------------------| +| `a + b` | `a` is added to `b` | +| `a - b` | `b` is subtracted from `a` | +| `a / b` | `a` is divided by `b` | +| `a % b` | Gets remainder of `a` by dividing with `b` | +| `a * b` | `a` is multiplied with `b` | +------ -```rust -fn main(){ +```rust {.wrap} +let (a, b) = (4, 5); - - let (e, f) = (1, 100); - let greater_than = f > e; - let less_than = f < e; - let greater_than_equal = f >= e; - let less_than_equal = e <= f; - let equalto = e == f; - let not_equalto = e != f; - - println!("The results of above operations are as follows: {}, {}, {}, {}", greater_than, less_than, greater_than_equal, less_than_equal); - -} +let sum: i32 = a + b; // => 9 +let subtractions: i32 = a - b; // => -1 +let multiplication: i32 = a * b; // => 20 +let division: i32 = a / b; // => 0 +let modulus: i32 = a % b; // => 4 ``` -## Bitwise Operators + + +### Bitwise Operators | Operator | Description | |----------|-------------------------| | `g & h` | Binary AND | | `g | h` | Binary OR | | `g ^ h` | Binary XOR | -| `g ~ h` | Binary One's Complement | -| `g << h` | Binary Shift Left | -| `g >> h` | Binary Shift Right | +| `g ~ h` | Binary one's complement | +| `g << h` | Binary shift left | +| `g >> h` | Binary shift right | +----- + +```rust {.wrap} +let (g, h) = (0x1, 0x2); + +let bitwise_and = g & h; // => 0 +let bitwise_or = g | h; // => 3 +let bitwise_xor = g ^ h; // => 3 +let right_shift = g >> 2; // => 0 +let left_shift = h << 4; // => 32 +``` + + + +### Logical Operators + +| Example | Meaning | +|----------------|------------------------| +| `c && d` | Both are true _(AND)_ | +| `c OR d` | Either is true _(OR)_ | +| `!c` | `c` is false _(NOT)_ | + +------ ```rust -fn main(){ +let (c, d) = (true, false); - let (g, h) = (0x1, 0x2); - let bitwise_and = g & h; - let bitwise_or = g | h; - let bitwise_xor = g ^ h; - let right_shift = g >> 2; - let left_shift = h << 4; +let and = c && d; // => false +let or = c || d; // => true +let not = !c; // => false +``` - println!("The results of the above bitwise AND is {} , bitwise Or is {}, Bitwise xor is {}, Right Shift is {}, left shift is {}", bitwise_and, bitwise_or, bitwise_xor, right_shift, left_shift); +### Compound Assignment Operator + +```rust +// To-DO +``` + + + +Misc {.cols-3} +-------------- + + +### Type Casting + +```rust +let a_int = 90; // int +// int to float +let mut type_cast = (a_int as f64); +``` +------ +```rust +let orginal: char = 'I'; +// char to int => 73 +let type_casted: i64 = orginal as i64; +``` + +To perform type-casting in Rust one must use the `as` keyword. + + + + +### Borrowing + +```rust +let mut foo = 4; +let mut borrowed_foo = &foo; +println!("{}", borrowed_foo); +``` +------ +```rust +let mut bar = 3; +let mut mutable_borrowed_bar = &mut bar; +println!("{}", mutable_borrowed_bar); +``` + +Here borrowed value borrows the value from value one using `&` operator. + + + +### De-referencing + +```rust +let mut borrow = 10; +let deref = &mut borrow; + +println!("{}", *deref); +``` + +De-referencing in rust can be done using the `*` operator + + +### Variable Scope +```rust +{ + // The scope limited to this braces + let a_number = 1; } +println!("{}", a_number); ``` - -## Type Casting - -```rust - -fn main(){ - - let original_type = 90; - let mut type_cast = (original_type as f64); // To perform type-casting in Rust one must use the 'as' keyword. - println!(" The original type of the variable is int and the value is : {}", type_cast); - type_cast = 90.009; - println!("After type casting the variable is float and the value is : {}", type_cast); - - let orginal: char = 'I'; - let type_casted: i64 = orginal as i64; - println!("The value of type casted from character to integer is : {}", type_casted); -} -``` - -## Borrowing - -```rust -fn main(){ - - let mut value_one = 4; - let mut borrowed_value = &value_one; //here borrowed value borrows the value from value one using '&' operator - println!("{}", borrowed_value); - let mut value_two = 3; - let mut mutable_borrowed_value = &mut value_two; - println!("The value of mutable borrowed value is {}", mutable_borrowed_value); - -} -``` - -## De-referencing - -```rust -fn main(){ +This will produce error as the scope of the variable `a_number` ends at the braces - let mut borrow = 10; - let deref = &mut borrow; - println!("{}", *deref); // de-referencing in rust can be done using the '*' operator -} -``` - -## Compound Assignment Operator - -```rust -//To-DO -``` +Also see +-------- +- [The Rust Document](https://doc.rust-lang.org/book/ch00-00-introduction.html) _(doc.rust-lang.org)_ +- [The Rust Reference](https://doc.rust-lang.org/reference/introduction.html) _(doc.rust-lang.org)_