Rust chapters

Chapter 16 of 17

Rust Syntax Cheatsheet

Try this in our Rust Compiler →

Everything in one place

Use this chapter as a quick reference once you've worked through the rest of the course. It collects every core construct of Rust into runnable, copy-pasteable snippets you can scan whenever you forget the exact syntax.

Hello world & variables

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

let age: i32 = 25;
let name = String::from("Aman");
let is_student = true;
println!("{} {} {}", name, age, is_student);

Data types & operators

let n: i32 = 42;
let f: f64 = 3.14;
let b: bool = true;
let s: &str = "hello";
let arr: [i32; 3] = [1, 2, 3];

let (a, b) = (10, 3);
println!("{} {} {}", a + b, a - b, a % b);
println!("{}", a > b && b < 5);

Conditionals & loops

let score = 72;
if score >= 90 {
    println!("A");
} else if score >= 60 {
    println!("Pass");
} else {
    println!("Fail");
}

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

let mut n = 0;
while n < 3 { n += 1; }

Functions & arrays

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

fn main() {
    println!("{}", add(2, 3));
}

let mut nums = vec![10, 20, 30];
nums.push(40);
for n in &nums {
    println!("{}", n);
}

Strings & objects

let name = String::from("PlayLearn");
println!("{}", name.len());
println!("{}", name.to_uppercase());

struct User { name: String, age: u32 }

impl User {
    fn greet(&self) -> String { format!("Hi {}", self.name) }
}

let u = User { name: String::from("Aman"), age: 20 };
println!("{}", u.greet());

Errors, modules & I/O

let n: Result<i32, _> = "abc".parse::<i32>();
match n {
    Ok(v) => println!("Got {}", v),
    Err(e) => println!("Bad input: {}", e),
}

// math.rs
pub fn add(a: i32, b: i32) -> i32 { a + b }

// main.rs
mod math;
fn main() { println!("{}", math::add(2, 3)); }

use std::io::{self, BufRead};
let mut line = String::new();
io::stdin().lock().read_line(&mut line).unwrap();
println!("Hello, {}", line.trim());

How to use this page

Bookmark it. When you start a new project, open this cheatsheet alongside your editor and use it as a syntax lookup. Once a construct becomes second nature you'll stop needing the reference for it — and that's exactly when you know you've mastered that part of Rust.

Practice and verify

Run reference snippets separately; they are not a single source file to concatenate. Check required imports and entry points for each.

Try it yourself

Output
Run your project to see output here.
Ctrl/Cmd+Enter runs · Ctrl/Cmd+S downloads the project · Local auto-save is always on