Rust Lectures2
Rust Lectures2
=======================================================================================================
- **Initiation (2006)**:
Rust was first conceived by Mozilla Research with the goal of creating a
systems programming language that would offer both performance and safety.
- **Continuous Evolution**:
Since then, Rust has seen numerous updates, adding features like async/await
(Rust 1.39), improved borrow checker diagnostics, and more, solidifying its
position in the programming landscape.
- **Memory Safety**:
Rust's ownership model and borrow checker ensure memory safety at compile
time, preventing null or dangling pointers.
- **Error Handling**:
Strong focus on explicit error handling through `Result` and `?`,
encouraging robust code.
01
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
- **Compiled Language**:
Rust code is compiled to machine code, providing performance similar to C
and C++.
- **Zero-Cost Abstractions**:
High-level abstractions without runtime overhead, thanks to its compilation
model.
- **Fearless Concurrency**:
Thanks to its safety features, Rust aims to make concurrency less daunting.
1. **Install `rustup`**:
- Go to [https://www.rust-lang.org/tools/install](https://www.rust-lang.org/
tools/install) and follow the installation instructions for your platform.
- `rustup` is the recommended toolchain installer for Rust.
2. **Verify Installation**:
- Open a new terminal or command prompt.
- Type `rustc --version` to verify the Rust compiler version.
- Type `cargo --version` to verify the package manager's version.
02
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
3. **Understanding `cargo`**:
- **Package Manager**: Manages dependencies for your projects.
- **Build System**: Compiles your project with a simple command.
- **Project Structure**: Initializes new projects with a conventional
directory structure.
```bash
cargo new hello_world
```
Navigate into the newly created project directory.
- **`main.rs` Contents (Generated by `cargo`)**:
fn main() {
println!("Hello, world!");
}
```bash
cargo run
```
03
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
- **Read Documentation**:
[https://doc.rust-lang.org/](https://doc.rust-lang.org/) is an invaluable
resource.
**Lecture Conclusion**
- You've now set up a Rust development environment.
- Successfully compiled and ran your first Rust program, "Hello, World!".
- Understand the foundational aspects of Rust: Safety, Performance, and
Concurrency.
.
**Homework/Next Steps**
- Dive deeper into Rust’s safety features with tutorials on ownership and
borrowing.
- Experiment with simple command-line tools using `cargo` and Rust.
- Explore projects on [crates.io](https://crates.io/) to see how dependencies
are managed in real-world projects.
04
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
* **Exercises**:
1. Modify the "Hello, World!" program to print your name.
2. Explore the Rust documentation for more `println!` macros.
1. **Integers**:
Whole numbers, either positive, negative, or zero (e.g., `-5`, `0`, `123`).
3. **Booleans**:
Logical values representing true or false.
4. **Characters**:
Single symbols, such as letters, digits, or special characters (e.g., `'a'`,
`'1'`, `'!'`).
05
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
#### **Scalars**
3. **Booleans (`bool`)**:
* Can be either `true` or `false`
4. **Characters (`char`)**:
* Represented as Unicode scalar values (e.g., `'a'`, `' 👍'`)
#### **Compound Types**
Compound types group multiple values into one.
1. **Tuples**:
* Fixed length, heterogeneous (can contain different data types).
* Defined using parentheses `()`.
* Example: `(i32, f64, char)`
2. **Arrays**:
* Fixed length, homogeneous (all elements must have the same data type).
* Defined using square brackets `[]`.
* Example: `[i32; 5]` (an array of 5 `i32` values)
06
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
h
fn main()
{
// Scalars
let signed_int: i32 = -20;
let unsigned_int: u8 = 255;
let pi: f64 = 3.141592653589793; // Default is f64 for float literals
let isAdmin: bool = true;
let smiley: char = ' '; 👍
// Compound Types
let person: (String, i32, f64) = (
String::from("John Doe"),
30,
1.83 // Height in meters
);
* **Declaration**:
Use the `let` keyword.
* **Immutability by Default**:
Variables are immutable unless explicitly made mutable with `mut`.
* **Type Inference**:
Rust can often infer the type of a variable from its initial value, but
explicit types are recommended for clarity and safety.
07
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
// Mutable variable
let mut age = 25;
age = 30; // This is allowed because 'age' is mutable
### **Exercises**
* **Interactivity**:
Allows programs to respond differently based on user actions or data.
08
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
* **Customization**:
Enhances user experience by enabling personalized interactions.
* **Data Collection**:
Crucial for gathering information from users, which can be processed or stored.
* **Dynamic Behavior**:
Programs can adapt their behavior based on input, making them more
versatile.
* **Displaying Text/Messages**:
Informing the user about program states, results, or errors.
* **Visual Feedback**:
Enhancing user experience through intuitive visual cues (e.g., progress
bars).
* **Logging**:
Recording events for debugging, auditing, or analytics purposes.
| **Operation** | **Description** |
| --- | --- |
| `print!()` | Displays text without a newline. |
| `println!()` | Prints text followed by a newline character.|
| `input()`/`readline()` | Reads user input until a delimiter |
(usually a newline). |
09
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
input/output operations.
**Key Concepts:**
* **Buffers**:
Temporary storage for data being moved from one place to another (e.g., from
keyboard to program).
* **Error Handling**:
Crucial in I/O operations due to potential failures (e.g., invalid input,
device errors).
use std::io;
fn main() {
// Prompt user for their name
println!("Please enter your name:");
// Create a mutable String to store the user's input
let mut user_name = String::new();
10
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
.
1. **Import `std::io`**:
Access Rust's input/output functionality.
2. **Prompt User**:
Inform the user what action to take using `println!`.
5. **Error Handling**:
Utilize `.expect()` to handle potential errors during input reading.
6. **Process and Output**:
* Trim the newline character from the input using `.trim()`.
* Greet the user by printing out their name with `println!`.
### **Exercises**
1. **Enhanced Greeting Program**:
* Modify the example to also ask for the user's age and print out a
greeting with their name and age.
2. **Simple Calculator**:
11
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
* Create a program that prompts the user for two numbers and an operation
(+, -, \*, /), then performs and displays the result.
3. **Input Validation**:
* Expand on the calculator exercise by adding input validation to ensure
the user enters valid numbers and operations.
fn main()
{
println!("Please enter your name:");
fn main()
{
print!("Hello, "); // No newline
println!("World!"); // With newline
println!("---");
print!("This is ");
print!("a test.");
}
12
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
**Output:**
Hello, World!
---
This is a test.
```
### **Placeholder Basics - `{}`**
- Use `{}` as placeholders for values.
fn main()
{
let name = "Alice";
let age = 30;
println!("My name is {} and I am {}.", name, age);
}
**Output:**
My name is Alice and I am 30.
fn main()
{
let numbers = [1, 2, 3, 4, 5];
for num in &numbers
{
println!("Number: {}", num);
}
}
**Output:**
```
Number: 1
Number: 2
Number: 3
13
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
Number: 4
Number: 5
.
fn main()
{
let fruits = ["Apple", "Banana", "Cherry"];
for (i, fruit) in fruits.iter().enumerate()
{
print!("{}: {}, ", i+1, fruit);
}
println!(); // Newline after the loop
}
**Output:**
1: Apple, 2: Banana, 3: Cherry,
fn main()
{
let pi = 3.14159265359;
println!("Pi (default): {}", pi);
println!("Pi (width 5, precision 2): {:5.2}", pi);
println!("Pi (left-aligned width 5, precision 2): {:<5.2}", pi);
println!("Pi (right-aligned width 5, precision 2): {:>5.2}", pi);
println!("Pi (centered width 5, precision 2): {:^5.2}", pi);
}
14
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
**Output:**
Pi (default): 3.14159265359
Pi (width 5, precision 2): 3.14
Pi (left-aligned width 5, precision 2): 3.14
Pi (right-aligned width 5, precision 2): 3.14
Pi (centered width 5, precision 2): 3.14
fn main() {
let students =
[
("John", 18, "Math"),
("Alice", 20, "Science"),
("Bob", 19, "History"),
];
**Output:**
15
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
* **Definition**:
Instructions that allow a program to make decisions based on conditions or
rules.
* **Purpose**:
Enable conditional execution of code blocks, enhancing program flexibility
and responsiveness.
* **Basic Structure**:
1. `if` *condition*: Execute if true
2. `else`: Optional, execute if initial condition(s) are false
3. `else if` *condition*: Additional conditions to check before reaching
the final `else` (if present)
* **Example in Pseudocode**:
```markdown
IF it_is_raining THEN
TAKE umbrella
ELSE IF it_is_sunny THEN
WEAR sunglasses
ELSE
DRESS normally
```
* **Definition**:
Placing conditional statements inside other conditional statements.
* **Use Case**:
Handling complex, multi-layered decision-making processes.
16
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
* **Example in Pseudocode**:
```markdown
IF user_is_authenticated THEN
IF user_has_admin_rights THEN
DISPLAY admin_dashboard
ELSE
DISPLAY standard_dashboard
ELSE
REDIRECT to_login_page
fn main()
{
let secret_number = 42;
let guess = 41;
if guess < secret_number
{ println!("Too small!"); }
else if guess > secret_number
{ println!("Too big!"); }
else{ println!("You win!"); }
}
17
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
fn main()
{
let maybe_number = Some(42);
if let Some(number) = maybe_number
{ println!("The number is: {}", number); }
else
{ println!("No number present."); }
}
#### **Additional Rust Features**
let day = 2;
match day
{
1 => println!("Monday"),
2 => println!("Tuesday"),
_ => println!("Another day"), // `_` catches any unmatched value
}
18
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
* **Keep it Concise**:
Prefer `if let` and `match` for readability.
* **Handle All Cases**:
Use `_` in `match` statements to ensure exhaustiveness.
* **Nest Conditionals Judiciously**:
Deep nesting can reduce readability; consider refactoring or using alternative
logic structures.
.
### **Exercises**
1. **Grade Checker**:
* Write a program that takes a score as input and uses conditional statements
to print out the corresponding grade (A-F).
let number = 3;
if number > 5 {
println!("condition was true");
} else {
println!("condition was false");
}
* **Nested If Statements**
+ Using `if` inside `if`
+ Best practices for readability
+ Example:
19
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
let x = 5;
if x > 10
{
if x > 20
{
println!("x is greater than 20");
}
else
{
println!("x is between 10 and 20");
}
}
* **Exercises**:
1. Implement a simple calculator with conditional statements for
operations.
2. Use `if let` to handle different conditions based on a variable's
value.
### Lecture 6: Loops in Rust Language ###
* **Definition**:
Loops enable iterative execution of code blocks, allowing tasks to repeat under
specified conditions.
1. **Infinite/Unconditional Loops**:
* Execute indefinitely until manually stopped or a break condition is met.
20
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
2. **Conditional Loops**:
* **Pre-Tested (While)**: Check the condition before each iteration.
* **Post-Tested (Do-While)**: Execute at least once, then check the
condition.
3. **Counter/For Loops**:
* Iterate over a sequence (e.g., arrays, ranges) or collections.
* **Syntax**:
```rust
loop {
// Code to execute indefinitely
} ```
fn main()
{
loop
{
println!("Server is running...");
// Simulate some work
std::thread::sleep(std::time::Duration::from_secs(2));
}
}
21
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
* **Syntax**:
```rust
while *condition* {
// Code to execute while condition is true
}
```
fn main()
{
let secret_number = 42;
let mut attempts = 0;
let max_attempts = 3;
22
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
}
}
#### `for` Loop (Counter/Iterator-Based Loop)**
* **Syntax ( Iterator-Based )**:
```rust
for *pattern* in *iterator* {
// Code to execute for each item
}
```
* **Example: Iterating Over an Array**:
fn main()
{
let numbers = [1, 2, 3, 4, 5];
fn main()
{
for i in 1..=5
{
println!("Number: {}", i);
}
}
23
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
* **`loop` with Labels**: Allow `break` and `continue` to target outer loops.
```rust
'outer_loop: loop {
loop {
break 'outer_loop; // Exits the outer loop
}
}
```
* **`while let` for Conditional Loops with Pattern Matching**:
### **Exercises**
1. **Fibonacci Sequence**:
* Use a `while` loop to print the first 10 Fibonacci numbers.
2. **Iterator-Based Loop**:
* Create a vector of names and use a `for` loop to print each name in
uppercase.
3. **Game Development - Tic-Tac-Toe**:
24
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
* Implement a simple game loop using `loop` that continues until the game is
won or drawn.
// Loop
let mut counter = 0;
loop
{
counter += 1;
if counter == 10
{
break;
}
println!("Again!");
}
// While
let mut number = 3;
while number != 0
{ println!("{}!", number);
number -= 1; }
// For
let a = [10, 20, 30, 40, 50];
for element in a.iter()
{
println!("the value is: {}", element);
}
25
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
* **Exercises**:
1. Use `loop` to continuously ask for user input until a specific
condition.
2. Create a multiplication table using nested `for` loops.
fn main() {
for i in 1..4 { // Outer loop (Rows)
for j in 1..4 { // Inner loop (Columns)
print!("({}, {}) ", i, j);
}
println!(); // Newline after each row
}
}
26
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
**Output:**
(1, 1) (1, 2) (1, 3)
(2, 1) (2, 2) (2, 3)
(3, 1) (3, 2) (3, 3)
fn main() {
for i in 1..4
{
for j in 1..4
{
print!("{:>5}", format!("({}, {})", i, j)); // Right-aligned, width 5
}
println!();
}
}
**Output:**
(1, 1) (1, 2) (1, 3)
(2, 1) (2, 2) (2, 3)
(3, 1) (3, 2) (3, 3)
fn main() {
print!(" {:>4}", ""); // Header spacing
for i in 1..10
{
print!("{:>4}", i); // Column headers
}
println!();
for i in 1..10
27
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
{
print!("{:>4}", i); // Row headers
for j in 1..10
{
print!("{:>4}", i*j);
}
println!();
}
}
**Output:**
1 2 3 4 5 6 7 8 9
1 1 2 3 4 5 6 7 8 9
2 2 4 6 8 10 12 14 16 18
3 3 6 9 12 15 18 21 24 27
4 4 8 12 16 20 24 28 32 36
5 5 10 15 20 25 30 35 40 45
6 6 12 18 24 30 36 42 48 54
7 7 14 21 28 35 42 49 56 63
8 8 16 24 32 40 48 56 64 72
9 9 18 27 36 45 54 63 72 81
### **Challenge: Nested Loop Formatted Output**
- Create a Rust program that prints a chessboard pattern using asterisks (\*)
and dots (.) in an 8x8 grid, utilizing nested loops for formatted output.
- Experiment with different placeholder formats to enhance the appearance of
your output.
28
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
29
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
```rust
let array_name: [data_type; size] = [initial_values];
```
```rust
array_name[n]
```
* **Example: Accessing the Second Element of `scores`**:
```rust
let second_score = scores[1]; // Returns 20
30
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
```rust
array_name[n] = new_value;
```
* **Example: Updating the Third Score**:
```rust
scores[2] = 35; // Updates the third element to 35
println!("Updated Scores: {:?}", scores);
```
31
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
```
* **Immutable Arrays Cannot Be Modified**:
```rust
let immutable_array = [1, 2, 3];
immutable_array[0] = 5; // Compiler Error!
```
### **Examples**
32
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
### **Exercises**
1. **Declare an array `colors` with 3 string elements**. Access and print the
second color.
* **Example Code**:
fn main()
{
let scores: [i32; 5] = [10, 20, 30, 40, 50];
* **Exercises**:
1. Calculate the sum of all elements in an array.
2. Find the maximum value in an array.
33
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
34
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
**Breakdown:**
- `i32`: The type of elements in the array.
- `[3]`: Specifies that each sub-array (row) will have exactly 3 elements.
- `; 3`: Indicates there are 3 rows in total.
fn main()
{
let mut arr_2d: [[i32; 3]; 3] =
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// Accessing an Element
35
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
// Modifying an Element
arr_2d[1][2] = 10;
println!("Modified Array:");
for row in &arr_2d
{
println!("{:?}", row);
}
}
**Output:**
Element at (1,2): 6
Modified Array:
[1, 2, 3]
[4, 5, 10]
[7, 8, 9]
#### **Use Cases for 2D Arrays**
- **Game Boards:**
Representing tic-tac-toe, chess, or any game that requires a grid structure.
- **Matrix Operations:**
Useful in linear algebra for operations like matrix multiplication.
- **Fixed-Size Tables:**
When the size of the data is known beforehand and doesn’t change.
36
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
fn main()
{
// Creating a New Empty Vector
let mut my_vec: Vec<i32> = Vec::new();
// Modifying an Element
if let Some(last_element) = my_vec.last_mut()
{
*last_element = 20;
}
println!("Vector after modification: {:?}", my_vec); // [5, 20]
}
37
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
- **Dynamic Size:**
Vectors can grow or shrink dynamically as elements are added or removed.
- **Memory Management:**
Rust handles the memory for vectors, reducing the risk of memory-related
bugs.
- **Flexibility:**
Useful in scenarios where the amount of data is unknown until runtime.
### **Conclusion**
This lecture has provided a comprehensive overview of working with two
dimensional arrays in Rust, including declaration, accessing, and modifying
elements. Additionally, it introduced vectors as a powerful tool for dynamic
collection management, highlighting their creation, initialization,
modification, and inherent advantages over fixed-size arrays. Understanding
these concepts is crucial for effectively handling data in Rust programming.
2. **Vector Manipulations:**
- Create a vector, add elements dynamically based on user input, and then
print the updated vector.
- Write a function that takes a vector as an argument, sorts it in ascending
order, and returns the sorted vector.
38
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
fn main()
{
let matrix: [[i32; 3]; 3] =
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
fn main()
{
let mut vec = vec![1, 2, 3];
vec.push(4);
println!("{:?}", vec); // Prints: [1, 2, 3, 4]
}
* **Exercises**:
1. Perform operations on a 2D array (e.g., transpose).
2. Explore vector methods (`pop`, `insert`, etc.).
39
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
1. **Reusability**:
Write once, use many times. Functions allow you to encapsulate code that
performs a specific task, reducing duplication.
2. **Modularity**:
Break down large programs into manageable pieces, making your code more
organized and easier to maintain.
3. **Abstraction**:
Hide complex implementation details from the caller, providing a simple
interface to interact with your code.
40
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
// Declaring a function
fn say_hello()
{
println!("Hello, World!");
}
fn main()
{
// Calling the function
say_hello();
}
fn greet(name: &str) {
println!("Hello, {}!", name);
}
fn main() {
greet("Alice");
}
41
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
fn main()
{
let result = add(5, 3);
println!("Result: {}", result); // Outputs: Result: 8
}
* `-> i32` specifies the return type of the function as `i32`.
* The last expression in the function body is implicitly returned (in this case,
`x + y`).
* In `main`, we assign the returned value to `result`.
42
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
fn main()
{
just_print();
}
* **Overview**:
This lecture covered defining reusable functions in Rust with parameters,
understanding how to declare and call them, work with various parameter types,
and handle return types including the unit type `()`.
* **Learning Objectives**:
1. **Define functions with various parameter types**:
* Demonstrated with `&str` (string slice) and `i32` (integer)
examples.
2. **Understand return types and the unit type `()`**:
* Shown through explicit `-> i32` return type declaration and
implicit/default `()` type.
2. **Calculator Functions**:
Implement separate functions for basic arithmetic operations (addition,
subtraction, multiplication, division) that take two numbers as parameters
43
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
### Overview
Understanding and manipulating strings is a fundamental aspect of
programming in any language, including Rust. This lecture delves into the
world of strings in Rust, covering the declaration, manipulation, and basic
operations that can be performed on string types, specifically `String` and
`&str`.
* **Definition**:
A string slice (`&str`) is a reference to a contiguous sequence of
characters (a string) that is stored elsewhere in memory.
* **Declaration**:
```rust
let hello: &str = "Hello, World!";
44
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
```
* **Key Points**:
+ Immutable by default.
+ The string data is typically stored in the binary itself when directly
assigned as shown above.
+ Can be used for substrings or referencing parts of a `String`.
* **Declaration**:
```rust
let mut hello: String = String::from("Hello, ");
```
* **Key Points**:
+ Mutable by declaration with `mut`.
+ Requires the `std::string` module, though usually in scope by default.
+ Can grow or shrink in size at runtime.
### a. Concatenation
* **Using `+` Operator**: Requires one operand to be `&str` and the other to be
`String`. The result is a new `String`.
45
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
```rust
let hello = "Hello, ";
let world = "World!";
let hello_world = format!("{}{}", hello, world);
println!("{}", hello_world); // Outputs: Hello, World!
```
* **Note on Indices**:
Be cautious with direct indexing (`&s[n]`) as it can panic if out
of bounds. Slicing (`&s[m..n]`) also risks panicking if the range is out of
bounds.
* **Length**:
* **Contains**:
46
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
## Examples
fn main()
{
// Declare a mutable string
let mut greeting: String = String::from("Hello, ");
fn main()
{
let s: &str = "Initial Content";
let mut owned: String = s.to_string();
47
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
### Conclusion
### Homework/Exercises
1. **String Reversal**:
Write a function to reverse a given string.
2. **Case Conversion**:
Implement functions to convert a string to all uppercase and all lowercase.
3. **String Searching**:
Create a program that searches for a substring within a larger text,
highlighting the first occurrence.
fn main()
{
let mut s = String::from("Hello, ");
s.push_str("Rust!");
println!("{}", s); // "Hello, Rust!"
{
greet("Alice");
let result = add(1, 2);
println!("Sum: {}", result);
}
48
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
* **Exercises**:
1. Create a function to calculate the area of a rectangle.
2. Implement a function with optional parameters (using `Option`).
49
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
* **Learning Objectives**:
use std::fs::File;
use std::io::{self, BufRead};
50
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
use std::fs::File;
use std::io;
* **Exercises**:
* **Overview**: Working with binary files for more complex data storage.
* **Learning Objectives**:
51
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
use std::fs::File;
use std::io::{self, Write};
#[derive(Debug)]
struct Person
{
name: String,
age: u8,
}
* **Note**: This example uses the `bincode` crate for serialization. Ensure to
add it as a dependency in
your `Cargo.toml`.
* **Exercises**:
52
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
* **Overview**:
Mastering robust error handling and insightful logging for reliable
applications.
* **Learning Objectives**:
+ Deep dive into `Result` and `Option` for error propagation.
+ Custom error types with `thiserror`.
+ Logging strategies using the `log` crate and its ecosystem (e.g.,
`env_logger`, `tracing`).
* **Example Code**:
use thiserror::Error;
#[derive(Error, Debug)]
enum MyError {
#[error("Failed to read file: {0}")]
Io(#[from] std::io::Error),
#[error("Invalid data")]
InvalidData,
}
* **Exercises**:
1. Implement comprehensive error handling for a command-line tool.
2. Set up logging for a web server using `actix-web` and `tracing`.
53
.Rust Programming Language / Department of Computer Science / By: Saif Basheer Mohammed AlKhoja.
=======================================================================================================
54