Home / Blog / Programming / Rust
Top 50 Rust Interview Questions with Answers
Programming · Rust · 26 min read
Fifty Rust interview questions with answers, from first programs to ownership and threads. Every program ran on rustc 1.99.1, with the real output shown.
How this sheet works
Fifty Rust interview questions fill this page, grouped by topic. Basics come first. Ownership and borrowing follow. Then come structs, enums, and pattern matching, then collections and errors. Traits and generics sit after those, with closures, smart pointers, and threads last. Six coding tasks close the page, each written out in full.
Every program below was compiled and run with rustc 1.99.1. What each program printed is shown word for word. Nothing on this page was typed in by hand as output. The thread programs wait for every thread to finish before they print, so the order of the lines stays fixed. One program is written to fail: it uses a value after moving it. Where its output would go, the compiler's error lines appear instead.
Take the questions one at a time. Say your own answer before you read the one here. Then type it out and run it yourself. Saying the answer aloud and running its program will lodge it in memory far better than reading alone.
The Rust track holds 440 lessons in three courses: 142 in Beginner, 149 in Intermediate, and 149 in Advanced. Async Rust has its own course, Tokio, with 45 more. When an answer is wrong, the lesson that teaches the idea is named. When an answer draws on two lessons, the page names both of them.
Three honest limits. Unsafe code, macros, and async Rust are not in this sheet. Unsafe code and macros live in Rust Advanced. Async Rust lives in the Tokio course. Each needs its own study.
1. What is Rust, and what is it used for?
Rust is a systems programming language. It runs close to the hardware. It gives the speed of C and C++ without their memory bugs. It is used for operating systems, browsers, servers, and embedded devices.
Rust checks memory safety when the code compiles. It has no garbage collector. It runs with no runtime overhead. Its ownership rules stop whole classes of bugs before the program ever runs.
The Rust Intro lesson introduces the language and its main uses. The Rust Get Started lesson walks through the setup.
fn main() {
let numbers = [3, 5, 7, 9];
let mut total = 0;
for n in numbers {
total += n * n;
}
println!("The sum of squares is {total}.");
}
Output:
The sum of squares is 164.2. What does a first Rust program look like?
A first Rust program is short. It starts with a main function. The main function is where the running code lives. A println! line prints text to the screen.
A function starts with the fn keyword. The word main names the entry point. Curly braces mark where the function begins and ends. Each statement ends with a semicolon.
The Rust Syntax lesson walks through the shape of a program. The Rust Output lesson shows how text is printed.
fn main() {
let name = "Rust";
println!("Hello, {name}!");
println!("2 + 3 = {}", 2 + 3);
}
Output:
Hello, Rust!
2 + 3 = 53. How do you build and run a Rust program with Cargo?
Cargo is Rust's build tool and package manager. It creates projects, builds code, and fetches libraries. A new project starts with cargo new.
The command cargo run builds the project and runs it in one step. The command cargo build makes a binary without running it. The command cargo check looks for errors without building the binary. The source code lives in src/main.rs inside the project folder.
The Rust Cargo Commands lesson lists the main Cargo commands. The Rust Get Started lesson shows how a first project is made.
fn main() {
let greeting = "Hello from a Cargo project!";
println!("{greeting}");
println!("2 * 21 = {}", 2 * 21);
}
Output:
Hello from a Cargo project!
2 * 21 = 424. What is a variable in Rust, and what does mut do?
A variable is a named place to store a value. The let keyword creates one. A variable is fixed by default in Rust. The mut keyword makes it changeable.
The line let count = 1 creates a variable holding 1. The line let mut count = 1 creates one that can change. Assigning a new value to a plain variable is a compile error. The type is usually worked out by the compiler.
The Rust Variables lesson works through variables and mut in detail.
fn main() {
let mut count = 1;
println!("count starts at {count}");
count = count + 4;
println!("count is now {count}");
count += 5;
println!("count ends at {count}");
}
Output:
count starts at 1
count is now 5
count ends at 105. What are the basic data types in Rust?
A data type names the kind of value a variable holds. Rust checks each type while the code compiles. A value cannot silently change its type.
The basic types are integers, floating-point numbers, booleans, and characters. An integer holds a whole number, like 42. A float holds a number with a decimal point, like 3.14. A bool holds true or false. A char holds one character, like 'R'.
The Rust Data Types lesson names each basic type. The Rust Integer Types lesson covers whole numbers in detail.
fn main() {
let whole: i32 = -42;
let decimal: f64 = 3.14;
let letter: char = 'R';
let text: &str = "Rust";
let flag: bool = true;
println!("whole: {whole}");
println!("decimal: {decimal}");
println!("letter: {letter}");
println!("text: {text}");
println!("flag: {flag}");
}
Output:
whole: -42
decimal: 3.14
letter: R
text: Rust
flag: true6. What is a constant in Rust?
A constant holds a value that stays fixed. It is fixed when the code is written. No later line can change it.
The const keyword declares a constant. Its type must always be written out. A constant name is usually written in capital letters. Constants can be used anywhere in the program.
The Rust Constants lesson covers constants and their rules.
const MAX_SCORE: u32 = 100;
const PAWNS: u32 = 8;
fn main() {
let score = 87;
println!("The top score is {MAX_SCORE}.");
println!("Your score is {score} out of {MAX_SCORE}.");
println!("A chess board has {PAWNS} pawns per side.");
}
Output:
The top score is 100.
Your score is 87 out of 100.
A chess board has 8 pawns per side.7. How do functions work in Rust?
A function is a named group of steps that does one job. It runs when it is called. It can take values in and send a value back.
The fn keyword starts a function. The round brackets hold its parameters, each with a type. The arrow -> states the return type. A function with no return type gives back nothing.
The Rust Functions lesson shows how to write and call functions.
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn greet(name: &str) {
println!("Hello, {name}!");
}
fn main() {
greet("Ada");
let sum = add(6, 7);
println!("6 + 7 = {sum}");
println!("The double of 9 is {}", add(9, 9));
}
Output:
Hello, Ada!
6 + 7 = 13
The double of 9 is 188. How do if expressions and loops work in Rust?
An if expression picks a value or a path by a condition. A loop repeats a block of code. Rust has for loops, while loops, and the loop keyword.
An if can be used as an expression, so it can give a value to a variable. A for loop walks through a range or a collection. A while loop runs while its condition stays true. The loop keyword repeats until a break stops it.
The Rust If..Else lesson covers if expressions. The Rust Loops lesson covers the three kinds of loop.
fn main() {
let hour = 14;
let greeting = if hour < 12 {
"Good morning"
} else {
"Good afternoon"
};
println!("{greeting}!");
let mut total = 0;
for n in 1..=5 {
total += n;
}
println!("1 + 2 + 3 + 4 + 5 = {total}");
let mut count = 3;
while count > 0 {
println!("Countdown: {count}");
count -= 1;
}
println!("Go!");
}
Output:
Good afternoon!
1 + 2 + 3 + 4 + 5 = 15
Countdown: 3
Countdown: 2
Countdown: 1
Go!9. What is ownership in Rust?
Ownership is Rust's way of managing memory. Every value has exactly one owner. The owner is the variable that holds the value. When the owner goes out of scope, Rust frees the value.
Ownership is checked when the code compiles. It removes the need for a garbage collector. It also stops two parts of a program freeing the same memory. The rules are simple, but they shape how Rust code is written.
The Rust Ownership lesson explains the three ownership rules.
fn main() {
let book = String::from("The Rust Book");
println!("The book is: {book}");
show_title(book);
let other = String::from("Ownership");
println!("A new value: {other}");
}
fn show_title(title: String) {
println!("Inside the function: {title}");
}
Output:
The book is: The Rust Book
Inside the function: The Rust Book
A new value: Ownership10. What does it mean to move a value?
To move a value means to hand its ownership to another variable. The first variable no longer owns it. The value itself is not copied.
Assigning a String to a new variable moves it. Passing a String to a function moves it too. The move is cheap, because only the pointer and length change hands. The data on the heap stays where it is.
The Rust Ownership lesson covers moves. The Rust Partial Moves lesson shows what happens when part of a value moves.
fn main() {
let gift = String::from("a bicycle");
let present = gift;
println!("The present is: {present}");
}
Output:
The present is: a bicycle11. Which types are Copy, and which move?
Some types are Copy, and the rest move. A Copy type is copied when it is assigned. A move type changes owner instead.
Integers, floats, booleans, and chars are Copy. A String is not Copy, because it owns heap memory. Copying a String would need a fresh copy of its heap data. A type can be Copy only when all of its parts are Copy.
The Rust Clone & Copy lesson explains which types copy and which move.
fn main() {
let number = 10;
let copy = number;
println!("number: {number}, copy: {copy}");
let word = String::from("hello");
let moved = word;
println!("moved: {moved}");
let again = moved.clone();
println!("moved: {moved}, again: {again}");
}
Output:
number: 10, copy: 10
moved: hello
moved: hello, again: hello12. What happens if you use a value after moving it?
Using a value after moving it is a compile error. The compiler stops the build. The old variable no longer owns anything, so there is nothing to use.
The compiler points at the line where the value was moved and the line where it is used again. The fix is to clone the value before moving it, or to borrow it instead of moving it. The working program shows the move, and the failing program shows the error.
The Rust Ownership lesson covers why a moved value cannot be used. The Rust Reading Compiler Errors lesson shows how to read the message the compiler prints.
fn main() {
let message = String::from("Hello");
let moved = message;
println!("The moved value is: {moved}");
}
Output:
The moved value is: Hello
fn main() {
let message = String::from("Hello");
let moved = message;
println!("{moved}");
println!("{message}");
}
Compile error:
error[E0382]: borrow of moved value: `message`
--> bad.rs:5:16
|
2 | let message = String::from("Hello");
| ------- move occurs because `message` has type `String`, which does not implement the `Copy` trait
3 | let moved = message;
| ------- value moved here
4 | println!("{moved}");
5 | println!("{message}");
| ^^^^^^^ value borrowed here after move
|
help: consider cloning the value if the performance cost is acceptable
|
3 | let moved = message.clone();
| ++++++++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0382`.13. What is borrowing, and how do references work?
Borrowing means using a value without taking ownership of it. A reference points at the value. The owner keeps the value, and the borrower only looks at it.
The & sign creates a reference. A function that takes &String reads the string without owning it. The reference ends when it is last used. The owner can use the value again after that.
The Rust Borrowing lesson covers references. The Rust Borrowed Arguments lesson shows functions that take borrowed values.
fn length_of(text: &String) -> usize {
text.len()
}
fn main() {
let word = String::from("borrowing");
let len = length_of(&word);
println!("\"{word}\" has {len} letters.");
println!("The word is still here: {word}");
}
Output:
"borrowing" has 9 letters.
The word is still here: borrowing14. What is the difference between a shared reference and a mutable reference?
A shared reference lets many readers look at a value at once. A mutable reference lets one writer change it. The two kinds follow different rules.
Many shared references can exist at the same time. Only one mutable reference can exist at a time. A mutable reference cannot exist alongside a shared one. These rules stop data races before the program runs.
The Rust Borrowing lesson covers shared references. The Rust Reborrowing lesson shows how a mutable reference can be passed on.
fn main() {
let mut score = 10;
let first = &score;
let second = &score;
println!("Shared views: {first} and {second}");
let change = &mut score;
*change += 5;
println!("After the change: {change}");
println!("Final score: {score}");
}
Output:
Shared views: 10 and 10
After the change: 15
Final score: 1515. What is a slice?
A slice is a view into a run of values. It points at a start and a length. It does not own the data it shows.
The range 1..4 takes elements 1, 2, and 3 from an array. A string slice takes part of a string. Slices are written with the & sign, like &[i32] or &str. A slice can be passed to a function without copying the data.
The Rust Slices lesson covers slices of arrays and strings. The Rust Slice Patterns lesson shows how to match on slices.
fn main() {
let numbers = [10, 20, 30, 40, 50];
let middle = &numbers[1..4];
println!("The middle slice is: {:?}", middle);
let text = "Hello, Rust!";
let hello = &text[0..5];
println!("The first word is: {hello}");
println!("The slice has {} numbers.", middle.len());
}
Output:
The middle slice is: [20, 30, 40]
The first word is: Hello
The slice has 3 numbers.16. What is the difference between String and &str?
A String is an owned piece of text. A &str is a borrowed view of some text. The two play different roles.
A String can grow and change, and it owns its bytes. A &str cannot change the text, and it only borrows it. A string literal like "hello" is a &str. A function that takes &str accepts both a String and a literal.
The Rust Strings lesson covers the String type. The Rust String Literals lesson covers borrowed string text.
fn shout(text: &str) {
println!("{}!", text.to_uppercase());
}
fn main() {
let owned = String::from("hello");
let borrowed = "world";
shout(&owned);
shout(borrowed);
println!("The owned string is still here: {owned}");
}
Output:
HELLO!
WORLD!
The owned string is still here: hello17. What are lifetimes, and when can you leave them out?
A lifetime is how long a reference stays valid. It ties a borrowed value to the data it points at. It stops a reference outliving its data.
Most functions never need a lifetime written out. The compiler fills in the missing lifetimes by a small set of rules, called elision. A lifetime must be written when a function returns a reference and takes two or more of them. The written form looks like fn longest<'a>(x: &'a str, y: &'a str) -> &'a str.
The Rust Lifetimes Basics lesson introduces lifetimes. The Rust Lifetime Elision lesson covers the rules for leaving them out.
fn longest<'a>(first: &'a str, second: &'a str) -> &'a str {
if first.len() >= second.len() {
first
} else {
second
}
}
fn first_word(text: &str) -> &str {
match text.find(' ') {
Some(index) => &text[..index],
None => text,
}
}
fn main() {
let one = "short";
let two = "a much longer phrase";
println!("The longest is: {}", longest(one, two));
println!("The first word is: {}", first_word(two));
}
Output:
The longest is: a much longer phrase
The first word is: a18. What is a struct in Rust?
A struct is a named group of related values. Each value has a name and a type. A struct lets one value hold a whole record, such as a user with a name and an age.
Fields are named, so code reads them by name rather than by position. A struct can hold values of different types side by side. Changing one field leaves the others untouched.
The Rust Structs lesson builds structs with named fields. The Rust Nested Structs lesson puts one struct inside another.
struct User {
name: String,
age: u32,
}
fn main() {
let ada = User {
name: String::from("Ada"),
age: 36,
};
println!("{} is {} years old.", ada.name, ada.age);
let older = User { age: 37, ..ada };
println!("{} is now {} years old.", older.name, older.age);
}
Output:
Ada is 36 years old.
Ada is now 37 years old.19. What are tuple structs and unit structs?
Tuple structs hold unnamed fields. Their values are read by position, like a tuple. A unit struct has no fields at all.
Tuple structs give a plain tuple a distinct type name. Two tuple structs with the same field types are still different types. A unit struct marks a type that carries no data, often as a marker or a placeholder.
The Rust Structs lesson introduces the three struct forms. The Rust Tuples lesson covers plain tuples and reading values by position.
#[derive(Debug)]
struct Point(i32, i32);
#[derive(Debug)]
struct Marker;
fn main() {
let p = Point(3, 4);
println!("x: {}, y: {}", p.0, p.1);
println!("point: {:?}", p);
let m = Marker;
println!("marker: {:?}", m);
}
Output:
x: 3, y: 4
point: Point(3, 4)
marker: Marker20. How do methods work on a struct?
A method is a function that belongs to a type. It is written inside an impl block for that type. Methods are called on a value with dot notation.
The first parameter is usually self, &self, or &mut self. A method with &self reads the value without taking it. A method with &mut self can change the value in place.
The Rust Methods lesson works through methods on a struct. The Rust Constructors & Methods lesson shows how values are built and then used.
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn scale(&mut self, factor: u32) {
self.width *= factor;
self.height *= factor;
}
}
fn main() {
let mut r = Rectangle {
width: 3,
height: 4,
};
println!("area: {}", r.area());
r.scale(2);
println!("scaled area: {}", r.area());
}
Output:
area: 12
scaled area: 4821. What is an enum in Rust?
An enum is a type that can be one of several named variants. Each variant can carry different data, or none at all. A value of an enum type is always exactly one variant.
Enums model choices that code must handle one by one. A variant can hold a number, a string, or a whole struct. Matching on an enum forces every variant to be covered.
The Rust Enums lesson defines enums with data-carrying variants. The Rust Enum Variants lesson goes further into the shapes variants can take.
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
}
fn main() {
let messages = [
Message::Quit,
Message::Move { x: 10, y: 20 },
Message::Write(String::from("hello")),
];
for m in messages {
match m {
Message::Quit => println!("quit"),
Message::Move { x, y } => println!("move to ({}, {})", x, y),
Message::Write(text) => println!("write: {}", text),
}
}
}
Output:
quit
move to (10, 20)
write: hello22. What is Option, and why does Rust use it instead of null?
Option is an enum with two variants: Some and None. Some holds a value. None means there is no value.
Rust has no null, so a missing value is written as None. Code must handle both variants before it can use the value inside. That check happens at compile time, not at run time.
The Rust Option lesson introduces Some and None. The Rust Option Defaults lesson shows how to supply a fallback when the value is missing.
fn first_even(numbers: &[i32]) -> Option<i32> {
for &n in numbers {
if n % 2 == 0 {
return Some(n);
}
}
None
}
fn main() {
match first_even(&[1, 3, 5]) {
Some(n) => println!("found: {}", n),
None => println!("no even number"),
}
match first_even(&[1, 2, 3]) {
Some(n) => println!("found: {}", n),
None => println!("no even number"),
}
}
Output:
no even number
found: 223. How does match work?
Match compares a value against a list of patterns. It runs the code under the first pattern that fits. A match must cover every possible value. Leave one out, and the code will not compile.
Patterns can be literal values, ranges, or enum variants with their data. A catch-all pattern, written as an underscore, handles everything left over. Match returns a value, so it can sit on the right of an equals sign.
The Rust Match lesson covers the basic shape of match. The Rust Match Guards lesson adds extra conditions to individual arms.
fn describe(n: i32) -> &'static str {
match n {
0 => "zero",
1..=9 => "a single digit",
_ => "bigger",
}
}
fn main() {
for n in [0, 5, 42] {
println!("{} is {}", n, describe(n));
}
}
Output:
0 is zero
5 is a single digit
42 is bigger24. What does if let do?
If let tests one pattern and runs code when it fits. It is a shorter form of match for a single case. The other cases are skipped without an error.
An else branch can handle the cases that do not fit. If let is handy when only one variant matters. Match is the better choice when every case needs its own code.
The Rust If Let lesson shows if let with Option values. The Rust Let Else lesson covers the matching pattern that returns early instead.
fn main() {
let maybe = Some(7);
if let Some(n) = maybe {
println!("the number is {}", n);
}
let nothing: Option<i32> = None;
if let Some(n) = nothing {
println!("the number is {}", n);
} else {
println!("there is no number");
}
}
Output:
the number is 7
there is no number25. What is a Vec, and how do you use it?
A Vec holds a list that can grow. Every item in it shares one type. It stores its elements in a row on the heap. New elements are added with push.
A Vec keeps a length and a capacity. Pushing past the capacity makes it allocate a bigger block and copy the elements over. Indexing reads one element by position, and get returns None past the end.
The Rust Vectors lesson builds a Vec and grows it. The Rust Resize & Split a Vec lesson shows how to change a Vec after it is built.
fn main() {
let mut scores = vec![10, 20];
println!("length: {}", scores.len());
scores.push(30);
scores.push(40);
println!("length: {}", scores.len());
println!("first: {}", scores[0]);
println!("sum: {}", scores.iter().sum::<i32>());
}
Output:
length: 2
length: 4
first: 10
sum: 10026. What is a HashMap, and when do you reach for one?
A HashMap stores pairs of keys and values. Each key maps to exactly one value. Looking a value up by its key is fast, even in a large map.
Insert adds a pair or replaces the value for a key that already exists. Get returns an Option, since the key may be absent. The entry method finds a key or creates it in one step.
The Rust HashMap lesson builds a map and reads values from it. The Rust Building a HashMap lesson covers the ways a map is filled.
use std::collections::HashMap;
fn main() {
let mut ages = HashMap::new();
ages.insert("Ada", 36);
ages.insert("Grace", 40);
ages.insert("Alan", 41);
println!("Ada is {}", ages["Ada"]);
let mut names: Vec<&str> = ages.keys().copied().collect();
names.sort();
for name in names {
println!("{}: {}", name, ages[name]);
}
}
Output:
Ada is 36
Ada: 36
Alan: 41
Grace: 4027. How do you work with strings in Rust?
Rust has two main string forms. A string slice, written &str, is a borrowed view of text. A String is an owned, growable piece of text.
String literals in source code are string slices. Owned strings are built with String::from or to_string. Text can be added with push_str, and methods like trim and split work on slices.
The Rust Strings lesson introduces both string forms. The Rust String Methods lesson works through the common ways text is changed and searched.
fn main() {
let mut greeting = String::from("hello");
greeting.push_str(", world");
println!("{}", greeting);
println!("length in bytes: {}", greeting.len());
println!("first word: {}", &greeting[..5]);
let shout = greeting.to_uppercase();
println!("{}", shout);
}
Output:
hello, world
length in bytes: 12
first word: hello
HELLO, WORLD28. What is an iterator, and what do map and filter do?
An iterator gives out items one at a time. It is created from a collection with iter. Each call to next returns the next item, wrapped in Some, until the items run out.
Map changes every item with a function. Filter keeps only the items that pass a test. Both are lazy, so they do nothing until a method like collect or sum pulls the items through.
The Rust Iterators Basics lesson builds an iterator from a Vec. The Rust Iterators lesson covers the adapters that transform items in a chain.
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6];
let doubled: Vec<i32> = numbers.iter().map(|n| n * 2).collect();
println!("doubled: {:?}", doubled);
let evens: Vec<i32> = numbers
.iter()
.filter(|&&n| n % 2 == 0)
.copied()
.collect();
println!("evens: {:?}", evens);
let total: i32 = numbers.iter().sum();
println!("total: {}", total);
}
Output:
doubled: [2, 4, 6, 8, 10, 12]
evens: [2, 4, 6]
total: 2129. What is Result, and how do you handle errors with it?
Result is an enum with two variants: Ok and Err. Ok holds a successful value. Err holds the error that stopped the work.
Functions that can fail return a Result instead of a plain value. The caller matches on it to handle success and failure separately. This keeps errors visible in the type, so they cannot be ignored by accident.
The Rust Result lesson introduces Ok and Err. The Rust Error Propagation lesson shows how errors move up through calling code.
fn parse_age(text: &str) -> Result<u32, std::num::ParseIntError> {
text.parse()
}
fn main() {
match parse_age("36") {
Ok(age) => println!("age: {}", age),
Err(e) => println!("could not parse: {}", e),
}
match parse_age("old") {
Ok(age) => println!("age: {}", age),
Err(e) => println!("could not parse: {}", e),
}
}
Output:
age: 36
could not parse: invalid digit found in string30. What does the ? operator do?
The ? operator unwraps a Result or an Option. On success it gives back the value inside. On failure it returns early from the function with the error.
The operator only works inside a function that returns a matching Result or Option. It replaces a match block with a single character. Several ? operators in a row pass an error up through each layer of calls.
The Rust Error Propagation lesson works through the ? operator step by step. The Rust Main Returns Result lesson shows main itself returning a Result so ? can be used there.
fn double(text: &str) -> Result<i32, std::num::ParseIntError> {
let n: i32 = text.parse()?;
Ok(n * 2)
}
fn main() {
match double("21") {
Ok(n) => println!("doubled: {}", n),
Err(e) => println!("error: {}", e),
}
match double("abc") {
Ok(n) => println!("doubled: {}", n),
Err(e) => println!("error: {}", e),
}
}
Output:
doubled: 42
error: invalid digit found in string31. When should a program panic, and when should it return an error?
A panic stops the current thread at once. It is used for bugs and broken assumptions, not for ordinary failures. A returned error is for problems the caller can handle.
Missing files, bad input, and network failures are errors, so they are returned as Result values. An index past the end of a Vec panics, since it means the program itself is wrong. Code can choose get, which returns None, instead of indexing.
The Rust Panic lesson shows when a panic fires. The Rust Panic Strategy lesson explains how to choose between panicking and returning an error.
fn divide(a: f64, b: f64) -> Result<f64, String> {
if b == 0.0 {
Err(String::from("cannot divide by zero"))
} else {
Ok(a / b)
}
}
fn main() {
match divide(10.0, 2.0) {
Ok(v) => println!("10 / 2 = {}", v),
Err(e) => println!("error: {}", e),
}
match divide(10.0, 0.0) {
Ok(v) => println!("10 / 0 = {}", v),
Err(e) => println!("error: {}", e),
}
let items = vec!["a", "b"];
println!("second item: {}", items.get(1).unwrap_or(&"missing"));
println!("tenth item: {}", items.get(9).unwrap_or(&"missing"));
}
Output:
10 / 2 = 5
error: cannot divide by zero
second item: b
tenth item: missing32. What is a trait?
A trait is a set of method signatures that a type can implement. It states what a type can do, without saying how. Any type that implements the trait promises those methods.
Traits let different types share the same behaviour under one name. A function can take any type that implements a trait. Traits can also supply a default method that implementers may keep or replace.
The Rust Traits Basics lesson defines a first trait. The Rust Traits lesson builds on it with more realistic examples.
trait Greet {
fn greet(&self) -> String;
}
struct Person {
name: String,
}
impl Greet for Person {
fn greet(&self) -> String {
format!("Hello, {}!", self.name)
}
}
fn say_hello(g: &impl Greet) {
println!("{}", g.greet());
}
fn main() {
let ada = Person {
name: String::from("Ada"),
};
say_hello(&ada);
println!("{}", ada.greet());
}
Output:
Hello, Ada!
Hello, Ada!33. What are generics?
Generics let code work with many types at once. A type parameter, often written T, stands in for a concrete type. One function or struct can then handle integers, strings, or any other type.
The compiler creates a separate copy of generic code for each type it is used with. That copy is checked at compile time, so generic code is as fast as code written for one type. Generics pair with traits to say what the type parameter must be able to do.
The Rust Generics Basics lesson introduces type parameters. The Rust Generics lesson covers generic functions and structs in more depth.
fn first<T>(items: &[T]) -> Option<&T> {
items.first()
}
fn pair<T, U>(a: T, b: U) -> (T, U) {
(a, b)
}
fn main() {
let numbers = [10, 20, 30];
println!("first number: {:?}", first(&numbers));
let words = ["red", "blue"];
println!("first word: {:?}", first(&words));
let p = pair(1, "one");
println!("pair: {:?}", p);
}
Output:
first number: Some(10)
first word: Some("red")
pair: (1, "one")34. What is a trait bound?
A trait bound is a rule on a type parameter. It says the type must implement a given trait. A generic function with a bound can use that trait's methods on its values.
Bounds are written after the type parameter, like T: Display. A where clause moves longer lists of bounds out of the angle brackets. Multiple bounds are joined with a plus sign.
The Rust Trait Bounds lesson works through bounds on generic functions. The Rust Where Clauses lesson shows how where clauses keep long bound lists readable.
use std::fmt::Display;
fn print_twice<T: Display>(value: T) {
println!("{} {}", value, value);
}
fn largest<T: PartialOrd>(a: T, b: T) -> T {
if a > b {
a
} else {
b
}
}
fn main() {
print_twice(42);
print_twice("hello");
println!("larger: {}", largest(3, 7));
println!("larger: {}", largest("apple", "banana"));
}
Output:
42 42
hello hello
larger: 7
larger: banana35. What is a closure?
A closure is an unnamed function value that can be stored in a variable. It can be called like a function. It can also capture values from the code around it.
A closure borrows or moves the values it uses from its surroundings. The compiler works out its parameter and return types from how it is used. Three traits describe what a closure does with its captures: Fn borrows them, FnMut changes them, and FnOnce takes them.
The Rust Closures lesson works through closures and their captures. The Rust Closure Captures lesson shows which values a closure takes from its surroundings.
fn main() {
let bonus = 5;
let add_bonus = |n: i32| n + bonus;
println!("10 + bonus = {}", add_bonus(10));
println!("20 + bonus = {}", add_bonus(20));
}
Output:
10 + bonus = 15
20 + bonus = 2536. How do iterator adapters like map and filter work?
An adapter takes an iterator and returns a new iterator. Map changes each item with a function. Filter keeps only the items that pass a test.
Adapters are lazy, so they do no work until the iterator is consumed. Chaining adapters builds a pipeline without touching the original data. The items flow through the chain one at a time.
The Rust Iterator Adapters lesson explains map, filter, and the other adapters. The Rust Lazy Iterators lesson shows why nothing runs until the result is used.
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6];
let doubled: Vec<i32> = numbers.iter().map(|n| n * 2).filter(|n| *n > 5).collect();
println!("{:?}", doubled);
}
Output:
[6, 8, 10, 12]37. What does collect do?
Collect gathers every item from an iterator into one collection. It turns a chain of adapters into a finished value. The target type is often a Vec.
Collect is a consuming adapter, so the iterator is used up by the call. The compiler needs to know which collection to build. A type annotation or a turbofish supplies that answer.
The Rust Consuming Iterators lesson shows collect beside the other consuming adapters. The Rust Iterators lesson explains how an iterator hands out its items.
fn main() {
let squares: Vec<i32> = (1..=5).map(|n| n * n).collect();
println!("{:?}", squares);
}
Output:
[1, 4, 9, 16, 25]38. What is Box, and when do you use it?
A Box is a smart pointer that stores a value on the heap. The Box itself lives on the stack and holds the heap address. The value is freed when the Box goes out of scope.
Box is the usual fix when a type has no fixed size at compile time. A recursive type is one example, since each level would otherwise need room for another level. Box also moves a large value to the heap so only a pointer is copied around.
The Rust Box lesson explains how a Box owns its heap value. The Rust When to Box lesson works through the cases where a Box is the right tool.
enum List {
Cons(i32, Box<List>),
Nil,
}
use List::{Cons, Nil};
fn sum(list: &List) -> i32 {
match list {
Cons(value, next) => value + sum(next),
Nil => 0,
}
}
fn main() {
let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
println!("list sum: {}", sum(&list));
}
Output:
list sum: 639. What are Rc and Arc?
Rc and Arc give several owners shared access to one value. Both count how many owners point at the value. The value is freed when the last owner drops.
Rc works in one thread, and its count is not safe to change from two threads at once. Arc works across threads, and its count is changed with atomic steps. Arc costs a little more, so Rc is the choice inside a single thread.
The Rust Rc & RefCell lesson shows shared ownership with Rc. The Rust Mutex & Arc lesson shows Arc sharing a value between threads.
use std::rc::Rc;
use std::sync::Arc;
fn main() {
let shared = Rc::new(vec![1, 2, 3]);
let second = Rc::clone(&shared);
let third = Rc::clone(&shared);
println!("rc owners: {}", Rc::strong_count(&shared));
println!("shared values: {:?}", second);
println!("third owner sees: {:?}", third);
let thread_safe = Arc::new(7);
let other = Arc::clone(&thread_safe);
println!("arc owners: {}", Arc::strong_count(&thread_safe));
println!("arc value: {}", other);
}
Output:
rc owners: 3
shared values: [1, 2, 3]
third owner sees: [1, 2, 3]
arc owners: 2
arc value: 740. What does RefCell do, and what is interior mutability?
RefCell lets code change a value through a shared reference. It moves the borrow check from compile time to run time. A program that breaks the rules panics instead of failing to compile.
Interior mutability means a value can change even when only a shared reference reaches it. RefCell holds the value and tracks borrows while the program runs. Calling borrow_mut twice at once panics, so only one mutable borrow exists at a time.
The Rust Interior Mutability lesson explains the idea behind changing shared data. The Rust Rc & RefCell lesson shows RefCell paired with Rc for shared mutable data.
use std::cell::RefCell;
fn main() {
let cell = RefCell::new(5);
*cell.borrow_mut() += 5;
println!("value: {}", cell.borrow());
}
Output:
value: 1041. How do threads work in Rust?
A thread is a separate path of execution inside a program. Rust starts one with thread::spawn and a closure. The closure runs on the new thread while the main thread carries on.
Spawn returns a handle, and joining the handle waits for the thread to finish. A spawned thread must own the values it uses, so the closure is usually marked move. Data shared between threads must be safe to send, which the Send trait marks.
The Rust Threads lesson shows spawning and joining a thread. The Rust Scoped Threads lesson shows threads that borrow data from the code around them.
use std::thread;
fn main() {
let handle = thread::spawn(|| (1..=10).sum::<i32>());
let total = handle.join().unwrap();
println!("sum from thread: {}", total);
println!("main finished");
}
Output:
sum from thread: 55
main finished42. How do channels move values between threads?
A channel is a pipe with a sending end and a receiving end. One thread sends a value into the pipe. Another thread takes the value out of the other end.
The mpsc::channel function makes a pair of ends for many senders and one receiver. Sending moves the value, so the sender cannot use it again. Receiving blocks until a value arrives or every sender has dropped.
The Rust Channels lesson works through senders, receivers, and multiple producers. The Rust Threads lesson shows the threads that a channel connects.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
let handle = thread::spawn(move || {
for n in 1..=3 {
tx.send(n).unwrap();
}
});
let mut received = Vec::new();
while let Ok(n) = rx.recv() {
received.push(n);
}
handle.join().unwrap();
println!("received: {:?}", received);
println!("channel closed");
}
Output:
received: [1, 2, 3]
channel closed43. How do Mutex and Arc share data between threads?
A Mutex is a lock that guards one value. Only the thread holding the lock can read or change the value. Other threads wait until the lock is free.
Arc wraps the Mutex so several threads can own the same lock. Each thread clones the Arc before it starts. Each thread locks the Mutex, changes the value, and drops the lock.
The Rust Mutex & Arc lesson builds the shared counter step by step. The Rust Mutex Basics lesson explains locking and unlocking on its own.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = Vec::new();
for _ in 0..3 {
let shared = Arc::clone(&counter);
handles.push(thread::spawn(move || {
let mut value = shared.lock().unwrap();
*value += 10;
}));
}
for handle in handles {
handle.join().unwrap();
}
println!("final count: {}", *counter.lock().unwrap());
}
Output:
final count: 3044. How do modules, crates, and Cargo.toml fit together?
A module groups related code inside one crate. A crate is a package of code that rustc compiles as one unit. Cargo.toml is the file that describes the crate to Cargo.
The src/main.rs file is the root of a binary crate, and src/lib.rs is the root of a library crate. The mod keyword declares a submodule, and pub marks items other modules may use. Cargo.toml names the crate, lists its version, and lists the crates it depends on.
The Rust Modules lesson shows how modules split code into parts. The Rust Crates lesson explains what a crate is and how it is shared.
mod greeting {
pub fn hello() -> &'static str {
"hello from a module"
}
}
fn main() {
println!("{}", greeting::hello());
}
Output:
hello from a module45. Coding task: reverse a string.
Reverse the string rust so its letters run in the opposite order. The answer is tsur. The first letter becomes the last, and the last becomes the first.
The chars method turns the string into an iterator over its characters. Rev flips that iterator around. Collect gathers the flipped characters back into a new String.
The Rust Strings lesson covers chars and other ways to walk a string. The Rust String Methods lesson shows more methods that work on strings.
fn main() {
let word = "rust";
let reversed: String = word.chars().rev().collect();
println!("original: {}", word);
println!("reversed: {}", reversed);
}
Output:
original: rust
reversed: tsur46. Coding task: count the vowels in a string.
Count the vowels in the sentence Rust is fun to learn. The vowels are a, e, i, o, and u. The sentence holds six of them.
Chars walks the sentence one character at a time. Each character is lowered to its lowercase form before the check. A match test checks each character against the five vowels, and the count rises by one on every match.
The Rust Strings lesson shows how to walk a string one character at a time. The Rust Iterator Adapters lesson explains the filter step that keeps only the vowels.
fn main() {
let sentence = "Rust is fun to learn";
let count = sentence
.chars()
.filter(|c| "aeiou".contains(c.to_ascii_lowercase()))
.count();
println!("sentence: {}", sentence);
println!("vowels: {}", count);
}
Output:
sentence: Rust is fun to learn
vowels: 647. Coding task: fizzbuzz for the numbers 1 to 15.
Count from 1 to 15 and print one line for each number. A multiple of 3 prints as Fizz instead of the number. A multiple of 5 prints as Buzz instead of the number.
A multiple of both 3 and 5 prints as FizzBuzz. Only 15 meets both tests in this range. Test for both first, since testing for 3 alone would label 15 as Fizz.
The Rust For Loops lesson shows the loop that runs from 1 to 15. The Rust If..Else lesson explains the branch that picks each line.
fn main() {
for n in 1..=15 {
if n % 15 == 0 {
println!("FizzBuzz");
} else if n % 3 == 0 {
println!("Fizz");
} else if n % 5 == 0 {
println!("Buzz");
} else {
println!("{}", n);
}
}
}
Output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz48. Coding task: find two numbers that add up to a target.
Find two numbers in the list 2, 7, 11, 15 that add up to 9. The pair is 2 and 7, at indexes 0 and 1. No other pair in this list reaches 9.
A HashMap stores each number beside its index as the list is walked. For each number, the needed partner is the target minus that number. A lookup finds the partner at once instead of scanning the list again.
The Rust HashMap lesson shows how a map stores keys beside values. The Rust Vectors lesson covers the list that holds the numbers.
use std::collections::HashMap;
fn main() {
let numbers = vec![2, 7, 11, 15];
let target = 9;
let mut seen: HashMap<i32, usize> = HashMap::new();
let mut pair = (0, 0);
for (index, &number) in numbers.iter().enumerate() {
let needed = target - number;
if let Some(&other) = seen.get(&needed) {
pair = (other, index);
break;
}
seen.insert(number, index);
}
println!("indexes: {} and {}", pair.0, pair.1);
println!("numbers: {} and {}", numbers[pair.0], numbers[pair.1]);
}
Output:
indexes: 0 and 1
numbers: 2 and 749. Coding task: remove duplicates from a vector.
Remove the repeated values from the list 1, 2, 2, 3, 1, 4 without changing the order. The answer is 1, 2, 3, 4. Each value appears once in the result.
A HashSet tracks the values already seen. Each value is checked against the set as the list is walked. A value joins the result only the first time it is seen.
The Rust Vectors lesson covers the vector that holds the numbers. The Rust HashSet lesson shows the set that tracks the values already seen.
use std::collections::HashSet;
fn main() {
let numbers = vec![1, 2, 2, 3, 1, 4];
let mut seen = HashSet::new();
let mut unique = Vec::new();
for &number in &numbers {
if seen.insert(number) {
unique.push(number);
}
}
println!("original: {:?}", numbers);
println!("without duplicates: {:?}", unique);
}
Output:
original: [1, 2, 2, 3, 1, 4]
without duplicates: [1, 2, 3, 4]50. Coding task: find the longest word in a sentence.
Find the longest word in the sentence Rust makes systems programming fast and safe. The longest word is programming, with 11 letters. Ties are broken by keeping the first longest word.
Split_whitespace breaks the sentence into words at the spaces. Max_by_key compares the words by their length. The word with the greatest length wins.
The Rust Splitting Text lesson shows how to split a sentence into words. The Rust Strings lesson covers the string the sentence lives in.
fn main() {
let sentence = "Rust makes systems programming fast and safe";
let longest = sentence.split_whitespace().max_by_key(|word| word.len()).unwrap();
println!("longest word: {}", longest);
println!("length: {}", longest.len());
}
Output:
longest word: programming
length: 11Questions readers ask
How do I spread this sheet over a week?
Work through one group a day, in order. Say your own answer before reading the one here. Type the programs out and run each one. Save the last day for the coding tasks and any questions you missed. Short sessions across the week beat a single long night before interview day.
Do I need Rust installed before I start?
Yes, if you want to run the programs. Get Rust through rustup, following the steps for your computer. Run rustc --version to check the install worked. This sheet was built with rustc 1.99.1. You can read every answer without installing anything, but running the programs is where the learning happens.
What comes after this sheet?
Rust Advanced, for unsafe code and macros. The Tokio course, for async Rust and real servers. The Capstone projects at the end of each course, which turn the ideas into working programs.
Do I need to know another language first?
No. Rust Beginner starts with a first program and defines each idea as it arrives. Knowing another language helps with loops and functions, but the course never assumes it. Ownership and borrowing are new to most readers either way, so everyone meets them fresh.