kuniga.me > Docs > Rust Cheatsheet
Rust Cheatsheet
Index
- Basic types
- Type names
- Arrays
- Initialize
- Iterate
- Bool
- Enum
- Integers
- Bit operations
- Iterator
- Optional
- Pair
- String
- Types
- String (variable length)
- Operations
- Struct
- Destructuring
- Methods
- Tuple
- Functions
- Closure
- Multi-line
- Flow Control
- Conditional
- Loops
- Data structures
- Vector
- Initialize
- Inserting
- Iterating
- Mapping
- Filtering
- Length
- Sorting
- Destructured assignment
- HashMap
- Set
- Queue
- Object Oriented
- I/O
- Read from stdin
- Read CLI arguments
- Printing to stdout
- Math
- Exponentiation
- Square root
- Mutability
Basic types
Type names
char
f32
, f64
- float point type
Arrays
Arrays are of fixed size. For variable size, see Vec
.
Initialize
Iterate
Bool
- Type:
bool
- Examples:
true
, false
Enum
Integers
- Types:
i8
, i16
, i32
, i64
, u8
, u16
, u32
, u64
Bit operations
!
is the Rust version of ~
Iterator
Note that Iterator
is not a class but rather a trait that classes implement.
Get the next element:
NOTE: next()
is not idempotent.
Optional
Create Some
:
Throw if None
:
Test if some:
Test if none:
Pair
Done via tuples. See Tuple.
String
Types
String
- string object
&str
- string slice
&'static str
- string literal
String (variable length)
Operations
From literal strings:
Convert to int:
Convert from int:
Convert to Vec<char>
:
Split:
Split into multiple lines. There’s a shortcut for splitting by the character \n
:
Substring:
Trim:
Struct
keywords: record / object / shape
Destructuring
Methods
Tuple
Type: (T1, T2)
, e.g. (i32, bool)
Create:
Access:
or via destructuring:
Functions
Rust doesn’t support default arguments
Closure
keywords: lambda
Multi-line
Flow Control
Conditional
Loops
See also “Iterating” on different data structures.
Data structures
Vector
Initialize
Fixed size, same value:
Inserting
Iterating
Mapping
Filtering
In-place
Length
Sorting
Destructured assignment
Like in Python, we can do destructured assignment by assuming a fixed length of a vector, but we have to handle the other cases:
HashMap
Reference: HashMap
Set
Use:
Create:
From vector:
Set intersection:
Queue
Object Oriented
I/O
Read from stdin
Read CLI arguments
Printing to stdout
Vector:
Math
A lot of the math operations are methods on the numerical types.
Exponentiation
Note that the exponent has to be positive, since a negative one could change the type of the base to floating point.
Square root
Not defined for integer types.
Mutability
Variable doesn’t need to be mutable if it’s initialized only once: