1 2 3 4 | // Hello, World! fn main(){ println!("Hello, World!"); } |
1 2 3 4 5 | //this is single line comment /* This is a Multi-line comment */ |
For more information on the difference between mutable and immutable variables see my post Mutability vs Immutability
1 2 3 4 5 6 7 8 9 10 11 12 13 | // Variables // Immutable let company_string = "TutorialsPoint"; // string type let rating_float = 4.5; // float type let is_growing_boolean = true; // boolean type let icon_char = '♥'; //unicode character type // Mutable ( can be changed ) let mut company_string = "TutorialsPoint"; // string type let mut rating_float = 4.5; // float type let mut is_growing_boolean = true; // boolean type let mut icon_char = '♥'; //unicode character type |
1 2 3 4 | // Constants const USER_LIMIT:i32 = 100; // Declare a integer constant const PI:f32 = 3.14; //Declare a float constant |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | // Integer let var0 = 0; // defaults to i32 ( see below ) let var1:i8 = 0; // signed 8 bit integer let var2:u8 = 0; // unsigned 8 bit integer let var3:i16 = 0; // signed 16 bit integer let var4:u16 = 0; // unsigned 16 bit integer let var5:i32 = 0; // signed 32 bit integer let var6:u32 = 0; // unsigned 32 bit integer let var7:i64 = 0; // signed 64 bit integer let var8:u64 = 0; // unsigned 64 bit integer let var9:i128 = 0; // signed 128 bit integer let var10:u128 = 0; // unsigned 128 bit integer let var11:isize = 0; // signed arch dependent integer let var12:usize = 0; // unsigned arch dependent integer |
For more information about the difference between 32-bit and 64-bit floating point precision see my post 32 bit vs 64 bit Floating Point
1 2 3 4 5 6 7 | // Floating Points let var 0 = 0.00; // Defaults to f64 let var1:f32 = 0.00; // 32 bit floating point let var2:f64 = 0.00; // 64 git double precision floating point |
1 2 3 4 5 6 | // Characters let special_character = '@'; //default let alphabet:char = 'A'; let emoji:char = '😁'; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | // Strings // Literals let firstName:&str = "Keith"; // String literal, default static let lastName:&str = "Sterling"; // String literal, default static // or explicit definition of static let first_name:&'static str = "Keith"; let last_name:&'static str = "Sterling"; // Objects let empty_string = String::new(); let first_name = String::new("Keith"); let last_name = String::new("Sterling"); let my_name = "Keith Stering".to_string(); // Convert literal to object // String methods new() to_string() replace() as_str() push() push_str() len() trim() split_whitespace() split() chars() format!("{} {}",str1,str2); // Format a string, {} is positional println!("{} {}",str1,str2); // Print a string ( with new line), {} is positional |
1 2 3 4 5 | // Aliases type NanoSecond = u64; type Inch = u64; type U64 = u64; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | // Operators // Arithmetic Operators + (Addition) returns the sum of the operands a+b is 15 - (Subtraction) returns the difference of the values a-b is 5 * (Multiplication) returns the product of the values a*b is 50 / (Division) performs division operation and returns the quotient a / b is 2 % (Modulus) performs division operation and returns the remainder a % b is 0 // Relational Operators > Greater than (A > B) is False < Lesser than (A < B) is True >= Greater than or equal to (A >= B) is False <= Lesser than or equal to (A <= B) is True == Equality (A == B) is fals != Not equal (A != B) is True // Logical Operators && (And) The operator returns true only if all the expressions specified return true (A > 10 && B > 10) is False ||(OR) The operator returns true if at least one of the expressions specified return true (A > 10 || B >10) is True ! (NOT) The operator returns the inverse of the expression’s result. For E.g.: !(>5) returns false !(A >10 ) is True // Bitwise Operators & (Bitwise AND) It performs a Boolean AND operation on each bit of its integer arguments. (A & B) is 2 | (BitWise OR) It performs a Boolean OR operation on each bit of its integer arguments. (A | B) is 3 ^ (Bitwise XOR) It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both. (A ^ B) is 1 ! (Bitwise Not) It is a unary operator and operates by reversing all the bits in the operand. (!B) is -4 << (Left Shift) It moves all the bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by 4, and so on. (A << 1) is 4 >> (Right Shift) Binary Right Shift Operator. The left operand’s value is moved right by the number of bits specified by the right operand. (A >> 1) is 1 >>> (Right shift with Zero) This operator is just like the >> operator, except that the bits shifted to the left are always zero. (A >>> 1) is 1 |
For more information on Bitwise Operators see my post Bitwise Operators
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | // Decision Making if num > 3 { do_something (); } // If else if num > 3 { do_something (); } else { do_something_else(); } // Nested If else if num == 1 { do_something (); } else if num == 2{ do_something_else(); } else { do_the_other(); } // Match match val { 1 => do_this (); 2 => do_that (); _ => do_the_other(); } let result = match val { 1 => { // do something "this"; } 2 => { // Do something "that"; } _ => { "other"; } } |
1 2 3 4 5 6 7 8 9 10 11 | // Match Destructing Destructuring Tuples Destructuring Arrays and Slices Destructuring Enums Destructuring Pointers Destructuring Structures // Match Guards // Match Binding |
1 2 3 | // If let https://doc.rust-lang.org/rust-by-example/flow_control/if_let.html |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | // Loops // for loop for x in 1..10 {. // exclusive of 10 (1..9) println!("x is {}",x); } for y in 1..=10 { // inclusive of 10 (1..10) println!("y is {}",y); } } for x in 1..10 { if x == 5 { continue; // Skip this loop } println!("x is {}",x); } for x in 1..10 { if x == 5 { break; // Exit this loop } println!("x is {}",x); } let names = vec!["Bob", "Frank", "Ferris"]; for name in names.iter() { println!("{}", name); } // while while x < 10{ x+=1; println!("x is {}",x); } |
1 2 3 | // while let https://doc.rust-lang.org/rust-by-example/flow_control/while_let.html |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | // Enums #[derive(Debug)] // So we can atleast print it enum Colour { Red, Yellow, Green, Blue, Purple, Orange } #[derive(Debug)] struct Car { name:String, main_colour:Colour, highlight:Colour } fn main () { let first_colour = Colour::Red; let second_colour = Colour::Yellow; let my_car = Car { name:String::from("Ferrari"), main_colour:Colour::Red, highlight:Colour::Yellow }; println!("{:?}",my_car); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | // Functions fn function_name(param1,param2..paramN) { // No return value // function body } // Or fn function_name() -> return_type { // Typed return value //statements return value; } // Or fn function_name() -> return_type { value //no semicolon means this value is returned } // Parameters fn my_function(var1:i32, var2:f32) { // function body } fn my_function(mut var1:i32, mut var2:f32) { // function body } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | // Pass by Reference vs Pass by Value fn main() { let var1:i32 = 1; let var2:f32 = 1.39; println!("Before {} {}", var1, var2); my_function(var1, var2); println!("After {} {}", var1, var2); let var3:i32 = 1; let var4:f32 = 1.39; println!("Before {} {}", var3, var4); my_function2(var3, var4); println!("After {} {}", var3, var4); let mut var5:i32 = 1; let mut var6:f32 = 1.39; println!("Before {} {}", var5, var6); my_function3(&mut var5, &mut var6); println!("After {} {}", var5, var6); } fn my_function(var1:i32, var2:f32) { println!("During {} {}", var1, var2); } fn my_function2(mut var1:i32, mut var2:f32) { var1 += 1; var2 += 1.0; println!("During {} {}", var1, var2); } fn my_function3(var1: &mut i32, var2: &mut f32) { *var1 += 1; *var2 += 2.0; println!("During {} {}", var1, var2); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | // Ownership // Assignment let v = vec![1,2,3]; // vector v owns the object in heap //only a single variable owns the heap memory at any given time let v2 = v; // Borrows println!("{}", v); // Compiler error, as v no longer owns the vector // Value to function let v = vec![1,2,3]; // vector v owns the object in heap let v2 = v; // moves ownership to v2 display(v2); // v2 is moved to display and v2 is invalidated println!("In main {:?}",v2); // Compiler error // Returning from function fn main(){ let v = vec![1,2,3]; // vector v owns the object in heap let v2 = v; // moves ownership to v2 let v2_return = display(v2); println!("In main {:?}",v2_return); } fn display(v:Vec<i32>)->Vec<i32> { println!("inside display {:?}",v); return v; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | // Borrowing // Immutable references fn main() { let v = vec![10,20,30]; bottow_me(&v); // passing reference // At this point the ownership is returned back } fn bottow_me(x:&Vec<i32>){ // Accept reference to object // x is still immutable, but borrowed from main } // Mutable references fn main() { let mut v = vec![10,20,30]; bottow_me(&mut v); // passing muttable reference // At this point the ownership is returned back } fn bottow_me(x:&mut Vec<i32>){ // Accept reference to object // x is still mutable, but borrowed from main x[0] = 0; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // Tuples let my_tuple1:(i8, f32, String, bool) = (1, 10.56, "Hello".to_string(), true); println!("{:?}", my_tuple1); println!("{}", my_tuple1[0]); println!("{}", my_tuple1.0); println!("{}", my_tuple1.1); println!("{}", my_tuple1.2); println!("{}", my_tuple1.3); let my_tuple2 = (1, 10.56, "Hello", true); println!("{:?}", my_tuple2); // Destructuring let (a, b, c, d) = my_tuple1; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | // Arrays let my_array1 = [1, 2, 3]; let my_array2:[i32;4] = [1, 2, 3, 4]; let my_array3:[i32; 5] = [0; 5]; let mut my_array4 = [1, 2, 3, 5]; let N: usize = 20; let arr = [0; N]; //Error: non-constant used with constant const N: usize = 20; let arr = [0; N]; // OK println!("{:?}", my_array1); println!("{:?}", my_array2); println!("{:?}", my_array3); for index in 0..5 { println!("{}", my_array3[index]); } for val in my_array3.iter() { println!("{}", val); } my_array4[3] = 4; for val in my_array4.iter() { println!("{}", val); } // Pass by value let arr = [10,20,30] update(arr); : fn update (mut arr:[i32;3] {} // Pass by Reference let mut arr = [10,20,30]; update(&mut arr); : fn update arr:&mut [i32;3]){} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | // Slices let my_data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let my_slice = &[1..4]; println!("{}", my_slice); // Mutable Slices let mut data = [10,20,30,40,50]; use_slice(&mut data[1..4]); fn use_slice(slice:&mut [i32]) { println!("length of slice is {:?}",slice.len()); println!("{:?}",slice); slice[0] = 1010; // replaces 20 with 1010 } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | // Structures struct Employee { name:String, company:String, age:u32 } fn main() { //initialize a structure let emp1 = Employee { company:String::from("TutorialsPoint"), name:String::from("Mohtashim"), age:50 }; let emp2 = Employee{ company:String::from("TutorialsPoint"), name:String::from("Kannan"), age:32 }; let mut emp3 = Employee{ company:String::from("TutorialsPoint"), name:String::from("Kannan"), age:32 }; //pass emp1 and emp2 to display() display(emp1); display(emp2); display2(&mut emp3); println!("Name is :{} company is {} age is {}",emp3.name,emp3.company,emp3.age); } // fetch values of specific structure fields using the // operator and print it to the console fn display( emp:Employee){ println!("Name is :{} company is {} age is {}",emp.name,emp.company,emp.age); } fn display2( emp: &mut Employee){ emp.age = 55; println!("Name is :{} company is {} age is {}",emp.name,emp.company,emp.age); } // Method in a structure impl Employee { fn display_employee(&self) { println!("{} {} {}", self.name, self.company, self.age); } } fn main() { let emp = Employee{name:"Keith".to_string(), company:"Inchkeith".to_string(), age:55}; emp.display_employee(); } // Static method in a structure impl Employee { fn display() { // Static Method println!("I'm an employee"); } } fn main() { let emp = Employee{name:"Keith".to_string(), company:"Inchkeith".to_string(), age:55}; emp.display_employee(); Employee::display() } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | // Collections // Vector let mut my_vector = Vec::new(); let my_vector = vec![1, 2, 3]; new() push() remove() contains() len() // HashMap let mut my_map = HashMap::new(); insert() len() get() iter() contains_key() remove() // HashSet let mut my_set = HashSet::new(); insert() len() get() iter() contains_key() remove() // Standard Collections Sequences: Vec, VecDeque, LinkedList Maps: HashMap, BTreeMap Sets: HashSet, BTreeSet Misc: BinaryHeap |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | // Generics #[derive(Debug)] struct MyData<T> { val1: T } fn main() { let md1: MyData<i32> = MyData{val1:1}; println!("{:?}", md1); let md2: MyData<f32> = MyData{val1:1.0045}; println!("{:?}", md2); let md2: MyData<String> = MyData{val1:"Hello".to_string()}; println!("{:?}", md2); } // Multiple Types #[derive(Debug)] struct MyData<X, Y> { val1: X, val2: Y } fn main() { let md1: MyData<i32, f32> = MyData{val1:1, val2:42.0001}; println!("{:?}", md1); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | // Traits struct Employee { name: String, age: i32, company: String } trait Printable { fn employee_info(&self); } impl Printable for Employee { fn employee_info(&self) { println!("{} {} {}", self.name, self.age, self.company); } } fn main (){ let emp = Employee {name:"Keith".to_string(), age:55, company:"Inchkeith".to_string()}; emp.employee_info() } // Generic Function, implements trait Display use std::fmt::Display; fn display_type<T:Display>(t:T){ println!("{}",t); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // Iterators let a = [10,20,30]; let mut iter = a.iter(); println!("{:?}", iter.next()); // First value if first, next value or None let b = [100,200,300]; for x in b.iter(){ println!("{}",x); } let names = vec!["Kannan", "Mohtashim", "Kiran"]; for name in names.into_iter() { : } let mut names = vec!["Kannan", "Mohtashim", "Kiran"]; for name in names.iter_mut() { : } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | // Closures let closure_function = |parameter| { //logic } closure_function(parameter); fn main() { let my_closure = || { println!("In a closure"); }; my_closure() } fn main() { let add_one = |x: i32| { return x+1 }; let result = add_one(3); println!("{}", result); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | // Error Handling // UnRecoverable fn main() { panic!("Its all gone wrong!"); } // Recoverable enum Result<T,E> { OK(T), Err(E) } use std::fs::File; fn main() { let f = File::open("my_file.txt"); println!("{:?}",f); // OK(File) if the file already exists and // Err(Error) if the file is not found. } let result = do_something().unwrap(); let f = File::open("my_file.txt").expect("File not able to open"); |
1 2 3 4 5 6 7 8 9 10 11 12 13 | // I/O // Read let mut line = String::new(); println!("Enter your name :"); let b1 = std::io::stdin().read_line(&mut line).unwrap(); println!("Hello , {}", line); // Write let b1 = std::io::stdout().write("Tutorials ".as_bytes()).unwrap(); let b2 = std::io::stdout().write(String::from("Point").as_bytes()).unwrap(); std::io::stdout().write(format!("\nbytes written {}",(b1+b2)).as_bytes()).unwrap(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // File I/O use std::io::Write; fn main() { let mut file = std::fs::File::create("data.txt").expect("create failed"); file.write_all("Hello World".as_bytes()).expect("write failed"); file.write_all("\nTutorialsPoint".as_bytes()).expect("write failed"); println!("data written to file" ); } use std::io::Read; fn main(){ let mut file = std::fs::File::open("data.txt").unwrap(); let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); print!("{}", contents); } use std::fs; fn main() { fs::remove_file("data.txt").expect("could not remove file"); println!("file is removed"); } |
1 2 3 4 5 6 7 8 9 10 11 12 | // Smart Pointers // Box let b = Box::new(32); // Store on the heap, not the stack println!("{}", b); println!("{}", *b); // * deference the value let c = *b * *b; println!("{}", c); use std::ops::Deref; use std::ops::Drop; |
1 2 3 | // Meta https://doc.rust-lang.org/rust-by-example/meta.html |
1 2 3 | // Some & Simple & Option https://doc.rust-lang.org/std/option/# |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | // Macros https://doc.rust-lang.org/reference/macros-by-example.html concat_bytesExperimental Concatenates literals into a byte slice. concat_identsExperimental Concatenates identifiers into one identifier. const_format_argsExperimental Same as format_args, but can be used in some const contexts. format_args_nlExperimental Same as format_args, but adds a newline in the end. log_syntaxExperimental Prints passed tokens into the standard output. trace_macrosExperimental Enables or disables tracing functionality used for debugging other macros. assert Asserts that a boolean expression is true at runtime. assert_eq Asserts that two expressions are equal to each other (using PartialEq). assert_ne Asserts that two expressions are not equal to each other (using PartialEq). cfg Evaluates boolean combinations of configuration flags at compile-time. column Expands to the column number at which it was invoked. compile_error Causes compilation to fail with the given error message when encountered. concat Concatenates literals into a static string slice. dbg Prints and returns the value of a given expression for quick and dirty debugging. debug_assert Asserts that a boolean expression is true at runtime. debug_assert_eq Asserts that two expressions are equal to each other. debug_assert_ne Asserts that two expressions are not equal to each other. env Inspects an environment variable at compile time. eprint Prints to the standard error. eprintln Prints to the standard error, with a newline. file Expands to the file name in which it was invoked. format Creates a String using interpolation of runtime expressions. format_args Constructs parameters for the other string-formatting macros. include Parses a file as an expression or an item according to the context. include_bytes Includes a file as a reference to a byte array. include_str Includes a UTF-8 encoded file as a string. line Expands to the line number on which it was invoked. matches Returns whether the given expression matches any of the given patterns. module_path Expands to a string that represents the current module path. option_env Optionally inspects an environment variable at compile time. panic Panics the current thread. print Prints to the standard output. println Prints to the standard output, with a newline. stringify Stringifies its arguments. thread_local Declare a new thread local storage key of type std::thread::LocalKey. todo Indicates unfinished code. tryDeprecated Unwraps a result or propagates its error. unimplemented Indicates unimplemented code by panicking with a message of “not implemented”. unreachable Indicates unreachable code. vec Creates a Vec containing the arguments. write Writes formatted data into a buffer. writeln Write formatted data into a buffer, with a newline appended. |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | // Modules pub mod my_utilities { pub fn do_something() { // do something } } fn main () { my_utilities::do_something(); } // Alternative use my_utilities::do_something(); fn main () { do_something(); } // Nested Modules pub mod my_utilities { pub mod my_file_utilities { pub fn do_something() { // do something } } pub mod my_disk_utilities { pub fn do_something() { // do something } } } fn main () { my_utilities::my_file_utilities::do_something(); my_utilities::my_disk_utilities::do_something(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | // Standard Library assert_matchesExperimental Unstable module containing the unstable assert_matches macro. async_iterExperimental Composable asynchronous iteration. intrinsicsExperimental Compiler intrinsics. simdExperimental Portable SIMD module. alloc Memory allocation APIs. any Utilities for dynamic typing or type reflection. arch SIMD and vendor intrinsics module. array Utilities for the array primitive type. ascii Operations on ASCII strings and characters. backtrace Support for capturing a stack backtrace of an OS thread borrow A module for working with borrowed data. boxed The Box<T> type for heap allocation. cell Shareable mutable containers. char Utilities for the char primitive type. clone The Clone trait for types that cannot be ‘implicitly copied’. cmp Utilities for comparing and ordering values. collections Collection types. convert Traits for conversions between types. default The Default trait for types with a default value. env Inspection and manipulation of the process’s environment. error Interfaces for working with Errors. f32 Constants for the f32 single-precision floating point type. f64 Constants for the f64 double-precision floating point type. ffi Utilities related to FFI bindings. fmt Utilities for formatting and printing Strings. fs Filesystem manipulation operations. future Asynchronous basic functionality. hash Generic hashing support. hint Hints to compiler that affects how code should be emitted or optimized. Hints may be compile time or runtime. i8Deprecation planned Constants for the 8-bit signed integer type. i16Deprecation planned Constants for the 16-bit signed integer type. i32Deprecation planned Constants for the 32-bit signed integer type. i64Deprecation planned Constants for the 64-bit signed integer type. i128Deprecation planned Constants for the 128-bit signed integer type. io Traits, helpers, and type definitions for core I/O functionality. isizeDeprecation planned Constants for the pointer-sized signed integer type. iter Composable external iteration. marker Primitive traits and types representing basic properties of types. mem Basic functions for dealing with memory. net Networking primitives for TCP/UDP communication. num Additional functionality for numerics. ops Overloadable operators. option Optional values. os OS-specific functionality. panic Panic support in the standard library. path Cross-platform path manipulation. pin Types that pin data to its location in memory. prelude The Rust Prelude primitive This module reexports the primitive types to allow usage that is not possibly shadowed by other declared types. process A module for working with processes. ptr Manually manage memory through raw pointers. rc Single-threaded reference-counting pointers. ‘Rc’ stands for ‘Reference Counted’. result Error handling with the Result type. slice Utilities for the slice primitive type. str Utilities for the str primitive type. string A UTF-8–encoded, growable string. sync Useful synchronization primitives. task Types and Traits for working with asynchronous tasks. thread Native threads. time Temporal quantification. u8Deprecation planned Constants for the 8-bit unsigned integer type. u16Deprecation planned Constants for the 16-bit unsigned integer type. u32Deprecation planned Constants for the 32-bit unsigned integer type. u64Deprecation planned Constants for the 64-bit unsigned integer type. u128Deprecation planned Constants for the 128-bit unsigned integer type. usizeDeprecation planned Constants for the pointer-sized unsigned integer type. vec A contiguous growable array type with heap-allocated contents, written Vec<T>. |
1 2 3 4 5 6 7 8 | // Package Manager cargo new <name> # <name> becomes the root name of the directory cargo build cargo check cargo run // Create a crate |
1 2 3 4 5 6 7 8 9 10 11 12 13 | // Dependencies // We list dependencies in the Cargo toml file as follows [package] name = "testapp" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] itoa = "1.0" # Using the integer to string crate |
1 2 3 4 5 6 7 8 | // Using a crate fn main() { let mut buffer = itoa::Buffer::new(); # Using the itoa crate let printed = buffer.format(128u64); assert_eq!(printed, "128"); println!("{}", printed); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | // Creating a create // Directory Structure my-app my-lib/ -->Cargo.toml -->src/ lib.rs myutils.rs // Cargo.toml [package] name = "my_lib" version = "0.1.0" authors = ["Keith"] // In lib.rs pub mod myutils; // In myutils.rs pub fun do_something () { // Do something here } // Build the library create $ cargo build |
1 2 3 4 | // VSCode Integration rust-analyxer rust and friends |