Getting Started
5 snippetsYour first steps with Rust basics
Hello World
fn main() {
println!("Hello, World!");
}Comments
// Single line comment
/* Multi-line
comment */
/// Doc commentPrint Values
println!("{}", value); // Display
println!("{:?}", value); // Debug
println!("{:#?}", value); // Pretty debugUser 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 & runVariables & Data Types
8 snippetsStore 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 snippetsSymbols for calculations and comparisons
Arithmetic
+ - * / // Add, Sub, Mul, Div
% // Modulus (remainder)
// No ++ or -- in RustComparison
== != // Equal, Not equal
> < // Greater, Less than
>= <= // Greater/Less or equalLogical
&& // Short-circuit AND
|| // Short-circuit OR
! // NOTAssignment
= += -= *= /= %=
&= |= ^= <<= >>=Bitwise
& // AND
| // OR
^ // XOR
! // NOT (for bool)
<< // Left shift
>> // Right shiftReference
&x // Immutable reference
&mut x // Mutable reference
*ptr // DereferenceError Propagation
? // Propagate error
result? // Return Err if errorTired of looking up syntax?
DocuWriter.ai generates documentation and explains code using AI.
Loops
10 snippetsRepeat 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 snippetsDirect 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 snippetsReusable 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 snippetsRust's unique memory management
Move
let s1 = String::from("hello");
let s2 = s1; // s1 is movedClone
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 snippetsDefine 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 snippetsMatch 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 snippetsTrait
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 }