Rust Cheat Sheet

Here’s a cheat sheet for Rust, a systems programming language:

Hello, World!

fn main() {
    println!("Hello, World!");
}

Variables and Mutability

Immutable Variable:

let x = 5;

Mutable Variable:

let mut y = 10;
y = y + 1;

Data Types

Integer:

let num: i32 = 42;

Floating Point:

let pi: f64 = 3.14159;

Boolean:

let is_true: bool = true;

Character:

let c: char = 'A';

String:

let s: String = String::from("Hello, Rust!");

Control Flow

If-Else:

let number = 5;
if number > 0 {
    println!("Positive");
} else {
    println!("Non-positive");
}

Match (Pattern Matching):

let day = "Wednesday";
match day {
    "Monday" => println!("It's Monday!"),
    "Friday" | "Saturday" => println!("Weekend!"),
    _ => println!("It's a regular day."),
}

Loop:

let mut counter = 0;
loop {
    println!("Count: {}", counter);
    counter += 1;
    if counter == 5 {
        break;
    }
}

While Loop:

let mut i = 0;
while i < 5 {
    println!("Count: {}", i);
    i += 1;
}

For Loop:

for num in 1..=5 {
    println!("Number: {}", num);
}

Functions

Function Definition:

fn add(x: i32, y: i32) -> i32 {
    x + y
}

Function Call:

let result = add(3, 5);

Structs

Define a Struct:

struct Point {
    x: f64,
    y: f64,
}

Create an Instance:

let origin = Point { x: 0.0, y: 0.0 };

Enums

Define an Enum:

enum Direction {
    Up,
    Down,
    Left,
    Right,
}

Use Enum Values:

let my_direction = Direction::Up;

Ownership and Borrowing

Ownership and Move:

let s1 = String::from("Hello");
let s2 = s1;
// s1 is no longer valid

Borrowing:

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

let s = String::from("Rust");
let len = calculate_length(&s);

Lifetimes

Function with Lifetimes:

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

Error Handling

Result and unwrap():

let result: Result<i32, &str> = Ok(42);
let value = result.unwrap();

Pattern Matching Result:

let result: Result<i32, &str> = Ok(42);
match result {
    Ok(value) => println!("Value: {}", value),
    Err(error) => println!("Error: {}", error),
}

This cheat sheet covers some basics of Rust programming. For more detailed information and advanced topics, refer to the official Rust documentation.