Programming Idioms Org Cheatsheet Rust
Programming Idioms Org Cheatsheet Rust
org
< Cheatsheets
Idiom ID Imports Comments Links filter...
Rust
1 Print Hello World
Print a literal string on standard output
println!("Hello World"); ×
2 Print Hello 10 times
Loop to execute some code a constant
for _ in 0..10 { println!("Hello"); } ×
number of times
Alternative implementation:
print!("{}", "Hello\n".repeat(10));
3 Create a procedure
Like a function which doesn't return
fn finish(name: &str) {
println!("My job here is done. Goo
×
any value, thus has only side effects
dbye {}", name);
(e.g. Print to standard output)
}
4 Create a function
Create a function which returns the
fn square(x : u32) -> u32 { x * x } ×
square of an integer
5 Create a 2D Point data structure
Declare a container type for two
struct Point {
x: f64,
×
floating-point numbers x and y
y: f64,
}
Alternative implementation:
struct Point(f64, f64);
Alternative implementation:
items.into_iter().for_each(|x| do_some
thing(x));
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
println!("Item {} = {}", i, x);
}
Alternative implementation:
items.iter().enumerate().for_each(|(i,
x)| {
println!("Item {} = {}", i, x);
})
Alternative implementation:
let x: HashMap<&str, i32> = [
("one", 1),
("two", 2),
].into_iter().collect();
10 Shuffle a list
Generate a random permutation of the
let mut rng = StdRng::new().unwrap();
rng.shuffle(&mut x);
×
elements of list x
Alternative implementation:
let mut rng = thread_rng();
x.shuffle(&mut rng);
Alternative implementation:
pub fn shuffle<T>(vec: &mut [T]) {
let n = vec.len();
for i in 0..(n - 1) {
let j = rand() % (n - i) + i;
vec.swap(i, j);
}
}
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
finish() as usize
}
Alternative implementation:
(&list).into_iter().any(|v| v == &x)
Alternative implementation:
list.binary_search(&x).is_ok()
Alternative implementation:
Uniform::new_inclusive(a, b).sample(&m
ut rand::thread_rng())
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
16 Depth-first traversal of a binary tree
Call a function f on every node of
fn depthFirstTraverse<T>(bt: &mut BiTr
ee<T>, f: fn(&mut BiTree<T>)) {
×
binary tree bt, in depth-first infix order
if let Some(left) = &mut bt.left {
depthFirstTraverse(left, f);
}
f(bt);
impl<V> Tree<V> {
pub fn dfs<F: Fn(&V)>(&self, f: F)
{
self.dfs_helper(&f);
}
fn dfs_helper<F: Fn(&V)>(&self, f:
&F) {
(f)(&self.value);
for child in &self.children {
child.dfs_helper(f)
}
}
// ...
}
19 Reverse a list
Reverse the order of the elements of
let y: Vec<_> = x.into_iter().rev().co
llect();
×
the list x.
This may reverse "in-place" and
destroy the original ordering. Alternative implementation:
x.reverse();
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
20 Return two values
Implement a function search which
fn search<T: Eq>(m: &Vec<Vec<T>>, x: &
T) -> Option<(usize, usize)> {
×
looks for item x in a 2D matrix m.
for (i, row) in m.iter().enumerate
Return indices i, j of the matching cell.
() {
Think of the most idiomatic way in the
for (j, column) in row.iter().
language to return the two values at
enumerate() {
the same time.
if *column == *x {
return Some((i, j));
}
}
}
None
}
21 Swap values
Swap the values of the variables a and
std::mem::swap(&mut a, &mut b); ×
b
Alternative implementation:
let (a, b) = (b, a);
Alternative implementation:
let i = match s.parse::<i32>() {
Ok(i) => i,
Err(_e) => -1,
};
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
then display "Hello, Alan" thread::spawn(move || {
loop {
let msg = recv.recv().unwrap
();
println!("Hello, {:?}", msg);
}
});
send.send("Alan").unwrap();
28 Sort by a property
Sort the elements of the list (or array-
items.sort_by(|a,b| a.p.cmp(&b.p)); ×
like collection) items in ascending
order of x.p, where p is a field of the Alternative implementation:
type Item of the objects in items.
items.sort_by_key(|x| x.p);
Alternative implementation:
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
(0..1000).into_par_iter().for_each(f);
Alternative implementation:
fn factorial(num: u64) -> u64 {
match num {
0 | 1 => 1,
_ => factorial(num - 1) * num,
}
}
Alternative implementation:
fn exp(x: u64, n: u32) -> u64 {
x.pow(n)
}
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
-> C), which returns the composition 'a + Fn(B) -> C
function g ∘ f {
Box::new(move |x| g(f(x)))
}
Alternative implementation:
fn compose<A, B, C>(f: impl Fn(A) ->
B, g: impl Fn(B) -> C) -> impl Fn(A) -
> C {
move |x| g(f(x))
}
Alternative implementation:
fn compose<A, B, C>(f: impl Fn(A) ->
B, g: impl Fn(B) -> C) -> impl Fn(A) -
> C {
move |x| g(f(x))
}
37 Currying
Transform a function that takes
fn add(a: u32, b: u32) -> u32 {
a + b
×
multiple arguments into a function for
which some of the arguments are
}
preset.
let add5 = move |x| add(5, x);
38 Extract a substring
Find substring t consisting in
let t = s.graphemes(true).skip(i).take
(j - i).collect::<String>();
×
characters i (included) to j (excluded)
of string s.
Character indices start at 0 unless Alternative implementation:
specified otherwise.
let t = s.substring(i, j);
Make sure that multibyte characters
are properly handled.
Alternative implementation:
let mut iter = s.grapheme_indices(tru
e);
let i_idx = iter.nth(i).map(|x|x.0).un
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
wrap_or(0);
let j_idx = iter.nth(j-i).map(|x|x.0).
unwrap_or(0);
let t = s[i_idx..j_idx];
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
Make sure that multibyte characters Alternative implementation:
are properly handled.
let t = s.chars().take(5).collect::<St
ring>();
Alternative implementation:
let s = r#"Huey
Dewey
Louie"#;
Alternative implementation:
let chunks: Vec<_> = s.split(' ').coll
ect();
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
some key. l| *val == v);
Alternative implementation:
let lines = fs::read_to_string(f).expe
ct("Can't read file.");
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
value substitution (e.g. "-2 is
negative").
60 Read command line argument
Assign to x the string value of the first
let first_arg = env::args().skip(1).ne
xt();
×
command line parameter, after the
program name.
let fallback = "".to_owned();
let x = first_arg.unwrap_or(fallback);
Alternative implementation:
let x = env::args().nth(1).unwrap_or
("".to_string());
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
67 Binomial coefficient "n choose k"
Calculate binom(n, k) = n! / (k! * (n-
fn binom(n: u64, k: u64) -> BigInt {
let mut res = BigInt::one();
×
k)!). Use an integer type able to handle
huge numbers.
for i in 0..k {
res = (res * (n - i).to_bigint
().unwrap()) /
(i + 1).to_bigint().unwr
ap();
}
res
}
68 Create a bitset
Create an object x to store n bits (n
let mut x = vec![false; n]; ×
being potentially large).
69 Seed random generator
Use seed s to initialize a random
let s = 32;
let mut rng = StdRng::seed_from_u64
×
generator.
(s);
If s is constant, the generator output
will be the same each time the
program runs. If s is based on the
current value of the system clock, the
generator output will be different each
time.
70 Use clock as random generator
seed
let d = SystemTime::now()
.duration_since(SystemTime::UNIX_E
×
Get the current datetime and provide it
POCH)
as a seed to a random generator. The
.expect("Duration since UNIX_EPOCH
generator sequence will be different at
failed");
each run.
let mut rng = StdRng::seed_from_u64(d.
as_secs());
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
p();
}
74 Compute GCD
Compute the greatest common divisor
let x = a.gcd(&b); ×
x of big integers a and b. Use an
integer type able to handle huge
numbers.
75 Compute LCM
Compute the least common multiple x
let x = a.lcm(&b); ×
of big integers a and b. Use an integer
type able to handle huge numbers.
76 Binary digits from an integer
Create the string s of integer x written
let s = format!("{:b}", x); ×
in base 2.
Alternative implementation:
E.g. 13 -> "1101"
let s = format!("{x:b}");
77 Complex number
Declare a complex x and initialize it
let mut x = Complex::new(-2, 3);
x *= Complex::i();
×
with value (3i - 2). Then multiply it by i.
Alternative implementation:
while {
doStuff();
c
} { /* EMPTY */ }
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
81 Round floating point number to
integer
let y = x.round() as i64; ×
Declare the integer y and initialize it
with the rounded value of the floating
point number x .
Ties (when the fractional part of x is
exactly .5) must be rounded up (to
positive infinity).
82 Count substring occurrences
Find how many times string s contains
let c = s.matches(t).count(); ×
substring t.
Specify if overlapping occurrences are
counted.
83 Regex with character repetition
Declare the regular expression r
let r = Regex::new(r"htt+p").unwrap(); ×
matching the strings "http", "htttp",
"httttp", etc.
84 Count bits set in integer binary
representation
let c = i.count_ones(); ×
Count number c of 1s in the integer i in
base 2.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
88 Allocate 1M bytes
Create a new bytes buffer buf of size
let buf: Vec<u8> = Vec::with_capacity
(1000000);
×
1,000,000.
90 Read-only outside
Expose a read-only integer x to the
struct Foo {
x: usize
×
outside world while being writable
inside a structure or a class Foo.
}
impl Foo {
pub fn new(x: usize) -> Self {
Foo { x }
}
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
runs f.
94 Print the type of a variable
Print the name of the type of x. Explain
fn type_of<T>(_: &T) -> &'static str {
std::intrinsics::type_name::<T>()
×
if it is a static type or dynamic type.
}
This may not make sense in all
println!("{}", type_of(&x));
languages.
Alternative implementation:
let x = fs::metadata(path)?.st_size();
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
let s = ureq::get(u).call().into_strin
g()?;
Alternative implementation:
let mut response = reqwest::blocking::
get(u)?;
let mut s = String::new();
response.read_to_string(&mut s)?;
fn main() -> () {
let s = get_exec_name().unwrap();
println!("{}", s);
}
Alternative implementation:
let s = std::env::current_exe()
.expect("Can't get the exec path")
.file_name()
.expect("Can't get the exec name")
.to_string_lossy()
.into_owned();
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
(This is not necessarily the folder
containing the executable itself)
107 Get folder containing current
program
let dir = std::env::current_exe()?
.canonicalize()
×
Assign to string dir the path of the
.expect("the current exe should ex
folder containing the currently running
ist")
executable.
.parent()
(This is not necessarily the working
.expect("the current exe should be
directory, though.)
a file")
.to_string_lossy()
.to_owned();
Alternative implementation:
let output = Command::new("x")
.args(&["a", "b"])
.output()
.expect("failed to execute pro
cess");
Alternative implementation:
let output = Command::new("x")
.args(&["a", "b"])
.status()
.expect("failed to execute pro
cess");
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
let n = get_input().trim().parse::<i64
>().unwrap();
Alternative implementation:
let mut input = String::new();
io::stdin().read_line(&mut input).unwr
ap();
let n: i32 = input.trim().parse().unwr
ap();
Alternative implementation:
let n: i32 = std::io::stdin()
.lock()
.lines()
.next()
.expect("stdin should be availabl
e")
.expect("couldn't read from stdi
n")
.trim()
.parse()
.expect("input was not an intege
r");
Alternative implementation:
let n: i32 = read!();
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
DIAMONDS, CLUBS. Hearts,
Diamonds,
Clubs,
}
impl<V> Tree<V> {
fn bfs(&self, f: impl Fn(&V)) {
let mut q = VecDeque::new();
q.push_back(self);
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
}
}
}
// ...
fn bft(start: Rc<RefCell<Vertex<V>>>,
f: impl Fn(&V)) {
let mut q = vec![start];
let mut i = 0;
while i < q.len() {
let v = Rc::clone(&q[i]);
i += 1;
(f)(&v.borrow().value);
for n in &v.borrow().neigh
bours {
let n = n.upgrade().ex
pect("Invalid neighbour");
if q.iter().all(|v| v.
as_ptr() != n.as_ptr()) {
q.push(n);
}
}
}
}
// ...
fn dft_helper(start: Rc<RefCell<Vertex
<V>>>, f: &impl Fn(&V), s: &mut Vec<*c
onst Vertex<V>>) {
s.push(start.as_ptr());
(f)(&start.borrow().value);
for n in &start.borrow().neigh
bours {
let n = n.upgrade().ex
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
pect("Invalid neighbor");
if s.iter().all(|&p| p
!= n.as_ptr()) {
Self::dft_help
er(n, f, s);
}
}
}
let ok = re.is_match(s);
Alternative implementation:
let ok = s.to_ascii_lowercase().contai
ns(&word.to_ascii_lowercase());
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
135 Remove item from list, by its value
Remove at most 1 item from list items,
if let Some(i) = items.iter().position
(|item| *item == x) {
×
having the value x.
This will alter the original list or return a
items.remove(i);
new list, depending on which is more
}
idiomatic.
If there are several occurrences of x in
items, remove only one of them. If x is
absent, keep items unchanged.
136 Remove all occurrences of a value
from a list
items = items.into_iter().filter(|&ite
m| item != x).collect();
×
Remove all occurrences of the value x
from list items.
This will alter the original list or return a Alternative implementation:
new list, depending on which is more
items.retain(|&item| item != x);
idiomatic.
137 Check if string contains only digits
Set the boolean b to true if the string s
let chars_are_numeric: Vec<bool> = s.c
hars()
×
contains only characters in the range
.map(|
'0'..'9', false otherwise.
c|c.is_numeric())
.colle
ct();
let b = !chars_are_numeric.contains(&f
alse);
Alternative implementation:
let b = s.chars().all(char::is_numeri
c);
Alternative implementation:
let b = s.bytes().all(|c| c.is_ascii_d
igit());
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
Explain what happens if k is not an
existing key in m.
141 Iterate in sequence over two lists
Iterate in sequence over the elements
for i in item1.iter().chain(item2.iter
()) {
×
of the list items1 then items2. For
print!("{} ", i);
each iteration print the element.
}
Alternative implementation:
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
155 Delete file
Delete from filesystem the file having
let r = fs::remove_file(filepath); ×
path filepath.
156 Format integer with zero-padding
Assign to the string s the value of the
let s = format!("{:03}", i); ×
integer i in 3 decimal digits. Pad with
zeros if i < 100. Keep all digits if i ≥
1000.
157 Declare constant string
Initialize a constant planet with string
const PLANET: &str = "Earth"; ×
value "Earth".
158 Random sublist
Create a new list y from randomly
let mut rng = &mut rand::thread_rng();
let y = x.choose_multiple(&mut rng,
×
picking exactly k elements from list x.
k).cloned().collect::<Vec<_>>();
It is assumed that x has at least k
elements.
Each element must have same
probability to be picked.
Each element from x must be picked at
most once.
Explain if the original ordering is
preserved or not.
159 Trie
Define a Trie data structure, where
struct Trie {
val: String,
×
entries have an associated value.
(Not all nodes are entries)
nodes: Vec<Trie>
}
Alternative implementation:
#[cfg(target_pointer_width = "64")]
f64();
#[cfg(target_pointer_width = "32")]
f32();
Alternative implementation:
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
elements.iter_mut().for_each(|x| *x *=
c);
Alternative implementation:
if let Some(arg) = ::std::env::args().
nth(1) {
match arg.as_str() {
"f" => fox(),
"b" => box(),
_ => eprintln!("invalid argume
nt: {}", arg),
};
} else {
eprintln!("missing argument");
}
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
166 Concatenate two lists
Create the list ab containing all the
let ab = [a, b].concat(); ×
elements of the list a, followed by all
the elements of the list b.
167 Trim prefix
Create the string t consisting of the
let t = s.trim_start_matches(p); ×
string s with its prefix p removed (if s
starts with p). Alternative implementation:
let t = if s.starts_with(p) { &s[p.len
()..] } else { s };
Alternative implementation:
let t = s.strip_prefix(p).unwrap_or
(s);
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
174 Make HTTP POST request
Make a HTTP request with method
let client = reqwest::blocking::Clien
t::new();
×
POST to the URL u
let mut response = client.post(u).body
("abc").send()?;
Alternative implementation:
let s = HEXLOWER.encode(&a);
Alternative implementation:
fn byte_to_hex(byte: u8) -> (u8, u8) {
static HEX_LUT: [u8; 16] = [b'0',
b'1', b'2', b'3', b'4', b'5', b'6',
b'7', b'8', b'9', b'a', b'b', b'c',
b'd', b'e', b'f'];
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
decoded into one byte (256 possible
let a: Vec<u8> = decode(s).expect("Hex
values).
string should be valid");
Alternative implementation:
let a: Vec<u8> = HEXLOWER_PERMISSIVE.d
ecode(&s.into_bytes()).unwrap();
impl Rect {
fn contains(&self, x: i32, y: i32)
-> bool {
return self.x1 < x && x < sel
f.x2 && self.y1 < y && y < self.y2;
}
}
impl Rectangle {
pub fn center(&self) -> (f64, f64)
{
((self.x1 + self.x2) / 2.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
0, (self.y1 + self.y2) / 2.0)
}
}
Alternative implementation:
fn main(){print!("{},{0:?})}}","fn mai
n(){print!(\"{},{0:?})}}\"")}
184 Tomorrow
Assign to t a string representing the
let t = chrono::Utc::now().date().succ
().to_string();
×
day, month and year of the day after
the current date.
185 Execute function in 30 seconds
Schedule the execution of f(42) in 30
sleep(Duration::new(30, 0));
f(42);
×
seconds.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
elements e of the list x that match the .map(T)
predicate P. .collect::<Vec<_>>();
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
for (i, j) in izip!(&a[0], &a[1])
{
sum += i * j
}
Alternative implementation:
let h = x.hypot(y);
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
202 Sum of squares
Calculate the sum of squares s of
let s = data.iter().map(|x| x.powi
(2)).sum::<f32>();
×
data, an array of floating point values.
0.785 2
205 Get an environment variable
Read an environment variable with the
let foo = match env::var("FOO") {
Ok(val) => val,
×
name "FOO" and assign it to the string
variable foo. If it does not exist or if the
Err(_e) => "none".to_string(),
system does not support environment
};
variables, assign a value of "none".
Alternative implementation:
let foo = env::var("FOO").unwrap_or("n
one".to_string());
Alternative implementation:
let foo = match env::var("FOO") {
Ok(val) => val,
Err(_e) => "none".to_string(),
};
Alternative implementation:
if let Ok(tnt_root) = env::var("TNT_RO
OT") {
//
}
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
the name of the respective procedure. "baz" => baz(),
Do it in a way natural to the language. "barfl" => barfl(),
_ => {}
}
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
println!("{:?} == {:?}", x[0], x
[1])
}
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
zip.write_all(b"Hello, World!\n")?;
zip.finish()?;
Alternative implementation:
fn zip(_name: &str, _list: Vec<&str>)
-> zip::result::ZipResult<()>
{
let path = std::path::Path::new(_n
ame);
let file = std::fs::File::create(&
path).unwrap();
let mut zip = zip::ZipWriter::new
(file);
for i in _list.iter() {
zip.start_file(i as &str, File
Options::default())?;
}
zip.finish()?;
Ok(())
}
Alternative implementation:
let set_a: HashSet<_> = a.into_iter().
collect();
let set_b: HashSet<_> = b.into_iter().
collect();
let c = set_a.intersection(&set_b);
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
220 Create a tuple value
Create t consisting of 3 values having
let t = (2.5, "hello", -1); ×
different types.
Alternative implementation:
let i = items.iter().position(|y| *y =
= x).map_or(-1, |n| n as i32);
Alternative implementation:
items
.iter()
.find(|&&item| item == "rockstar p
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
rogrammer")
.or_else(|| {
println!("NotFound");
Some(&"rockstar programmer")
});
Alternative implementation:
if 'search: loop {
for i in items {
if i == &"qux" {
println!("found it");
break 'search false;
}
}
break 'search true
} {
println!("not found!");
}
Alternative implementation:
'label: {
for &item in items {
if item == "baz" {
println!("foun
d");
break 'label;
}
}
println!("not found");
}
if matches.is_present("verbose") {
println!("verbose is true")
} else {
println!("verbose is false")
}
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
(x, y)| x ^ y).collect();
a and b have the same size.
239 Find first regular expression match
Assign to string x the first word of
let re = Regex::new(r"\b\d\d\d\b").exp
ect("failed to compile regex");
×
string s consisting of exactly 3 digits, or
let x = re.find(s).map(|x| x.as_str
the empty string if no such match
()).unwrap_or("");
exists.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
For languages that don't have mutable }
lists, refer to idiom #57 instead. }
x.truncate(j);
Alternative implementation:
x.retain(p);
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
and is not required to remain the same
next time.
256 Count backwards
Print the numbers 5, 4, ..., 0 (included),
(0..=5).rev().for_each(|i| println!("
{}", i));
×
one line per number.
Alternative implementation:
for i in (0..=5).rev() {
println!("{}", i);
}
Alternative implementation:
for (i, x) in items.iter().rev().enu
merate() {
println!("{i} = {x}");
}
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
integer n.
fn main() {
for n in 1..=12 {
let f = f64::from(n);
println!("{} {} {}", n, log2d
(f), log2u(f));
}
}
fn main() {
let matrix = vec![
vec![1, 2, 3],
vec![4, 5, 6],
];
foo(&matrix);
}
Alternative implementation:
fn foo<const X: usize, const Y: usize>
(_: [[i32;X];Y]) {
println!("{} {}", Y, X);
}
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
let a = [
[1, 2, 3],
[4, 5, 6],
];
foo(a);
fn main() {
foo(&"Hello, world!".to_owned());
foo(&42);
}
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
z: self.x * rhs.y - self.y
* rhs.x,
}
}
}
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
274 Remove all white space characters
Create the string t from the string s,
let t: String = s.chars().filter(|c| !
c.is_whitespace()).collect();
×
removing all the spaces, newlines,
tabulations, etc.
275 Binary digits to byte array
From the string s consisting of 8n
let a: Vec<u8> = s.as_bytes()
.chunks(8)
×
binary digit characters ('0' or '1'), build
the equivalent array a of n bytes.
.map(|chunk| unsafe {
let chunk_str = std::str::from
Each chunk of 8 binary digits (2
_utf8_unchecked(chunk);
possible values per digit) is decoded
into one byte (256 possible values).
u8::from_str_radix(chunk_str,
2).unwrap_unchecked()
})
.collect();
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
283 Split with a custom string separator
Build the list parts consisting of
let parts = s.split(sep); ×
substrings of input string s, separated
by the string sep. Alternative implementation:
let parts = s.split(sep).collect::<Vec
<&str>>();
Alternative implementation:
let parts: Vec<&str> = s.split(sep).co
llect();
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
Alternative implementation:
let s = a + b;
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
}
}
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
Alternative implementation:
fn random_string(n: usize) -> String {
Alphanumeric.sample_string(&mut ra
nd::thread_rng(), n)
}
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
321 Access character in string, by index
Assign to c the value of the i-th
let c = s.chars().nth(i).expect("s is
too short");
×
character of the string s.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
331 Clear map
Remove all entries from the map m.
m.clear(); ×
Explain if other references to the same
map now see an empty map as well.
332 List of the keys of a map
Create the list k containing all the keys
m.keys().collect::<Vec<_>>() ×
of the map m
335 List to map
Create the map m containing all the
let mut m = HashMap::new(); ×
elements e of the list a, using as key
for e in a {
the field e.id.
m.entry(e.id).or_insert_with(V
ec::new).push(e);
}
336 Exponent
Compute x = b ⁿ
let x = b.pow(n) ×
b raised to the power of n is equal to
the product of n terms b × b × ... × b
339 Clear a byte array
Set all the elements of the byte array a
a.fill(0); ×
to zero
340 Last character of string
Assign to c the value of the last
let c = s.chars().last().unwrap(); ×
character of the string s.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
355 Absolute value
Assign to y the absolute value of the
let y = n.abs(); ×
number n
356 Parse list of integers
Create the list of integers items for the
let items = s
.split_whitespace()
×
string s containing integers separated
by one or more whitespace characters
.map(|x| x.parse::<i32>().unwrap
())
(space, tab, newline).
.collect::<Vec<i32>>();
Alternative implementation:
let items = s
.split_whitespace()
.map(|x| x.parse::<i32>().unwrap
())
.collect::<Vec<i32>>();
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF