AI Generate Rust docs instantly

Rust Cheat Sheet

Quick reference guide with copy-paste ready code snippets

Try DocuWriter Free

Getting Started

5 snippets

Your first steps with Rust basics

Hello World

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

Comments

// Single line comment
/* Multi-line
   comment */
/// Doc comment

Print Values

println!("{}", value);       // Display
println!("{:?}", value);     // Debug
println!("{:#?}", value);    // Pretty debug

User Input

let mut input = String::new();
std::io::stdin().read_line(&mut input)?;

Build & Run

cargo new project   // Create
cargo build         // Compile
cargo run           // Build & run

Variables & Data Types

8 snippets

Store and manage data in Rust

Let (Immutable)

let name = "John";

Let Mut

let mut count = 0;

Const

const MAX: u32 = 100;

Type Annotation

let age: i32 = 25;

Tuple

let tuple: (i32, f64, &str) = (1, 2.0, "hello");

Array

let arr: [i32; 5] = [1, 2, 3, 4, 5];

Vector

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

HashMap

let mut map = HashMap::new();

Operators

7 snippets

Symbols for calculations and comparisons

Arithmetic

+ - * /    // Add, Sub, Mul, Div
%          // Modulus (remainder)
// No ++ or -- in Rust

Comparison

==  !=     // Equal, Not equal
>   <      // Greater, Less than
>=  <=     // Greater/Less or equal

Logical

&&   // Short-circuit AND
||   // Short-circuit OR
!    // NOT

Assignment

=   +=  -=  *=  /=  %=
&=  |=  ^=  <<= >>=

Bitwise

&   // AND
|   // OR
^   // XOR
!   // NOT (for bool)
<<  // Left shift
>>  // Right shift

Reference

&x      // Immutable reference
&mut x  // Mutable reference
*ptr    // Dereference

Error Propagation

?    // Propagate error
result?  // Return Err if error

Tired of looking up syntax?

DocuWriter.ai generates documentation and explains code using AI.

Try Free

Loops

10 snippets

Repeat code efficiently with iterations

Loop (Infinite)

loop {
    if done { break; }
}

Loop with Return

let result = loop {
    if found {
        break value;
    }
};

While

while count < 10 {
    count += 1;
}

While Let

while let Some(x) = stack.pop() {
    println!("{}", x);
}

For Range

for i in 0..5 {
    println!("{}", i);  // 0, 1, 2, 3, 4
}

For Range Inclusive

for i in 0..=5 {
    println!("{}", i);  // 0, 1, 2, 3, 4, 5
}

For Iterator

for item in vec.iter() {
    println!("{}", item);
}

For Enumerate

for (i, item) in vec.iter().enumerate() {
    println!("{}: {}", i, item);
}

Break/Continue

for i in 0..10 {
    if i == 5 { continue; }
    if i == 8 { break; }
}

Labeled Loops

'outer: for i in 0..3 {
    for j in 0..3 {
        if j == 1 { break 'outer; }
    }
}

Conditionals

5 snippets

Direct program execution with conditions

If/Else

if x > 0 {
    println!("positive");
} else if x < 0 {
    println!("negative");
} else {
    println!("zero");
}

If Expression

let result = if condition { 5 } else { 10 };

If Let

if let Some(x) = option {
    println!("{}", x);
}

Match

match value {
    1 => println!("one"),
    2 | 3 => println!("two or three"),
    4..=10 => println!("4 to 10"),
    _ => println!("other"),
}

Match Guards

match num {
    n if n < 0 => "negative",
    0 => "zero",
    n if n > 0 => "positive",
    _ => unreachable!(),
}

Functions

4 snippets

Reusable blocks of code and closures

Function

fn greet(name: &str) -> String {
    format!("Hello, {}!", name)
}

No Return

fn print_msg(msg: &str) {
    println!("{}", msg);
}

Closure

let add = |a, b| a + b;

Closure with Types

let square = |x: i32| -> i32 { x * x };

Ownership & Borrowing

4 snippets

Rust's unique memory management

Move

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

Clone

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

Borrow

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

Mutable Borrow

fn append(s: &mut String) {
    s.push_str(" world");
}

Structs & Enums

5 snippets

Define custom data types

Struct

struct Person {
    name: String,
    age: u32,
}

Impl

impl Person {
    fn new(name: &str, age: u32) -> Self {
        Self { name: name.to_string(), age }
    }

    fn greet(&self) -> String {
        format!("Hi, I'm {}", self.name)
    }
}

Enum

enum Status {
    Active,
    Inactive,
    Pending(String),
}

Option

let value: Option<i32> = Some(5);
let none: Option<i32> = None;

Result

fn divide(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 {
        Err("Division by zero".to_string())
    } else {
        Ok(a / b)
    }
}

Error Handling

4 snippets

Match Result

match result {
    Ok(val) => println!("Success: {}", val),
    Err(e) => println!("Error: {}", e),
}

? Operator

fn read_file() -> Result<String, io::Error> {
    let content = fs::read_to_string("file.txt")?;
    Ok(content)
}

Unwrap

let value = some_option.unwrap();

Expect

let value = result.expect("Failed to get value");

Traits

3 snippets

Trait

trait Greet {
    fn greet(&self) -> String;
}

Impl Trait

impl Greet for Person {
    fn greet(&self) -> String {
        format!("Hello, I'm {}", self.name)
    }
}

Derive

#[derive(Debug, Clone, PartialEq)]
struct Point { x: i32, y: i32 }

More Cheat Sheets

FAQ

Frequently asked questions

What is a Rust cheat sheet?

A Rust cheat sheet is a quick reference guide containing the most commonly used syntax, functions, and patterns in Rust. It helps developers quickly look up syntax without searching through documentation.

How do I learn Rust quickly?

Start with the basics: variables, control flow, and functions. Use this cheat sheet as a reference while practicing. For faster learning, try DocuWriter.ai to automatically explain code and generate documentation as you learn.

What are the most important Rust concepts?

Key Rust concepts include variables and data types, control flow (if/else, loops), functions, error handling, and working with data structures like arrays and objects/dictionaries.

How can I document my Rust code?

Use inline comments for complex logic, docstrings for functions and classes, and README files for projects. DocuWriter.ai can automatically generate professional documentation from your Rust code using AI.

Code Conversion Tools

Convert Rust to Other Languages

Easily translate your Rust code to other programming languages with our AI-powered converters

Related resources

Stop memorizing. Start shipping.

Generate Rust Docs with AI

DocuWriter.ai automatically generates comments, docstrings, and README files for your code.

Auto-generate comments
Create README files
Explain complex code
API documentation
Start Free - No Credit Card

Join 33,700+ developers saving hours every week