Common Syntax

PurposeSyntaxExample
Create a variablelet name: Type = value;let age: i32 = 25;
Mutable variablelet mut name: Type = value;let mut score = 0;
Constantconst NAME: Type = value;const PI: f64 = 3.14;
Functionfn name(param: Type) { }fn greet(name: &str) { }
Function with returnfn name() -> Type { }fn add() -> i32 { }
Return a valuelast expression or returnx + y
If statementif condition { }if age >= 18 { }
Else ifelse if condition { }else if age == 18 { }
Elseelse { }else { println!("No"); }
Matchmatch value { }match n { 1 => ..., _ => ... }
Loop foreverloop { }loop { break; }
While loopwhile condition { }while x < 10 { }
For loopfor item in collection { }for n in 1..5 { }
Structstruct Name { }struct User { age: u32 }
Enumenum Name { }enum Color { Red, Blue }
Methodimpl Type { fn method(...) { } }impl User { fn greet(&self) {} }
Type castingvalue as Typecount as u64
Reference&value&name
Mutable reference&mut value&mut score
Generic typeType<T>Vec<String>
Generic functionfn name<T>()fn print<T>(value: T)
Trait implementationimpl Trait for Typeimpl Display for User
Error propagation?file.read_to_string()?;

Rust Symbols & Syntax

SymbolNameCommon use
()ParenthesesFunction calls, parameters, unit type
{}Curly bracesBlocks, functions, structs, match arms
[]Square bracketsArrays, indexing, attributes (#[derive])
<>Angle bracketsGenerics (Vec<T>, Option<T>)
:ColonType annotations (x: i32)
::Double colonModules and namespaces (std::io::stdin)
;SemicolonEnds a statement
,CommaSeparates items
.DotField and method access (user.name)
..Range operator1..5, struct update syntax
..=Inclusive range1..=5
=>Fat arrowMatch arms
->Thin arrowFunction return type
=AssignmentAssign a value
==EqualityCompare values
!=Not equalCompare values
>Greater thanComparison
<Less thanComparison, generics
>=Greater than or equalComparison
<=Less than or equalComparison
+PlusAddition
-MinusSubtraction
*AsteriskMultiplication, dereference
/SlashDivision
%ModuloRemainder
+=Add assignmentx += 1
-=Subtract assignmentx -= 1
*=Multiply assignmentx *= 2
/=Divide assignmentx /= 2
&AmpersandImmutable reference (borrow)
&mutMutable referenceMutable borrow
&&Double ampersandLogical AND
||Double pipeLogical OR
!Exclamation markMacros (println!), logical NOT, never type
?Question markError propagation
_UnderscoreIgnore a value, wildcard pattern
@At symbolPattern binding in match
|PipeClosures, pattern alternatives
#[]Attribute#[derive(Debug)], #[test]

Common Rust Macros

MacroPurposeExample
println!Print with newlineprintln!("Hello");
print!Print without newlineprint!("Hello");
dbg!Debug a valuedbg!(value);
assert!Assert a conditionassert!(x > 0);
assert_eq!Assert equalityassert_eq!(x, 5);
assert_ne!Assert inequalityassert_ne!(x, 0);
vec!Create a vectorvec![1, 2, 3]
format!Format into a Stringformat!("Hi {}", name)
panic!Stop executionpanic!("Something went wrong");