Rust Cheatsheet
Tags: rust, programming, webdev, softwareengineering
Published: 2024-05-07 04:30:31


### Basics

#### 1. Hello World

```rust
fn main() {
    println!("Hello, world!");
}
```

#### 2. Variables and Mutability

```rust
// Immutable variable
let x = 5;

// Mutable variable
let mut y = 10;
y = 15; // OK

// Constants
const MAX_POINTS: u32 = 100_000;
```

#### 3. Data Types

```rust
// Scalar Types
let num: i32 = -10;
let floating: f64 = 3.14;
let is_true: bool = true;
let character: char = 'a';

// Compound Types
let tuple: (i32, f64, bool) = (500, 6.4, true);
let array: [i32; 5] = [1, 2, 3, 4, 5];
```

### Control Flow

#### 1. If Statement

```rust
let number = 6;

if number % 2 == 0 {
    println!("Even");
} else {
    println!("Odd");
}
```

#### 2. Loop

```rust
let mut counter = 0;

loop {
    counter += 1;

    if counter == 5 {
        break;
    }
}
```

#### 3. While Loop

```rust
let mut countdown = 5;

while countdown > 0 {
    println!("{}", countdown);
    countdown -= 1;
}
```

#### 4. For Loop

```rust
let numbers = [1, 2, 3, 4, 5];

for num in numbers.iter() {
    println!("{}", num);
}
```

### Functions

#### 1. Basic Function

```rust
fn greet(name: &str) {
    println!("Hello, {}!", name);
}

greet("Ali");
```

#### 2. Functions with Return Values

```rust
fn add(a: i32, b: i32) -> i32 {
    a + b
}

let result = add(5, 3);
```

### Error Handling

#### 1. Result Type

```rust
fn divide(a: f64, b: f64) -> Result<f64, &'static str> {
    if b == 0.0 {
        return Err("Division by zero");
    }
    Ok(a / b)
}

match divide(10.0, 2.0) {
    Ok(result) => println!("Result: {}", result),
    Err(err) => println!("Error: {}", err),
}
```

### Ownership, Borrowing, and Lifetimes

#### 1. Ownership

```rust
let s1 = String::from("hello");
let s2 = s1; // Ownership moved to s2
```

#### 2. Borrowing

```rust
fn calculate_length(s: &String) -> usize {
    s.len()
}

let s = String::from("hello");
let len = calculate_length(&s); // Borrowed s
```

#### 3. Lifetimes

```rust
fn longest<'a>(s1: &'a str, s2: &'a str) -> &'a str {
    if s1.len() > s2.len() {
        s1
    } else {
        s2
    }
}
```

### Advanced Concepts

#### 1. Structs

```rust
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

let rect = Rectangle { width: 10, height: 20 };
let area = rect.area();
```

#### 2. Enums

```rust
enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter,
}

fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Penny => 1,
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter => 25,
    }
}
```

#### 3. Traits

```rust
trait Vehicle {
    fn drive(&self);
}

struct Car;

impl Vehicle for Car {
    fn drive(&self) {
        println!("Car is driving...");
    }
}

let car = Car;
car.drive();
```

### Conclusion

This Rust cheatsheet provides a quick overview of essential concepts and syntax in Rust programming language, catering to beginners and intermediate developers alike. Whether you're building a small utility or a complex system, Rust's safety features and performance make it an excellent choice for various applications.