Rust Exercises
Fill in the blanks to check your knowledge. Each exercise belongs to a lesson.
Rust Introduction
Exercise
Which macro prints a line?
!("Hi");Rust Get Started
Exercise
Run a Cargo project.
cargo Rust Syntax
Exercise
End a statement.
println!("a")Rust Output
Exercise
Print with a placeholder.
println!("Hi {}", name);
Variables and Types
Exercise
Allow a variable to change.
let n = 1;
If, Loop, While and For
Exercise
Count 1 to 3 inclusive.
for i in 13 {}
Mutability and Shadowing
Exercise
Allow a change.
let n = 0;
Rust Data Types
Exercise
Convert with as.
a f64
Integer Overflow and Methods
Exercise
Return None on overflow.
x.(10)
Numbers and Math
Exercise
Square root.
x.()
Characters and Booleans
Exercise
Check for a letter.
c.is_()
Tuples and Arrays
Exercise
First tuple field.
t.Variables and Mutability
Exercise
Make it changeable.
let n = 1;
Shadowing
Exercise
Redeclare.
let x = "a"; x = 1;
Scalar Types
Exercise
Unsigned byte.
let b: = 255;
Casting with as
Exercise
Convert.
x f64
Tuples
Exercise
Read the first item.
t.Arrays
Exercise
Repeat a value.
[0; ]
println! and Formatting
Exercise
Debug print.
println!("{}", v)
Operators
Exercise
Remainder.
7 2
Numbers and Math
Exercise
Square root.
x.()
Overflow Handling
Exercise
Safe add.
a.add(1)
Rust Strings
Exercise
Append text.
s.(" more")
String Slicing and Chars
Exercise
Count characters.
s.chars().()
Formatting and to_string
Exercise
Convert text to a number.
"5".::<i32>()
String and &str
Exercise
Owned string.
let s = ::from("a");
String Methods
Exercise
Parse text.
"5".::<i32>()
Chars and Bytes
Exercise
Count characters.
s.chars().()
Rust If and Else
Exercise
Second branch.
if a {} if b {}
Rust Match
Exercise
Catch all pattern.
match x { 1 => 0, => 1 }
Rust Loops
Exercise
Infinite loop.
{ break; }if let and while let
Exercise
Match one pattern.
if Some(x) = opt {}
if Expressions
Exercise
Return from if.
let x = c { 1 } else { 2 };
loop, while and for
Exercise
Infinite loop.
{ break; }Ranges
Exercise
Inclusive range.
15
match
Exercise
Catch all.
=> "x"if let and while let
Exercise
Short match.
if Some(x) = o {}
Loop Labels
Exercise
Label syntax.
': for
Rust Functions
Exercise
Return type arrow.
fn f() i32 { 1 }
Returning Tuples and Early Returns
Exercise
Leave a function early.
0;Rust Closures
Exercise
Double x.
let f = |x| x 2;
Recursion
Exercise
Return 1 in the base case.
if n <= 1 { } else { n }
Functions
Exercise
Return type arrow.
fn f() i32
Closures
Exercise
Add one.
let f = |x| x 1;
Passing Functions
Exercise
Function type.
f: (i32) -> i32
Recursion
Exercise
Base case.
if n <= 1 { return ; }
Ownership and Borrowing
Exercise
Borrow without moving.
length(s1)
Structs and Enums
Exercise
Add methods to a type.
Rect { }Vectors and HashMaps
Exercise
Create a growable list.
let v = ![1, 2];
References and Borrowing Rules
Exercise
Mutable borrow.
& s
Move, Copy and Clone
Exercise
Make a deep copy.
s.()
Slices
Exercise
Slice from index 1 to 3.
&v[14]
Lifetimes
Exercise
Lifetime marker.
fn f<a>() {}
Box, Rc and RefCell
Exercise
Share ownership.
::new(5)Ownership
Exercise
Copy for small types.
let x = 5; let y = ;
Borrowing and References
Exercise
Mutable borrow.
& s
Clone and Copy
Exercise
Deep copy.
a.()
Slices
Exercise
Slice syntax.
&v[13]
Lifetimes Intro
Exercise
Lifetime mark.
fn f< a>(x: &a str)
Box and the Heap
Exercise
Heap allocation.
::new(5)Vectors
Exercise
Add an item.
v.(5)
HashMaps and the Entry API
Exercise
Insert if missing.
map.entry(k).(0)
HashSet, BTreeMap and VecDeque
Exercise
Sorted map.
Map::new()Iterators
Exercise
Add up the items.
v.iter().::<i32>()
Iterator Patterns
Exercise
Test all items.
v.iter().(|x| *x > 0)
Vectors
Exercise
Add an item.
v.(5)
HashMap
Exercise
Insert if missing.
m.entry(k).(0)
HashSet and BTreeSet
Exercise
Sorted set.
SetIterators
Exercise
Consume into a Vec.
.::<Vec<_>>()
More Iterator Methods
Exercise
Index and value.
v.iter().()
Sorting
Exercise
Sort by key.
w.sort_by(f)
VecDeque and BinaryHeap
Exercise
Front insert.
d.(0)
Struct Methods and Associated Functions
Exercise
Constructor name by convention.
fn () -> Self
Enums with Data
Exercise
Declare an enum.
Shape { A, B }Derive and Common Traits
Exercise
Auto implement Debug.
#[(Debug)]
Modules and Visibility
Exercise
Make an item public.
fn area() {}Generics
Exercise
Type parameter brackets.
struct PairT> { a: T }
Structs
Exercise
Struct keyword.
User {}Methods with impl
Exercise
Method receiver.
fn area(self)
Enums
Exercise
Enum keyword.
Msg {}Option
Exercise
No value.
let x: Option<i32> = ;
Result and the ? operator
Exercise
Early return on error.
s.parse::<i32>()Modules
Exercise
Make public.
fn area() {}derive Attributes
Exercise
Debug derive.
#[derive()]
Option and Result
Exercise
Missing value variant.
Option has Some and Traits and Generics
Exercise
Define shared behaviour.
Speak { }Panic, unwrap and expect
Exercise
Safe default.
opt.(0)
The ? Operator and Custom Errors
Exercise
Propagate an error.
let n = s.parse::<i32>();
Trait Objects and dyn
Exercise
Dynamic dispatch keyword.
Box< Speak>
Operator Overloading and Default Methods
Exercise
Trait for +.
impl for V
panic, unwrap and expect
Exercise
Fallback value.
r.unwrap(0)
Custom Errors
Exercise
Error trait.
impl std::error:: for E {}
Traits
Exercise
Trait keyword.
Speak { fn say(&self) -> String; }Generics and Trait Bounds
Exercise
Bound.
fn f<T: >(x: T)
Default, From and Into
Exercise
Standard value.
#[derive()]
Tests and Docs
Exercise
Test attribute.
#[]
Practice: Word Frequency
Exercise
Split on spaces.
s.()
Practice: FizzBuzz
Exercise
Match on a pair.
match (a, )
Practice: Stats
Exercise
Average.
sum / v.len() f64
Threads
Premium exercise. See plans
Message Passing with Channels
Premium exercise. See plans
Shared State with Arc and Mutex
Premium exercise. See plans
Drop and RAII
Premium exercise. See plans
Advanced Patterns
Premium exercise. See plans
Macros
Premium exercise. See plans
Async Rust
Premium exercise. See plans
Unsafe Rust
Premium exercise. See plans
Cargo and Crates
Premium exercise. See plans
Testing in Rust
Premium exercise. See plans
JSON with serde
Premium exercise. See plans
Files and Input
Premium exercise. See plans
Web Servers with Axum
Premium exercise. See plans
Command Line Tools
Premium exercise. See plans
Performance and Profiling
Premium exercise. See plans
WebAssembly and FFI
Premium exercise. See plans
Rust Best Practices
Premium exercise. See plans
Practice Projects
Exercise
Beginner exercises tool.
cargo install