Consider the following Rust program. What will it print when run?
fn greet() {
println!("Hello from greet!");
}
fn main() {
println!("Start main");
greet();
println!("End main");
}Think about the order in which functions are called and how println! outputs text.
The main function prints "Start main", then calls greet() which prints "Hello from greet!", and finally prints "End main". So the output is in that order.
What will this Rust program print?
fn first() {
println!("First");
}
fn second() {
println!("Second start");
first();
println!("Second end");
}
fn main() {
second();
}Remember that when a function calls another, the called function runs completely before returning.
The main calls second(), which prints "Second start", then calls first() which prints "First", then second() prints "Second end".
What will this Rust program print?
fn countdown(n: u32) {
if n == 0 {
println!("Blast off!");
} else {
println!("{}", n);
countdown(n - 1);
}
}
fn main() {
countdown(3);
}Think about how recursion works and when the base case triggers.
The function prints the current number, then calls itself with one less. When it reaches zero, it prints "Blast off!". So it prints 3, 2, 1, then "Blast off!".
What will this Rust program print?
fn a() {
println!("A");
}
fn b() {
println!("B start");
a();
println!("B end");
}
fn c() {
println!("C start");
b();
println!("C end");
}
fn main() {
c();
}Follow the chain of calls from main to c, then b, then a.
main calls c(), which prints "C start", calls b(), which prints "B start", calls a() printing "A", then b() prints "B end", and finally c() prints "C end".
Given the following Rust code, what is the state of the call stack just before println!("Inside inner"); executes?
fn inner() {
println!("Inside inner");
}
fn middle() {
inner();
}
fn outer() {
middle();
}
fn main() {
outer();
}Think about the order functions call each other and how the stack grows.
Each function call adds a frame on top of the stack. Before inner prints, main called outer, which called middle, which called inner. So the stack from bottom to top is main, outer, middle, inner.
