DEV Community

Syed Muhammad Ali Raza
Syed Muhammad Ali Raza

Posted on

17 3 1 2 1

Rust Cheatsheet

Basics

1. Hello World

fn main() {
    println!("Hello, world!");
}
Enter fullscreen mode Exit fullscreen mode

2. Variables and Mutability

// Immutable variable
let x = 5;

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

// Constants
const MAX_POINTS: u32 = 100_000;
Enter fullscreen mode Exit fullscreen mode

3. Data Types

// 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];
Enter fullscreen mode Exit fullscreen mode

Control Flow

1. If Statement

let number = 6;

if number % 2 == 0 {
    println!("Even");
} else {
    println!("Odd");
}
Enter fullscreen mode Exit fullscreen mode

2. Loop

let mut counter = 0;

loop {
    counter += 1;

    if counter == 5 {
        break;
    }
}
Enter fullscreen mode Exit fullscreen mode

3. While Loop

let mut countdown = 5;

while countdown > 0 {
    println!("{}", countdown);
    countdown -= 1;
}
Enter fullscreen mode Exit fullscreen mode

4. For Loop

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

for num in numbers.iter() {
    println!("{}", num);
}
Enter fullscreen mode Exit fullscreen mode

Functions

1. Basic Function

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

greet("Ali");
Enter fullscreen mode Exit fullscreen mode

2. Functions with Return Values

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

let result = add(5, 3);
Enter fullscreen mode Exit fullscreen mode

Error Handling

1. Result Type

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),
}
Enter fullscreen mode Exit fullscreen mode

Ownership, Borrowing, and Lifetimes

1. Ownership

let s1 = String::from("hello");
let s2 = s1; // Ownership moved to s2
Enter fullscreen mode Exit fullscreen mode

2. Borrowing

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

let s = String::from("hello");
let len = calculate_length(&s); // Borrowed s
Enter fullscreen mode Exit fullscreen mode

3. Lifetimes

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

Advanced Concepts

1. Structs

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();
Enter fullscreen mode Exit fullscreen mode

2. Enums

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,
    }
}
Enter fullscreen mode Exit fullscreen mode

3. Traits

trait Vehicle {
    fn drive(&self);
}

struct Car;

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

let car = Car;
car.drive();
Enter fullscreen mode Exit fullscreen mode

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.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay