Rust quiz – 42 questions with answers
Try it interactively
With scoring, random questions, and saved progress – or go straight to the timed exam with certificate.
Beginner (14 questions)
How do you declare a mutable variable in Rust?
- var x = 5;
- let mut x = 5;
- mut let x = 5;
- let x = mut 5;
Show answer
Correct: let mut x = 5;
Variables are immutable by default; mut after let allows changes.
What happens with let x = 5; if you later write x = 6;?
- It works, x is 6 afterwards
- Compiler error: x is immutable
- A panic is triggered at runtime
- x is automatically redeclared
Show answer
Correct: Compiler error: x is immutable
Without mut, a variable is immutable, and the compiler refuses the assignment.
What does this code print?
fn main() {
let x = 5;
let x = x + 1;
{
let x = x * 2;
println!("{x}");
}
println!("{x}");
}- 12 and 6
- 6 and 6
- 12 and 12
- Compiler error
Show answer
Correct: 12 and 6
Shadowing: in the inner block x = 6 * 2 = 12, and afterwards the outer x = 6 applies again.
What does the ! in println! stand for?
- It negates the output
- It marks a macro
- It marks unsafe code
- It means: can fail
Show answer
Correct: It marks a macro
Names with ! are macros. They are expanded at compile time and can, for example, take a variable number of arguments and check format strings.
Does this compile?
fn f() -> i32 {
5;
}- Yes, returns 5
- No: the semicolon turns the expression into a statement, so the return type would be ()
- Yes, returns 0
- Only with a return before the 5
Show answer
Correct: No: the semicolon turns the expression into a statement, so the return type would be ()
Without the semicolon, 5 would be the return value. With ; the block value is (), which does not match i32.
Which numbers does for i in 1..=3 iterate over?
- 1, 2
- 1, 2, 3
- 0, 1, 2, 3
- 2, 3
Show answer
Correct: 1, 2, 3
1..=3 is an inclusive range: 1, 2, 3. 1..3 would only yield 1 and 2.
Does this compile?
fn main() {
let s1 = String::from("a");
let s2 = s1;
println!("{s1}");
}- Yes, prints a
- No: s1 was moved to s2
- Yes, prints nothing
- No: String has no from
Show answer
Correct: No: s1 was moved to s2
String owns heap memory and is moved. Afterwards s1 is invalid (“borrow of moved value”). Fix: s1.clone() or borrowing.
Which of these types implements Copy?
- String
- Vec<i32>
- i32
- Box<i32>
Show answer
Correct: i32
Simple fixed-size values such as numbers, bool, and char are Copy. String, Vec, and Box own heap memory and are moved.
What does .clone() do on a String?
- Creates a second reference to the same text
- Creates a deep copy with its own heap memory
- Moves the ownership
- Deletes the original string
Show answer
Correct: Creates a deep copy with its own heap memory
clone duplicates the content. This can be expensive and should be used deliberately.
How many &mut references to the same value may exist at the same time?
- Any number
- At most one
- Exactly two
- None, &mut is forbidden
Show answer
Correct: At most one
The borrow checker allows either any number of &T or exactly one &mut T, which prevents data races.
What does this code print?
fn main() {
let mut s = String::from("Hi");
let r = &mut s;
r.push('!');
println!("{s}");
}- Hi!
- Hi
- Compiler error: s is borrowed
- Compiler error: push needs a String
Show answer
Correct: Hi!
r is no longer used after push, so the borrow ends (NLL). s may therefore be read again: “Hi!”.
What is neu in impl Rechteck { fn neu(b: f64, h: f64) -> Self { ... } }?
- A method with self
- An associated function (comparable to a static method)
- A destructor
- A macro
Show answer
Correct: An associated function (comparable to a static method)
Functions without self in the impl block are called with Type::name(). This is the usual form for constructors.
What type does the literal "hello" have?
- String
- &str
- char
- &String
Show answer
Correct: &str
String literals are &'static str: an immutable view of text that is embedded in the program. A String is created, for example, with String::from.
Which command creates a new Rust project with Cargo?
- rustc new hallo
- cargo init --file hallo
- cargo new hallo
- rustup create hallo
Show answer
Correct: cargo new hallo
cargo new hallo creates the folder, Cargo.toml, src/main.rs, and a Git repository.
Intermediate (16 questions)
What applies to a match over an enum?
- It must cover all variants (or use
_) - It may only match
Option - Missing cases are ignored at runtime
- Every branch needs a return
Show answer
Correct: It must cover all variants (or use _)
match is exhaustive: if a variant is missing and there is no catch-all _ arm, the compiler refuses to compile.
What does the ? operator do after a Result?
- Ignores the error
- Returns from the function immediately on
Err, and yields the value onOk - Converts the Result to an Option
- Always triggers a panic
Show answer
Correct: Returns from the function immediately on Err, and yields the value on Ok
? unwraps Ok and does an early return on Err (with From conversion of the error).
What does this code print?
fn main() {
let v = vec![1, 2, 3];
let s: i32 = v.iter().map(|x| x * 2).sum();
println!("{s}");
}- 6
- 12
- [2, 4, 6]
- Compiler error
Show answer
Correct: 12
The values are doubled (2, 4, 6) and summed: 12.
Which variants does Option<T> have?
- Ok(T) and Err(E)
- Some(T) and None
- Just(T) and Nothing
- Value(T) and Null
Show answer
Correct: Some(T) and None
Option<T> is either Some(T) or None. Ok/Err belong to Result.
What does this code print?
fn main() {
let x: Option<i32> = None;
println!("{}", x.unwrap_or(7));
}- 7
- 0
- None
- Panic
Show answer
Correct: 7
On None, unwrap_or returns the given fallback value: 7.
What is a trait?
- A class with inheritance
- A collection of methods that types can implement
- A memory model
- A preprocessor macro
Show answer
Correct: A collection of methods that types can implement
Traits describe shared behavior (similar to interfaces, but with default methods) and replace inheritance.
What does this code print?
fn main() {
println!("{}", "Élève".len());
}- 5
- 7
- 6
- 10
Show answer
Correct: 7
len() counts bytes, not characters. In UTF-8, É and è take 2 bytes each: 2+1+2+1+1 = 7 (chars().count() would be 5).
Does this compile?
fn main() {
let mut v = vec![1, 2, 3];
let erstes = &v[0];
v.push(4);
println!("{erstes}");
}- Yes, prints 1
- No: v is borrowed mutably while erstes is still in use
- No: push does not exist for Vec
- Yes, prints 4
Show answer
Correct: No: v is borrowed mutably while erstes is still in use
erstes is an immutable reference that is still read after the push. push might move the memory, so the borrow checker rejects it.
What does *map.entry("a").or_insert(0) += 1; do?
- Always sets the value to 1
- Creates the key with 0 if it is missing, and increments the value by 1
- Deletes the key
- Returns an error if the key is missing
Show answer
Correct: Creates the key with 0 if it is missing, and increments the value by 1
entry().or_insert(0) returns a &mut reference to the value (newly created with 0 if necessary); * dereferences it so it can be incremented. The classic counter pattern.
What does this code print?
fn main() {
let mut z = 0;
let mut inc = || z += 1;
inc();
inc();
println!("{z}");
}- 0
- 1
- 2
- Compiler error
Show answer
Correct: 2
The closure borrows z mutably. After the last call the borrow ends, so println! may read it: 2.
What does this code print?
fn main() {
let v = vec![1, 2, 3];
let _it = v.iter().map(|x| {
println!("processing {x}");
x * 2
});
println!("done");
}- done
- Three "processing" lines, then done
- done, then three "processing" lines
- Compiler error
Show answer
Correct: done
Iterator adapters are lazy. Without a consumer (collect, sum, for ...), the closure is never called.
What does cargo check do?
- Runs all tests
- Checks the code for errors without producing a binary
- Formats the code
- Updates all dependencies
Show answer
Correct: Checks the code for errors without producing a binary
cargo check runs the type checker and borrow checker but skips code generation, which makes it much faster than cargo build.
What does #[derive(Debug)] enable on a struct?
- Automatic cloning
- Output with
{:?}and{:#?} - Comparison with ==
- Serialization to JSON
Show answer
Correct: Output with {:?} and {:#?}
Debug generates a text representation for developers. Cloning would be Clone, comparison PartialEq.
What does this code print?
fn main() {
let x: u8 = 255;
let y = x.wrapping_add(1);
println!("{y}");
}- 0
- 256
- Panic
- 255
Show answer
Correct: 0
wrapping_add wraps around on overflow: 255 + 1 = 256 mod 256 = 0. checked_add would return None, and + in a debug build would panic.
What does v.get(10) return for a Vec with 3 elements?
- A panic
None- The value 0
- A compiler error
Show answer
Correct: None
get returns an Option<&T>: None for an invalid index. Only v[10] would panic.
What does this code print?
fn main() {
let z = [1, 2, 3, 4, 5, 6];
let r: Vec<i32> = z.iter().copied().filter(|x| x % 2 == 0).collect();
println!("{:?}", r);
}- [1, 3, 5]
- [2, 4, 6]
- [2, 4]
- [1, 2, 3, 4, 5, 6]
Show answer
Correct: [2, 4, 6]
The filter keeps the even numbers 2, 4, and 6.
Advanced (12 questions)
What does a lifetime annotation like &'a str describe?
- It extends the lifetime of the reference
- It describes how long references must remain valid relative to each other, but does not change the actual lifetime
- It makes the reference mutable
- It moves the value to the heap
Show answer
Correct: It describes how long references must remain valid relative to each other, but does not change the actual lifetime
Lifetimes are relationships for the borrow checker. They change nothing at runtime; they help the compiler prove that no reference becomes invalid.
Does this compile?
fn laenger(a: &str, b: &str) -> &str {
if a.len() > b.len() { a } else { b }
}- Yes
- No: missing lifetime specifier, because the compiler does not know whether the result depends on a or b
- No: str has no len
- Yes, but with a warning
Show answer
Correct: No: missing lifetime specifier, because the compiler does not know whether the result depends on a or b
With two reference parameters, elision does not apply. You need, for example, fn laenger<'a>(a: &'a str, b: &'a str) -> &'a str.
How does Arc<T> differ from Rc<T>?
- Arc can hold mutable values
- Arc uses atomic counters and is thread-safe (Send/Sync), Rc is not
- Arc lives on the stack
- There is no difference
Show answer
Correct: Arc uses atomic counters and is thread-safe (Send/Sync), Rc is not
Arc = atomic reference counting: slightly more expensive, but usable across threads. Rc is for a single thread only and is not Send.
What does this code print?
struct W(&'static str);
impl Drop for W {
fn drop(&mut self) { println!("{}", self.0); }
}
fn main() {
let _a = W("A");
let _b = W("B");
println!("End");
}- End, B, A
- A, B, End
- End, A, B
- B, A, End
Show answer
Correct: End, B, A
First main runs to the end (“End”). After that, local variables are freed in reverse order of declaration: first _b, then _a.
What is special about RefCell<T>?
- It checks the borrow rules at runtime; violations lead to a panic
- It is thread-safe
- It prevents any modification
- It always lives on the stack and cannot be cloned
Show answer
Correct: It checks the borrow rules at runtime; violations lead to a panic
RefCell allows “interior mutability” through shared references. The rules (one &mut or many &) are then only checked at runtime.
What does the marker trait Send mean?
- A type may be sent through a channel, that is, moved to another thread
- A type can be converted to JSON
- A type is network-capable
- A type holds no references
Show answer
Correct: A type may be sent through a channel, that is, moved to another thread
Send allows moving ownership to another thread. Sync means that &T may be used by several threads at the same time.
When is the lock of a Mutex released again?
- Only by an explicit call to unlock()
- When the
MutexGuardleaves its scope (Drop) - Automatically after 1 second
- When the program exits
Show answer
Correct: When the MutexGuard leaves its scope (Drop)
lock() returns a MutexGuard. Its Drop releases the lock; there is no unlock method, so you cannot forget it.
How is the call f.flaeche() resolved for f: &Box<dyn Form>?
- At compile time (static dispatch)
- At runtime via a vtable (dynamic dispatch)
- Not at all, it does not compile
- Via reflection
Show answer
Correct: At runtime via a vtable (dynamic dispatch)
With dyn Trait, the compiler does not know the concrete type. The method call goes through a table of function pointers (vtable).
What does this code print?
use std::rc::Rc;
fn main() {
let rc = Rc::new(5);
let rc2 = Rc::clone(&rc);
println!("{}", Rc::strong_count(&rc));
drop(rc2);
}- 1
- 2
- 5
- Compiler error
Show answer
Correct: 2
Rc::clone does not copy the content but only increments the reference counter: two owners, so strong_count is 2.
Why does thread::spawn(|| println!("{}", v.len())) with a local v normally need move?
- Because println! otherwise does not work
- The thread can outlive the function; the closure may therefore not merely borrow local variables
- Because v has to be mutable
- Because threads do not accept closures
Show answer
Correct: The thread can outlive the function; the closure may therefore not merely borrow local variables
spawn requires 'static: the closure may not borrow anything short-lived. With move it takes ownership (or you use thread::scope).
Does this compile?
use std::rc::Rc;
use std::thread;
fn main() {
let rc = Rc::new(1);
thread::spawn(move || println!("{rc}"));
}- Yes, prints 1
- No: Rc is not Send and may not go into another thread
- Yes, but only in a release build
- No: println cannot print an Rc
Show answer
Correct: No: Rc is not Send and may not go into another thread
Rc uses a non-atomic counter and is therefore not Send. For threads, use Arc. This is how the compiler prevents data races.
What is the difference between fn f<T: Tier>(t: T) and fn f(t: &dyn Tier)?
- No difference
- The generic version is monomorphized per type (static dispatch), the dyn version uses a vtable (dynamic dispatch)
- The generic version is slower
- The dyn version only works with Copy types
Show answer
Correct: The generic version is monomorphized per type (static dispatch), the dyn version uses a vtable (dynamic dispatch)
Generics produce separate code for each type, often optimized with inlining (larger binary). dyn saves code but costs an indirect call and allows mixed types in one collection.