Control Flow and Functions
`if` as an expression, `loop` with a value, `while`, `for` over ranges, labels, functions, and the line between expressions and statements.
12 questions
JuniorTheoryCommonWhat does the program print?
What does the program print?
4
Open full question →Common mistakes
- ✗Expecting a compile error over the missing
;afterx + 1: a block's last expression is written without;on purpose, and it becomes the block's value. - ✗Expecting
3fromlet x = 3;: aletis a statement and gives no value; the block's value is its last expression,x + 1.
Follow-up questions
- →What would
yhold if the block's last line werex + 1;? - →Why is
xno longer visible after the block's closing}?
JuniorTheoryCommonHow do expressions and statements differ, and why does a final ; give ()?
How do expressions and statements differ, and why does a final ; give ()?
An expression yields a value, a statement does not: let is a statement, and ; turns an expression into one, dropping its value. A block, if and match are expressions valued by their last expression without ;, so a trailing ; leaves ().
Common mistakes
- ✗Treating
;as a pure separator that cannot change a function's result - ✗Thinking
letreturns the assigned value, as assignment does in C - ✗Believing
ifis a statement and looking for a ternary?:operator
Follow-up questions
- →What ends up in
xafterlet x = y = 6;, and why? - →When may the
;after a block-like expression such asifbe omitted?
JuniorCodeCommonWrite the classic FizzBuzz exercise with a for range and a match
Write the classic FizzBuzz exercise with a for range and a match
Loop for i in 1..=n, since the inclusive range reaches n, and match on (i % 3, i % 5): (0, 0) prints FizzBuzz, (0, _) Fizz, (_, 0) Buzz and _ the number. The first matching arm wins, so (0, 0) must come first.
Common mistakes
- ✗Writing
1..n, which stops beforenand drops the last number - ✗Putting
(0, 0)after(0, _), so multiples of 15 printFizzand the arm is unreachable - ✗Reaching for a
whilecounter withi++, althoughforover a range needs none and Rust has no++
Follow-up questions
- →How would you return the lines as a
Vec<String>instead of printing them? - →Why does the compiler warn when
(0, 0)comes after(0, _)?
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
5, as if;changed nothing:5;is a statement that discards the value, sofivereturns()and breaks its-> i32promise (E0308). - ✗Expecting a default value such as
0: Rust never makes up a return value, and a body without a final expression returns().
Follow-up questions
- →Which two different edits make
fivecompile and return5? - →Why does a function without
->compile when its last line ends with;?
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
yes, as in C or Python: Rust has no truthiness, anifcondition must be abool, soif nis error E0308 until it readsif n != 0. - ✗Expecting a panic at run time: the type of the condition is checked while building, so the compiler rejects
if nand no program is produced.
Follow-up questions
- →How would you change the condition so that the program prints
yes? - →Why does an
ifwhose branches return ani32and a&strnot compile?
JuniorTheoryCommonWhat does the program print?
What does the program print?
20
Open full question →Common mistakes
- ✗Expecting a compile error because loops have no value:
loopis an expression, andbreak count * 2makescount * 2the value of the whole loop. - ✗Expecting
10:breaktakes the whole expression after it, sobreak count * 2leaves withcount * 2, not withcount.
Follow-up questions
- →What would
resulthold if the loop ended with a barebreak;? - →Why may a
whileloop not end withbreak count * 2?
JuniorTheoryCommonHow do loop, while and for differ, and what are loop labels for?
How do loop, while and for differ, and what are loop labels for?
loop runs until break and alone returns a value (break value); while checks a bool before each pass; for walks an iterator: 0..n stops before n, 0..=n reaches it. A label like 'outer aims break or continue at an outer loop.
Common mistakes
- ✗Expecting
whileorforto return a value throughbreak value(error E0571) - ✗Reading
0..nas includingn, an off-by-one in every loop over a range - ✗Assuming a bare
breakin a nested loop leaves all the enclosing loops
Follow-up questions
- →Why does the compiler suggest
loopinstead ofwhile true? - →Why does
loopallowbreak valuewhilewhileandforforbid it?
JuniorTheoryCommonWhat does the program print?
What does the program print?
6
Open full question →Common mistakes
- ✗Expecting
10: the range1..4excludes its end, soitakes 1, 2 and 3; the form that reaches 4 is the inclusive1..=4. - ✗Expecting the range to skip its start:
a..bbegins ataitself and stops just beforeb.
Follow-up questions
- →How would you change the range so that the loop adds 1 through 4?
- →What does
for i in 4..1print, and how do you count down instead?
JuniorTheoryOccasionalWhat does the program print?
What does the program print?
2
Open full question →Common mistakes
- ✗Expecting
3, as with a plainbreak: a barebreakleaves only the nearest loop, whilebreak 'outerends the labelled outer loop too. - ✗Expecting
6, mixing upbreakandcontinue:continueskips one pass, whilebreak 'outerstops both loops completely.
Follow-up questions
- →What would the program print with
continue 'outerinstead ofbreak 'outer? - →Why may
break 'outernot carry a value when'outerlabels aforloop?
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
5because the calladd(2, 3)shows the types: inference stops at the signature, so each parameter is written asa: i32. - ✗Expecting a shared type such as
a, b: i32: Rust has no such shorthand, and every parameter carries its ownname: Type.
Follow-up questions
- →Why does Rust require parameter types when
let x = 5;needs none? - →How would you write
addso that it accepts bothi32andf64?
JuniorTheoryOccasionalWhat does main do in a Rust program, and what happens if it returns Err?
What does main do in a Rust program, and what happens if it returns Err?
A minimal program is fn main() {}, the entry point; it takes no parameters (arguments come from std::env::args()). main may return Result<(), E> with E: Debug; an Err prints Error: and its Debug form to stderr and exits with code 1.
Common mistakes
- ✗Believing an
Errreturned frommainis a panic with exit code 101 - ✗Expecting
mainto receive the command-line arguments as a parameter - ✗Thinking the error type needs
Display, whenmainprints it withDebug
Follow-up questions
- →How do you exit with a custom status code without panicking?
- →Why does
mainprint the error withDebugrather thanDisplay?
MiddleTheoryOccasionalWhat are () and the never type !, and why does ! fit any type?
What are () and the never type !, and why does ! fit any type?
(), the unit type, has one value; a function without -> or a block ending in ; returns it. ! has no values: panic!, return, break, continue and an endless loop never yield, so ! coerces to any type, e.g. in a match arm.
Common mistakes
- ✗Calling
!thevoidof Rust, when that role is played by() - ✗Not seeing why a
panic!arm fits the other arms' type: its type!coerces to any type - ✗Forgetting that
return,breakandcontinueare expressions of type!too
Follow-up questions
- →Why must the
elseblock of alet … elseend inreturn,breakorpanic!? - →What does a function signature ending in
-> !promise, and which std function has one?