0% found this document useful (0 votes)
3 views56 pages

Programming Idioms Org Cheatsheet Rust

The document provides a collection of programming idioms in Rust, detailing various common tasks and their idiomatic implementations. Each entry includes a brief description of the task, along with code snippets demonstrating how to achieve it in Rust. The idioms cover a wide range of functionalities, from basic operations like printing and looping to more complex structures like trees and concurrency.

Uploaded by

justin.c.fin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views56 pages

Programming Idioms Org Cheatsheet Rust

The document provides a collection of programming idioms in Rust, detailing various common tasks and their idiomatic implementations. Each entry includes a brief description of the task, along with code snippets demonstrating how to achieve it in Rust. The idioms cover a wide range of functionalities, from basic operations like printing and looping to more complex structures like trees and concurrency.

Uploaded by

justin.c.fin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Programming-Idioms.

org
< Cheatsheets
Idiom ID Imports Comments Links filter...

The snippets are under the CC-BY-SA license.


Please consider keeping a bookmark
(instead of printing)

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);

6 Iterate over list values


Do something with each item x of the
for x in items {
do_something(x);
×
list (or array) items, regardless
}
indexes.

Alternative implementation:
items.into_iter().for_each(|x| do_some
thing(x));

7 Iterate over list indexes and values


Print each index i with its value x from
for (i, x) in items.iter().enumerate()
{
×
an array-like collection items

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);
})

8 Create a map (associative array)


Create a new map object x, and
let mut x = BTreeMap::new();
x.insert("one", 1);
×
provide some (key, value) pairs as
x.insert("two", 2);
initial content.

Alternative implementation:
let x: HashMap<&str, i32> = [
("one", 1),
("two", 2),
].into_iter().collect();

9 Create a Binary Tree data structure


The structure must be recursive
struct BinTree<T> {
value: T,
×
because left child and right child are
left: Option<Box<BinTree<T>>>,
binary trees too. A node has access to
right: Option<Box<BinTree<T>>>,
children nodes, but not to its parent.
}

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);
}
}

pub fn rand() -> usize {


RandomState::new().build_hasher().

Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
finish() as usize
}

11 Pick a random element from a list


The list x must be non-empty.
x[rand::thread_rng().gen_range(0..x.le
n())]
×
Alternative implementation:
let mut rng = rand::thread_rng();
let choice = x.choose(&mut rng).unwrap
();

12 Check if list contains a value


Check if the list contains the value x.
list.contains(&x); ×
list is an iterable finite container.
Alternative implementation:
list.iter().any(|v| v == &x)

Alternative implementation:
(&list).into_iter().any(|v| v == &x)

Alternative implementation:
list.binary_search(&x).is_ok()

13 Iterate over map keys and values


Access each key k with its value x
for (k, x) in &mymap {
println!("Key={key}, Value={val}",
×
from an associative array mymap, and
key=k, val=x);
print them.
}

14 Pick uniformly a random floating


point number in [a..b)
thread_rng().gen_range(a..b); ×
Pick a random number greater than or
equals to a, strictly inferior to b.
Precondition : a < b.
15 Pick uniformly a random integer in
[a..b]
fn pick(a: i32, b: i32) -> i32 {
let between = Range::new(a, b);
×
Pick a random integer greater than or
let mut rng = rand::thread_rng();
equals to a, inferior or equals to b.
between.ind_sample(&mut rng)
Precondition : a < b.
}

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);

if let Some(right) = &mut bt.right


{
depthFirstTraverse(right, f);
}
}

17 Create a Tree data structure


The structure must be recursive. A
struct Node<T> {
value: T,
×
node may have zero or more children.
children: Vec<Node<T>>,
A node has access to its children
}
nodes, but not to its parent.

18 Depth-first traversal of a tree


Call a function f on every node of a
pub struct Tree<V> {
children: Vec<Tree<V>>,
×
tree, in depth-first prefix order
value: V
}

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);

22 Convert string to integer


Extract the integer value i from its
let i = s.parse::<i32>().unwrap(); ×
string representation s (in radix 10)
Alternative implementation:
let i: i32 = s.parse().unwrap_or(0);

Alternative implementation:
let i = match s.parse::<i32>() {
Ok(i) => i,
Err(_e) => -1,
};

23 Convert real number to string with 2


decimal places
let s = format!("{:.2}", x); ×
Given a real number x, create its string
representation s with 2 decimal digits
following the dot.
24 Assign to string the japanese word
ネコ let s = " ネコ"; ×
Declare a new string s and initialize it
with the literal value "ネコ
" (which
means "cat" in japanese)
25 Send a value to another thread
Share the string value "Alan" with an
let (send, recv) = channel(); ×
existing running process which will

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();

26 Create a 2-dimensional array


Declare and initialize a matrix x having
let mut x = vec![vec![0.0f64; N]; M]; ×
m rows and n columns, containing real
numbers. Alternative implementation:
let mut x = [[0.0; N] ; M];

27 Create a 3-dimensional array


Declare and initialize a 3D array x,
let x = vec![vec![vec![0.0f64; p]; n];
m];
×
having dimensions boundaries m, n, p,
and containing real numbers.
Alternative implementation:
let x = [[[0.0f64; P]; N]; M];

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);

29 Remove item from list, by its index


Remove i-th item from list items.
items.remove(i) ×
This will alter the original list or return a
new list, depending on which is more
idiomatic.
Note that in most languages, the
smallest valid value for i is 0.
30 Parallelize execution of 1000
independent tasks
let threads: Vec<_> = (0..1000).map(|i
| {
×
Launch the concurrent execution of the
procedure f with parameter i from 1 to
thread::spawn(move || f(i))
1000.
}).collect();
Tasks are independent and f(i) doesn't
for thread in threads {
return any value.
thread.join();
Tasks need not run all at the same
}
time, so you may use a pool.

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);

31 Recursive factorial (simple)


Create the recursive function f which
fn f(n: u32) -> u32 {
if n < 2 {
×
returns the factorial of the non-negative
1
integer i, calculated from f(i-1)
} else {
n * f(n - 1)
}
}

Alternative implementation:
fn factorial(num: u64) -> u64 {
match num {
0 | 1 => 1,
_ => factorial(num - 1) * num,
}
}

32 Integer exponentiation by squaring


Create function exp which calculates
fn exp(x:
match
u64, n: u64) -> u64 {
n {
×
(fast) the value x power n.
x and n are non-negative integers.
0 => 1,
1 => x,
i if i % 2 == 0 => exp(x * x,
n / 2),
_ => x * exp(x * x, (n - 1) /
2),
}
}

Alternative implementation:
fn exp(x: u64, n: u32) -> u64 {
x.pow(n)
}

33 Atomically read and update variable


Assign to the variable x the new value
let mut x = x.lock().unwrap();
*x = f(x);
×
f(x), making sure that no other thread
may modify x between the read and
the write.
34 Create a set of objects
Declare and initialize a set x containing
let x: HashSet<T> = HashSet::new(); ×
unique objects of type T.
35 First-class function : compose
Implement a function compose (A ->
fn compose<'a, A, B, C, G, F>(f: F, g:
G) -> Box<Fn(A) -> C + 'a>
×
C) with parameters f (A -> B) and g (B
where F: 'a + Fn(A) -> B, G:

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))
}

36 First-class function : generic


composition
fn compose<'a, A, B, C, G, F>(f: F, g:
G) -> Box<Fn(A) -> C + 'a>
×
Implement a function compose which
where F: 'a + Fn(A) -> B, G:
returns composition function g ∘ f for
'a + Fn(B) -> C
any functions f and g having exactly 1
{
parameter.
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))
}

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];

39 Check if string contains a word


Set the boolean ok to true if the string
let ok = s.contains(word); ×
word is contained in string s as a
substring, or to false otherwise.
41 Reverse a string
Create the string t containing the same
let t = s.chars().rev().collect::<Stri
ng>();
×
characters as the string s, in reverse
order.
The original string s must remain Alternative implementation:
unaltered. Each character must be
let t: String = s.chars().rev().collec
handled correctly regardless its
t();
number of bytes in memory.
42 Continue outer loop
Print each item v of list a which is not
'outer: for va in &a {
for vb in &b {
×
contained in list b.
For this, write an outer loop to iterate
if va == vb {
on a and an inner loop to iterate on b.
continue 'outer;
}
}
println!("{}", va);
}

43 Break outer loop


Look for a negative value v in 2D
'outer: for v in m {
'inner: for i in v {
×
integer matrix m. Print it and stop
if i < 0 {
searching.
println!("Found {}", i);
break 'outer;
}
}
}

44 Insert element in list


Insert the element x at position i in the
s.insert(i, x); ×
list s. Further elements must be shifted
to the right.
45 Pause execution for 5 seconds
Sleep for 5 seconds in current thread,
thread::sleep(time::Duration::from_sec
s(5));
×
before proceeding with the next
instructions.
46 Extract beginning of string (prefix)
Create the string t consisting of the 5
let t = s.char_indices().nth(5).map_or
(s, |(i, _)| &s[..i]);
×
first characters of the string s.

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>();

47 Extract string suffix


Create string t consisting in the 5 last
let last5ch = s.chars().count() - 5;
let t: String = s.chars().skip(last5c
×
characters of string s.
h).collect();
Make sure that multibyte characters
are properly handled.
Alternative implementation:
let s = "a̐éö̲\r\n";
let t = s.grapheme_indices(true).rev
().nth(5).map_or(s, |(i,_)|&s[i..]);

48 Multi-line string literal


Assign to variable s a string literal
let s = "line 1
line 2
×
consisting in several lines of text,
including newlines.
line 3";

Alternative implementation:
let s = r#"Huey
Dewey
Louie"#;

49 Split a space-separated string


Build list chunks consisting in
let chunks: Vec<_> = s.split_whitespac
e().collect();
×
substrings of the string s, separated by
one or more space characters.
Alternative implementation:
let chunks: Vec<_> = s.split_ascii_whi
tespace().collect();

Alternative implementation:
let chunks: Vec<_> = s.split(' ').coll
ect();

50 Make an infinite loop


Write a loop that has no end clause.
loop {
// Do something
×
}

51 Check if map contains key


Determine whether the map m
m.contains_key(&k) ×
contains an entry for the key k
52 Check if map contains value
Determine whether the map m
let does_contain = m.values().any(|&va ×
contains an entry with the value v, for

Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
some key. l| *val == v);

53 Join a list of strings


Concatenate elements of string list x
let y = x.join(", "); ×
joined by the separator ", " to create a
single string y.
54 Compute sum of integers
Calculate the sum s of the integer list
x.iter().sum() ×
or array x.
Alternative implementation:
let s = x.iter().sum::<i32>();

55 Convert integer to string


Create the string representation s (in
let s = i.to_string(); ×
radix 10) of the integer value i.
Alternative implementation:
let s = format!("{}", i);

56 Launch 1000 parallel tasks and wait


for completion
let threads: Vec<_> = (0..1000).map(|i
| thread::spawn(move || f(i))).collect
×
Fork-join : launch the concurrent
();
execution of procedure f with
parameter i from 1 to 1000.
for t in threads {
Tasks are independent and f(i) doesn't
t.join();
return any value.
}
Tasks need not run all at the same
time, so you may use a pool.
Wait for the completion of the 1000
tasks and then print "Finished".
57 Filter list
Create the list y containing the items
let y: Vec<_> = x.iter().filter(p).col
lect();
×
from the list x that satisfy the predicate
p. Respect the original ordering. Don't
modify x in-place.
58 Extract file content to a string
Create the string lines from the
let mut file = File::open(f)?;
let mut lines = String::new();
×
content of the file with filename f.
file.read_to_string(&mut lines)?;

Alternative implementation:
let lines = fs::read_to_string(f).expe
ct("Can't read file.");

59 Write to standard error stream


Print the message "x is negative" to
eprintln!("{} is negative", x); ×
standard error (stderr), with integer x

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());

61 Get current date


Assign to the variable d the current
let d = time::now(); ×
date/time value, in the most standard
type. Alternative implementation:
let d = SystemTime::now();

62 Find substring position


Set i to the first position of string y
let i = x.find(y); ×
inside string x, if exists.

Specify if i should be regarded as a


character index or as a byte index.

Explain the behavior when y is not


contained in x.
63 Replace fragment of a string
Assign to x2 the value of string x with
let x2 = x.replace(&y, &z); ×
all occurrences of y replaced by z.
Assume occurrences of y are not
overlapping.
64 Big integer : value 3 power 247
Assign to x the value 3^247
let a = 3.to_bigint().unwrap();
let x = num::pow(a, 247);
×
65 Format decimal number
From the real value x in [0,1], create its
let s = format!("{:.1}%", 100.0 * x); ×
percentage string representation s with
one digit after decimal point. E.g.
0.15625 -> "15.6%"
66 Big integer exponentiation
Calculate the result z of x power n,
let z = num::pow(x, n); ×
where x is a big integer and n is a
positive integer.

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());

71 Echo program implementation


Basic implementation of the Echo
println!("{}", env::args().skip(1).col
lect::<Vec<_>>().join(" "));
×
program: Print all arguments except
the program name, separated by
space, followed by newline. Alternative implementation:
The idiom demonstrates how to skip
println!("{}", std::env::args().skip
the first argument if necessary,
(1).format(" "));
concatenate arguments as strings,
append newline and print it to stdout.
73 Create a factory
Create a factory named fact for any
fn fact<Parent: std::str::FromStr>(st
r: String, _: Parent) -> Parent where
×
sub class of Parent and taking exactly
<Parent as FromStr>::Err: Debug
one string str as constructor
parameter.
{
return str.parse::<Parent>().unwra

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.

78 "do while" loop


Execute a block once, then execute it
loop {
doStuff();
×
again as long as boolean condition c is
if !c { break; }
true.
}

Alternative implementation:
while {
doStuff();
c
} { /* EMPTY */ }

79 Convert integer to floating point


number
let y = x as f64; ×
Declare the floating point number y
and initialize it with the value of the
integer x .
80 Truncate floating point number to
integer
let y = x as i32; ×
Declare integer y and initialize it with
the value of floating point number x .
Ignore non-integer digits of x .
Make sure to truncate towards zero: a
negative x must yield the closest
greater integer (not lesser).

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.

E.g. i=6 → c=2


85 Check if integer addition will
overflow
fn adding_will_overflow(x: usize, y: u
size) -> bool {
×
Write boolean function
addingWillOverflow which takes two
x.checked_add(y).is_none()
integers x, y and return true if (x+y)
}
overflows.

An overflow may be above the max


positive value, or below the min
negative value.
86 Check if integer multiplication will
overflow
fn multiply_will_overflow(x: i64, y: i
64) -> bool {
×
Write the boolean function
x.checked_mul(y).is_none()
multiplyWillOverflow which takes two
integers x, y and returns true if (x*y)
}
overflows.

An overflow may reach above the max


positive value, or below the min
negative value.
87 Stop program
Exit immediately.
std::process::exit(0); ×
If some extra cleanup work is executed
by the program runtime (not by the OS
itself), describe it.

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.

89 Handle invalid argument


You've detected that the integer value
enum CustomError { InvalidAnswer } ×
of argument x passed to the current
fn do_stuff(x: i32) -> Result<i32, Cus
function is invalid. Write the idiomatic
tomError> {
way to abort the function execution and
if x != 42 {
signal the problem.
Err(CustomError::InvalidAnswe
r)
} else {
Ok(x)
}
}

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 }
}

pub fn x<'a>(&'a self) -> &'a usiz


e {
&self.x
}

pub fn bar(&mut self) {


self.x += 1;
}
}

91 Load JSON file into object


Read from the file data.json and write
let x = ::serde_json::from_reader(Fil
e::open("data.json")?)?;
×
its content into the object x.
Assume the JSON data is suitable for
the type of x.
92 Save object into JSON file
Write the contents of the object x into
::serde_json::to_writer(&File::create
("data.json")?, &x)?
×
the file data.json.

93 Pass a runnable procedure as


parameter
fn control(f: impl Fn()) {
f();
×
Implement the procedure control
}
which receives one parameter f, and

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.

95 Get file size


Assign to variable x the length (number
let x = fs::metadata(path)?.len(); ×
of bytes) of the local file at path.
Alternative implementation:
let x = path.metadata()?.len();

Alternative implementation:
let x = fs::metadata(path)?.st_size();

96 Check string prefix


Set the boolean b to true if string s
let b = s.starts_with(prefix); ×
starts with prefix prefix, false
otherwise.
97 Check string suffix
Set boolean b to true if string s ends
let b = s.ends_with(suffix); ×
with string suffix, false otherwise.
98 Epoch seconds to date object
Convert a timestamp ts (number of
let d = NaiveDateTime::from_timestamp
(ts, 0);
×
seconds in epoch-time) to a date with
time d. E.g. 0 -> 1970-01-01 00:00:00
99 Format date YYYY-MM-DD
Assign to the string x the value of the
Utc::today().format("%Y-%m-%d") ×
fields (year, month, day) of the date d,
in format YYYY-MM-DD. Alternative implementation:
let format = format_description!("[yea
r]-[month]-[day]");
let x = d.format(&format).expect("Fail
ed to format the date");

100 Sort by a comparator


Sort elements of array-like collection
items.sort_by(c); ×
items, using a comparator c.
101 Load from HTTP GET request into a
string
let client = Client::new();
let s = client.get(u).send().and_then
×
Make an HTTP request with method
GET to the URL u, then store the body
(|res| res.text())?;
of the response in the string s.
Alternative implementation:

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)?;

102 Load from HTTP GET request into a


file
let client = Client::new();
match client.get(&u).send() {
×
Make an HTTP request with method
Ok(res) => {
GET to the URL u, then store the body
let file = File::create("resul
of the response in the file result.txt.
t.txt")?;
Try to save the data as it arrives if
::std::io::copy(res, file)?;
possible, without having all its content
},
in memory at once.
Err(e) => eprintln!("failed to sen
d request: {}", e),
};

105 Current executable name


1
fn get_exec_name() -> Option<String> {
std::env::current_exe()
×
.ok()
.and_then(|pb| pb.file_name().
map(|s| s.to_os_string()))
.and_then(|s| s.into_string().
ok())
}

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();

106 Get program working directory


Assign to string dir the path of the
let dir = env::current_dir().unwrap(); ×
working directory.

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();

109 Number of bytes of a type


Set n to the number of bytes of a
let n = std::mem::size_of::<T>(); ×
variable t (of type T).
110 Check if string is blank
Set the boolean blank to true if the
let blank = s.trim().is_empty(); ×
string s is empty, or null, or contains
only whitespace ; false otherwise. Alternative implementation:
let blank = s.chars().all(|c| c.is_whi
tespace());

111 Launch other program


From current process, run program x
let output = Command::new("x")
.args(&["a", "b"])
×
with command-line parameters "a", "b".
.spawn()
.expect("failed to execute proces
s");

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");

112 Iterate over map entries, ordered by


keys
for (k, x) in mymap {
println!("({}, {})", k, x);
×
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
Print each key k with its value x from }
an associative array mymap, in
ascending order of k.
113 Iterate over map entries, ordered by
values
for (k, x) in mymap.iter().sorted_by_k
ey(|x| x.1) {
×
Print each key k with its value x from
println!("[{},{}]", k, x);
an associative array mymap, in
}
ascending order of x.
Multiple entries may exist for the same
value x. Alternative implementation:
let mut items: Vec<_> = mymap.iter().c
ollect();
items.sort_by_key(|item| item.1);
for (k, x) in items {
println!("[{},{}]", k, x);
}

114 Test deep equality


Set boolean b to true if objects x and y
let b = x == y; ×
contain the same values, recursively
comparing all referenced elements in x
and y.
Tell if the code correctly handles
recursive types.
115 Compare dates
Set boolean b to true if date d1 is
let b = d1 < d2; ×
strictly before date d2 ; false otherwise.
116 Remove occurrences of word from
string
s2 = s1.replace(w, ""); ×
Remove all occurrences of string w
from string s1, and store the result in Alternative implementation:
s2.
let s2 = str::replace(s1, w, "");

117 Get list size


Set n to the number of elements of the
let n = x.len(); ×
list x.

118 List to set


Create the set y from the list x.
let y: HashSet<_> = x.into_iter().coll
ect();
×
x may contain duplicates. y is
unordered and has no repeated
values.
119 Deduplicate list
Remove duplicates from the list x.
x.sort();
x.dedup();
×
Explain if the original order is
preserved.
Alternative implementation:

Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust

let dedup: Vec<_> = x.iter().unique().


collect();

120 Read integer from stdin


Read an integer value from the
fn get_input() -> String {
let mut buffer = String::new();
×
standard input into the variable n
std::io::stdin().read_line(&mut bu
ffer).expect("Failed");
buffer
}

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!();

121 UDP listen and read


Listen UDP traffic on port p and read
let mut b = [0 as u8; 1024];
let sock = UdpSocket::bind(("localhos
×
1024 bytes into the buffer b.
t", p)).unwrap();
sock.recv_from(&mut b).unwrap();

122 Declare an enumeration


Create an enumerated type Suit with 4
enum Suit {
Spades,
×
possible values SPADES, HEARTS,

Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
DIAMONDS, CLUBS. Hearts,
Diamonds,
Clubs,
}

123 Assert condition


Verify that predicate isConsistent
assert!(is_consistent); ×
returns true, otherwise report assertion
violation.
Explain if the assertion is executed
even in production environment or not.
124 Binary search for a value in sorted
array
a.binary_search(&x).unwrap_or(-1); ×
Write the function binarySearch which
returns the index of an element having
the value x in the sorted array a, or -1
if no such element exists.
125 Measure function call duration
measure the duration t, in
let start = Instant::now();
foo();
×
nanoseconds, of a call to the function
let duration = start.elapsed();
foo. Print this duration.
println!("{}", duration);

126 Multiple return values


Write a function foo that returns a
fn foo() -> (String, bool) {
(String::from("bar"), true)
×
string and a boolean value.
}

127 Source code inclusion


Import the source code for the function
fn main() {
include!("foobody.txt");
×
foo body from a file "foobody.txt".
}

128 Breadth-first traversing of a tree


Call a function f on every node of a
struct Tree<V> {
children: Vec<Tree<V>>,
×
tree, in breadth-first prefix order
value: V
}

impl<V> Tree<V> {
fn bfs(&self, f: impl Fn(&V)) {
let mut q = VecDeque::new();
q.push_back(self);

while let Some(t) = q.pop_fron


t() {
(f)(&t.value);
for child in &t.children {
q.push_back(child);
}

Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
}
}
}

129 Breadth-first traversal in a graph


Call the function f on every vertex
struct Vertex<V> {
value: V,
×
accessible from the vertex start, in
neighbours: Vec<Weak<RefCell<V
breadth-first prefix order
ertex<V>>>>,
}

// ...

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);
}
}
}
}

130 Depth-first traversal in a graph


Call th function f on every vertex
struct Vertex<V> {
value: V,
×
accessible from the vertex v, in depth-
neighbours: Vec<Weak<RefCell<V
first prefix order
ertex<V>>>>,
}

// ...

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);
}
}
}

131 Successive conditions


Execute f1 if condition c1 is true, or
if c1 { f1() } else if c2 { f2() } els
e if c3 { f3() }
×
else f2 if condition c2 is true, or else f3
if condition c3 is true.
Don't evaluate a condition when a Alternative implementation:
previous condition was true.
match true {
_ if c1 => f1(),
_ if c2 => f2(),
_ if c3 => f3(),
_ => (),
}

132 Measure duration of procedure


execution
let start = Instant::now();
f();
×
Run the procedure f, and return the
let duration = start.elapsed();
duration of the execution of f.

133 Case-insensitive string contains


Set boolean ok to true if string word is
let re = Regex::new(&format!("(?i){}",
regex::escape(word))).unwrap();
×
contained in string s as a substring,
let ok = re.is_match(&s);
even if the case doesn't match, or to
false otherwise.
Alternative implementation:
let re =
RegexBuilder::new(&regex::escape(w
ord))
.case_insensitive(true)
.build().unwrap();

let ok = re.is_match(s);

Alternative implementation:
let ok = s.to_ascii_lowercase().contai
ns(&word.to_ascii_lowercase());

134 Create a new list


Declare and initialize a new list items,
let items = vec![a, b, c]; ×
containing 3 elements a, b, c.

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());

138 Create temp file


Create a new temporary file on the
let temp_dir = TempDir::new("prefi
x")?;
×
filesystem.
let temp_file = File::open(temp_dir.pa
th().join("file_name"))?;

139 Create temp directory


Create a new temporary folder on
let tmp = TempDir::new("prefix")?; ×
filesystem, for writing.
140 Delete map entry
Delete from map m the entry having
m.remove(&k); ×
key k.

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.
}

142 Hexadecimal digits of an integer


Assign to string s the hexadecimal
let s = format!("{:X}", x); ×
representation (base 16) of integer x.

E.g. 999 -> "3e7"


143 Iterate alternatively over two lists
Iterate alternatively over the elements
for pair in izip!(&items1, &items2) {
println!("{}", pair.0);
×
of the lists items1 and items2. For
each iteration, print the element.
println!("{}", pair.1);
}
Explain what happens if items1 and
items2 have different size.
144 Check if file exists
Set boolean b to true if file at path fp
let b = std::path::Path::new(fp).exist
s();
×
exists on filesystem; false otherwise.

Beware that you should not do this and


then in the next instruction assume the
result is still valid, this is a race
condition on any multitasking OS.
145 Print log line with datetime
Print message msg, prepended by
eprintln!("[{}] {}", humantime::format
_rfc3339_seconds(std::time::SystemTim
×
current date and time.
e::now()), msg);
Explain what behavior is idiomatic: to
stdout or stderr, and what the date
format is.
146 Convert string to floating point
number
let f = s.parse::<f32>().unwrap(); ×
Extract floating point value f from its
string representation s Alternative implementation:
let f: f32 = s.parse().unwrap();

147 Remove all non-ASCII characters


Create string t from string s, keeping
let t = s.replace(|c: char| !c.is_asci
i(), "");
×
only ASCII characters

Alternative implementation:

Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust

let t = s.chars().filter(|c| c.is_asci


i()).collect::<String>();

148 Read list of integers from stdin


Read a list of integer numbers from the
let mut string = String::new();
io::stdin().read_to_string(&mut strin
×
standard input, until EOF.
g)?;
let result = string
.lines()
.map(i32::from_str)
.collect::<Result<Vec<_>, _>>();

150 Remove trailing slash


Remove the last character from the
if p.ends_with('/') { p.pop(); } ×
string p, if this character is a forward
slash /
151 Remove string trailing path
separator
let p = if ::std::path::is_separator
(p.chars().last().unwrap()) {
×
Remove last character from string p, if
this character is the file path separator
&p[0..p.len()-1]
of current platform.
} else {
p
Note that this also transforms unix root
};
path "/" into the empty string!
Alternative implementation:
p = p.strip_suffix(std::path::is_separ
ator).unwrap_or(p);

152 Turn a character into a string


Create string s containing only the
let s = c.to_string(); ×
character c.
153 Concatenate string with integer
Create the string t as the
let t = format!("{}{}", s, i); ×
concatenation of the string s and the
integer i. Alternative implementation:
let t = format!("{s}{i}");

154 Halfway between two hex color


codes
"Too long for text box, see online dem
o"
×
Find color c, the average between
colors c1, c2.

c, c1, c2 are strings of hex color


codes: 7 chars, beginning with a
number sign # .
Assume linear computations, ignore
gamma corrections.

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>
}

160 Detect if 32-bit or 64-bit architecture


Execute f32() if platform is 32-bit, or
match
4
std::mem::size_of::<&char>() {
=> f32(),
×
f64() if platform is 64-bit.
8 => f64(),
This can be either a compile-time
_ => {}
condition (depending on target) or a
}
runtime detection.

Alternative implementation:
#[cfg(target_pointer_width = "64")]
f64();

#[cfg(target_pointer_width = "32")]
f32();

161 Multiply all the elements of a list


Multiply all the elements of the list
let elements = elements.into_iter().ma
p(|x| c * x).collect::<Vec<_>>();
×
elements by a constant c

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);

162 Execute procedures depending on


options
if let Some(arg) = ::std::env::args().
nth(1) {
×
execute bat if b is a program option
if &arg == "f" {
and fox if f is a program option.
fox();
} else if &arg = "b" {
bat();
} else {
eprintln!("invalid argument:
{}", arg),
}
} else {
eprintln!("missing argument");
}

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");
}

163 Print list elements by group of 2


Print all the list elements, two by two,
for pair in list.chunks(2) {
println!("({}, {})", pair[0], pair
×
assuming list length is even.
[1]);
}

164 Open URL in the default browser


Open the URL s in the default browser.
webbrowser::open(s).expect("failed to
open URL");
×
Set the boolean b to indicate whether
the operation was successful.
165 Last element of list
Assign to the variable x the last
let x = items[items.len()-1]; ×
element of the list items.
Alternative implementation:
let x = items.last().unwrap();

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);

168 Trim suffix


Create string t consisting of string s
let t = s.trim_end_matches(w); ×
with its suffix w removed (if s ends with
w). Alternative implementation:
let t = s.strip_suffix(w).unwrap_or
(s);

169 String length


Assign to the integer n the number of
let n = s.chars().count(); ×
characters of the string s.
Make sure that multibyte characters
are properly handled.
n can be different from the number of
bytes of s.
170 Get map size
Set n to the number of elements stored
let n = mymap.len(); ×
in mymap.

This is not always equal to the map


capacity.
171 Add an element at the end of a list
Append the element x to the list s.
s.push(x); ×
172 Insert an entry in a map
Insert value v for key k in map m.
m.insert(k, v); ×
173 Format a number with grouped
thousands
println!("{}", 1000.separated_string
());
×
Number will be formatted with a
comma separator between every group
of thousands.

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()?;

175 Bytes to hex string


From the array a of n bytes, build the
let s = a.encode_hex::<String>(); ×
equivalent hex string s of 2n digits.
Each byte (256 possible values) is Alternative implementation:
encoded as two hexadecimal
let mut s = String::with_capacity(2 *
characters (16 possible values per
n);
digit).
for byte in a {
write!(s, "{:02X}", byte)?;
}

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'];

let upper = HEX_LUT[(byte >> 4) as


usize];
let lower = HEX_LUT[(byte & 0xF) a
s usize];
(lower, upper)
}

let utf8_bytes: Vec<u8> = a.iter().cop


ied().flat_map(|byte| {
let (lower, upper) = byte_to_h
ex(byte);
[upper, lower]
}).collect();
let s = unsafe { String::from_utf8_unc
hecked(utf8_bytes) };

176 Hex string to byte array


From hex string s of 2n digits, build the
let a: Vec<u8> = Vec::from_hex(s).expe
ct("Invalid Hex String");
×
equivalent array a of n bytes.
Each pair of hexadecimal characters
(16 possible values per digit) is Alternative implementation:

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();

177 Find files for a list of filename


extensions
let d = Path::new("/path/to/D");
let l: Vec<PathBuf> = d
×
Construct a list L that contains all
.read_dir()?
filenames that have the extension
.filter_map(|f| f.ok())
".jpg" , ".jpeg" or ".png" in directory D
.filter(|f| match f.path().extensi
and all its subdirectories.
on() {
None => false,
Some(ex) => ex == "jpg" || ex
== "jpeg" || ex == "png"
})
.map(|f| f.path())
.collect();

178 Check if point is inside rectangle


Set boolean b to true if if the point with
struct Rect {
x1: i32,
×
coordinates (x,y) is inside the
rectangle with coordinates
x2: i32,
(x1,y1,x2,y2) , or to false otherwise.
y1: i32,
Describe if the edges are considered to
y2: i32,
be inside the rectangle.
}

impl Rect {
fn contains(&self, x: i32, y: i32)
-> bool {
return self.x1 < x && x < sel
f.x2 && self.y1 < y && y < self.y2;
}
}

179 Get center of a rectangle


Return the center c of the rectangle
struct Rectangle {
x1: f64,
×
with coördinates(x1,y1,x2,y2)
y1: f64,
x2: f64,
y2: f64,
}

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)
}
}

180 List files in directory


Create the list x containing the
let x = std::fs::read_dir(d).unwrap(); ×
contents of the directory d.
Alternative implementation:
x may contain files and subfolders.
let x = std::fs::read_dir(d)?.collec
No recursive subfolder listing.
t::<Result<Vec<_>, _>>()?;

182 Quine program


Output the source of the current
fn main() {
let x = "fn main() {\n let x =
×
program. A quine is a computer
program that takes no input and
";
let y = "print!(\"{}{:?};\n let
produces a copy of its own source
code as its only output.
y = {:?};\n {}\", x, x, y, y)\n}
\n";
Reading the source file from disk is
print!("{}{:?};
cheating.
let y = {:?};
{}", x, x, y, y)
}

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.

186 Exit program cleanly


Exit a program cleanly indicating no
exit(0); ×
error to OS
188 Matrix multiplication
Perform matrix multiplication of a real
let c = a.dot(&b); ×
matrix a with nx rows and ny columns,
a real matrix b with ny rows and nz
columns and assign the value to a real
matrix c with nx rows and nz columns.
189 Filter and transform list
Produce a new list y containing the
let y = x.iter()
.filter(P)
×
result of the function T applied to all

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<_>>();

190 Call an external C function


Declare an external C function with the
extern "C" {
/// # Safety
×
prototype
///
/// `a` must point to an array of
void foo(double *a, int n);
at least size 10
fn foo(a: *mut libc::c_double, n:
and call it, passing an array (or a list)
libc::c_int);
of size 10 to a and 10 to n.
}
Use only standard features of your
let mut a = [0.0, 1.0, 2.0, 3.0, 4.0,
language.
5.0, 6.0, 7.0, 8.0, 9.0];
let n = 10;
unsafe {
foo(a.as_mut_ptr(), n);
}

191 Check if any value in a list is larger


than a limit
if a.iter().any(|&elem| elem > x) {
f()
×
Given a one-dimensional array a,
check if any value is larger than x, and
}
execute the procedure f if that is the
case
192 Declare a real variable with at least
20 digits
let a = Decimal::from_str("1234567890.
123456789012345").unwrap();
×
Declare a real variable a with at least
20 digits; if the type does not exist,
issue an error at compile time.
193 Transpose a two-dimensional matrix
Declare two two-dimensional arrays a
let a = DMatrix::<u8>::from_fn(n, m, |
_, _| rand::thread_rng().gen());
×
and b of dimension n*m and m*n,
let b = a.transpose();
respectively. Assign to b the transpose
of a (i.e. the value with index
interchange).
195 Pass a two-dimensional array
Pass an array a of real numbers to the
fn foo(a: Vec<Vec<usize>>) {
println!(
×
procedure (resp. function) foo. Output
the size of the array, and the sum of all
"Length of array: {}",
its elements when each element is
a.clone()
multiplied with the array indices i and j
.into_iter()
(assuming they start from one).
.flatten()
.collect::<Vec<usize>>()
.len()
);

let mut sum = 0;

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
}

println!("Sum of all products of i


ndices: {}", sum);
}

196 Pass a sub-array


Given an integer array a of size n,
fn foo(el: &mut i32) {
*el = 42;
×
pass the first, third, fifth and seventh,
}
... up to the m th element to a routine
a.iter_mut().take(m).step_by(2).for_ea
foo which sets all these elements to
ch(foo);
42.

197 Get a list of lines from a file


Retrieve the contents of file at path
let lines = BufReader::new(File::open
(path).unwrap())
×
into a list of strings lines, in which
each element is a line of the file.
.lines()
.collect::<Vec<_>>();

198 Abort program execution with error


condition
process::exit(x); ×
Abort program execution with error
condition x (where x is an integer
value)
199 Truncate a file at the current file
position
let pos = f.stream_position()?;
f.set_len(pos)?;
×
Truncate a file F at the given file
position.
200 Return hypotenuse
Compute the hypotenuse h of the
fn hypot(x:f64, y:f64)-> f64 {
let num = x.powi(2) + y.powi(2);
×
triangle where the sides adjacent to the
num.powf(0.5)
square angle have lengths x and y.
}

Alternative implementation:
let h = x.hypot(y);

201 Euclidean norm


Calculate n, the Euclidean norm of
fn euclidean(data: Vec<f64>) -> f64 {
let mut n = 0.0;
×
data, where data is a list of floating
point values.
for i in data {
n += i*i;
}
return sqrt(n as f64)
}
let n = euclidean(data);

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.

203 Calculate mean and standard


deviation
let sum: f64 = data.iter().sum();
let m = sum / (data.len() as f64);
×
Calculate the mean m and the
let sum_of_squares: f64 = data.iter().
standard deviation s of the list of
map(|item| (item - m) * (item - m)).su
floating point values data.
m();
let s = (sum_of_squares / (list.len()
as f64)).sqrt();

204 Return fraction and exponent of a


real number
let sign = if a < 0.0 { a = -a; -1 } e
lse { 1 };
×
Given a real number a, print the
fractional part and the exponent of the
let exponent = (a + f64::EPSILON).log2
().ceil() as i32;
internal representation of that number.
For 3.14, this should print
let fraction = a / 2.0f64.powi(exponen
(approximately)
t);

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") {
//
}

206 Switch statement with strings


Execute different procedures foo, bar,
match str {
"foo" => foo(),
×
baz and barfl if the string str contains
"bar" => bar(),

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(),
_ => {}
}

207 Allocate a list that is automatically


deallocated
let a = vec![0; n]; ×
Allocate a list a containing n elements
(n assumed to be too large for a stack)
that is automatically deallocated when
the program exits the scope it is
declared in.
208 Formula with arrays
Given the arrays a,b,c,d of equal
for i in 0..a.len() {
a[i] = e * (a[i] + b[i] * c[i] + d
×
length and the scalar e, calculate a =
[i].cos());
e*(a+b*c+cos(d)).
}
Store the results in a.

209 Type with automatic deep


deallocation
struct T {
s: String,
×
Declare a type t which contains a
string s and an integer array n with
n: Vec<usize>,
}
variable size, and allocate a variable v
of type t. Allocate v.s and v.n and set
them to the values "Hello, world!" for s
fn main() {
and [1,4,9,16,25], respectively.
let v = T {
Deallocate v, automatically
s: "Hello, world!".int
deallocating v.s and v.n (no memory
o(),
leaks).
n: vec![1,4,9,16,25]
};
}

211 Create folder


Create the folder at path on the
fs::create_dir(path)?; ×
filesystem
Alternative implementation:
fs::create_dir_all(path)?;

212 Check if folder exists


Set the boolean b to true if path exists
let b: bool = Path::new(path).is_dir
();
×
on the filesystem and is a directory;
false otherwise.
213 Case-insensitive string compare
Compare four strings in pair-wise
for x in strings
.iter()
×
variations. The string comparison can
be implemented with an equality test or
.combinations(2)
a containment test, must be case-
.filter(|x| x[0].to_lowercase() ==
insensitive and must apply Unicode
x[1].to_lowercase())
casefolding.
{

Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
println!("{:?} == {:?}", x[0], x
[1])
}

214 Pad string on the right


Append extra character c at the end of
let out = s.pad_to_width_with_char(m,
c);
×
string s to make sure its length is at
least m.
The length is the number of characters,
not the number of bytes.
215 Pad string on the left
Prepend extra character c at the
if let Some(columns_short) = m.checked
_sub(s.width()) {
×
beginning of string s to make sure its
let padding_width = c
length is at least m.
.width()
The length is the number of characters,
.filter(|n| *n > 0)
not the number of bytes.
.expect("padding character sho
uld be visible");
// Saturate the columns_short
let padding_needed = columns_short
+ padding_width - 1 / padding_width;
let mut t = String::with_capacity
(s.len() + padding_needed);
t.extend((0..padding_needed).map(|
_| c)
t.push_str(&s);
s = t;
}

216 Pad a string on both sides


Add the extra character c at the
let n = (m + s.len())/2;
s = format!("{s:X>n$}");
×
beginning and ending of string s to
make sure its length is at least m.
s = format!("{out:X<m$}");
After the padding the original content
of s should be at the center of the Alternative implementation:
result.
s = s.pad(m, c, Alignment::Middle, tru
The length is the number of characters,
e);
not the number of bytes.

E.g. with s="abcd", m=10 and c="X"


the result should be "XXXabcdXXX".
217 Create a Zip archive
Create a zip-file with filename name
let path = std::path::Path::new(_nam
e);
×
and add the files listed in list to that
zip-file.
let file = std::fs::File::create(&pat
h).unwrap();
let mut zip = zip::ZipWriter::new(fil
e); zip.start_file("readme.txt", FileO
ptions::default())?;

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(())
}

218 List intersection


Create the list c containing all unique
let unique_a = a.iter().collect::<Hash
Set<_>>();
×
elements that are contained in both
let unique_b = b.iter().collect::<Hash
lists a and b.
Set<_>>();
c should not contain any duplicates,
even if a and b do.
let c = unique_a.intersection(&unique_
The order of c doesn't matter.
b).collect::<Vec<_>>();

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);

219 Replace multiple spaces with single


space
let re = Regex::new(r"\s+").unwrap();
let t = re.replace_all(s, " ");
×
Create the string t from the value of
string s with each sequence of spaces
replaced by a single space.

Explain if only the space characters will


be replaced, or the other whitespaces
as well: tabs, newlines.

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.

Explain if the elements of t are strongly


typed or not.
221 Remove all non-digits characters
Create string t from string s, keeping
let t: String = s.chars().filter(|c|
c.is_digit(10)).collect();
×
only digit characters 0, 1, 2, 3, 4, 5, 6,
7, 8, 9.
222 Find the first index of an element in
list
let opt_i = items.iter().position(|y|
*y == x);
×
Set i to the first index in list items at
which the element x can be found, or
-1 if items does not contain x.
let i = match opt_i {
Some(index) => index as i32,
None => -1
};

Alternative implementation:
let i = items.iter().position(|y| *y =
= x).map_or(-1, |n| n as i32);

223 for else loop


Loop through list items checking a
let mut found = false;
for item in items {
×
condition. Do something else if no
if item == &"baz" {
matches are found.
println!("found it");
found = true;
A typical use case is looping through a
break;
series of containers looking for one
}
that matches a condition. If found, an
}
item is inserted; otherwise, a new
if !found {
container is created.
println!("never found it");
}
These are mostly used as an inner
nested loop, and in a location where
refactoring inner logic into a separate Alternative implementation:
function reduces clarity.
if let None = items.iter().find(|&&ite
m| item == "rockstar programmer") {
println!("NotFound");
};

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");
}

224 Add element to the beginning of the


list
items.push_front(x); ×
Insert the element x at the beginning of
the list items.
225 Declare and use an optional
argument
fn f(x: Option<()>) {
match x {
×
Declare an optional integer argument x
Some(x) => println!("Present
to procedure f, printing out "Present"
{}", x),
and its value if it is present, "Not
None => println!("Not presen
present" otherwise
t"),
}
}

226 Delete last element from list


items.pop(); ×
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
Remove the last element from the list
items.
227 Copy a list
Create the new list y containing the
let y = x.clone(); ×
same elements as the list x.

Subsequent modifications of y must


not affect x (except for the contents
referenced by the elements
themselves if they contain pointers).
228 Copy a file
Copy the file at path src to dst.
fs::copy(src, dst).unwrap(); ×
230 Timeout
Cancel an ongoing processing p if it
timeout(Duration::from_secs(5), p()).a
wait;
×
has not finished after 5s.

231 Test if bytes are a valid UTF-8 string


Set b to true if the byte sequence s
let b = std::str::from_utf8(&bytes).is
_ok();
×
consists entirely of valid UTF-8
character code points, false otherwise.
232 Read a command line boolean flag
Print "verbose is true" if the flag -v was
let matches = App::new("My Program")
.arg(Arg::with_name("v
×
passed to the program command line,
erbose")
"verbose is false" otherwise.
.short("v")
.takes_value(fals
e))
.get_matches();

if matches.is_present("verbose") {
println!("verbose is true")
} else {
println!("verbose is false")
}

234 Encode bytes to base64


Assign to the string s the standard
let s = base64::encode(data); ×
base64 encoding of the byte array
data, as specified by RFC 4648.
235 Decode base64
Assign to byte array data the bytes
let bytes = base64::decode(s).unwrap
();
×
represented by the base64 string s, as
specified by RFC 4648.
237 Xor integers
Assign to c the result of (a xor b)
let c = a ^ b; ×
238 Xor byte arrays
Write in a new byte array c the xor
let c: Vec<_> = a.iter().zip(b).map(| ×
result of byte arrays a and b.

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.

A word containing more digits, or 3


digits as a substring fragment, must
not match.
240 Sort 2 lists together
Lists a and b have the same length.
let mut tmp: Vec<_> = a.iter().zip(b).
collect();
×
Apply the same permutation to a and b
tmp.as_mut_slice().sort_by_key(|(&x, _
to have them sorted based on the
y)| x);
values of a.
let (aa, bb): (Vec<i32>, Vec<i32>) = t
mp.into_iter().unzip();

241 Yield priority to other threads


Explicitly decrease the priority of the
::std::thread::yield_now();
busywork();
×
current process, so that other
execution threads have a better
chance to execute now. Then resume
normal execution and call the function
busywork.
242 Iterate over a set
Call a function f on each element e of a
for item in &x {
f(item);
×
set x.
}

243 Print list


Print the contents of the list or array a
println!("{:?}", a) ×
on the standard output.
244 Print a map
Print the contents of the map m to the
println!("{:?}", m); ×
standard output: keys and values.
245 Print value of custom type
Print the value of object x having
println!("{:?}", x); ×
custom type T, for log or debug.
246 Count distinct elements
Set c to the number of distinct
let c = items.iter().unique().count(); ×
elements in the list items.
247 Filter list in-place
Remove all the elements from list x
let mut j = 0;
for i in 0..x.len() {
×
that don't satisfy the predicate p,
if p(x[i]) {
without allocating a new list.
x[j] = x[i];
Keep all the elements that do satisfy p.
j += 1;

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);

248 Construct a 64-bit floating-point


value
let d = if s { -1.0 } else { 1.0 } * m
as f64 * 2.0f64.powf(e as f64);
×
Construct the "double precision" (64-
bit) floating point number d from the
mantissa m, the exponent e and the
sign flag s (true means the sign is
negative).
249 Declare and assign multiple
variables
let (a, b, c) = (42, "hello", 5.0); ×
Define variables a, b and c in a
concise way.
Explain if they need to have the same
type.
250 Pick a random value from a map
Choose a value x from map m.
let mut rng = rand::thread_rng();
let x = m.values().choose(&mut rng).ex
×
m must not be empty. Ignore the keys.
pect("m is empty");

251 Parse binary digits


Extract integer value i from its binary
let i = i32::from_str_radix(s, 2).expe
ct("Not a binary number!");
×
string representation s (in radix 2)
E.g. "1101" -> 13
252 Conditional assignment
Assign to the variable x the string
x = if condition() { "a" } else { "b"
};
×
value "a" if calling the function
condition returns true, or the value "b"
otherwise.
253 Print stack trace
Print the stack frames of the current
let bt = Backtrace::new();
println!("{:?}", bt);
×
execution thread of the program.

254 Replace value in list


Replace all exact occurrences of "foo"
for v in &mut x {
if *v == "foo" {
×
with "bar" in the string list x
*v = "bar";
}
}

255 Print a set


Print the values of the set x to the
println!("{:?}", x); ×
standard output.
The order of the elements is irrelevant

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);
}

257 Traverse list backwards


Print each index i and value x from the
for (i, item) in items.iter().enumerat
e().rev() {
×
list items, from the last down to the
println!("{} = {}", i, *item);
first.
}

Alternative implementation:
for (i, x) in items.iter().rev().enu
merate() {
println!("{i} = {x}");
}

258 Convert list of strings to list of


integers
let b: Vec<i64> = a.iter().map(|x| x.p
arse::<i64>().unwrap()).collect();
×
Convert the string values from list a
into a list of integers b.
Alternative implementation:
let b: Vec<i32> = a.iter().flat_map(|s
| s.parse().ok()).collect();

259 Split on several separators


Build the list parts consisting of
let parts: Vec<_> = s.split(&[',', '-
', '_'][..]).collect();
×
substrings of the input string s,
separated by any of the characters ','
(comma), '-' (dash), '_' (underscore).
260 Create an empty list of strings
Declare a new list items of string
let items: Vec<String> = vec![]; ×
elements, containing zero elements
261 Format time hours-minutes-seconds
Assign to the string x the value of fields
let format = format_description!("[hou
r]:[minute]:[second]");
×
(hours, minutes, seconds) of the date
let x = d.format(&format).expect("Fail
d, in format HH:MM:SS.
ed to format the time");

262 Count trailing zero bits


Assign to t the number of trailing 0 bits
let t = n.trailing_zeros(); ×
in the binary representation of the

Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
integer n.

E.g. for n=112, n is 1110000 in base 2


⇒ t=4
263 Integer logarithm in base 2
Write two functions log2d and log2u,
fn log2d(n: f64) -> f64 {
n.log2().floor()
×
which calculate the binary logarithm of
}
their argument n rounded down and
up, respectively. n is assumed to be
fn log2u(n: f64) -> f64 {
positive. Print the result of these
n.log2().ceil()
functions for numbers from 1 to 12.
}

fn main() {
for n in 1..=12 {
let f = f64::from(n);
println!("{} {} {}", n, log2d
(f), log2u(f));
}
}

264 Automated passing of array bounds


Pass a two-dimensional integer array a
fn foo(matrix: &[Vec<i32>]) {
let iter = matrix.iter();
×
to a procedure foo and print the size of
the array in each dimension. Do not
let (vertical, _) = iter.size_hint
();
pass the bounds manually. Call the
let horizontal = iter
procedure with a two-dimensional
array.
.max()
.expect("empty array!")
.len();
println!("{horizontal} by {vertica
l}");
}

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);

265 Even parity bit


Calculate the parity p of the integer
let p = i.count_ones() % 2; ×
variable i : 0 if it contains an even
number of bits set, 1 if it contains an
odd number of bits set.
266 Repeated string
Assign to the string s the value of the
let s = v.repeat(n); ×
string v repeated n times, and write it
out.

E.g. v="abc", n=5 ⇒


s="abcabcabcabcabc"
267 Pass string to argument that can be
of any type
fn foo(x: &dyn Any) {
if let Some(s) = x.downcast_ref::<
×
Declare an argument x to a procedure
String>() {
foo that can be of any type. If the type
println!("{}", s);
of the argument is a string, print it,
} else {
otherwise print "Nothing."
println!("Nothing")
}
Test by passing "Hello, world!" and 42
}
to the procedure.

fn main() {
foo(&"Hello, world!".to_owned());
foo(&42);
}

268 User-defined operator


Define a type vector containing three
struct
x:
Vector {
f32,
×
floating point numbers x, y, and z.
y: f32,
Write a user-defined operator x that
calculates the cross product of two
z: f32,
}
vectors a and b.

impl Mul for Vector {


type Output = Self;

fn mul(self, rhs: Self) -> Self {


Self {
x: self.y * rhs.z - self.z
* rhs.y,
y: self.z * rhs.x - self.x
* rhs.z,

Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
z: self.x * rhs.y - self.y
* rhs.x,
}
}
}

269 Enum to String


Given the enumerated type t with 3
let e = t::bike;
let s = format!("{:?}", e);
×
possible values: bike, car, horse.
Set the enum value e to one of the
println!("{}", s);
allowed values of t.
Set the string s to hold the string
representation of e (so, not the ordinal
value).
Print s.
271 Test for type extension
If a variable x passed to procedure tst
fn type_of<T>(_: &T) -> &str {
std::any::type_name::<T>()
×
is of type foo, print "Same type." If it is
}
of a type that extends foo, print
"Extends type." If it is neither, print "Not
related."
if type_of(&x) == type_of(&foo) {
println!("x & foo -> same type");
} else {
println!("x & foo -> not relate
d");
}

272 Play FizzBuzz


Fizz buzz is a children's counting
for i in 1..101 {
match i {
×
game, and a trivial programming task
i if (i % 15) == 0 => println!
used to affirm that a programmer
("FizzBuzz"),
knows the basics of a language: loops,
conditions and I/O.
i if (i % 3) == 0 => println!
("Fizz"),
The typical fizz buzz game is to count
i if (i % 5) == 0 => println!
("Buzz"),
from 1 to 100, saying each number in
_ => println!("{i}"),
turn. When the number is divisible by
3, instead say "Fizz". When the
}
}
number is divisible by 5, instead say
"Buzz". When the number is divisible
by both 3 and 5, say "FizzBuzz"
273 Check if folder is empty
Set the boolean b to true if the
let b = fs::read_dir(p).unwrap().count
() == 0;
×
directory at filepath p is empty (i.e.
doesn't contain any other files and
directories)

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();

276 Insert an element in a set


Insert an element e into the set x.
x.insert(e); ×
277 Remove an element from a set
Remove the element e from the set x.
x.remove(e); ×
Explains what happens if e was Alternative implementation:
already absent from x.
x.take(e)

278 Read one line from the standard


input
let mut buffer = String::new();
let mut stdin = io::stdin();
×
Read one line into the string line.
stdin.read_line(&mut buffer).unwrap();
Explain what happens if EOF is
reached.
279 Read list of strings from the
standard input
let lines = std::io::stdin().lock().li
nes().map(|x| x.unwrap()).collect::<Ve
×
Read all the lines (until EOF) into the
c<String>>();
list of strings lines.

280 Filter map


Remove all the elements from the map
m.retain(|_, &mut v| p(v)); ×
m that don't satisfy the predicate p.
Keep all the elements that do satisfy p.

Explain if the filtering happens in-place,


i.e. if m is reused or if a new map is
created.
281 Use a Point as a map key
You have a Point with integer
let mut map: HashMap<Point, String> =
HashMap::new();
×
coordinates x and y. Create a map m
with key type Point (or equivalent) and
map.insert(Point { x: 42, y: 5 }, "Hel
lo".into());
value type string. Insert "Hello" at
position (42, 5).

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();

284 Create a zeroed list of integers


Create a new list a (or array, or slice)
let a = vec![0; n]; ×
of size n, where all elements are
integers initialized with the value 0.
285 Set variable to NaN
Given two floating point variables a
let a: f64 = f64::NAN; ×
and b, set a to a to a quiet NaN and b
to a signalling NaN. Use standard
features of the language only, without
invoking undefined behavior.
286 Iterate over characters of a string
Print a line "Char i is c" for each
for (i, c) in s.chars().enumerate() {
println!("Char {} is {}", i, c);
×
character c of the string s, where i is
}
the character index of c in s (not the
byte index).

Make sure that multi-byte characters


are properly handled, and count for a
single character.
287 Number of bytes of a string
Assign to n the number of bytes in the
let n = s.len(); ×
string s.

This can be different from the number


of characters. If n includes more bytes
than the characters per se (trailing
zero, length field, etc.) then explain it.
One byte is 8 bits.
288 Check if set contains a value
Set the boolean b to true if the set x
let b = x.contains(&e); ×
contains the element e, false
otherwise.
289 Concatenate two strings
Create the string s by concatenating
let s = format!("{}{}", a, b); ×
the strings a and b.

Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
Alternative implementation:
let s = a + b;

290 Sort sublist


Sort the part of the list items from
items[i..j].sort_by(c); ×
index i (included) to index j (excluded),
in place, using the comparator c.

Elements before i and after j must


remain unchanged.
291 Remove sublist
Delete all the elements from index i
items.drain(i..j) ×
(included) to index j (excluded) from
the list items.
292 Write "Ni Hao" in Chinese to
standard output in UTF-8
println!("Hello World and 你好") ×
Write "Hello World and 你好
" to
standard output in UTF-8.
293 Create a stack
Create a new stack s, push an element
let mut s: Vec<T> = vec![];
s.push(x);
×
x, then pop the element into the
let y = s.pop().unwrap();
variable y.

294 Print a comma-separated list of


integers
let a = [1, 12, 42];
println!("{}", a.map(|i| i.to_string
×
Given an array a containing the three
()).join(", "))
values 1, 12, 42, print out
"1, 12, 42" with a comma and a space
after each integer except the last one.
295 String to Enum
Given the enumerated type T, create a
enum MyEnum {
Foo,
×
function TryStrToEnum that takes a
string s as input and converts it into an
Bar,
enum value of type T.
Baz,
}
Explain whether the conversion is case
impl FromStr for MyEnum{
sensitive or not.
type Err = String;
Explain what happens if the conversion
fails.
fn from_str(s: &str) -> Result<Sel
f, Self::Err> {
match s.to_lowercase().as_str
() {
"foo" => Ok(MyEnum::Foo),
"bar" => Ok(MyEnum::Bar),
"baz" => Ok(MyEnum::Baz),
_ => Err("Could not conver
t str to enum".to_string())
}

Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust
}
}

299 Comment out a single line


Write a line of comments.
// This is a comment ×
This line will not be compiled or
executed.
301 Recursive Fibonacci sequence
Compute the Fibonacci sequence of n
fn fib(n: i32) -> i32 {
if n < 2 {
×
numbers using recursion.
1
} else {
Note that naive recursion is extremely
fib(n - 2) + fib(n - 1)
inefficient for this task.
}
}

302 String interpolation


Given the integer x = 8, assign to the
let s = format!("Our sun has {} planet
s", x);
×
string s the value "Our sun has 8
planets", where the number 8 was
evaluated from x. Alternative implementation:
let s = format!("Our sun has {x} plane
ts");

304 Encode string into UTF-8 bytes


Create the array of bytes data by
let data = s.into_bytes(); ×
encoding the string s in UTF-8.
306 Ensure list capacity
Preallocate memory in the list x for a
x.reserve(200); ×
minimum total capacity of 200
elements.

This is not possible in all languages. It


is only meant as a performance
optimization, should not change the
length of x, and should not have any
effect on correctness.
307 XOR encrypt/decrypt string
Create a function that XOR
fn xor(s: Vec<u8>, key: &[u8]) -> Vec<
u8> {
×
encrypts/decrypts a string
let mut b = key.iter().cycle();
s.into_iter().map(|x| x ^ b.next
().unwrap()).collect()
}

308 Integer to string in base b


Create the string representation s of
let s = radix(n, b); ×
the integer value n in base b.

Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rust

18 in base 3 -> "200"


26 in base 5 -> "101"
121 in base 12 -> "a1"

309 Clone a 2D array


Create the new 2-dimensional array y
let y = x.clone(); ×
containing a copy of the elements of
the 2-dimensional array x.

x and y must not share memory.


Subsequent modifications of y must
not affect x.
310 Fill array with random bytes
Fill the byte array a with randomly
let mut rng = rand::thread_rng();
rng.fill(&mut a);
×
generated bytes.

312 Test for list equality


Set b to true if the lists p and q have
b = p == q; ×
the same size and the same elements,
false otherwise.
314 Fill array with value
Set all the elements in the array x to
x.fill(v); ×
the same value v
317 Random string
Create a string s of n characters
fn random_string(n: usize) -> String {
rand::thread_rng()
×
having uniform random values out of
.sample_iter(Alphanumeric)
the 62 alphanumeric values A-Z, a-z,
.take(n)
0-9
.map(char::from)
.collect()
}

Alternative implementation:
fn random_string(n: usize) -> String {
Alphanumeric.sample_string(&mut ra
nd::thread_rng(), n)
}

318 Cryptographically secure random


number
let mut rng = rand::thread_rng();
let x = rng.gen_range(0..18);
×
Assign to the integer x a random
number between 0 and 17 (inclusive),
from a crypto secure random number
generator.
320 Test if string is empty
Set b to true if the string s is empty,
b = s.is_empty() ×
false otherwise

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.

Make sure to properly handle multi-


byte characters. i is the character
index, which may not be equal to the
byte index.
322 replace value of variable with new
one and return old value
std::mem::replace(&mut x, v); ×
324 Read HTTP response header
Set the string c to the (first) value of
let c = res.headers()
.get(CACHE_CONTROL)
×
the header "cache-control" of the
.expect("cache-control header exis
HTTP response res.
ts")
.to_str()
.expect("cache-control header cont
ains only visible ascii");

325 Create a queue


Create a new queue q, then enqueue
let mut q = VecDeque::new();
q.push_back(x);
×
two elements x and y, then dequeue
q.push_back(x);
an element into the variable z.
let z = q.pop_front();
println!("1st item ~> {}",z.unwrap());

327 Convert string to lower case


Assign to t the value of the string s,
let t = s.to_lowercase() ×
with all letters mapped to their lower
case.
328 Convert string to upper case
Assign to t the value of the string s,
let t = s.to_uppercase(); ×
with all letters mapped to their upper
case.
329 Read value in a map
Assign to v the value stored in the map
let v = m.get(&k); ×
m for the key k.

Explain what happens if there is no


entry for k in m.
330 Map to list
Create the list a containing all the
let a = m.into_values().collect::<Vec<
_>>();
×
values of the map m.

Ignore the keys of m. The order of a


doesn't matter. a may contain duplicate
values.

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.

Explain the type of c, and what


happens if s is empty.

Make sure to properly handle multi-


bytes characters.
341 Find substring last position
Set i to the position of the last
let i = x.rfind(y); ×
occurrence of the string y inside the
string x, if exists.

Specify if i should be regarded as a


character index or as a byte index.

Explain the behavior when y is not


contained in x.
342 Leap year?
Determine if the current year is a leap
let leap_year = year % 4 == 0 && (year
% 100 != 0 || year % 400 == 0);
×
year.

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>>();

357 Swap elements of list


Swap the elements at indices i, j in the
items.swap(i, j); ×
list items

Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF

You might also like