Challenge - 5 Problems
Rust Return Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this Rust function?
Consider the following Rust code. What will be printed when
main runs?Rust
fn add_one(x: i32) -> i32 {
x + 1
}
fn main() {
let result = add_one(5);
println!("{}", result);
}Attempts:
2 left
💡 Hint
Look at what the function returns and what value is passed in.
✗ Incorrect
The function
add_one returns the input value plus one. Passing 5 returns 6, which is printed.❓ Predict Output
intermediateWhat does this Rust function return?
What is the value of
result after calling compute()?Rust
fn compute() -> i32 {
let x = 10;
let y = 20;
x + y
}
fn main() {
let result = compute();
println!("{}", result);
}Attempts:
2 left
💡 Hint
The last expression without a semicolon is returned.
✗ Incorrect
The function returns the sum of x and y, which is 30.
🔧 Debug
advancedWhy does this Rust function cause a compilation error?
Examine the code below. Why does it fail to compile?
Rust
fn faulty() -> i32 {
let x = 5;
return;
}
fn main() {
let val = faulty();
println!("{}", val);
}Attempts:
2 left
💡 Hint
Check the function's declared return type and what it actually returns.
✗ Incorrect
The function declares it returns i32 but returns nothing, causing a compilation error.
❓ Predict Output
advancedWhat is printed by this Rust function with multiple return points?
What will be printed when
main runs?Rust
fn check_number(n: i32) -> &'static str {
if n > 0 {
return "Positive";
} else if n < 0 {
return "Negative";
}
"Zero"
}
fn main() {
println!("{}", check_number(0));
}Attempts:
2 left
💡 Hint
Look at the input value and which return path it triggers.
✗ Incorrect
Input 0 triggers the last expression which returns "Zero".
🧠 Conceptual
expertWhat is the type of the return value in this Rust function?
Consider this Rust function. What is the exact return type of
mystery?Rust
fn mystery(flag: bool) -> Option<i32> {
match flag {
true => Some(42),
false => None,
}
}Attempts:
2 left
💡 Hint
Look at the function signature and what is returned inside the match.
✗ Incorrect
The function returns an Option wrapping an i32, either Some(42) or None.
