Misc 6 @orlp @Noratrieb
Warning: this quiz is still "work-in-progress", some questions might not have good explanations (or any at all), formatting/structure/titles/etc are not final, and so on. You might want to return here on a later date.
What does this program print?
#![allow(unreachable_code)]
struct PrintOnDrop(&'static str);
impl Drop for PrintOnDrop {
fn drop(&mut self) {
eprint!("{}", self.0);
}
}
fn main() {
owo();
uwu();
}
fn owo() {
(
(PrintOnDrop("1"), PrintOnDrop("2"), PrintOnDrop("3")),
return,
);
}
fn uwu() {
(PrintOnDrop("1"), PrintOnDrop("2"), PrintOnDrop("3"), return);
}
Solution
123321
Every expression in the outermost tuple is evaluated from left to right.
return
is the last expression, at which point the function returns and all tuple elements are dropped.
When an expression during tuple construction causes drops to be invoked, all elements are dropped from last to first.
This is a general rule for local variables or temporaries in Rust and also applies to local variables.
But in owo
, the first element is a fully constructed tuple, which is dropped the same way all structures are - from first to last.