Show Menu
Cheatography

Rust Essentials Cheat Sheet (DRAFT) by

Rust Programming

This is a draft cheat sheet. It is a work in progress and is not finished yet.

HashMaps

use std::c­oll­ect­ion­s::­Has­hMap;
let mut h: HashMa­p<(­i64­,i6­4),­i64> = HashMa­p::­new();
h.cont­ain­s_k­ey(­&(­n,k))
check whether key is present
h.inse­rt(­(n,k), res);
insert new value
*h.get­(&­(n,­k)).un­wrap()
retrieve value

Variables and constants

const N: i32 = 5
(Global) constant
let v = vec![3, 1, 4]
Define and initialize vector
let zero_vec = vec![0; len]
let mut p : [usize; 9] = [0; 9];

Primitive types

bool
Boolean
char
character
f32, f64
32-bits, 64-bits floats
i64, i32, i16, i8
signed 16- ... integers
u64, u32, u16, u8
unsigned 16-bits, ... integers
isize
pointe­r-sized signed integers
usize
pointe­r-sized unsigned integers

Processor directives

#![fea­tur­e(i­ter­ato­r_s­tep­_by)]
for n in (0..10­0).s­te­p_by(2) { ... } iterates over even numbers
#![fea­­tu­r­e­(i­­ncl­­us­i­v­e_­­ran­­ge­_­s­yn­­tax)]
1..=n is a range which includes both 1 and n
 

Boolean operators

Operator
Syntax
And
a & b or a && b
Or
a . b or a .. b
And
a ^ b
Not
!a

Conver­sions

To convert say an
n: i32
to a
u64
use
n as u64
To convert a number
x
to a string use
x.to_s­tring()
To convert
s: String*
to
x.pars­e().un­wrap()
x.unwr­ap_­or(­def­aul­t_v­alue)

Formatting

printl­n!(­"­{}", x);
printl­n!(­"­{:0­10b­}", x);
binary, 10 digits, print leading zeros
format­!("H­ell­o");
"­Hel­lo"
format­!("H­ello, {}!", "­wor­ld");
"­Hello, world!­"
format­!("The number is {}", 1);
"The number is 1"
format­!("{­:?}­", (3, 4));
"­4"
format­!("{­val­ue}­", value=4);
"1 2"
format­!("{­:04­}", 42);
"­004­2" with leading zeros

Vectors and iterators

(0..16­usi­ze).ma­p(|x| x.coun­t_o­nes() as usize).co­llect()

Assertions

let x = 42;
assert!(x == 42);
assert_eq!(x, 42);
Use the macro
assert!
to check for a boolean true, and
assert_eq!
for the equality of two expres­sions.