Challenge - 5 Problems
Rust Function Parameters Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of function with mutable reference parameter
What is the output of this Rust code?
Rust
fn add_one(x: &mut i32) {
*x += 1;
}
fn main() {
let mut num = 5;
add_one(&mut num);
println!("{}", num);
}Attempts:
2 left
💡 Hint
Think about how mutable references allow modifying the original variable.
✗ Incorrect
The function takes a mutable reference and increments the value it points to. So num changes from 5 to 6.
❓ Predict Output
intermediateOutput of function with default parameter simulation
Rust does not support default parameters directly. What is the output of this code simulating default parameters?
Rust
fn greet(name: Option<&str>) {
let name = name.unwrap_or("Guest");
println!("Hello, {}!", name);
}
fn main() {
greet(Some("Alice"));
greet(None);
}Attempts:
2 left
💡 Hint
Look at how Option and unwrap_or work.
✗ Incorrect
The function prints 'Hello, Alice!' when Some("Alice") is passed, and 'Hello, Guest!' when None is passed.
🔧 Debug
advancedIdentify the error with lifetime in function parameters
What error does this Rust code produce?
Rust
fn longest(x: &str, y: &str) -> &str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let string1 = String::from("long string");
let result;
{
let string2 = String::from("short");
result = longest(string1.as_str(), string2.as_str());
}
println!("{}", result);
}Attempts:
2 left
💡 Hint
Check the function signature for lifetime annotations.
✗ Incorrect
The function returns a reference but does not specify lifetimes, so Rust cannot guarantee safety. This causes a compilation error.
📝 Syntax
advancedWhich function parameter syntax is invalid?
Which of these Rust function parameter declarations is invalid?
Attempts:
2 left
💡 Hint
Consider how mutability is declared in parameters.
✗ Incorrect
You cannot write &mut x: i32 in parameter list. The correct syntax is x: &mut i32.
🚀 Application
expertDetermine the output of function with pattern matching parameters
What is the output of this Rust code using pattern matching in function parameters?
Rust
fn print_point(&(x, y): &(i32, i32)) {
println!("x: {}, y: {}", x, y);
}
fn main() {
let point = (10, 20);
print_point(&point);
}Attempts:
2 left
💡 Hint
Look at how the tuple is destructured in the parameter.
✗ Incorrect
The function parameter destructures the tuple reference into x and y, so it prints their values.
