Rust Basics
Toolchain and Cargo, `let` and `mut`, shadowing, `const` and `static`, scalar types, integer overflow, conversions, tuples and arrays — where every Rust interview starts.
18 questions
JuniorTheoryCommonWhat does the program print?
What does the program print?
44
Open full question →Common mistakes
- ✗Expecting
255: anascast between integers does not stop at the largest value; it keeps what fits in 8 bits, and 300 − 256 = 44. - ✗Expecting a panic, as with overflow in a debug build:
asnever checks the range, it truncates silently.
Follow-up questions
- →How would you convert 300 to
u8so that the failure is reported, not hidden? - →What does
-1_i32 as u8give, and why?
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting
6, as in most languages: a Rust variable can be given a new value only when it is declared withlet mut. - ✗Expecting the error to show up at run time: immutability is a compile-time rule, so the program is never built.
Follow-up questions
- →What is the smallest change that makes the program print
6? - →How could you give
xa new value without declaring itmut?
JuniorTheoryCommonWhat does cargo new generate, and what do cargo build, run and test do?
What does cargo new generate, and what do cargo build, run and test do?
cargo new creates the manifest Cargo.toml, src/main.rs with hello world and a git repo. cargo build compiles to target/debug/, cargo run builds and starts the program, and cargo test builds and runs the #[test] functions.
Common mistakes
- ✗Thinking
cargo buildmakes an optimized build by default; that needs--releaseand goes totarget/release/ - ✗Expecting
target/to exist right aftercargo new; it appears with the first build - ✗Believing
cargo runskips compilation; it first rebuilds whatever has changed
Follow-up questions
- →How do
Cargo.tomlandCargo.lockdiffer in what they record? - →Why is the
target/directory kept out of version control?
JuniorTheoryCommonWhen are let, const and static evaluated, where do they live, and why avoid static mut?
When are let, const and static evaluated, where do they live, and why avoid static mut?
let is a run-time local of its scope. const is computed at compile time and inlined at each use, with no fixed address. static is also compile-time but has one address for the whole run; edition 2024 refuses references to a static mut.
Common mistakes
- ✗Treating
constas a global variable with an address, the waystaticis - ✗Expecting a
constorstaticinitializer to call an ordinary function at run time - ✗Assuming an
unsafeblock is enough to take&mutof astatic mutin edition 2024
Follow-up questions
- →What would you use instead of a
static mutcounter that several threads update? - →Why must
constandstaticitems always spell out their type?
JuniorTheoryCommonWhat does the program print?
What does the program print?
3 3.5
Open full question →Common mistakes
- ✗Expecting
3.5from7 / 2: dividing one integer by another gives an integer, and the fraction is dropped. - ✗Expecting integer division to round:
7 / 2drops the.5and gives 3, never 4.
Follow-up questions
- →How would you get 3.5 from two integer variables
a = 7andb = 2? - →What does
-7 / 2give in Rust, and why?
JuniorTheoryCommonWhat does mut allow on a let binding, and why is immutability the default?
What does mut allow on a let binding, and why is immutability the default?
Without mut a binding is assigned once and its value cannot change: x = 6 or v.push(1) is a compile error. let mut allows reassignment and &mut borrows. Immutability is the default so a value changes only where the code marks it with mut.
Common mistakes
- ✗Treating
mutas part of the value's type rather than a property of the binding - ✗Expecting
v.push(1)to work on a plainletbinding because it is not an assignment - ✗Believing an immutable
letcannot be initialised after its declaration, as inlet x; x = 5;
Follow-up questions
- →Why does
let v = vec![1]; let mut w = v; w.push(2);compile? - →What does the compiler say about a
let mutvariable that is never changed?
JuniorTheoryCommonWhich scalar types does Rust have, how are literals typed, and what is usize for?
Which scalar types does Rust have, how are literals typed, and what is usize for?
Integers (i8–i128, u8–u128, isize, usize), floats f32/f64, bool and char, a 4-byte Unicode scalar value. By default an integer literal is i32, a float one f64. usize is pointer-sized, the type of lengths and indexes.
Common mistakes
- ✗Indexing a
Vecwith ani32and expecting an automatic conversion tousize - ✗Thinking
charis a single byte, as in C - ✗Assuming integer literals default to
i64or to the machine word size
Follow-up questions
- →Why does
v[i]fail to compile wheniis ani32, and how do you fix it? - →What happens when an unannotated literal such as
3_000_000_000does not fit ini32?
JuniorTheoryCommonWhat does the program print (lines separated by spaces)?
What does the program print (lines separated by spaces)?
11 10
Open full question →Common mistakes
- ✗Expecting
11 11: theletinside the block makes a separatexthat hides the outer one only until the block's}. - ✗Expecting a redeclaration error: a second
let xis legal in Rust and shadows the firstxinstead of clashing with it.
Follow-up questions
- →How would the output change with
let mut xoutside andx += 1;inside the block? - →Can a shadowing
letgivexa different type, and why?
JuniorTheoryCommonHow does shadowing differ from mut, and why can it change the type?
How does shadowing differ from mut, and why can it change the type?
Shadowing declares a new variable with the same name by another let: the old one is hidden, not changed, and a shadow made in a block ends at its }. Being new, it may have another type. mut changes the value in place and keeps the type.
Common mistakes
- ✗Treating shadowing as mutation and expecting the outer variable to change after an inner block
- ✗Believing a shadowing
letmust keep the original variable's type - ✗Thinking the shadowed value is destroyed at once instead of merely hidden until the end of its scope
Follow-up questions
- →When is shadowing handier than
let mut, for example after callingparse()? - →Is a shadowed value dropped at once, or does it live to the end of its scope?
JuniorTheoryCommonHow do tuples and arrays differ, and when is a tuple better than a struct?
How do tuples and arrays differ, and when is a tuple better than a struct?
A tuple (i32, &str) groups a fixed number of values of any types, read as t.0 or by let (a, b) = t. An array [i32; 3] holds N values of one type, and a[i] is bounds-checked. A tuple suits a short-lived group, like two return values.
Common mistakes
- ✗Indexing a tuple with
t[i]instead of the field syntaxt.0 - ✗Expecting an out-of-bounds array index to read stray memory instead of panicking
- ✗Keeping a tuple as a long-lived data type where named struct fields would document the meaning
Follow-up questions
- →Why can a tuple not be indexed with a variable, as in
t[i]? - →What happens at compile time and at run time when an array index is out of bounds?
MiddleTheoryCommonas, From or TryFrom for numbers: which lose data, which can fail, which to prefer?
as, From or TryFrom for numbers: which lose data, which can fail, which to prefer?
as never fails: integers keep their low bits, floats saturate. From/Into exist only for lossless pairs (u8 → u32). TryFrom/try_into return Err when the value does not fit. Prefer them; use as only for intended truncation.
Common mistakes
- ✗Expecting
asto panic or stop at the limit when an integer does not fit the target type - ✗Looking for
From<i64> for f64, which does not exist because largei64values would lose precision - ✗Using
ason untrusted input wheretry_into()would report the overflow
Follow-up questions
- →Why is there
From<i32> for f64but noFrom<i64> for f64? - →What does a float-to-integer
ascast give forNaNand for out-of-range values?
MiddleTheoryCommonHow do debug and release builds handle integer overflow, and how can you control it?
How do debug and release builds handle integer overflow, and how can you control it?
Debug builds panic on overflow; release builds wrap in two's complement. Overflow the compiler can compute, as in 255u8 + 1, is a compile error. checked_* gives Option, wrapping_* wraps, saturating_* clamps, overflowing_* adds a flag.
Common mistakes
- ✗Assuming release builds also panic on overflow; they wrap unless
overflow-checks = trueis set - ✗Calling Rust integer overflow undefined behaviour, as signed overflow is in C
- ✗Expecting
255u8 + 1between literals to panic at run time; the compiler rejects it
Follow-up questions
- →How would you make a release build panic on integer overflow as well?
- →How does Rust guard an out-of-range index like
v[i], and how does C differ?
JuniorTheoryOccasionalWhat does the cargo check command do?
What does the cargo check command do?
Checks that the code compiles, but builds no executable
Common mistakes
- ✗Expecting a quick debug build:
cargo checkstops before the translation into machine code, so it finds the same errors ascargo buildbut leaves nothing to run. - ✗Expecting it to check code style: formatting is
cargo fmt, andcargo checkreports only what the compiler itself reports.
Follow-up questions
- →Why does
cargo checkfinish faster thancargo buildon the same code? - →When do you still need
cargo buildrather thancargo check?
JuniorTheoryOccasionalWhat does the program print?
What does the program print?
None
Open full question →Common mistakes
- ✗Expecting a panic, as with overflow in a debug build:
checked_addnotices the overflow itself and returnsNoneinstead of panicking. - ✗Expecting the sum to wrap around to 0: that is
wrapping_add, whilechecked_addreturnsSomeonly when the result fits.
Follow-up questions
- →What does
250u8.checked_add(5)print with{:?}, and why? - →Why would a plain
255u8 + 1in the same program fail to compile?
JuniorTheoryOccasionalWhat does the program print?
What does the program print?
2 + 3 = 5
Open full question →Common mistakes
- ✗Expecting
2 + 3 = 23:aandbare integers, soa + bis computed as 5 beforeprintln!puts it in place of the third{}. - ✗Expecting only the numbers: the text between the placeholders belongs to the format string and prints exactly as written.
Follow-up questions
- →How would you write the same line with the variable names inside the braces?
- →Why is
{a + b}rejected inside the braces, and what do you write instead?
JuniorTheoryOccasionalWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting a panic at run time:
println!checks the format string while compiling, so the missing argument stops the build and nothing runs. - ✗Expecting
xto fill both placeholders: each{}takes its own argument, so two{}need two arguments.
Follow-up questions
- →How would you fix the line so that it prints
5 5? - →What does the compiler say when there are more arguments than placeholders?
JuniorTheoryOccasionalWhat does the program print?
What does the program print?
2 3
Open full question →Common mistakes
- ✗Expecting
3.0:{}prints anf64with a zero fraction as a whole number; only{:?}keeps the.0. - ✗Expecting
_not to count in thelet: it fills the second place, socgets the third element.
Follow-up questions
- →How would you read the second element without destructuring the tuple?
- →What would
{:?}print forcin this program, and why?
MiddleTheoryOccasionalWhat may a const fn do, when does it run, and how do const and static differ in use?
What may a const fn do, when does it run, and how do const and static differ in use?
A const fn runs at compile time in a const context (const, static, array length), elsewhere as a normal call. It allows if, match, while, not for, allocation or non-const calls. A const is copied per use; a static has one address.
Common mistakes
- ✗Thinking a
const fncan only be called with arguments known at compile time - ✗Expecting
forloops andVec::pushto work inside aconst fn - ✗Putting a
Cellin aconstand expectingsetto persist, although every use is a fresh copy
Follow-up questions
- →Why does
C.set(5)on aconst C: Cell<i32>leaveC.get()at the old value? - →What happens when a
const fnpanics while aconstitem is being evaluated?