├── Examples ├── Enum │ ├── CLike Enums.rs │ ├── Enum with Values.rs │ ├── Http Status.rs │ ├── README.md │ ├── Struct Variants.rs │ └── Using Enums in Structs.rs ├── ErrorHandling │ ├── CustomError.rs │ ├── ExpectExample.rs │ ├── FileReadWithSimpleErrorHandling.rs │ ├── GettingInputFromUser.rs │ ├── ReadUserFileProgram │ ├── ReadUserFileProgram.rs │ ├── ReadUserFileProgramQuestionMark.rs │ └── UnwrapExample.rs ├── Generics │ ├── ComparisonOperatorOverloading.rs │ ├── GenericEnumExample.rs │ ├── GenericStructExample.rs │ └── MathmaticalOperatorOverloading.rs ├── Pattern │ ├── EnumMatching.rs │ ├── LiteralMatching.rs │ ├── MatchingEnumValues.rs │ ├── README.md │ ├── atPattern.rs │ ├── dereferencingInPatterns.rs │ ├── extractingValuesFromNestedStructsAndEnums.rs │ ├── extractingValuesFromStructs.rs │ ├── extractingValuesFromTuples.rs │ ├── ignoringValuesInPatterns.rs │ ├── ignoringValuesInStructs.rs │ ├── patternGuards.rs │ ├── rangePatterns.rs │ ├── simpleProgramBySwitch.c │ └── usingMultiplePatterns.rs ├── Struct │ ├── C Analogy of method.c │ ├── DifferentTypeRepresentations.rs │ ├── Method and associated function.rs │ ├── README.md │ ├── RecursiveTypeInfiniteSize.rs │ ├── TupleLikeStruct.rs │ ├── UnitLikeStruct.rs │ ├── ValueInheritance.rs │ └── ValueInheritanceWithClone.rs ├── Trait │ ├── associatedFunctionInTrait.rs │ ├── c++InterfaceExample.cpp │ ├── callMethodsWithSameName.rs │ ├── callingMethodsLikeAssociatedFunction.rs │ ├── callingMethodsLikeAssociatedFunctionOnTraits.rs │ ├── flyingString.rs │ ├── implementingOthersTraits.rs │ ├── polymorphicFunctionUsingTraitExample.rs │ ├── subtraitsExample.rs │ ├── traitImplementationExample.rs │ └── traitMethodDefaultImplementation.rs └── lifetime │ ├── enum_lifetime.rs │ ├── function_with_lifetime.rs │ ├── mutable_static_value.rs │ └── struct_method_lifetime.rs ├── Exercises ├── part 5 │ ├── ex1.rs │ └── ex2.rs └── part 6 │ └── factorial.rs ├── README.md └── rust_tutorial ├── Cargo.lock ├── Cargo.toml ├── CompileFailTest ├── 1.rs ├── 10.rs ├── 11.rs ├── 12.rs ├── 14.rs ├── 16.rs ├── 17.rs ├── 2.rs ├── 20.rs ├── 3.rs ├── 4.rs ├── 6.rs ├── 7.rs ├── 8.rs ├── 9.rs └── Makefile ├── ReadMe.md ├── src └── main.rs └── tests ├── 1.rs ├── 10.rs ├── 11.rs ├── 12.rs ├── 13.rs ├── 14.rs ├── 15.rs ├── 16.rs ├── 17.rs ├── 18.rs ├── 2.rs ├── 20.rs ├── 21.rs ├── 3.rs ├── 4.rs ├── 5.rs ├── 6.rs ├── 7.rs ├── 8.rs └── 9.rs /Examples/Enum/CLike Enums.rs: -------------------------------------------------------------------------------- 1 | enum Colour { 2 | RGB, 3 | Hex 4 | } 5 | 6 | fn main() { 7 | let a = Colour::RGB; 8 | let b = Colour::Hex; 9 | println!("RGB value in memory: {}", a as u8); 10 | println!("Hex value in memory: {}", b as u8); 11 | } 12 | -------------------------------------------------------------------------------- /Examples/Enum/Enum with Values.rs: -------------------------------------------------------------------------------- 1 | enum Colour { 2 | RGB(u16, u16, u16), 3 | Hex(String) 4 | } 5 | 6 | fn main() { 7 | let rgb_colour = Colour::RGB(255, 0, 0); 8 | let hex_colour = Colour::Hex(String::from("ff0000")); 9 | } 10 | -------------------------------------------------------------------------------- /Examples/Enum/Http Status.rs: -------------------------------------------------------------------------------- 1 | enum HttpStatus { 2 | Ok = 200, 3 | NotFound = 404, 4 | InternalServerError = 500 5 | } 6 | 7 | fn main() { 8 | let a = HttoStatus::Ok; 9 | let b = HttoStatus::NotFound; 10 | let c = HttoStatus::InternalServerError; 11 | println!("Ok value in the memory: {}", a as u8); 12 | println!("NotFound value in the memory: {}", b as u16); 13 | println!("InternalServerError value in the memory: {}", c as u16); 14 | } 15 | -------------------------------------------------------------------------------- /Examples/Enum/README.md: -------------------------------------------------------------------------------- 1 | # Examples of Enum in Rust 2 | There are different examples of enum decleration and usage in Rust programming language. 3 | 4 | Below files are associated with [Rust turorial episode No 13 in Persian](https://blog.alihoseiny.ir/%d8%a2%d9%85%d9%88%d8%b2%d8%b4-%d8%b2%d8%a8%d8%a7%d9%86-%d8%a8%d8%b1%d9%86%d8%a7%d9%85%d9%87%e2%80%8c%d9%86%d9%88%db%8c%d8%b3%db%8c-rust-%d9%82%d8%b3%d9%85%d8%aa%db%b1%db%b3-%d8%b4%d8%b1%d9%88%d8%b9-%da%a9%d8%a7%d8%b1-%d8%a8%d8%a7-enumeration-%d9%87%d8%a7/?utm_source=Github&utm_medium=Readme&utm_campaign=RustTutorial): 5 | 6 | ## C Like enums 7 | Example of C like enums and getting associated number to each variant by compiler are in the `CLike Enums.rs` file. 8 | 9 | ## C Like enums with custom values 10 | Example of how we can change stored value of enum varients in the memory is in the `Http Status.rs` file. Explained by a simple enum representing brief version of http statuts. 11 | 12 | ## Enum with Values 13 | Example of how storing values in the enums is in the `Enum with Values.rs` file. 14 | 15 | ## Enum with struct-like variants 16 | The example of how we could declare enum varients like structs is in the `Struct Variants.rs` file. 17 | 18 | ## Using enums in the structs 19 | We can use enums like fields of a struct. The example of this usage is in the `Using Enums in Structs.rs` file. 20 | -------------------------------------------------------------------------------- /Examples/Enum/Struct Variants.rs: -------------------------------------------------------------------------------- 1 | enum Colour { 2 | RGB {red: u16, green: u16, blue: u16}, 3 | Hex(String) 4 | } 5 | 6 | fn main() { 7 | let rgb_colour = Colour::RGB { 8 | blue: 0, 9 | red: 255, 10 | green: 0 11 | }; 12 | 13 | let hex_colour = Colour::Hex(String::from("ff0000")); 14 | } 15 | 16 | -------------------------------------------------------------------------------- /Examples/Enum/Using Enums in Structs.rs: -------------------------------------------------------------------------------- 1 | enum Colour { 2 | RGB, 3 | Hex 4 | } 5 | 6 | struct ColourStruct { 7 | colour_type: Colour, 8 | value: String 9 | } 10 | 11 | fn main() { 12 | let rgb_colour = ColourStruct { 13 | colour_type: Colour::RGB, 14 | value: String::from("(255, 0, 0)") 15 | }; 16 | 17 | let hex_colour = ColourStruct { 18 | colour_type: Colour::Hex, 19 | value: String::from("ff0000") 20 | }; 21 | } 22 | -------------------------------------------------------------------------------- /Examples/ErrorHandling/CustomError.rs: -------------------------------------------------------------------------------- 1 | use std::error; 2 | use std::fmt; 3 | 4 | #[derive(Debug, Clone)] 5 | struct MyError; 6 | 7 | impl error::Error for MyError {} 8 | 9 | impl fmt::Display for MyError { 10 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 11 | write!(f, "Oooops.") 12 | } 13 | } 14 | 15 | 16 | fn main() { 17 | let func_result = get_always_error(); 18 | match func_result { 19 | Err(error) => println!("Error message: {}", error), 20 | _ => {} 21 | } 22 | } 23 | 24 | fn get_always_error() -> Result { 25 | let my_error: MyError = MyError{}; 26 | return Err(my_error); 27 | } 28 | -------------------------------------------------------------------------------- /Examples/ErrorHandling/ExpectExample.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | fn get_file_path(user_input: &mut String) { 4 | println!("Input file path:"); 5 | io::stdin().read_line(user_input).expect("We are unable to get input from the standard input."); 6 | } 7 | -------------------------------------------------------------------------------- /Examples/ErrorHandling/FileReadWithSimpleErrorHandling.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | use std::fs; 3 | use std::process::exit; 4 | 5 | fn main() { 6 | let mut path = String::new(); 7 | get_file_path(&mut path); 8 | let trimmed_path = path.trim(); 9 | let file_content = read_file(trimmed_path); 10 | println!("file content:\n {}", file_content); 11 | } 12 | 13 | fn get_file_path(user_input: &mut String) { 14 | println!("Input file path:"); 15 | match io::stdin().read_line(user_input) { 16 | Err(_) => println!("Error happened in getting input from user"), 17 | _ => {} 18 | } 19 | } 20 | 21 | fn read_file(file_name: &str) -> String { 22 | let read_result = fs::read_to_string(file_name); 23 | match read_result { 24 | Ok(content) => content, 25 | Err(error) => { 26 | match error.kind() { 27 | io::ErrorKind::NotFound => { 28 | println!("The {} file not found. Please re-run the program and try another file.", file_name); 29 | exit(0); 30 | } 31 | _ => panic!("Something bad happened. :(") 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Examples/ErrorHandling/GettingInputFromUser.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | fn main() { 4 | let mut user_input = String::new(); 5 | let read_result = io::stdin().read_line(&mut user_input); 6 | match read_result { 7 | Ok(num_of_characters) => { 8 | println!("user input is: {}", user_input); 9 | println!("user input read result: {:?}", read_result); 10 | }, 11 | Err(error) => println!("Error happened!") 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Examples/ErrorHandling/ReadUserFileProgram: -------------------------------------------------------------------------------- 1 | This files are all related to the Rust tutorial episode 21. 2 | -------------------------------------------------------------------------------- /Examples/ErrorHandling/ReadUserFileProgram.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | use std::fs; 3 | 4 | fn main() { 5 | let mut path= String::new(); 6 | loop { 7 | path.clear(); 8 | get_file_path(&mut path); 9 | 10 | let trimmed_path = path.trim(); 11 | let file_reading_result = read_file(trimmed_path); 12 | 13 | match file_reading_result { 14 | Ok(file_content) => { 15 | println!("file content:\n {}", file_content); 16 | return; 17 | } 18 | Err(error) => { 19 | println!("{}", error); 20 | println!("Please try again."); 21 | } 22 | } 23 | 24 | } 25 | } 26 | 27 | fn get_file_path(user_input: &mut String) { 28 | println!("Input file path:"); 29 | match io::stdin().read_line(user_input) { 30 | Err(_) => println!("Error happened in getting input from user"), 31 | _ => {} 32 | } 33 | } 34 | 35 | fn read_file(file_name: &str) -> Result { 36 | let read_result = fs::read_to_string(file_name); 37 | match read_result { 38 | Ok(content) => Ok(content), 39 | Err(error) => { 40 | match error.kind() { 41 | io::ErrorKind::NotFound => Err(error), 42 | _ => panic!("Something bad happened. :(") 43 | } 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Examples/ErrorHandling/ReadUserFileProgramQuestionMark.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | use std::fs; 3 | 4 | fn main() { 5 | let mut path= String::new(); 6 | loop { 7 | path.clear(); 8 | get_file_path(&mut path); 9 | 10 | let trimmed_path = path.trim(); 11 | let file_reading_result = read_file(trimmed_path); 12 | 13 | match file_reading_result { 14 | Ok(file_content) => { 15 | println!("file content:\n {}", file_content); 16 | return; 17 | } 18 | Err(error) => { 19 | println!("{}", error); 20 | println!("Please try again."); 21 | } 22 | } 23 | 24 | } 25 | } 26 | 27 | fn get_file_path(user_input: &mut String) { 28 | println!("Input file path:"); 29 | match io::stdin().read_line(user_input) { 30 | Err(_) => println!("Error happened in getting input from user"), 31 | _ => {} 32 | } 33 | } 34 | 35 | d_file(file_name: &str) -> Result { 36 | let file_content: String = fs::read_to_string(file_name)?; 37 | return Ok(file_content); 38 | } 39 | -------------------------------------------------------------------------------- /Examples/ErrorHandling/UnwrapExample.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | fn get_file_path(user_input: &mut String) { 4 | println!("Input file path:"); 5 | io::stdin().read_line(user_input).unwrap(); 6 | } 7 | -------------------------------------------------------------------------------- /Examples/Generics/ComparisonOperatorOverloading.rs: -------------------------------------------------------------------------------- 1 | use std::cmp::Ordering; 2 | 3 | struct Point { 4 | x: u8, 5 | y: u8 6 | } 7 | 8 | 9 | impl PartialEq for Point { 10 | fn eq(&self, other: &Point) -> bool { 11 | self.x == other.x && self.y == other.y 12 | } 13 | } 14 | 15 | 16 | impl PartialOrd for Point { 17 | fn partial_cmp(&self, other: &Self) -> Option { 18 | if self.x + self.y > other.x + other.y { 19 | return Some(Ordering::Greater); 20 | } else if self.x + self.y == other.x + other.y { 21 | return Some(Ordering::Equal); 22 | } else { 23 | return Some(Ordering::Less); 24 | } 25 | } 26 | } 27 | 28 | fn main() { 29 | let my_point = Point{ 30 | x: 14, 31 | y: 11 32 | }; 33 | let other_point = Point { 34 | x: 1, 35 | y: 13 36 | }; 37 | println!("my_point == other_point is: {}", my_point > other_point); 38 | } 39 | 40 | 41 | -------------------------------------------------------------------------------- /Examples/Generics/GenericEnumExample.rs: -------------------------------------------------------------------------------- 1 | enum Result { 2 | OK(T), 3 | Err(()) 4 | } 5 | 6 | fn main() { 7 | let mut my_point = Point:: { 8 | x: 10, 9 | y: 12 10 | }; 11 | 12 | let that_is_ok = Result::OK::>(my_point); 13 | 14 | match that_is_ok { 15 | Result::OK(Point {x, y}) => println!("x: {}, y: {}", x, y), 16 | Result::Err(_) => println!("An Error happened"), 17 | _ => {} 18 | }; 19 | } 20 | -------------------------------------------------------------------------------- /Examples/Generics/GenericStructExample.rs: -------------------------------------------------------------------------------- 1 | use std::mem; 2 | 3 | struct Point { 4 | x: T, 5 | y: T 6 | } 7 | 8 | impl Point { 9 | fn swap_coordinates(&mut self) { 10 | mem::swap(&mut self.x, &mut self.y); 11 | } 12 | } 13 | 14 | fn main() { 15 | let pointer_u8 = Point:: { 16 | x: 10, 17 | y: 12 18 | }; 19 | 20 | let float_pointer = Point:: { 21 | x: 0.0, 22 | y: 666.32 23 | }; 24 | 25 | let detect_my_type = Point { 26 | x: 10, 27 | y: 11 28 | }; 29 | 30 | let mut point_integer = Point { 31 | x: 10, 32 | y: 11 33 | }; 34 | 35 | println!("Before swapping x: {} y: {}", point_integer.x, point_integer.y); 36 | 37 | point_integer.swap_coordinates(); 38 | 39 | println!("After swapping x: {} y: {}", point_integer.x, point_integer.y); 40 | 41 | let my_point2 = Point:: { 42 | x: 10, 43 | y: 12 44 | }; 45 | 46 | let swapped_point = swap_point::(my_point2); 47 | println!("swapped point x: {}, y: {}", swapped_point.x, swapped_point.y); 48 | } 49 | -------------------------------------------------------------------------------- /Examples/Generics/MathmaticalOperatorOverloading.rs: -------------------------------------------------------------------------------- 1 | use std::ops::Mul; 2 | 3 | struct Point { 4 | x: u8, 5 | y: u8 6 | } 7 | 8 | 9 | impl Mul for Point { 10 | type Output = Point; 11 | 12 | fn mul(self, rhs: u8) -> Self::Output { 13 | Point { 14 | x: self.x * rhs, 15 | y: self.y * rhs 16 | } 17 | } 18 | } 19 | 20 | fn main() { 21 | let my_point = Point{ 22 | x: 10, 23 | y: 11 24 | }; 25 | let new_point = my_point * 10; 26 | println!("new point. x: {}, y: {}", new_point.x, new_point.y); 27 | } 28 | 29 | 30 | -------------------------------------------------------------------------------- /Examples/Pattern/EnumMatching.rs: -------------------------------------------------------------------------------- 1 | enum HttpStatus { 2 | Ok = 200, 3 | NotFound = 404, 4 | InternalServerError = 500 5 | } 6 | 7 | fn print_status(http_status: HttpStatus) { 8 | match http_status { 9 | HttpStatus::Ok => println!("status: 200 Ok"), 10 | HttpStatus::NotFound => println!("status: 404 Not Found"), 11 | HttpStatus::InternalServerError => println!("status: 500 Internal Server Error") 12 | } 13 | } 14 | 15 | fn main() { 16 | let a = HttpStatus::Ok; 17 | let b = HttpStatus::NotFound; 18 | let c = HttpStatus::InternalServerError; 19 | print_status(a); 20 | print_status(b); 21 | print_status(c); 22 | } 23 | -------------------------------------------------------------------------------- /Examples/Pattern/LiteralMatching.rs: -------------------------------------------------------------------------------- 1 | fn print_message(user_level: u8) { 2 | match user_level { 3 | 0 => println!("Welcome dear admin."), 4 | 1 => println!("Welcome back our best member."), 5 | 2 => println!("Hello. Please register first."), 6 | _ => println!("Bad Input") 7 | } 8 | } 9 | 10 | fn main() { 11 | let user_inputs: [u8;5] = [0, 1, 2, 3, 4]; 12 | for value in user_inputs.iter() { 13 | print_message(*value); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Examples/Pattern/MatchingEnumValues.rs: -------------------------------------------------------------------------------- 1 | enum Colour { 2 | RGB(u16, u16, u16), 3 | Hex(String) 4 | } 5 | 6 | fn print_colour(colour_value: Colour) { 7 | match colour_value { 8 | Colour::RGB(255, 0, 0) => println!("RED Colour. Here is a completely different code."), 9 | Colour::RGB(red, green, blue) => { 10 | println!("The colour is in rgb format. red value: {}, green value: {}, blue value: {}", red, green, blue); 11 | }, 12 | Colour::Hex(hex) => println!("The colour is in hex format: #{}", hex) 13 | } 14 | } 15 | 16 | fn main() { 17 | let a = Colour::RGB(255, 123, 30); 18 | let b = Colour::Hex(String::from("ff7b1e")); 19 | let red = Colour::RGB(255, 0, 0); 20 | print_colour(a); 21 | print_colour(b); 22 | print_colour(red); 23 | } 24 | -------------------------------------------------------------------------------- /Examples/Pattern/README.md: -------------------------------------------------------------------------------- 1 | # Examples of Patterns in Rust 2 | There are different examples of patterns in Rust programming language. 3 | 4 | Below files are associated with [Rust turorial episode No 14 in Persian](https://blog.alihoseiny.ir/%d8%a2%d9%85%d9%88%d8%b2%d8%b4-%d8%b2%d8%a8%d8%a7%d9%86-%d8%a8%d8%b1%d9%86%d8%a7%d9%85%d9%87%e2%80%8c%d9%86%d9%88%db%8c%d8%b3%db%8c-rust-%d9%82%d8%b3%d9%85%d8%aa%db%b1%db%b4-%d9%be%d8%aa%d8%b1%d9%86%e2%80%8c%d9%87%d8%a7/?utm_source=Github&utm_medium=Readme&utm_campaign=RustTutorial): 5 | 6 | ## switch case 7 | Example of C switch case is in the `simpleProgramBySwitch.c` file and corresponding example of this program in Rust is in the `LiteralMatching.rs` file. 8 | 9 | ## Matching Simple Enums 10 | Example of matching simple enum values is in the `EnumMatching.rs` file 11 | 12 | ## Matching Values of Enums 13 | Example of matching values of enums is in the `MatchingEnumValues.rs` file. 14 | 15 | ## Using Ranges as Patterns 16 | Example of using ranges in patterns is in teh ` rangePatterns.rs ` file. 17 | 18 | ## Using Multiple Patterns 19 | Example of using multiple patterns in a single match arm is in the `usingMultiplePatterns.rs` file. 20 | 21 | ## Extracting Values of Tuples 22 | Example of extracting values from tuples with patterns is in the `extractingValuesFromTuples.rs` file. 23 | 24 | ## Extracting Values of Struct 25 | Example of extracting values from structs with patterns is in the `extractingValuesFromStructs.rs `. 26 | 27 | ## Extracting Values from Nested Structs and Enums 28 | Example of extracting values of nested structs and enums is in the `extractingValuesFromNestedStructsAndEnums.rs ` file. 29 | 30 | ## Dereferencing in Patterns 31 | Example of dereferencing in patterns is in the `dereferencingInPatterns.rs` file. 32 | 33 | ## Ignoring Values 34 | Example of ignoring values in the input tuple is in the `ignoringValuesInPatterns.rs ` file. 35 | 36 | ## Ignoring Values of Structs 37 | Example of ignoring values of structs in the patterns is in the ` ignoringValuesInStructs.rs` file. 38 | 39 | ## Guards 40 | Example of pattern guards is in the ` patternGuards.rs ` file. 41 | 42 | ## @ Pattern 43 | Example of @ operator in patterns is in the ` atPattern.rs` file. 44 | 45 | 46 | -------------------------------------------------------------------------------- /Examples/Pattern/atPattern.rs: -------------------------------------------------------------------------------- 1 | struct RgbStruct { 2 | red: u16, 3 | green: u16, 4 | blue: u16 5 | } 6 | 7 | fn extract_and_match(colour: RgbStruct) { 8 | match colour { 9 | RgbStruct {red: r @ 0...100, green: 0, blue} => println!("This is my colour: rgb({}, 0, {})", r, blue), 10 | _ => println!("Not desired colour.") 11 | } 12 | } 13 | 14 | fn main() { 15 | let colour1 = RgbStruct { 16 | red: 120, 17 | green: 0, 18 | blue: 255 19 | }; 20 | 21 | let colour2 = RgbStruct { 22 | red: 50, 23 | blue: 20, 24 | green: 0 25 | }; 26 | 27 | extract_and_match(colour1); 28 | extract_and_match(colour2); 29 | } 30 | -------------------------------------------------------------------------------- /Examples/Pattern/dereferencingInPatterns.rs: -------------------------------------------------------------------------------- 1 | struct RgbStruct { 2 | red: u16, 3 | green: u16, 4 | blue: u16 5 | } 6 | 7 | 8 | fn print_number(n: u16) { 9 | println!("number is: {}", n); 10 | } 11 | 12 | 13 | fn main() { 14 | let colours = [ 15 | RgbStruct { 16 | red: 112, 17 | green: 0, 18 | blue: 0 19 | }, 20 | RgbStruct { 21 | red: 123, 22 | green: 124, 23 | blue: 8 24 | }, 25 | RgbStruct { 26 | red: 0, 27 | green: 41, 28 | blue: 223 29 | } 30 | ]; 31 | 32 | for rgb_reference in colours.iter() { 33 | match rgb_reference { 34 | &RgbStruct {red, blue: 0, green: 0} => { 35 | println!("This is a kind of red colour."); 36 | print_number(red); 37 | }, 38 | RgbStruct {red, green, blue} => println!("rgb({}, {}, {})", red, green, blue) 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Examples/Pattern/extractingValuesFromNestedStructsAndEnums.rs: -------------------------------------------------------------------------------- 1 | struct RgbStruct { 2 | red: u16, 3 | green: u16, 4 | blue: u16 5 | } 6 | 7 | enum Colour { 8 | Transparent, 9 | RGB(RgbStruct), 10 | Hex(String), 11 | CMYK {cyan: f32, magenta: f32, yellow: f32, black: f32} 12 | } 13 | 14 | fn print_nested_structures(colour: Colour) { 15 | match colour { 16 | Colour::Transparent => println!("This is Transparent! You can not see anything"), 17 | Colour::RGB(RgbStruct{red, green, blue}) => { 18 | println!("Colour is in rgb format: ({}, {}, {})", red, green, blue) 19 | }, 20 | Colour::Hex(hex_value) => println!("The colour in the hex format: #{}", hex_value), 21 | Colour::CMYK {cyan: c, magenta: m, yellow: y, black: k} => { 22 | println!("Colour is in cmyk format: ({}, {}, {}, {})", c, m, y, k) 23 | } 24 | } 25 | } 26 | 27 | fn main() { 28 | let t = Colour::Transparent; 29 | let rgb = Colour::RGB(RgbStruct{ 30 | red: 255, 31 | green: 255, 32 | blue: 255 33 | }); 34 | 35 | let hex = Colour::Hex(String::from("ffffff")); 36 | 37 | let cmyk = Colour::CMYK { 38 | cyan: 0.0, 39 | magenta: 0.0, 40 | yellow: 0.0, 41 | black: 0.0 42 | }; 43 | 44 | print_nested_structures(t); 45 | print_nested_structures(rgb); 46 | print_nested_structures(hex); 47 | print_nested_structures(cmyk); 48 | } 49 | -------------------------------------------------------------------------------- /Examples/Pattern/extractingValuesFromStructs.rs: -------------------------------------------------------------------------------- 1 | struct RGB { 2 | red: u16, 3 | green: u16, 4 | blue: u16 5 | } 6 | 7 | fn print_rgb_struct(rgb: RGB) { 8 | match rgb { 9 | RGB {red: r, green: 0, blue: 0} => println!("This colour is a gradient of red. red value: {}", r), 10 | RGB {red, blue, green} => println!("rgb({}, {}, {})", red, green, blue) 11 | } 12 | } 13 | 14 | fn main() { 15 | let r1 = RGB { 16 | red: 113, 17 | green: 0, 18 | blue: 0 19 | }; 20 | 21 | let r2 = RGB { 22 | red: 123, 23 | green: 221, 24 | blue: 0 25 | }; 26 | 27 | print_rgb_struct(r1); 28 | print_rgb_struct(r2); 29 | } 30 | -------------------------------------------------------------------------------- /Examples/Pattern/extractingValuesFromTuples.rs: -------------------------------------------------------------------------------- 1 | fn print_rgb_tuple(rgb: (u16, u16, u16)) { 2 | match rgb { 3 | (red, 0, 0) => println!("This colour is a gradient of red. red value: {}", red), 4 | (red, green, blue) => println!("rgb({}, {}, {})", red, green, blue) 5 | } 6 | } 7 | 8 | fn main() { 9 | let r1 = (113, 0, 0); 10 | let r2 = (123, 221, 0); 11 | print_rgb_tuple(r1); 12 | print_rgb_tuple(r2); 13 | } 14 | -------------------------------------------------------------------------------- /Examples/Pattern/ignoringValuesInPatterns.rs: -------------------------------------------------------------------------------- 1 | fn ignore_tuple(input_tuple: (u8, u8, u8, u8)) { 2 | match input_tuple { 3 | (0, _, _, val4) => println!("4th value: {}", val4), 4 | (_, val2, val3, _) => println!("second and third values are: {} and {}", val2, val3) 5 | } 6 | } 7 | 8 | fn main() { 9 | ignore_tuple((10, 12, 13, 14)); 10 | ignore_tuple((0, 1, 2, 3)); 11 | } 12 | -------------------------------------------------------------------------------- /Examples/Pattern/ignoringValuesInStructs.rs: -------------------------------------------------------------------------------- 1 | struct BigStruct { 2 | key1: u16, 3 | key2: u16, 4 | key3: u16, 5 | key4: u16, 6 | key5: u16, 7 | key6: u16, 8 | key7: u16, 9 | } 10 | 11 | fn main() { 12 | let a = BigStruct { 13 | key1: 0, 14 | key2: 1, 15 | key3: 2, 16 | key4: 3, 17 | key5: 4, 18 | key6: 5, 19 | key7: 6 20 | }; 21 | 22 | match a { 23 | BigStruct {key1: 0, key7: x, ..} => println!(" x = {}", x), 24 | BigStruct {key6: y, ..} => println!(" y = {}", y) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Examples/Pattern/patternGuards.rs: -------------------------------------------------------------------------------- 1 | struct Foo(u8, u8); 2 | 3 | fn print_guarded_pattern(input: Foo) { 4 | match input { 5 | Foo(x, _) if x % 2 == 0 => println!("{} is an even number", x), 6 | Foo(x, y) => println!("first value is not even. pair is: ({}, {})", x, y) 7 | } 8 | } 9 | 10 | fn main() { 11 | print_guarded_pattern(Foo(2, 10)); 12 | print_guarded_pattern(Foo(7, 8)); 13 | } 14 | -------------------------------------------------------------------------------- /Examples/Pattern/rangePatterns.rs: -------------------------------------------------------------------------------- 1 | fn print_character_type(character: char) { 2 | match character { 3 | 'a'...'z' => println!("{} is a lowercase english character.", character), 4 | 'A'...'Z' => println!("{} is a uppercase english character.", character), 5 | '0'...'9' => println!("{} is an english digit.", character), 6 | _ => println!("This character is not an english character.") 7 | } 8 | } 9 | 10 | fn main() { 11 | let characters = ['X', 'y', '4', 'س']; 12 | for ch in characters.iter() { 13 | print_character_type(*ch); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Examples/Pattern/simpleProgramBySwitch.c: -------------------------------------------------------------------------------- 1 | #include "stdio.h" 2 | 3 | /* 4 | * This function gets userLevel integer and prints proper message according to the input value. 5 | */ 6 | void printMessage(int userLevel) { 7 | // Checking userLevel parameter for different probabilities 8 | switch (userLevel) { 9 | case 0: // Is userLevel value equals to 0? 10 | printf("Welcome dear admin.\n"); // userLevel is zero, so user is an admin. 11 | break; // We found what we wanted, so we breaking decision structure. 12 | case 1: // Is userLevel value equals to 1? 13 | printf("Welcome back our best member.\n"); // userLevel is one, so user is a member. 14 | break; // We found what we wanted, so we breaking decision structure. 15 | case 2: // Is userLevel value equals to 2? 16 | printf("Hello. Please register first.\n"); // userLevel is two, so user is a guest. 17 | break; // We found what we wanted, so we breaking decision structure. 18 | } 19 | } 20 | 21 | /* 22 | * This function gets an integer from user and returns it. 23 | */ 24 | int getUserInput() { 25 | int userValue; 26 | printf("Please enter your level. enter -1 for exit.\n"); 27 | scanf("%d", &userValue); 28 | return userValue; 29 | } 30 | 31 | int main() { 32 | int userInput = getUserInput(); // Getting input from user for the first time. 33 | while (userInput != -1) { // While user input is not equal to the -1, the program will repeat. 34 | printMessage(userInput); // Showing proper message for user according to his/hers type. 35 | userInput = getUserInput(); // Getting new input from the user. 36 | } 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /Examples/Pattern/usingMultiplePatterns.rs: -------------------------------------------------------------------------------- 1 | fn show_store_status(hour: f32) { 2 | match hour { 3 | 8.0...12.0 | 13.0...18.0 => println!("The store is open."), 4 | 12.0...13.0 => println!("We will start working again at 13"), 5 | _ => println!("closed") 6 | } 7 | } 8 | 9 | fn main() { 10 | let hours = [8.5, 12.0, 12.25, 13.0, 19.0]; 11 | for hour in hours.iter() { 12 | show_store_status(*hour); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Examples/Struct/C Analogy of method.c: -------------------------------------------------------------------------------- 1 | #include 2 | struct Course { 3 | char *name; 4 | short int passed; 5 | void (*pass) (struct Course * c); 6 | }; 7 | 8 | void pass(struct Course *c) { 9 | c->passed = 1; 10 | } 11 | 12 | int main() { 13 | struct Course course; 14 | course.name = "We can not use Persian Letters simply"; 15 | course.passed = 0; 16 | course.pass = pass; // Assigning pass function to pass value of the struct 17 | course.pass(&course); // We should send instance of the struct to the function expressly 18 | if (course.passed) { 19 | printf("Worked. But we can not print the whole struct simply like what we did in rust."); 20 | } else { 21 | printf("Didn't work"); 22 | } 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /Examples/Struct/DifferentTypeRepresentations.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * For running performance-test.py file, you need compile this file with C 3 | * Representation with following command: 4 | * rustc DifferentTypeRepresentations.rs -o clike.o 5 | * The you should compile this file with Rust representation with following command: 6 | * rustc DifferenetTypeRepresentations.rs -o rlike.o 7 | * Then you can run that script for performance testing 8 | * */ 9 | #[repr(C)] // Comment This Line if You Want to use Rust Representation 10 | #[derive(Debug)] 11 | struct CLikeStruct { 12 | p1: i32, 13 | p2: i8, 14 | p3: i32, 15 | p4: i8, 16 | p5: f64 17 | } 18 | 19 | fn main() { 20 | for i in 0..10000 { 21 | CLikeStruct{ p1: i - 10, p2: 10, p3: i * 11, p4: 20, p5: 3000.3000 }; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Examples/Struct/Method and associated function.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug)] 2 | struct Student { 3 | name: String, 4 | id: u32, 5 | courses: [Course; 3] 6 | } 7 | 8 | #[derive(Debug)] 9 | struct Course { 10 | name: String, 11 | passed: bool 12 | } 13 | 14 | impl Student { 15 | fn check_graduation(self) -> bool { 16 | for course in self.courses.iter() { 17 | if !course.passed { 18 | return false; 19 | } 20 | } 21 | return true; 22 | } 23 | 24 | fn construct(name: String, id: u32, courses: [Course; 3]) -> Student{ 25 | Student { 26 | name, 27 | id, 28 | courses, 29 | } 30 | } 31 | } 32 | 33 | impl Course { 34 | fn print(&self) { 35 | println!("Course in the print method: {:#?}", self); 36 | } 37 | } 38 | 39 | impl Course { 40 | fn pass(&mut self) { 41 | self.passed = true; 42 | } 43 | } 44 | 45 | fn main() { 46 | 47 | let course1 = Course { 48 | name: String::from("مهندسی نرم افزار"), 49 | passed: true 50 | }; 51 | 52 | let course2 = Course { 53 | name: String::from("طراحی پایگاه داده"), 54 | passed: true 55 | }; 56 | 57 | let course3 = Course { 58 | name: String::from("روش های رسمی در مهندسی نرم افزار"), 59 | passed: true 60 | }; 61 | 62 | let mut asghar = Student::construct(String::from("اصغر اکبرآبادی اصل"), 96532147, [course1, course2, course3]); 63 | println!("Asghar revived with an associated function: {:#?}", asghar); 64 | println!("Checking asghar graduation result is: {}", asghar.check_graduation()); 65 | 66 | let mut course_instance = Course { 67 | name: String::from("یک اسم الکی"), 68 | passed: false 69 | }; 70 | course_instance.print(); 71 | course_instance.pass(); 72 | course_instance.print(); 73 | } 74 | -------------------------------------------------------------------------------- /Examples/Struct/README.md: -------------------------------------------------------------------------------- 1 | # Method Definition and Usage Example 2 | In the `Method and associated function.rs` file, There are examples of defining and using methods and associated functions for structs. 3 | All the codes in the list below has been taught in the [Rust free tutorial in persian No: 11](https://blog.alihoseiny.ir/%d8%a2%d9%85%d9%88%d8%b2%d8%b4-%d8%b2%d8%a8%d8%a7%d9%86-%d8%a8%d8%b1%d9%86%d8%a7%d9%85%d9%87%e2%80%8c%d9%86%d9%88%db%8c%d8%b3%db%8c-rust-%d9%82%d8%b3%d9%85%d8%aa%db%b1%db%b1-%d8%a7%d9%81%d8%b2%d9%88%d8%af%d9%86-method-%d9%88-associated-function-%d8%a8%d9%87-struct-%d9%87%d8%a7/?utm_source=Github&utm_medium=Readme&utm_campaign=RustTutorial). 4 | ## Basic Concpets 5 | - Struct creation 6 | - Struct instantiation 7 | - Method creation 8 | - Method with Ownership moving 9 | - Printing an instance of a struct 10 | - Associated Function 11 | - Struct creation shorthand 12 | 13 | 14 | Other concepts those are directly related to the structs and has been taught in the [Rust free tutorial in perisan No: 12](https://blog.alihoseiny.ir/%d8%a2%d9%85%d9%88%d8%b2%d8%b4-%d8%b2%d8%a8%d8%a7%d9%86-%d8%a8%d8%b1%d9%86%d8%a7%d9%85%d9%87%e2%80%8c%d9%86%d9%88%db%8c%d8%b3%db%8c-rust-%d9%82%d8%b3%d9%85%d8%aa%db%b1%db%b2-%d8%af%d8%b1-%d8%a7%d8%b9%d9%85%d8%a7%d9%82-struct/?utm_source=Github&utm_medium=Readme&utm_campaign=RustTutorial). 15 | ## Advanced Concepts 16 | - Tuple Like Structs (`TupleLikeStruct.rs`) 17 | - Unit Like Structs (`UnitLikeStructs.rs`) 18 | - Value Inheritance (`ValueInheritance.rs` and `ValueInheritanceWithClone.rs`) 19 | - Infinite Recursive Type Problem (`RecursiveTypeInfiniteSize.rs`) 20 | -------------------------------------------------------------------------------- /Examples/Struct/RecursiveTypeInfiniteSize.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug)] 2 | struct Course { 3 | name: String, 4 | passed: bool, 5 | teacher: Teacher 6 | } 7 | 8 | #[derive(Debug)] 9 | struct Teacher { 10 | name: String, 11 | course: Course 12 | } 13 | 14 | 15 | fn main() { 16 | let course: Course; 17 | course = Course { 18 | name: String::from("درس۱"), 19 | passed: false, 20 | teacher: Teacher { 21 | name: String::from("عین الله"), 22 | course 23 | } 24 | }; 25 | } 26 | 27 | -------------------------------------------------------------------------------- /Examples/Struct/TupleLikeStruct.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug)] 2 | struct CMYK (u8, u8, u8, u8); 3 | 4 | #[derive(Debug)] 5 | struct IPv4 (u8, u8, u8, u8); 6 | 7 | fn main() { 8 | let red = CMYK(0, 1, 1, 0); 9 | let local_ip = IPv4(127, 0, 0, 1); 10 | println!("red color {:?} and local ip {:?}. These values have different types.", red, local_ip); 11 | } 12 | 13 | -------------------------------------------------------------------------------- /Examples/Struct/UnitLikeStruct.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug)] 2 | struct UnitLikeStruct; 3 | 4 | fn main() { 5 | let my_unit = UnitLikeStruct; 6 | let same_unit_as_my_unit = UnitLikeStruct {}; 7 | println!("my_unit: {:?}, same_unit_as_my_unit: {:?}", my_unit, same_unit_as_my_unit); 8 | } 9 | 10 | -------------------------------------------------------------------------------- /Examples/Struct/ValueInheritance.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug)] 2 | struct TestStruct { 3 | val1: i32, 4 | val2: u8, 5 | val3: i64, 6 | val4: f64, 7 | val5: u16 8 | } 9 | 10 | fn main() { 11 | let struct1 = TestStruct { 12 | val1: -1238, 13 | val2: 5, 14 | val3: -6464564564, 15 | val4: 1234.5678, 16 | val5: 15 17 | }; 18 | let struct2 = TestStruct {val5: 236, ..struct1}; 19 | println!("struct1: {:#?}", struct1); 20 | println!("struct2: {:#?}", struct2); 21 | } 22 | 23 | -------------------------------------------------------------------------------- /Examples/Struct/ValueInheritanceWithClone.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug, Clone)] 2 | struct Student { 3 | name: String, 4 | id: u32, 5 | courses: [Course; 3] 6 | } 7 | 8 | #[derive(Debug, Clone)] 9 | struct Course { 10 | name: String, 11 | passed: bool, 12 | } 13 | 14 | fn main() { 15 | let courses = [Course {name: String::from("درس۱"), passed: false}, 16 | Course {name: String::from("درس۲"), passed: false}, 17 | Course {name: String::from("درس۳"), passed: false}]; 18 | let student1 = Student { 19 | name: String::from("اصغر اکبرزاده اصل"), 20 | id: 97959493, 21 | courses 22 | }; 23 | let student2 = Student {id: 98999694, ..student1.clone()}; 24 | println!("student1: {:#?}", student1); 25 | println!("student2: {:#?}", student2); 26 | } 27 | 28 | -------------------------------------------------------------------------------- /Examples/Trait/associatedFunctionInTrait.rs: -------------------------------------------------------------------------------- 1 | trait Fly { 2 | fn new() -> Self; 3 | fn fly(&self); 4 | fn land(&self) { 5 | println!("Flyable Object now landing."); 6 | } 7 | } 8 | 9 | struct Kaftar (); 10 | 11 | impl Fly for Kaftar { 12 | fn new() -> Self { 13 | return Kaftar{}; 14 | } 15 | 16 | fn fly(&self) { 17 | println!("Kafter The Kakol Be Sar is flying"); 18 | } 19 | } 20 | 21 | 22 | fn main() { 23 | let kakol_be_sar = Kaftar::new(); 24 | kakol_be_sar.fly(); 25 | } 26 | -------------------------------------------------------------------------------- /Examples/Trait/c++InterfaceExample.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | class CouldFlyInterface { 5 | public: 6 | virtual void fly() = 0; 7 | virtual void land() = 0; 8 | }; 9 | 10 | class CouldEatInterface { 11 | public: 12 | virtual void eat() = 0; 13 | }; 14 | 15 | 16 | class Airplane: public CouldFlyInterface { 17 | public: 18 | Airplane() = default; 19 | 20 | void fly() { 21 | std::cout << "Airplane is flying" << std::endl; 22 | } 23 | 24 | void land() { 25 | std::cout << "Airplane is landing" << std::endl; 26 | } 27 | }; 28 | 29 | class Kaftar: public CouldFlyInterface, CouldEatInterface { 30 | public: 31 | Kaftar() = default; 32 | 33 | void eat() { 34 | std::cout << "Kaftar the Kakol Be Sar is eating" << std::etl; 35 | } 36 | 37 | void fly() { 38 | std::cout << "Kaftar the Kakol Be Sar is flying" << std::endl; 39 | } 40 | 41 | void land() { 42 | std::cout << "Kaftar the Kakol Be Sar is landing"; 43 | } 44 | }; 45 | 46 | void flyTheAirplanes(Airplane *airplaneArray[], int numOfAirplanes) { 47 | for (int i = 0; i < numOfAirplanes; i++) { 48 | airplaneArray[i]->fly(); 49 | } 50 | } 51 | 52 | void flyTheKaftars(Kaftar *kaftarsArray[], int numOfKaftars) { 53 | for (int i = 0; i < numOfKaftars; i++) { 54 | kaftarsArray[i]->fly(); 55 | } 56 | } 57 | 58 | void flyBird(CouldFlyInterface * flyableArray[], int numOfFlyables) { 59 | for (int i = 0; i < numOfFlyables; i++) { 60 | flyableArray[i]->fly(); 61 | } 62 | } 63 | 64 | /* 65 | * int main() { 66 | * Airplane *Airplane1 = new Airplane(); 67 | * Airplane *Airplane2 = new Airplane(); 68 | * Airplane *Airplane3 = new Airplane(); 69 | * Airplane *airplanes[3] = {Airplane1, Airplane2, Airplane3}; 70 | * flyTheAirplanes(airplanes, 3); 71 | * Kaftar *kakolBeSar1 = new Kaftar(); 72 | * Kaftar *kakolBeSar2 = new Kaftar(); 73 | * Kaftar *kakolBeSar3 = new Kaftar(); 74 | * Kaftar * kaftars[3] = {kakolBeSar1, kakolBeSar2, kakolBeSar3}; 75 | * flyTheKaftars(kaftars, 3); 76 | * return 0; 77 | * }*/ 78 | 79 | int main() { 80 | Airplane *Airplane1 = new Airplane(); 81 | Airplane *Airplane2 = new Airplane(); 82 | Airplane *Airplane3 = new Airplane(); 83 | Kaftar *kakolBeSar1 = new Kaftar(); 84 | Kaftar *kakolBeSar2 = new Kaftar(); 85 | Kaftar *kakolBeSar3 = new Kaftar(); 86 | CouldFlyInterface * flyablesArray[] = {Airplane1, Airplane2, Airplane3, kakolBeSar1, kakolBeSar2,kakolBeSar3}; 87 | flyBird(flyablesArray, 6); 88 | return 0; 89 | } 90 | -------------------------------------------------------------------------------- /Examples/Trait/callMethodsWithSameName.rs: -------------------------------------------------------------------------------- 1 | trait Brush { 2 | fn draw(&self); 3 | fn change_colour(&self); 4 | } 5 | 6 | trait Screen { 7 | fn draw(&self); 8 | fn turnoff(&self); 9 | } 10 | 11 | struct Something(); 12 | 13 | impl Brush for Something { 14 | fn draw(&self) { 15 | println!("Draw a line on the paper."); 16 | } 17 | 18 | fn change_colour(&self) { 19 | println!("Brush colour changed."); 20 | } 21 | } 22 | 23 | impl Screen for Something { 24 | fn draw(&self) { 25 | println!("Draw a line on the screen"); 26 | } 27 | 28 | fn turnoff(&self) { 29 | println!("Screen turned off"); 30 | } 31 | } 32 | 33 | fn main() { 34 | let something = Something{}; 35 | Brush::draw(&something); 36 | Screen::draw(&something); 37 | } 38 | -------------------------------------------------------------------------------- /Examples/Trait/callingMethodsLikeAssociatedFunction.rs: -------------------------------------------------------------------------------- 1 | trait Fly { 2 | fn new(distance: u8) -> Self; 3 | fn fly(self: &Self); 4 | fn land(&self) { 5 | println!("Flyable Object now landing."); 6 | } 7 | fn change_distance(&mut self, distance: u8); 8 | } 9 | 10 | struct Kaftar { 11 | fly_distance: u8 12 | } 13 | 14 | impl Fly for Kaftar { 15 | fn new(distance: u8) -> Self { 16 | Kaftar { 17 | fly_distance: distance 18 | } 19 | } 20 | 21 | fn fly(&self) { 22 | println!("Kafter The Kakol Be Sar is flying"); 23 | } 24 | 25 | fn change_distance(& mut self, distance: u8) { 26 | self.fly_distance = distance; 27 | } 28 | } 29 | 30 | 31 | fn main() { 32 | let mut kakol_be_sar = Kaftar::new(10); 33 | Kaftar::fly(&kakol_be_sar); 34 | Kaftar::change_distance(&mut kakol_be_sar, 100); 35 | println!("Flying distance: {}", kakol_be_sar.fly_distance); 36 | } 37 | -------------------------------------------------------------------------------- /Examples/Trait/callingMethodsLikeAssociatedFunctionOnTraits.rs: -------------------------------------------------------------------------------- 1 | 2 | trait Animal { 3 | fn eat(&self); 4 | } 5 | 6 | trait Fly { 7 | fn new() -> Self; 8 | fn fly(self: &Self); 9 | fn land(&self) { 10 | println!("Flyable Object now landing."); 11 | } 12 | } 13 | 14 | struct Kaftar (); 15 | 16 | impl Fly for Kaftar { 17 | fn new() -> Self {return Kaftar{};} 18 | fn fly(&self) { 19 | println!("Kafter The Kakol Be Sar is flying"); 20 | } 21 | } 22 | 23 | 24 | fn main() { 25 | let kakol_be_sar = Kaftar::new(); 26 | Fly::fly(&kakol_be_sar); 27 | } 28 | -------------------------------------------------------------------------------- /Examples/Trait/flyingString.rs: -------------------------------------------------------------------------------- 1 | trait Fly { 2 | fn fly(&self); 3 | fn land(&self) { 4 | println!("Flyable Object now landing."); 5 | } 6 | } 7 | 8 | impl Fly for String { 9 | fn fly(&self) { 10 | println!("Oh my گاج. It's a flying string!"); 11 | } 12 | } 13 | 14 | fn main() { 15 | let flying_string = String::from("بغبغو"); 16 | flying_string.fly(); 17 | } 18 | -------------------------------------------------------------------------------- /Examples/Trait/implementingOthersTraits.rs: -------------------------------------------------------------------------------- 1 | use std::clone::Clone; 2 | #[derive(Debug)] 3 | struct YouCanCloneMe { 4 | name: String, 5 | age: u8 6 | } 7 | 8 | impl Clone for YouCanCloneMe { 9 | fn clone(&self) -> Self { 10 | return YouCanCloneMe{name: self.name.clone(), age: self.age}; 11 | } 12 | } 13 | 14 | fn main() { 15 | let yaroo = YouCanCloneMe { 16 | name: String::from("Name"), 17 | age: 22 18 | }; 19 | 20 | println!("cloned yaroo: {:#?}", yaroo.clone()); 21 | } 22 | -------------------------------------------------------------------------------- /Examples/Trait/polymorphicFunctionUsingTraitExample.rs: -------------------------------------------------------------------------------- 1 | trait Fly { 2 | fn fly(&self); 3 | fn land(&self); 4 | } 5 | 6 | struct Kaftar (); 7 | struct AirPlane(); 8 | 9 | impl Fly for Kaftar { 10 | fn fly(&self) { 11 | println!("Kafter The Kakol Be Sar is flying"); 12 | } 13 | 14 | fn land(&self) { 15 | println!("Kafter The Kakol Be Sar is landing"); 16 | } 17 | 18 | } 19 | 20 | impl Fly for AirPlane { 21 | fn fly(&self) { 22 | println!("Airplane is flying."); 23 | } 24 | 25 | fn land(&self) { 26 | println!("Airplane is landing."); 27 | } 28 | } 29 | 30 | fn fly_bird(flyable: &Fly) { 31 | flyable.fly(); 32 | } 33 | 34 | fn main() { 35 | let airplane = AirPlane{}; 36 | let kakol_be_sar = Kaftar{}; 37 | fly_bird(&airplane); 38 | fly_bird(&kakol_be_sar); 39 | } 40 | -------------------------------------------------------------------------------- /Examples/Trait/subtraitsExample.rs: -------------------------------------------------------------------------------- 1 | trait Animal { 2 | fn eat(&self); 3 | } 4 | 5 | trait Fly: Animal { 6 | fn fly(&self); 7 | fn land(&self) { 8 | println!("Flyable Object now landing."); 9 | } 10 | } 11 | 12 | struct Kaftar (); 13 | 14 | impl Fly for Kaftar { 15 | fn fly(&self) { 16 | println!("Kafter The Kakol Be Sar is flying"); 17 | } 18 | } 19 | 20 | impl Animal for Kaftar { 21 | fn eat(&self) { 22 | println!("I'm busy now. Let me eat my Arzans."); 23 | } 24 | } 25 | 26 | fn main() { 27 | let kakol_be_sar = Kaftar{}; 28 | kakol_be_sar.fly(); 29 | kakol_be_sar.eat(); 30 | } 31 | -------------------------------------------------------------------------------- /Examples/Trait/traitImplementationExample.rs: -------------------------------------------------------------------------------- 1 | trait Fly { 2 | fn fly(&self); 3 | fn land(&self); 4 | } 5 | 6 | struct Kaftar (); 7 | 8 | impl Fly for Kaftar { 9 | fn fly(&self) { 10 | println!("Kafter The Kakol Be Sar is flying"); 11 | } 12 | 13 | fn land(&self) { 14 | println!("Kafter The Kakol Be Sar is landing"); 15 | } 16 | 17 | } 18 | 19 | fn main() { 20 | let kakol_be_sar = Kaftar{}; 21 | kakol_be_sar.fly(); 22 | kakol_be_sar.land(); 23 | } 24 | -------------------------------------------------------------------------------- /Examples/Trait/traitMethodDefaultImplementation.rs: -------------------------------------------------------------------------------- 1 | trait Fly { 2 | fn fly(&self); 3 | fn land(&self) { 4 | println!("Flyable Object now landing."); 5 | } 6 | } 7 | 8 | struct Kaftar (); 9 | struct AirPlane(); 10 | struct UnknownFlyable(); 11 | 12 | impl Fly for UnknownFlyable { 13 | fn fly(&self) { 14 | println!("Unknown flyable is flying."); 15 | } 16 | } 17 | 18 | impl Fly for Kaftar { 19 | fn fly(&self) { 20 | println!("Kafter The Kakol Be Sar is flying"); 21 | } 22 | 23 | fn land(&self) { 24 | println!("Kafter The Kakol Be Sar is landing"); 25 | } 26 | 27 | } 28 | 29 | impl Fly for AirPlane { 30 | fn fly(&self) { 31 | println!("Airplane is flying."); 32 | } 33 | 34 | fn land(&self) { 35 | println!("Airplane is landing."); 36 | } 37 | } 38 | 39 | fn main() { 40 | let airplane = AirPlane{}; 41 | let kakol_be_sar = Kaftar{}; 42 | let unknown = UnknownFlyable{}; 43 | 44 | airplane.land(); 45 | kakol_be_sar.land(); 46 | unknown.land(); 47 | } 48 | -------------------------------------------------------------------------------- /Examples/lifetime/enum_lifetime.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug)] 2 | enum Something <'a> { 3 | Some(&'a u8), 4 | Thing(u8) 5 | } 6 | 7 | fn main() { 8 | let number: u8 = 10; 9 | let a = Something::Some(&number); 10 | println!("{:?}", a); 11 | } 12 | -------------------------------------------------------------------------------- /Examples/lifetime/function_with_lifetime.rs: -------------------------------------------------------------------------------- 1 | fn greatest_sum <'a>(array1: &'a [i32], array2: &'a [i32]) -> &'a [i32] { 2 | let mut sum1 = 0; 3 | let mut sum2 = 0; 4 | 5 | for i in array1 { 6 | sum1 += *i; 7 | } 8 | 9 | for j in array2 { 10 | sum2 += *j; 11 | } 12 | 13 | if sum1 < sum2 { 14 | return array1; 15 | } 16 | return array2; 17 | } 18 | 19 | fn main() { 20 | let arr1 = [1, 2, 3]; 21 | let arr2 = [1, 2, 3, 4]; 22 | 23 | let greatest_array = greatest_sum(&arr1, &arr2); 24 | println!("greatest array: {:?}", greatest_array); 25 | } 26 | -------------------------------------------------------------------------------- /Examples/lifetime/mutable_static_value.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | call_me(); 3 | call_me(); 4 | call_me(); 5 | call_me(); 6 | } 7 | 8 | fn call_me() { 9 | static mut NUMBER_OF_CALLS: u8 = 0; 10 | unsafe { 11 | NUMBER_OF_CALLS += 1; 12 | println!("number of calls: {}", NUMBER_OF_CALLS); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Examples/lifetime/struct_method_lifetime.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug)] 2 | struct MyStruct<'a> { 3 | name: &'a str, 4 | age: u8 5 | } 6 | 7 | impl<'a> MyStruct<'a> { 8 | fn change_name(&mut self, new_name: &'a str) -> &str { 9 | let old_name = self.name; 10 | self.name = new_name; 11 | return old_name; 12 | } 13 | } 14 | 15 | fn main() { 16 | let name = "Asghar"; 17 | let mut person = MyStruct { 18 | name, 19 | age: 10 20 | }; 21 | 22 | println!("{:?}", person); 23 | 24 | person.change_name("Akbar"); 25 | 26 | println!("{:?}", person); 27 | } 28 | -------------------------------------------------------------------------------- /Exercises/part 5/ex1.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let while_condition: bool; 3 | while_condition = true; // Creates a infinite loop. But it's just an example and we don't care. 4 | loop{ 5 | if while_condition { 6 | println!("loop code"); 7 | } 8 | else { 9 | break; 10 | } 11 | } 12 | } 13 | 14 | -------------------------------------------------------------------------------- /Exercises/part 5/ex2.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let num_of_rows = 9; // number of rows we want 3 | let mut current_row = 1; // number of the row that we are printing right now. 4 | for column_counter in 0..num_of_rows { // We want 9 rows, so we should repeat the loop 9 times. column_counter value starts from 0 to 8 5 | for _ in 0..current_row { // Before the middle, we should print n start in nth row (We change the row number for other rows below) 6 | // Using the underscore(_) for the variable in the loop because i will not use it in the loop. 7 | // Using underscore in this case prevents compiler warning about unused variable. 8 | print!("*"); // Print * without new line after it. 9 | } 10 | print!("\n"); // Just a new line after each column 11 | 12 | if column_counter < num_of_rows / 2{ 13 | current_row += 1; // We did not reach the middle of the pattern yet. So rows should increase the row number. 14 | } 15 | else { 16 | current_row -= 1; // We passed the middle and now rows should get shorter each time. So we decrease the row number. 17 | } 18 | } 19 | } 20 | 21 | -------------------------------------------------------------------------------- /Exercises/part 6/factorial.rs: -------------------------------------------------------------------------------- 1 | // خطوطی که به این شکل با دو "/" شروع می‌شوند کامنت هستند. یعنی توضیحاتی اضافی هستند و جزو کد محسوب نمی‌شوند 2 | // چون خطوط به هم می‌ریزند از این به بعد کامنت‌ها را انگلیسی می‌نویسم. ولی تمام تلاشم را می‌کنم که تا حد امکان ساده باشند 3 | 4 | fn factorial_recursive(n: i32) -> i32 { 5 | if n <= 1 { 6 | return 1; 7 | } 8 | 9 | // Like the arithmetic formula: 10 | // n! = n * (n - 1) * (n - 2) ... * 2 * 1 11 | n * factorial_recursive(n - 1) 12 | } 13 | 14 | fn factorial_with_for(n: i32) -> i32 { 15 | // Storing the result of (n - 1) 16 | let mut result = 1; 17 | 18 | // For looping in numbers from 1 to n, we should create a range from 1 to n + 1 19 | for number in 1..n + 1 { 20 | // Creating the: 1 * 2 * ... * n 21 | result *= number; 22 | } 23 | 24 | result 25 | } 26 | 27 | fn main() { 28 | 29 | // "\t" is a tab 30 | println!("factorial_recursive function results:"); 31 | println!("{}!\tis equal to:\t{}", 0, factorial_recursive(0)); 32 | println!("{}!\tis equal to:\t{}", 1, factorial_recursive(1)); 33 | println!("{}!\tis equal to:\t{}", 5, factorial_recursive(5)); 34 | println!("{}!\tis equal to:\t{}", 7, factorial_recursive(7)); 35 | println!("{}!\tis equal to:\t{}", 10, factorial_recursive(10)); 36 | 37 | print!("\n"); // New line 38 | 39 | println!("factorial_with_for function results:"); 40 | println!("{}!\tis equal to:\t{}", 0, factorial_with_for(0)); 41 | println!("{}!\tis equal to:\t{}", 1, factorial_with_for(1)); 42 | println!("{}!\tis equal to:\t{}", 5, factorial_with_for(5)); 43 | println!("{}!\tis equal to:\t{}", 7, factorial_with_for(7)); 44 | println!("{}!\tis equal to:\t{}", 10, factorial_with_for(10)); 45 | 46 | } 47 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rust-tutorial 2 | Examples and Exercises related to My Rust Programming Languag Tutorial. 3 | These files are related to [my Free Rust tutorial](http://blog.alihoseiny.ir/category/%d8%a2%d9%85%d9%88%d8%b2%d8%b4-%d8%b2%d8%a8%d8%a7%d9%86-%d8%a8%d8%b1%d9%86%d8%a7%d9%85%d9%87%e2%80%8c%d9%86%d9%88%db%8c%d8%b3%db%8c-rust/?utm_source=Github&utm_medium=Readme&utm_campaign=RustTutorial). 4 | 5 | Last tested version: 1.35.0 6 | 7 | See `rust_tutorial` For tests. 8 | 9 | If you have questions abut codes, or have better solutions, please open an issue or contact me with salam@alihoseiny.ir. 10 | 11 |
12 | 13 | # آموزش زبان برنامه‌نویسی Rust 14 | 15 | در اینجا مثال‌ها و تمرین‌های مرتبط با [دوره‌ٕ آموزشی رایگان زبان‌برنامه‌نویسی 16 | Rust](http://blog.alihoseiny.ir/category/%d8%a2%d9%85%d9%88%d8%b2%d8%b4-%d8%b2%d8%a8%d8%a7%d9%86-%d8%a8%d8%b1%d9%86%d8%a7%d9%85%d9%87%e2%80%8c%d9%86%d9%88%db%8c%d8%b3%db%8c-rust/?utm_source=Github&utm_medium=Readme&utm_campaign=RustTutorial 17 | ) را قرار می‌دهم. 18 | اگر درمورد کدهای هر بخش سؤالی داشتید یا راه حل بهتری به ذهنتان می‌رسد می‌توانید یک [issue](https://github.com/alihoseiny/Rust-tutorial/issues/new) باز کنید یا به من [ایمیل]() بدهید 19 | 20 |
21 | -------------------------------------------------------------------------------- /rust_tutorial/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "rust_tutorial" 5 | version = "0.1.0" 6 | 7 | -------------------------------------------------------------------------------- /rust_tutorial/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rust_tutorial" 3 | version = "0.1.0" 4 | authors = ["alihoseiny "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | -------------------------------------------------------------------------------- /rust_tutorial/CompileFailTest/1.rs: -------------------------------------------------------------------------------- 1 | ///```compile_fail 2 | ///fn test() { 3 | /// let x = 10; 4 | /// x = 5; 5 | ///} 6 | ///``` 7 | fn test1() { 8 | 9 | } 10 | 11 | /// 12 | /// This test does not check compile error when you define variable in the global scope, but it should do! 13 | /// ```compile_fail 14 | /// const BUFFER_SIZE: i32 = 10; 15 | //let x = 10; 16 | // 17 | //fn main() { 18 | // println!("سلام دنیا!"); 19 | //}``` 20 | /// 21 | fn test2(){} 22 | 23 | 24 | 25 | /// 26 | /// This error is not because of assigning a function to a variable, is because defining a constant 27 | /// if another scope rather than global. But it should test the first case 28 | /// ```compile_fail 29 | /// const BUFFER_SIZE: i32 = function(); 30 | /// ``` 31 | fn test3(){} 32 | 33 | -------------------------------------------------------------------------------- /rust_tutorial/CompileFailTest/10.rs: -------------------------------------------------------------------------------- 1 | /// 2 | /// ```compile_fail 3 | /// struct Student { 4 | /// name: String, 5 | /// id: u32, 6 | /// graduated: bool 7 | /// } 8 | /// fn main() { 9 | /// let asghar = Student { 10 | /// id: 963258741, 11 | /// name: String::from("اصغر اکبرآبادی اصل"), 12 | /// graduated: false 13 | /// }; 14 | /// println!("{}", asghar); 15 | /// } 16 | /// ``` 17 | fn test1(){} 18 | 19 | /// 20 | /// ```compile_fail 21 | /// #[derive(Debug)] 22 | ///struct Student { 23 | /// name: String, 24 | /// id: u32, 25 | /// graduated: bool 26 | ///} 27 | /// fn main() { 28 | /// let asghar = Student { 29 | /// id: 963258741, 30 | /// name: String::from("اصغر اکبرآبادی اصل"), 31 | /// graduated: false 32 | /// }; 33 | /// asghar.name = String::from("اکبر اصغر زاده"); 34 | /// println!("Student name: {}", asghar.name); 35 | ///} 36 | /// ``` 37 | fn test2(){} 38 | 39 | 40 | -------------------------------------------------------------------------------- /rust_tutorial/CompileFailTest/11.rs: -------------------------------------------------------------------------------- 1 | /// 2 | /// ```compile_fail 3 | /// #[derive(Debug)] 4 | ///struct Student { 5 | /// name: String, 6 | /// id: u32, 7 | /// courses: [Course; 3] 8 | ///} 9 | /// 10 | ///#[derive(Debug)] 11 | ///struct Course { 12 | /// name: String, 13 | /// passed: bool 14 | ///} 15 | /// impl Student { 16 | /// fn check_graduation(self) -> bool { 17 | /// for course in self.courses.iter() { 18 | /// if !course.passed { 19 | /// return false; 20 | /// } 21 | /// } 22 | /// return true; 23 | /// } 24 | ///} 25 | /// 26 | /// fn main() { 27 | /// let course1 = Course { 28 | /// name: String::from("مهندسی نرم افزار"), 29 | /// passed: true 30 | /// }; 31 | /// let course2 = Course { 32 | /// name: String::from("طراحی پایگاه داده"), 33 | /// passed: true 34 | /// }; 35 | /// let course3 = Course { 36 | /// name: String::from("روش های رسمی در مهندسی نرم افزار"), 37 | /// passed: true 38 | /// }; 39 | /// let asghar = Student { 40 | /// name: String::from("اصغر اکبرآبادی اصل"), 41 | /// id: 96532147, 42 | /// courses: [course1, course2, course3] 43 | /// }; 44 | /// println!("Checking asghar graduation result is: {}", asghar.check_graduation()); 45 | /// print!("Asghar: {:#?}", asghar); 46 | ///} 47 | /// ``` 48 | fn test1(){} -------------------------------------------------------------------------------- /rust_tutorial/CompileFailTest/12.rs: -------------------------------------------------------------------------------- 1 | /// 2 | /// ```compile_fail 3 | /// #[derive(Debug)] 4 | ///struct Student { 5 | /// name: String, 6 | /// id: u32, 7 | /// courses: [Course; 3] 8 | ///} 9 | /// 10 | ///#[derive(Debug)] 11 | ///struct Course { 12 | /// name: String, 13 | /// passed: bool 14 | ///} 15 | /// fn main() { 16 | /// 17 | /// let courses = [Course {name: String::from("درس۱"), passed: false}, 18 | /// Course {name: String::from("درس۲"), passed: false}, 19 | /// Course {name: String::from("درس۳"), passed: false}]; 20 | /// 21 | /// let student1 = Student { 22 | /// name: String::from("اصغر اکبرزاده اصل"), 23 | /// id: 9796959493, 24 | /// courses 25 | /// }; 26 | /// 27 | /// let student2 = Student {id: 9899969594, ..student1.clone()}; 28 | /// 29 | /// println!("student1: {:#?}", student1); 30 | /// println!("student2: {:#?}", student2); 31 | ///} 32 | /// ``` 33 | fn test1(){} 34 | 35 | /// 36 | /// ```compile_fail 37 | /// #[derive(Debug, Clone)] 38 | ///struct Course { 39 | /// name: String, 40 | /// passed: bool, 41 | /// teacher: Teacher 42 | ///} 43 | /// 44 | ///#[derive(Debug)] 45 | ///struct Teacher { 46 | /// name: String, 47 | /// course: Course 48 | ///} 49 | /// fn main() { 50 | /// let course: Course; 51 | /// course = Course { 52 | /// name: String::from("درس۱"), 53 | /// passed: false, 54 | /// teacher: Teacher { 55 | /// name: Student::from("عین الله"), 56 | /// course 57 | /// } 58 | /// }; 59 | ///} 60 | ///``` 61 | fn test2(){} -------------------------------------------------------------------------------- /rust_tutorial/CompileFailTest/14.rs: -------------------------------------------------------------------------------- 1 | /// 2 | ///```compile_fail 3 | /// fn print_message(user_level: u8) { 4 | /// match user_level { 5 | /// 0 => println!("Welcome dear admin."), 6 | /// 1 => println!("Welcome back our best member."), 7 | /// 2 => println!("Hello. Please register first.") 8 | /// } 9 | ///} 10 | /// 11 | ///fn main() { 12 | /// let user_inputs: [u8;5] = [0, 1, 2, 3, 4]; 13 | /// for value in user_inputs.iter() { 14 | /// print_message(*value); 15 | /// } 16 | ///} 17 | /// ``` 18 | fn test1(){} 19 | 20 | /// 21 | /// ```compile_fail 22 | /// struct RgbStruct { 23 | /// red: u16, 24 | /// green: u16, 25 | /// blue: u16 26 | ///} 27 | /// 28 | ///fn print_number(n: u16) { 29 | /// println!("number is: {}", n); 30 | ///} 31 | /// 32 | ///fn main() { 33 | /// let colours = [ 34 | /// RgbStruct { 35 | /// red: 112, 36 | /// green: 0, 37 | /// blue: 0 38 | /// }, 39 | /// RgbStruct { 40 | /// red: 123, 41 | /// green: 124, 42 | /// blue: 8 43 | /// }, 44 | /// RgbStruct { 45 | /// red: 0, 46 | /// green: 41, 47 | /// blue: 223 48 | /// } 49 | /// ]; 50 | /// 51 | /// for rgb_reference in colours.iter() { 52 | /// match rgb_reference { 53 | /// RgbStruct {red, blue: 0, green: 0} => { 54 | /// println!("This is a kind of red colour."); 55 | /// print_number(red); 56 | /// }, 57 | /// RgbStruct {red, green, blue} => println!("rgb({}, {}, {})", red, green, blue) 58 | /// } 59 | /// } 60 | ///} 61 | /// ``` 62 | fn test2(){} 63 | 64 | 65 | /// 66 | /// ```compile_fail 67 | /// struct RgbStruct { 68 | /// red: u16, 69 | /// green: u16, 70 | /// blue: u16 71 | ///} 72 | /// fn extract_and_match(colour: RgbStruct) { 73 | /// match colour { 74 | /// new_colour @ RgbStruct {..} => println!("This is my colour: rgb({}, {}, {})", new_colour.red, new_colour.green, new_colour.blue), 75 | /// } 76 | ///} 77 | /// 78 | /// let colour = RgbStruct { 79 | /// red: 120, 80 | /// green: 0, 81 | /// blue: 255 82 | /// }; 83 | /// 84 | /// match colour { 85 | /// new_colour @ RgbStruct {..} => println!("This is my colour: rgb({}, {}, {})", new_colour.red, new_colour.green, new_colour.blue), 86 | /// } 87 | /// 88 | /// println!("{:?}", colour); 89 | /// ``` 90 | /// 91 | fn test3(){} -------------------------------------------------------------------------------- /rust_tutorial/CompileFailTest/16.rs: -------------------------------------------------------------------------------- 1 | /// 2 | /// ```compile_fail 3 | /// trait Animal { 4 | /// fn eat(&self); 5 | ///} 6 | /// 7 | ///trait Fly: Animal { 8 | /// fn fly(&self); 9 | /// fn land(&self) { 10 | /// println!("Flyable Object now landing."); 11 | /// } 12 | ///} 13 | ///struct Kaftar (); 14 | /// 15 | ///impl Fly for Kaftar { 16 | /// fn fly(&self) { 17 | /// println!("Kafter The Kakol Be Sar is flying"); 18 | /// } 19 | ///} 20 | /// fn main() { 21 | /// let kakol_be_sar = Kaftar{}; 22 | /// kakol_be_sar.fly(); 23 | /// kakol_be_sar.eat(); 24 | ///} 25 | /// ``` 26 | fn test1(){} -------------------------------------------------------------------------------- /rust_tutorial/CompileFailTest/17.rs: -------------------------------------------------------------------------------- 1 | /// 2 | /// ```compile_fail 3 | /// trait Brush { 4 | /// fn draw(&self); 5 | /// fn change_colour(&self); 6 | ///} 7 | /// 8 | ///trait Screen { 9 | /// fn draw(&self); 10 | /// fn turnoff(&self); 11 | ///} 12 | /// 13 | ///struct Something(); 14 | /// 15 | ///impl Brush for Something { 16 | /// fn draw(&self) { 17 | /// println!("Draw a line on the paper."); 18 | /// } 19 | /// 20 | /// fn change_colour(&self) { 21 | /// println!("Brush colour changed."); 22 | /// } 23 | ///} 24 | /// 25 | ///impl Screen for Something { 26 | /// fn draw(&self) { 27 | /// println!("Draw a line on the screen"); 28 | /// } 29 | /// 30 | /// fn turnoff(&self) { 31 | /// println!("Screen turned off"); 32 | /// } 33 | ///} 34 | /// fn main() { 35 | /// let something = Something{}; 36 | /// something.draw(); 37 | ///} 38 | /// ``` 39 | fn test1(){} 40 | 41 | /// 42 | /// ```compile_fail 43 | /// let x = -10; 44 | ///x.abs(x); 45 | /// ``` 46 | fn test2(){} -------------------------------------------------------------------------------- /rust_tutorial/CompileFailTest/2.rs: -------------------------------------------------------------------------------- 1 | /// 2 | /// ```compile_fail 3 | /// let a = 5; 4 | /// let c = 2.5; 5 | /// let d = a - c; 6 | /// println!("{}\n", d); 7 | ///``` 8 | fn test1(){} -------------------------------------------------------------------------------- /rust_tutorial/CompileFailTest/20.rs: -------------------------------------------------------------------------------- 1 | ///```compile_fail 2 | /// fn main() 3 | /// { 4 | /// let a; 5 | /// { 6 | /// let b = 10; 7 | /// a = &b; 8 | /// } 9 | /// println!("a = {}", a); 10 | ///} 11 | ///``` 12 | fn test1(){} 13 | 14 | ///```compile_fail 15 | /// #[derive(Debug)] 16 | /// struct MyStruct { 17 | /// name: &str, 18 | /// age: u8 19 | ///} 20 | /// fn main() { 21 | /// let name = "Asghar"; 22 | /// let person = MyStruct { 23 | /// name: name, 24 | /// age: 10 25 | /// }; 26 | /// println!("{:?}", person); 27 | ///} 28 | /// ``` 29 | fn test2(){} -------------------------------------------------------------------------------- /rust_tutorial/CompileFailTest/3.rs: -------------------------------------------------------------------------------- 1 | /// 2 | /// ```compile_fail 3 | /// println!("my array is: {}", [10i8;10]); 4 | /// ``` 5 | fn test1(){} -------------------------------------------------------------------------------- /rust_tutorial/CompileFailTest/4.rs: -------------------------------------------------------------------------------- 1 | /// 2 | /// ```compile_fail 3 | /// let condition = 1; 4 | /// if condition { 5 | /// println!("این نوشته هیچ‌وقت چاپ نمی‌شود. چون این برنامه هنگام کامپایل به ارور می‌خورد"); 6 | /// } 7 | /// ``` 8 | fn test1(){} -------------------------------------------------------------------------------- /rust_tutorial/CompileFailTest/6.rs: -------------------------------------------------------------------------------- 1 | /// 2 | /// ```compile_fail 3 | /// let a = b = 10; 4 | /// ``` 5 | fn test1(){} 6 | 7 | /// 8 | /// ```compile_fail 9 | /// let a = (let b = 10); 10 | /// ``` 11 | fn test2(){} -------------------------------------------------------------------------------- /rust_tutorial/CompileFailTest/7.rs: -------------------------------------------------------------------------------- 1 | /// 2 | /// ```compile_fail 3 | /// fn main() { 4 | /// let local_variable = "این یک متغیر محلی است و خارج از تابع main قابل دسترس نیست."; 5 | /// println!("{}", local_variable); 6 | /// another_function(); 7 | ///} 8 | ///fn another_function() { 9 | /// println!("{}", local_variable); // Error! 10 | ///} 11 | /// ``` 12 | /// 13 | fn test1(){} 14 | 15 | /// 16 | /// ```compile_fail 17 | /// let a = String::from("hello"); 18 | /// let b = a; 19 | /// println!("a: {}", a); 20 | /// println!("b: {}", b); 21 | /// ``` 22 | fn test2(){} 23 | 24 | /// 25 | /// ```compile_fail 26 | /// fn main() { 27 | /// let a = String::from("hello"); 28 | /// i_am_owner(a); 29 | /// println!("a in main function: {}", a); 30 | /// } 31 | /// fn i_am_owner(input: String) { 32 | /// println!("The input value is: {}", input); 33 | /// } 34 | /// ``` 35 | 36 | fn test3(){} -------------------------------------------------------------------------------- /rust_tutorial/CompileFailTest/8.rs: -------------------------------------------------------------------------------- 1 | /// 2 | /// ```compile_fail 3 | /// fn main() { 4 | /// let a = String::from("hello"); 5 | /// i_am_owner(&a); 6 | /// println!("a in main function: {}", a); 7 | /// } 8 | /// fn modifier(reference: &String) { 9 | /// reference.push_str(" a new string to push to the old one"); 10 | /// } 11 | /// ``` 12 | fn test1(){} 13 | 14 | /// 15 | /// ```compile_fail 16 | /// fn main() { 17 | /// let mut a = String::from("hello"); 18 | /// modifier(&a); 19 | /// println!("a in main function: {}", a); 20 | /// } 21 | /// fn modifier(reference: &String) { 22 | /// reference.push_str(" a new string to push to the old one"); 23 | /// } 24 | /// ``` 25 | fn test2(){} 26 | 27 | /// 28 | /// ```compile_fail 29 | /// fn main() { 30 | /// let a = String::from("hello"); 31 | /// modifier(&mut a); 32 | /// println!("a in main function: {}", a); 33 | /// } 34 | /// fn modifier(reference: &mut String) { 35 | /// reference.push_str(" a new string to push to the old one"); 36 | /// } 37 | /// ``` 38 | fn test3(){} 39 | 40 | /// 41 | /// ```compile_fail 42 | /// fn main() { 43 | /// let mut a = String::from("hello"); 44 | /// let reference1 = &a; 45 | /// let reference2 = &a; 46 | /// let reference3 = &mut a; 47 | /// ali(reference1); 48 | /// mohammad(reference3); 49 | /// hossein(reference2); 50 | /// println!("a in main function: {}", a); 51 | ///} 52 | ///fn ali(original_text: &String) { 53 | /// println!("Ali says: {}", original_text); 54 | ///} 55 | ///fn hossein(text: &String) { 56 | /// println!("{} hossein", text); 57 | ///} 58 | ///fn mohammad(original_input: &mut String) { 59 | /// original_input.push_str("!"); 60 | ///} 61 | /// ``` 62 | fn test4(){} 63 | 64 | /// 65 | /// ```compile_fail 66 | /// fn main() { 67 | /// let b = dangle_generator(); 68 | /// println!("a in main function: {}", b); 69 | /// } 70 | /// fn dangle_generator() -> &String { 71 | /// let a = String::from("hello"); 72 | /// &a 73 | /// } 74 | /// ``` 75 | fn test5(){} -------------------------------------------------------------------------------- /rust_tutorial/CompileFailTest/9.rs: -------------------------------------------------------------------------------- 1 | /// 2 | /// ```compile_fail 3 | /// fn main() { 4 | /// let mut my_array = [-5, -3, -10, 0, 1, 8, 9]; 5 | /// let not_negative_item = first_not_negative_element(&my_array); 6 | /// if not_negative_item.len() == 1 { 7 | /// println!("First not negative element in the my_array is: {:?}", not_negative_item); 8 | /// } else { 9 | /// println!("All elements of my_array are negative."); 10 | /// } 11 | /// my_array = [0i32; 7]; 12 | /// println!("Incorrect not negative value: {:?}", my_array); 13 | /// } 14 | /// fn first_not_negative_element(array: &[i32; 7]) -> &[i32] { 15 | /// for (index, &item) in array.iter().enumerate() { 16 | /// if item > -1 { 17 | /// return &array[index..index + 1]; 18 | /// } 19 | /// } 20 | /// return &array[0..array.len()]; 21 | /// } 22 | /// ``` 23 | fn test1(){} -------------------------------------------------------------------------------- /rust_tutorial/CompileFailTest/Makefile: -------------------------------------------------------------------------------- 1 | test: 2 | find . -name "*.rs" -exec rustdoc --test {} \; 3 | -------------------------------------------------------------------------------- /rust_tutorial/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Why we need these tests? 2 | Rust is under heavy development and many features are changing. So we need tests those show us the tutorial is correct when a new version is coming. 3 | So we have two kinds of tests for this tutorial. 4 | # Compilation Fail Tests 5 | Those tests are in the **CompileFailTest** directory. Each file contains examples of compiling fail in the tutorial with the same number. 6 | 7 | These tests are *document test*s because we can check `compile_faile` only in this kind of test. 8 | 9 | For running all the tests, you can simply run `make` command in that directory. 10 | 11 | # Syntax and Behaviour Tests 12 | These tests are in the **tests* directory. For running them you can run `cargo test` in the current directory. 13 | One thing you should consider is many of these tests are not **good tests**. Because They are not really *unit tests*. Most of the times we just want to check that this code will compile. 14 | 15 | -------------------------------------------------------------------------------- /rust_tutorial/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("Hello, world!"); 3 | } 4 | -------------------------------------------------------------------------------- /rust_tutorial/tests/1.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod test1 { 3 | #[test] 4 | fn test_variable_declaration(){ 5 | let var1; 6 | let var2 = 10; 7 | let var3: i32 = 20; 8 | var1 = 50; 9 | } 10 | 11 | #[test] 12 | fn test_reassigning_mutable_var() { 13 | let mut x = 10; 14 | x = 5; 15 | } 16 | 17 | 18 | } -------------------------------------------------------------------------------- /rust_tutorial/tests/10.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod test10 { 3 | 4 | #[derive(Debug)] 5 | struct Student { 6 | name: String, 7 | id: u32, 8 | graduated: bool 9 | } 10 | 11 | fn create_student(name: String, id: u32, graduated: bool) -> Student { 12 | Student { 13 | name, 14 | id, 15 | graduated 16 | } 17 | } 18 | 19 | #[test] 20 | fn test_struct_construction() { 21 | let asghar = Student { 22 | id: 963258741, 23 | name: String::from("اصغر اکبرآبادی اصل"), 24 | graduated: false 25 | }; 26 | } 27 | 28 | #[test] 29 | fn test_struct_printing() { 30 | let asghar = Student { 31 | id: 963258741, 32 | name: String::from("اصغر اکبرآبادی اصل"), 33 | graduated: false 34 | }; 35 | println!("{:?}", asghar); 36 | } 37 | 38 | #[test] 39 | fn test_struct_value_access() { 40 | let asghar = Student { 41 | id: 963258741, 42 | name: String::from("اصغر اکبرآبادی اصل"), 43 | graduated: false 44 | }; 45 | assert_eq!("اصغر اکبرآبادی اصل", asghar.name); 46 | } 47 | 48 | #[test] 49 | fn test_value_modification() { 50 | let mut asghar = Student { 51 | id: 963258741, 52 | name: String::from("اصغر اکبرآبادی اصل"), 53 | graduated: false 54 | }; 55 | assert_eq!(asghar.name, "اصغر اکبرآبادی اصل"); 56 | asghar.name = String::from("اکبر اصغر زاده"); 57 | assert_eq!(asghar.name, "اکبر اصغر زاده"); 58 | } 59 | 60 | #[test] 61 | fn test_struct_construction_using_factory_func() { 62 | let asghar = create_student(String::from("اصغر اکبرآبادی اصل"), 963258741, true); 63 | assert_eq!(asghar.name, "اصغر اکبرآبادی اصل"); 64 | } 65 | } -------------------------------------------------------------------------------- /rust_tutorial/tests/11.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod test11 { 3 | 4 | #[derive(Debug)] 5 | struct Course { 6 | name: String, 7 | passed: bool 8 | } 9 | 10 | #[derive(Debug)] 11 | struct Student { 12 | name: String, 13 | id: u32, 14 | courses: [Course; 3] 15 | } 16 | 17 | impl Student { 18 | fn check_graduation(&self) -> bool { 19 | for course in self.courses.iter() { 20 | if !course.passed { 21 | return false; 22 | } 23 | } 24 | return true; 25 | } 26 | } 27 | 28 | impl Course { 29 | fn print(&self) { 30 | println!("Course in the print method: {:#?}", self); 31 | } 32 | } 33 | 34 | impl Course { 35 | fn pass(&mut self) { 36 | self.passed = true; 37 | } 38 | } 39 | 40 | impl Student { 41 | fn construct(name: String, id: u32, courses: [Course; 3]) -> Student{ 42 | Student { 43 | name, 44 | id, 45 | courses, 46 | } 47 | } 48 | } 49 | 50 | #[test] 51 | fn test_method_with_getting_ownership() { 52 | let course1 = Course { 53 | name: String::from("مهندسی نرم افزار"), 54 | passed: true 55 | }; 56 | let course2 = Course { 57 | name: String::from("طراحی پایگاه داده"), 58 | passed: true 59 | }; 60 | let course3 = Course { 61 | name: String::from("روش های رسمی در مهندسی نرم افزار"), 62 | passed: true 63 | }; 64 | let asghar = Student { 65 | name: String::from("اصغر اکبرآبادی اصل"), 66 | id: 96532147, 67 | courses: [course1, course2, course3] 68 | }; 69 | assert_eq!(asghar.check_graduation(), true); 70 | } 71 | 72 | #[test] 73 | fn test_method_without_getting_ownership() { 74 | let course_instance = Course { 75 | name: String::from("یک اسم الکی"), 76 | passed: false 77 | }; 78 | course_instance.print(); 79 | println!("Course in the main function: {:#?}", course_instance); // If ownership has been taken throws an error 80 | } 81 | 82 | #[test] 83 | fn test_changing_value_using_method() { 84 | let mut course_instance = Course { 85 | name: String::from("یک اسم الکی"), 86 | passed: false 87 | }; 88 | assert_eq!(course_instance.passed, false); 89 | course_instance.pass(); 90 | assert_eq!(course_instance.passed, true); 91 | } 92 | 93 | #[test] 94 | fn test_struct_construction_using_associated_function() { 95 | let course1 = Course { 96 | name: String::from("مهندسی نرم افزار"), 97 | passed: true 98 | }; 99 | let course2 = Course { 100 | name: String::from("طراحی پایگاه داده"), 101 | passed: true 102 | }; 103 | let course3 = Course { 104 | name: String::from("روش های رسمی در مهندسی نرم افزار"), 105 | passed: true 106 | }; 107 | let asghar = Student::construct(String::from("اصغر اکبرآبادی اصل"), 96532147, [course1, course2, course3]); 108 | assert_eq!(asghar.name, "اصغر اکبرآبادی اصل"); 109 | assert_eq!(asghar.id, 96532147); 110 | } 111 | } -------------------------------------------------------------------------------- /rust_tutorial/tests/12.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod test12 { 3 | #[derive(Debug)] 4 | struct TestStruct { 5 | val1: i32, 6 | val2: u8, 7 | val3: i64, 8 | val4: f64, 9 | val5: u16 10 | } 11 | 12 | #[derive(Debug, Clone)] 13 | struct Student { 14 | name: String, 15 | id: u32, 16 | courses: [Course; 3] 17 | } 18 | 19 | #[derive(Debug, Clone)] 20 | struct Course { 21 | name: String, 22 | passed: bool 23 | } 24 | 25 | #[derive(Debug)] 26 | struct TupleLike (u8, u8, u8); 27 | 28 | #[derive(Debug)] 29 | struct UnitLikeStruct; 30 | 31 | #[test] 32 | fn test_struct_inheriting_similar_values() { 33 | let struct1 = TestStruct { 34 | val1: -1238, 35 | val2: 5, 36 | val3: -6464564564, 37 | val4: 1234.5678, 38 | val5: 15 39 | }; 40 | let struct2 = TestStruct {val5: 236, ..struct1}; 41 | assert_eq!(struct1.val1, struct2.val1); 42 | assert_eq!(struct1.val2, struct2.val2); 43 | assert_eq!(struct1.val3, struct2.val3); 44 | assert_eq!(struct1.val4, struct2.val4); 45 | assert_ne!(struct1.val5, struct2.val5); 46 | assert_eq!(struct2.val5, 236); 47 | } 48 | 49 | #[test] 50 | /// 51 | /// Only test syntax. not functionality 52 | fn test_inheritance_with_clone() { 53 | let courses = [Course {name: String::from("درس۱"), passed: false}, 54 | Course {name: String::from("درس۲"), passed: false}, 55 | Course {name: String::from("درس۳"), passed: false}]; 56 | 57 | let student1 = Student { 58 | name: String::from("اصغر اکبرزاده اصل"), 59 | id: 97959493, 60 | courses 61 | }; 62 | 63 | let student2 = Student {id: 98999694, ..student1.clone()}; 64 | } 65 | 66 | #[test] 67 | fn test_tuple_like_struct() { 68 | let mut tuple_like = TupleLike(10, 11, 13); 69 | assert_eq!(tuple_like.0, 10); 70 | tuple_like.0 = 18; 71 | assert_eq!(tuple_like.0, 18); 72 | } 73 | 74 | #[test] 75 | /// 76 | /// Only test syntax. 77 | fn test_unit_like_struct() { 78 | let my_unit = UnitLikeStruct; 79 | let same_unit_as_my_unit = UnitLikeStruct {}; 80 | } 81 | 82 | 83 | 84 | } -------------------------------------------------------------------------------- /rust_tutorial/tests/13.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod test13 { 3 | 4 | enum Colour { 5 | RGB, 6 | Hex 7 | } 8 | 9 | enum HttpStatus { 10 | Ok = 200, 11 | NotFound = 404, 12 | InternalServerError = 500 13 | } 14 | 15 | struct ColourStruct { 16 | colour_type: Colour, 17 | value: String 18 | } 19 | 20 | enum ColourWithValue { 21 | RGB(u16, u16, u16), 22 | Hex(String) 23 | } 24 | 25 | enum ColourWithStruct { 26 | RGB {red: u16, green: u16, blue: u16}, 27 | Hex(String) 28 | } 29 | 30 | #[test] 31 | fn test_enum_declaration() { 32 | let a = Colour::RGB; 33 | } 34 | 35 | #[test] 36 | fn test_enum_values_memory_representation() { 37 | let a = Colour::RGB; 38 | let b = Colour::Hex; 39 | assert_eq!(a as u8, 0); 40 | assert_eq!(b as u8, 1); 41 | } 42 | 43 | #[test] 44 | fn test_enum_value_number_declaration() { 45 | let a = HttpStatus::Ok; 46 | let b = HttpStatus::NotFound; 47 | let c = HttpStatus::InternalServerError; 48 | assert_eq!(a as u8, 200); 49 | assert_eq!(b as u16, 404); 50 | assert_eq!(c as u16, 500); 51 | } 52 | 53 | #[test] 54 | /// 55 | /// Only tests syntax. 56 | fn test_enum_in_struct() { 57 | let rgb_colour = ColourStruct { 58 | colour_type: Colour::RGB, 59 | value: String::from("(255, 0, 0)") 60 | }; 61 | 62 | let hex_colour = ColourStruct { 63 | colour_type: Colour::Hex, 64 | value: String::from("ff0000") 65 | }; 66 | } 67 | 68 | #[test] 69 | /// 70 | /// Only tests the syntax 71 | fn test_storing_value_in_enum() { 72 | let rgb_colour = ColourWithValue::RGB(255, 0, 0); 73 | let hex_colour = ColourWithValue::Hex(String::from("ff0000")); 74 | } 75 | 76 | #[test] 77 | /// 78 | /// Only tests the syntax 79 | fn test_struct_in_tuple() { 80 | let rgb_colour = ColourWithStruct::RGB { 81 | blue: 0, 82 | red: 255, 83 | green: 0 84 | }; 85 | 86 | let hex_colour = ColourWithStruct::Hex(String::from("ff0000")); 87 | } 88 | } -------------------------------------------------------------------------------- /rust_tutorial/tests/14.rs: -------------------------------------------------------------------------------- 1 | extern crate core; 2 | 3 | #[cfg(test)] 4 | mod test14 { 5 | 6 | fn print_message(user_level: u8) { 7 | match user_level { 8 | 0 => println!("Welcome dear admin."), 9 | 1 => println!("Welcome back our best member."), 10 | 2 => println!("Hello. Please register first."), 11 | _ => println!("Bad Input") 12 | } 13 | } 14 | 15 | enum HttpStatus { 16 | Ok = 200, 17 | NotFound = 404, 18 | InternalServerError = 500 19 | } 20 | 21 | enum Colour { 22 | RGB(u16, u16, u16), 23 | Hex(String) 24 | } 25 | 26 | fn get_pair(slice: &[i32]) -> (i32, i32) { 27 | match slice { 28 | [e1] => (*e1, *e1), 29 | [e1, e2, .., e3, e4] => { 30 | let average1 = (e1 + e2).pow(2); 31 | let average2 = (e3 + e4).pow(2); 32 | (average1, average2) 33 | } 34 | [e1, .., e2] => (*e1, *e2), 35 | [] => (0, 0) 36 | } 37 | } 38 | 39 | #[test] 40 | fn test_match_literal_syntax() { 41 | let user_inputs: [u8;5] = [0, 1, 2, 3, 4]; 42 | for value in user_inputs.iter() { 43 | print_message(*value); 44 | } 45 | } 46 | 47 | struct RGB { 48 | red: u16, 49 | green: u16, 50 | blue: u16 51 | } 52 | 53 | struct RgbStruct { 54 | red: u16, 55 | green: u16, 56 | blue: u16 57 | } 58 | 59 | enum Colour2 { 60 | Transparent, 61 | RGB(RgbStruct), 62 | Hex(String), 63 | CMYK {cyan: f32, magenta: f32, yellow: f32, black: f32} 64 | } 65 | 66 | struct Foo(u8, u8); 67 | 68 | struct Point(u8, u8); 69 | 70 | fn print_point(Point(x, y): Point) { 71 | assert_eq!(x, 10); 72 | assert_eq!(y, 10); 73 | } 74 | 75 | #[test] 76 | fn test_enum_matching() { 77 | let a = HttpStatus::Ok; 78 | match a { 79 | HttpStatus::Ok => println!("passed"), 80 | HttpStatus::InternalServerError => panic!("Pattern matching for enum values failed"), 81 | HttpStatus::NotFound => panic!("Pattern matching for enum values failed") 82 | } 83 | } 84 | 85 | #[test] 86 | fn test_enum_value_extraction() { 87 | let a = Colour::RGB(255, 123, 30); 88 | let b = Colour::Hex(String::from("ff7b1e")); 89 | match a { 90 | Colour::RGB(red, green, blue) => { 91 | assert_eq!(red, 255); 92 | assert_eq!(green, 123); 93 | assert_eq!(blue, 30); 94 | } 95 | Colour::Hex(hex) => panic!("Invalid extraction") 96 | } 97 | 98 | match b { 99 | Colour::RGB(red, green, blue) => panic!("Invalid extraction"), 100 | Colour::Hex(hex) => assert_eq!(hex, "ff7b1e") 101 | } 102 | } 103 | 104 | #[test] 105 | fn test_literal_and_variable_in_match() { 106 | let a = Colour::RGB(255, 0, 0); 107 | match a { 108 | Colour::RGB(255, 0, 0) => println!("RED Colour. Here is a completely different code."), 109 | Colour::RGB(red, green, blue) => { 110 | panic!("bad match"); 111 | }, 112 | Colour::Hex(hex) => panic!("bad match") 113 | } 114 | } 115 | 116 | #[test] 117 | fn test_range_in_pattern() { 118 | match 'a' { 119 | 'A'...'Z' => panic!("bad match"), 120 | 'a'...'z' => println!("is a lowercase english character."), 121 | _ => panic!("bad match") 122 | } 123 | } 124 | 125 | #[test] 126 | fn test_or_in_patterns() { 127 | let a = 12.0; 128 | match a { 129 | 8.0...12.0 | 13.0...18.0 => println!("The store is open."), 130 | 12.0...13.0 => panic!("bad match"), 131 | _ => panic!("bad match") 132 | } 133 | } 134 | 135 | #[test] 136 | fn test_value_extraction_from_tuple_by_pattern() { 137 | let rgb = (113, 0, 0); 138 | match rgb { 139 | (red, 0, 0) => println!("This colour is a gradient of red. red value: {}", red), 140 | (red, green, blue) => panic!("bad match") 141 | } 142 | } 143 | 144 | #[test] 145 | fn test_value_extraction_from_struct_by_pattern() { 146 | let r1 = RGB { 147 | red: 113, 148 | green: 0, 149 | blue: 0 150 | }; 151 | match r1 { 152 | RGB {red: r, green: 0, blue: 0} => println!("This colour is a gradient of red. red value: {}", r), 153 | RGB {red, blue, green} => panic!("bad match") 154 | } 155 | } 156 | 157 | #[test] 158 | fn test_value_extraction_from_nested_struct_enum() { 159 | let rgb = Colour2::RGB(RgbStruct{ 160 | red: 255, 161 | green: 255, 162 | blue: 255 163 | }); 164 | match rgb { 165 | Colour2::Transparent => panic!("bad match"), 166 | Colour2::RGB(RgbStruct{red, green, blue}) => { 167 | assert_eq!(red, 255); 168 | assert_eq!(green, 255); 169 | assert_eq!(blue, 255); 170 | }, 171 | Colour2::Hex(hex_value) => panic!("bad match"), 172 | Colour2::CMYK {cyan: c, magenta: m, yellow: y, black: k} => panic!("bad match") 173 | } 174 | } 175 | 176 | #[test] 177 | fn test_reference_matching() { 178 | let colours = [ 179 | RgbStruct { 180 | red: 112, 181 | green: 0, 182 | blue: 0 183 | }, 184 | RgbStruct { 185 | red: 123, 186 | green: 0, 187 | blue: 0 188 | } 189 | ]; 190 | for rgb_reference in colours.iter() { 191 | match rgb_reference { 192 | &RgbStruct {red, blue: 0, green: 0} => println!("This is a kind of red colour."), 193 | RgbStruct {red, green, blue} => panic!("bad match") 194 | } 195 | } 196 | } 197 | 198 | #[test] 199 | fn test_pattern_guards() { 200 | let input = Foo(2, 9); 201 | match input { 202 | Foo(x, _) if x % 2 == 0 => println!("{} is an even number", x), 203 | Foo(x, y) => panic!("bad match") 204 | } 205 | } 206 | 207 | #[test] 208 | fn test_at_in_pattern() { 209 | let colour = RgbStruct { 210 | red: 50, 211 | blue: 20, 212 | green: 0 213 | }; 214 | match colour { 215 | RgbStruct {red: r @ 0...100, green: 0, blue} => println!("This is my colour:rgb({}, 0, {})", r, blue), 216 | _ => panic!("bad match") 217 | } 218 | } 219 | 220 | #[test] 221 | fn test_pattern_in_if_let() { 222 | let hour: u8 = 10; 223 | if let 0...24 = hour { 224 | println!("a valid hour"); 225 | } else { 226 | panic!("bad match"); 227 | } 228 | } 229 | 230 | #[test] 231 | fn test_pattern_in_while_let() { 232 | let mut counter = 0; 233 | while let 0 | 1 | 2 | 3 = counter { 234 | counter += 1; 235 | } 236 | assert_eq!(4, counter); 237 | } 238 | 239 | #[test] 240 | fn test_pattern_in_let() { 241 | let (a, b, c) = (10, String::from("A String"), false); 242 | assert_eq!(a, 10); 243 | assert_eq!("A String", b); 244 | assert_eq!(c, false); 245 | } 246 | 247 | fn test_pattern_extraction_in_function_input_parameter() { 248 | print_point(Point(10, 10)); 249 | } 250 | 251 | macro_rules! slice_tests { 252 | ($($name: ident: ($slice: expr, $expected_result: expr),) *) => { 253 | $( 254 | #[test] 255 | fn $name() { 256 | let a = [1, 2, 3, 4, 5, 6, 7, 8, 9]; 257 | let test_slice = &a[$slice]; 258 | let pair = get_pair(test_slice); 259 | assert_eq!(pair, $expected_result); 260 | } 261 | )* 262 | } 263 | } 264 | 265 | slice_tests!{ 266 | test_slice_pattern_single: (0..1, (1, 1)), 267 | test_slice_pattern_two: (..=1, (1, 2)), 268 | test_slice_pattern_three: (..3, (1, 3)), 269 | test_slice_pattern_more: (..=4, (9, 81)), 270 | test_slice_pattern_all: (.., (9, 289)), 271 | } 272 | 273 | #[test] 274 | fn test_slice_pattern_empty() { 275 | let pair = get_pair(&[]); 276 | assert_eq!(pair, (0, 0)); 277 | } 278 | } -------------------------------------------------------------------------------- /rust_tutorial/tests/15.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod test15 { 3 | trait Fly { 4 | fn fly(&self); 5 | fn land(&self); 6 | } 7 | 8 | struct Kaftar (); 9 | struct AirPlane(); 10 | 11 | impl Fly for Kaftar { 12 | fn fly(&self) { 13 | println!("Kafter The Kakol Be Sar is flying"); 14 | } 15 | 16 | fn land(&self) { 17 | println!("Kafter The Kakol Be Sar is landing"); 18 | } 19 | } 20 | 21 | 22 | impl Fly for AirPlane { 23 | fn fly(&self) { 24 | println!("Airplane is flying."); 25 | } 26 | 27 | fn land(&self) { 28 | println!("Airplane is landing."); 29 | } 30 | } 31 | 32 | fn fly_bird(flyable: &Fly) { 33 | flyable.fly(); 34 | } 35 | 36 | 37 | #[test] 38 | fn test_trait_syntax() { 39 | let kakol_be_sar = Kaftar{}; 40 | kakol_be_sar.fly(); 41 | kakol_be_sar.land(); 42 | } 43 | 44 | #[test] 45 | fn test_using_trait_object_as_fn_parameter() { 46 | let airplane = AirPlane{}; 47 | let kakol_be_sar = Kaftar{}; 48 | fly_bird(&airplane); 49 | fly_bird(&kakol_be_sar); 50 | } 51 | } -------------------------------------------------------------------------------- /rust_tutorial/tests/16.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod test16 { 3 | trait Fly { 4 | fn fly(&self); 5 | fn land(&self) { 6 | println!("Flyable Object now landing."); 7 | } 8 | } 9 | 10 | struct Kaftar (); 11 | struct AirPlane(); 12 | struct UnknownFlyable(); 13 | 14 | impl Fly for UnknownFlyable { 15 | fn fly(&self) { 16 | println!("Unknown flyable is flying."); 17 | } 18 | } 19 | 20 | impl Fly for Kaftar { 21 | fn fly(&self) { 22 | println!("Kafter The Kakol Be Sar is flying"); 23 | } 24 | 25 | fn land(&self) { 26 | println!("Kafter The Kakol Be Sar is landing"); 27 | } 28 | 29 | } 30 | 31 | impl Fly for AirPlane { 32 | fn fly(&self) { 33 | println!("Airplane is flying."); 34 | } 35 | 36 | fn land(&self) { 37 | println!("Airplane is landing."); 38 | } 39 | } 40 | 41 | impl Fly for String { 42 | fn fly(&self) { 43 | println!("Oh my گاج. It's a flying string!"); 44 | } 45 | } 46 | 47 | #[test] 48 | fn test_default_method_syntax() { 49 | let airplane = AirPlane{}; 50 | let kakol_be_sar = Kaftar{}; 51 | let unknown = UnknownFlyable{}; 52 | 53 | airplane.land(); 54 | kakol_be_sar.land(); 55 | unknown.land(); 56 | } 57 | 58 | #[test] 59 | fn test_implementing_custom_traits_for_default_types_syntax() { 60 | let flying_string = String::from("بغبغو"); 61 | flying_string.fly(); 62 | } 63 | } -------------------------------------------------------------------------------- /rust_tutorial/tests/17.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod test17 { 3 | trait Fly { 4 | fn new() -> Self; 5 | fn fly(&self); 6 | fn land(&self) { 7 | println!("Flyable Object now landing."); 8 | } 9 | } 10 | 11 | struct Kaftar (); 12 | 13 | impl Fly for Kaftar { 14 | fn new() -> Self { 15 | return Kaftar{}; 16 | } 17 | 18 | fn fly(&self) { 19 | println!("Kafter The Kakol Be Sar is flying"); 20 | } 21 | } 22 | 23 | trait Brush { 24 | fn draw(&self); 25 | fn change_colour(&self); 26 | } 27 | 28 | trait Screen { 29 | fn draw(&self); 30 | fn turnoff(&self); 31 | } 32 | 33 | struct Something(); 34 | 35 | impl Brush for Something { 36 | fn draw(&self) { 37 | println!("Draw a line on the paper."); 38 | } 39 | 40 | fn change_colour(&self) { 41 | println!("Brush colour changed."); 42 | } 43 | } 44 | 45 | impl Screen for Something { 46 | fn draw(&self) { 47 | println!("Draw a line on the screen"); 48 | } 49 | 50 | fn turnoff(&self) { 51 | println!("Screen turned off"); 52 | } 53 | } 54 | 55 | 56 | #[test] 57 | fn test_associated_function_call_syntax() { 58 | let kakol_be_sar = Kaftar::new(); 59 | kakol_be_sar.fly(); 60 | } 61 | 62 | #[test] 63 | fn test_calling_method_by_trait() { 64 | let something = Something{}; 65 | Brush::draw(&something); 66 | Screen::draw(&something); 67 | } 68 | 69 | #[test] 70 | fn test_calling_method_by_type() { 71 | let x = -10; 72 | i32::abs(x); 73 | } 74 | } -------------------------------------------------------------------------------- /rust_tutorial/tests/18.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod test18 { 3 | use std::mem; 4 | 5 | struct Point { 6 | x: Type, 7 | y: Type 8 | } 9 | 10 | impl Point { 11 | fn swap_coordinates(&mut self) { 12 | mem::swap(&mut self.x, &mut self.y); 13 | } 14 | } 15 | 16 | fn swap_point(original_point: Point) -> Point { 17 | let Point {x, y} = original_point; 18 | return Point { 19 | x: y, 20 | y: x 21 | } 22 | } 23 | 24 | enum Result { 25 | OK(T), 26 | Err(()) 27 | } 28 | 29 | #[test] 30 | fn test_type_casting_u8_to_i32() { 31 | let a: u8 = 10; 32 | let b: i32 = a as i32; 33 | assert_eq!(b, 10); 34 | } 35 | 36 | #[test] 37 | fn test_type_casting_signed_to_unsigned() { 38 | let a: i8 = -10; 39 | let b: u8 = a as u8; 40 | assert_eq!(b, 246); 41 | } 42 | 43 | #[test] 44 | fn test_type_casting_overflow() { 45 | let a: u64 = 1_000_000; 46 | let b: u8 = a as u8; 47 | assert_eq!(b, 64); 48 | } 49 | 50 | fn test_type_casting_bool_to_number() { 51 | let yes = true; 52 | let no = false; 53 | assert_eq!(yes as u8, 1); 54 | assert_eq!(no as u8, 0); 55 | } 56 | 57 | #[test] 58 | fn test_generic_swap_function() { 59 | let my_point = Point:: { 60 | x: 10, 61 | y: 12 62 | }; 63 | 64 | let swapped_point = swap_point(my_point); 65 | 66 | assert_eq!(swapped_point.x, 12); 67 | assert_eq!(swapped_point.y, 10); 68 | } 69 | 70 | #[test] 71 | fn test_generic_struct_generic_method_swap() { 72 | let mut my_point = Point:: { 73 | x: 10, 74 | y: 12 75 | }; 76 | my_point.swap_coordinates(); 77 | assert_eq!(my_point.x, 12); 78 | assert_eq!(my_point.y, 10); 79 | } 80 | 81 | #[test] 82 | fn test_generic_enum_syntax() { 83 | let mut my_point = Point:: { 84 | x: 10, 85 | y: 12 86 | }; 87 | 88 | let that_is_ok = Result::OK::>(my_point); 89 | 90 | match that_is_ok { 91 | Result::OK(Point {x, y}) => println!("x: {}, y: {}", x, y), 92 | Result::Err(_) => println!("An Error happened"), 93 | _ => {} 94 | }; 95 | } 96 | } -------------------------------------------------------------------------------- /rust_tutorial/tests/2.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod test2 { 3 | #[test] 4 | fn test_numeric_types_var_declaration() { 5 | let a: u64 = 1024; 6 | let b: i8 = -7; 7 | let c : usize = 800; 8 | let d = -64; 9 | } 10 | 11 | #[test] 12 | fn test_numeric_representations_vars() { 13 | let a = 123_456; 14 | let b = 0xf2; // hexadecimal 15 | let c = 0o71; // octal 16 | let d = 0b1110_0001; // binary 17 | let c = b'C'; // byte 18 | } 19 | 20 | #[test] 21 | fn test_u8_overflow() { 22 | #[allow(overflowing_literals)] 23 | let a:i8 = 0xf_f; 24 | assert_eq!(a, -1); 25 | } 26 | 27 | #[test] 28 | fn test_float_declaration() { 29 | let b: f32 = 2.95; 30 | let a = 2.95; 31 | } 32 | } -------------------------------------------------------------------------------- /rust_tutorial/tests/20.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod test20 { 3 | fn greatest_sum <'a>(array1: &'a [i32], array2: &'a [i32]) -> &'a [i32] { 4 | let mut sum1 = 0; 5 | let mut sum2 = 0; 6 | 7 | for i in array1 { 8 | sum1 += *i; 9 | } 10 | 11 | for j in array2 { 12 | sum2 += *j; 13 | } 14 | 15 | if sum1 > sum2 { 16 | return array1; 17 | } 18 | return array2; 19 | } 20 | 21 | #[derive(Debug)] 22 | struct MyStruct<'a> { 23 | name: &'a str, 24 | age: u8 25 | } 26 | 27 | impl<'a> MyStruct<'a> { 28 | fn change_name(&mut self, new_name: &'a str) -> &str { 29 | let old_name = self.name; 30 | self.name = new_name; 31 | return old_name; 32 | } 33 | } 34 | 35 | #[derive(Debug)] 36 | enum Something <'a> { 37 | Some(&'a u8), 38 | Thing(u8) 39 | } 40 | 41 | fn call_me() { 42 | static mut NUMBER_OF_CALLS: u8 = 0; 43 | unsafe { 44 | NUMBER_OF_CALLS += 1; 45 | println!("number of calls: {}", NUMBER_OF_CALLS); 46 | } 47 | } 48 | 49 | #[test] 50 | fn test_function_lifetime() { 51 | let arr1 = [1, 2, 3]; 52 | let arr2 = [1, 2, 3, 4]; 53 | let greatest_array = greatest_sum(&arr1, &arr2); 54 | 55 | assert_eq!(&arr2, greatest_array); 56 | } 57 | 58 | #[test] 59 | fn test_struct_method_lifetime() { 60 | let name = "Asghar"; 61 | let mut person = MyStruct { 62 | name, 63 | age: 10 64 | }; 65 | 66 | assert_eq!(person.name, "Asghar"); 67 | 68 | person.change_name("Akbar"); 69 | 70 | assert_eq!(person.name, "Akbar"); 71 | } 72 | 73 | #[test] 74 | fn test_enum_lifetime_syntax() { 75 | let number: u8 = 10; 76 | let a = Something::Some(&number); 77 | } 78 | 79 | #[test] 80 | fn test_mutable_static_syntax() { 81 | call_me(); 82 | } 83 | } -------------------------------------------------------------------------------- /rust_tutorial/tests/21.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod test21 { 3 | #[test] 4 | #[should_panic] 5 | fn test_panic_vector_invalid_index() { 6 | let a = vec![1, 2, 3, 4, 5, 6]; 7 | println!("This program will panic and this line never will print. {}", a[100]); 8 | } 9 | } -------------------------------------------------------------------------------- /rust_tutorial/tests/3.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod test3 { 3 | #[test] 4 | fn test_array_declaration() { 5 | let months = ["فروردین", "اردیبهشت", "خرداد", 6 | "تیر", "مرداد", "شهریور", 7 | "مهر", "آبان", "آذر", 8 | "دی", "بهمن", "اسفند"]; 9 | } 10 | 11 | #[test] 12 | fn test_array_access_by_index() { 13 | let months = ["فروردین", "اردیبهشت", "خرداد", 14 | "تیر", "مرداد", "شهریور", 15 | "مهر", "آبان", "آذر", 16 | "دی", "بهمن", "اسفند"]; 17 | assert_eq!(months[0], "فروردین"); 18 | assert_eq!(months[11], "اسفند"); 19 | } 20 | 21 | fn test_array_element_modification_by_index() { 22 | let mut months = ["فروردین", "اردیبهشت", "خرداد", 23 | "تیر", "مرداد", "شهریور", 24 | "مهر", "آبان", "آذر", 25 | "دی", "بهمن", "اسفند"]; 26 | assert_eq!(months[6], "مهر"); 27 | months[6] = "محمّدرضا علی حسینی"; 28 | assert_eq!(months[6], "محمّدرضا علی حسینی"); 29 | } 30 | 31 | #[test] 32 | fn test_array_shorthand() { 33 | let array = [0i32;7]; 34 | assert_eq!(array, [0, 0, 0, 0, 0, 0, 0]); 35 | } 36 | 37 | #[test] 38 | fn test_array_printing() { 39 | println!("my array is: {:?}", [10i8;10]); 40 | } 41 | 42 | #[test] 43 | fn test_tuple_declaration() { 44 | let tup0: (i32, char, bool, f64); 45 | let tup1 = (1, true, "سلام", 9.99); 46 | tup0 = (33, 'G', false, 9.87); 47 | } 48 | 49 | #[test] 50 | fn test_tuple_access_by_index() { 51 | let tup = (1, true, "سلام", 9.99); 52 | assert_eq!(tup.2, "سلام"); 53 | } 54 | 55 | #[test] 56 | fn test_tuple_extract_by_pattern_matching() { 57 | let tup = (1, true, "سلام", 9.99); 58 | let (x, y, v, z) = tup; 59 | assert_eq!(x, 1); 60 | assert_eq!(y, true); 61 | assert_eq!(v, "سلام"); 62 | assert_eq!(z, 9.99); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /rust_tutorial/tests/4.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod test4 { 3 | #[test] 4 | fn test_if_else() { 5 | let a = 5; 6 | if a < 10{ 7 | } 8 | else { 9 | panic!("Should not run the else"); 10 | } 11 | } 12 | 13 | #[test] 14 | fn test_multiple_else_if() { 15 | let user_type = "Guest"; 16 | let mut chosen_message: &str; 17 | if user_type == "Admin"{ 18 | 19 | chosen_message = "Hello dear Admin. You have full access to all the settings and you can change \ 20 | them if you want."; 21 | } 22 | else if user_type == "Member"{ 23 | chosen_message = "Welcome our beautiful member!"; 24 | } 25 | else if user_type == "Guest" { 26 | chosen_message = "Please register dear guest."; 27 | } 28 | else{ 29 | chosen_message = "I can not understand who you are. Get out right now."; 30 | } 31 | 32 | assert_eq!(chosen_message, "Please register dear guest.") 33 | } 34 | 35 | #[test] 36 | fn test_ternary_assignment() { 37 | let condition = true; 38 | let a = if condition { 39 | 0 40 | } 41 | else{ 42 | 1 43 | }; 44 | assert_eq!(a, 0); 45 | } 46 | } -------------------------------------------------------------------------------- /rust_tutorial/tests/5.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod test5 { 3 | #[test] 4 | fn test_loop_syntax() { 5 | loop { 6 | break; 7 | } 8 | } 9 | 10 | #[test] 11 | fn test_while() { 12 | let mut a = 1; 13 | while a % 10 != 0 { 14 | a += 1; 15 | } 16 | assert_eq!(a, 10); 17 | } 18 | 19 | #[test] 20 | fn test_for() { 21 | let mut result_array = [0i32;9]; 22 | let expected_array: [i32;9] = [2, 3, 4, 5, 6, 7, 8, 9, 10]; 23 | for counter in 2..11 { 24 | result_array[counter - 2] = counter as i32; 25 | } 26 | assert_eq!(expected_array, result_array); 27 | } 28 | 29 | #[test] 30 | fn test_array_iteration_by_for() { 31 | let my_array: [i32;5] = [1,2,3,4,5]; 32 | let mut expected_value: i32 = 0; 33 | for counter in 0..5 { 34 | expected_value += 1; 35 | assert_eq!(my_array[counter], expected_value); 36 | } 37 | } 38 | 39 | #[test] 40 | fn test_array_iteration_by_for_using_iter() { 41 | let my_array: [i32;5] = [1,2,3,4,5]; 42 | let mut expected_value: i32 = 0; 43 | for element in my_array.iter(){ 44 | expected_value += 1; 45 | assert_eq!(*element, expected_value); // using * because iter returns an reference 46 | } 47 | } 48 | 49 | } -------------------------------------------------------------------------------- /rust_tutorial/tests/6.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod test6 { 3 | 4 | fn duplicator(input_number : i32) -> i32 { 5 | let result = input_number * 2; 6 | return result; 7 | } 8 | 9 | fn duplicator_without_return(input_number : i32) -> i32 { 10 | input_number * 2 11 | } 12 | 13 | fn recursive_function(mut input_number: i32) { 14 | if input_number < 1 { 15 | return; 16 | } 17 | println!("{}", input_number); 18 | input_number -= 1; 19 | recursive_function(input_number); 20 | } 21 | 22 | #[test] 23 | fn test_duplicator_function() { 24 | assert_eq!(4, duplicator(2)); 25 | } 26 | 27 | #[test] 28 | fn test_duplicator_without_return() { 29 | assert_eq!(4, duplicator_without_return(2)); 30 | } 31 | 32 | #[test] 33 | /// Only tests syntax, not functionality 34 | fn test_recursive_function_syntax() { 35 | recursive_function(10); 36 | } 37 | } -------------------------------------------------------------------------------- /rust_tutorial/tests/7.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod test7 { 3 | const GLOBAL_CONSTANT: &str = "test"; 4 | 5 | fn i_am_owner(input: String) -> String { 6 | return input; 7 | } 8 | 9 | #[test] 10 | fn test_global_constant_access_in_function() { 11 | assert_eq!("test", GLOBAL_CONSTANT); 12 | } 13 | 14 | #[test] 15 | fn test_string_creation() { 16 | let my_string = String::from("یک رشته جدید."); 17 | assert_eq!(my_string, "یک رشته جدید."); 18 | } 19 | 20 | fn test_push_string() { 21 | let mut my_string = String::from("یک رشته جدید"); 22 | assert_eq!(my_string, "یک رشته جدید"); 23 | my_string.push_str(" که این متن به انتهایش اضافه شده است."); 24 | assert_eq!("یک رشته جدید که این متن به انتهایش اضافه شده است.", my_string); 25 | } 26 | 27 | #[test] 28 | fn test_ownership_move_and_back() { 29 | let mut a = String::from("hello"); 30 | a = i_am_owner(a); 31 | assert_eq!(a, "hello"); 32 | } 33 | } -------------------------------------------------------------------------------- /rust_tutorial/tests/8.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod test8 { 3 | fn i_am_owner(input: &String) { 4 | println!("The input value is: {}", input); 5 | } 6 | 7 | fn i_am_owner_referenced(input: &String) { 8 | assert_eq!(*input, "hello"); 9 | } 10 | 11 | fn modifier(reference: &mut String) { 12 | reference.push_str(" a new string to push to the old one"); 13 | } 14 | 15 | fn ali(original_text: &String) { 16 | println!("Ali says: {}", original_text); 17 | } 18 | fn hossein(text: &String) { 19 | println!("{} hossein", text); 20 | } 21 | fn mohammad (original_input: &mut String) { 22 | original_input.push_str("!"); 23 | } 24 | 25 | #[test] 26 | fn test_reference_passing() { 27 | let a = String::from("hello"); 28 | i_am_owner(&a); 29 | assert_eq!(a, "hello"); 30 | } 31 | 32 | #[test] 33 | fn test_dereferencing() { 34 | let a = String::from("hello"); 35 | i_am_owner_referenced(&a); 36 | } 37 | 38 | #[test] 39 | fn test_borrowing() { 40 | let mut a = String::from("hello"); 41 | modifier(&mut a); 42 | assert_eq!(a, "hello a new string to push to the old one"); 43 | } 44 | 45 | #[test] 46 | fn test_multiple_references() { 47 | let mut a = String::from("hello"); 48 | ali(&a); 49 | mohammad(&mut a); 50 | hossein(&a); 51 | assert_eq!(a, "hello!"); 52 | } 53 | 54 | } -------------------------------------------------------------------------------- /rust_tutorial/tests/9.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod test9 { 3 | fn first_not_negative_element(array: [i32; 7]) -> i32 { 4 | for (index, &item) in array.iter().enumerate() { 5 | if item > -1 { 6 | return item; 7 | } 8 | } 9 | return -1; 10 | } 11 | 12 | fn first_not_negative_element_sliced(array: &[i32; 7]) -> &[i32] { 13 | for (index, &item) in array.iter().enumerate() { 14 | if item > -1 { 15 | return &array[index..index + 1]; 16 | } 17 | } 18 | return &array[0..array.len()]; 19 | } 20 | 21 | #[test] 22 | fn test_first_not_negative_element() { 23 | let my_array = [-5, -3, -10, 0, 1, 8, 9]; 24 | let not_negative_item = first_not_negative_element(my_array); 25 | assert_eq!(not_negative_item, 0); 26 | } 27 | 28 | #[test] 29 | fn test_first_not_negative_element_sliced() { 30 | let mut my_array = [-5, -3, -10, 0, 1, 8, 9]; 31 | let not_negative_item = first_not_negative_element_sliced(&my_array); 32 | assert_eq!([0], not_negative_item); 33 | } 34 | 35 | #[test] 36 | fn test_first_not_negative_element_scoped() { 37 | let mut my_array = [-5, -3, -10, 0, 1, 8, 9]; 38 | { // New scope for slicing my_array 39 | let not_negative_item = first_not_negative_element_sliced(&my_array); 40 | assert_eq!(not_negative_item, [0]); 41 | } // End of the scope 42 | my_array = [7i32; 7]; 43 | assert_eq!(first_not_negative_element_sliced(&my_array), [7]); 44 | } 45 | 46 | #[test] 47 | fn test_first_not_negative_element_copy() { 48 | let my_array = [-5, -3, -10, 0, 1, 8, 9]; 49 | let not_negative_item = first_not_negative_element_sliced(&my_array); 50 | assert_eq!([0], not_negative_item); 51 | let mut my_second_array = my_array; // copying my_array to new variable 52 | my_second_array[0] = 100; 53 | assert_eq!([100], first_not_negative_element_sliced(&my_second_array)); 54 | } 55 | 56 | } --------------------------------------------------------------------------------