Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save abhishekmishragithub/c2f6b046fce0befeb28730b1b8670164 to your computer and use it in GitHub Desktop.
Save abhishekmishragithub/c2f6b046fce0befeb28730b1b8670164 to your computer and use it in GitHub Desktop.
Rust beginner cheatsheet

Primitive Types

Integer

Declares an integer x with value 1.

let x: i32 = 1;

Floating point

Declares a floating-point y with value 3.14.

let y: f64 = 3.14;

Boolean

Declares a boolean z with value true.

let z: bool = true;

Character

Declares a character a with value 'a'.

let a: char = 'a';

String

Declares a string s with value "hello".

let s: String = String::from("hello");

Control Flow

If

If x is greater than 5, print "x is greater than 5". Otherwise, print "x is not greater than 5".

if x > 5 {
    println!("x is greater than 5");
} else {
    println!("x is not greater than 5");
}

Loop

Loop indefinitely, printing "Loop forever!".

loop {
    println!("Loop forever!");
}

While

While x is greater than 5, print "x is greater than 5".

while x > 5 {
    println!("x is greater than 5");
}

For

For i in the range 0 to 5, print i.

for i in 0..5 {
    println!("{}", i);
}

Match

Match x to different patterns and execute code accordingly.

match x {
    1 => println!("one"),
    2 => println!("two"),
    _ => println!("anything"),
}

Functions

Function definition

Defines a function add that takes two i32 parameters and returns an i32.

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

Function call

Calls the function add with arguments 5 and 7, and stores the result.

let result = add(5, 7);

Closure

Defines a closure add and calls it with arguments 5 and 7.

let add = |x, y| {
    x + y
};
let result = add(5, 7);

Ownership and Borrowing

Ownership

s1 is no longer valid after its ownership is moved to s2.

let s1 = String::from("hello");
let s2 = s1;

Borrowing

s1 is still valid after s2 borrows a reference to s1.

let s1 = String::from("hello");
let s2 = &s1;

Mutable borrowing

s1 is mutable and s2 borrows a mutable reference to s1.

let mut s1 = String::from("hello");
let s2 = &mut s1;

Structs

Struct definition

Defines a struct Point with fields x and y.

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

Struct instantiation

Instantiates a Point with x as 5 and y as 7.

let p = Point {
    x: 5,
    y: 7,
};

Enums

Enum definition

Defines an enum Direction with variants Up, Down, Left, and Right.

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

Enum instantiation

Instantiates a Direction as Up.

let dir = Direction::Up;

Modules

Module definition

Defines a module math with a public function add.

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

Use statement

Imports the function add from the module math.

use math::add;

Collections

Vector

Creates a vector v with elements 1, 2, 3.

let v = vec![1, 2, 3];

String

Creates a string s with value "hello".

let s = String::from("hello");

Hash map

Creates a mutable hash map scores.

let mut scores = HashMap::new();

Error Handling

Unrecoverable Errors

Causes the program to panic with a custom error message.

panic!("This is an unrecoverable error.");

Recoverable Errors

Tries to open a file and panics with a custom error message if it fails.

let f = File::open("file.txt").unwrap_or_else(|error| {
    panic!("Problem opening the file: {:?}", error)
});

Concurrency

Creating a new thread

Spawns a new thread that prints numbers from 1 to 10.

let handle = thread::spawn(|| {
    for i in 1..10 {
        println!("hi number {} from the spawned thread!", i);
    }
});

Macros

Macro definition

Defines a macro say_hello that prints "Hello, world!".

macro_rules! say_hello {
    () => {
        println!("Hello, world!");
    };
}

Macro invocation

Invokes the macro say_hello.

say_hello!();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment