Functions and Return Values
Easy
+2 pts
Intro to Rust
4/15
π― In Python, functions use def, type hints are optional, and you return with return:
def area(width: int, height: int) -> int:
return width * height
Rust functions look similar but with important differences:
fn area(width: i32, height: i32) -> i32 {
width * height
}
Three things to notice:
- Types are required β every parameter and the return type must be declared. No optional hints.
- Expression-based returns β the last expression (without a semicolon) is the return value. No
returnkeyword needed. - Semicolons matter β adding a semicolon to the last line turns it into a statement and the function returns
()(Rust's unit type, like Python'sNone).
The semicolon trap
This is a common gotcha for Python developers:
fn broken(width: i32, height: i32) -> i32 {
width * height; // semicolon makes this a statement, not a return value
// ERROR: expected i32, found ()
}
Remove the semicolon and it works. The return keyword exists but is mainly used for early returns from within branches.
Your Task
Implement add_and_double β takes two i32 values, returns (a + b) * 2.
Use expression-based return (no return keyword).
Example
assert_eq!(add_and_double(2, 3), 10);
assert_eq!(add_and_double(-1, 4), 6);
Further Reading
- The Rust Book β Functions β parameters, return types, and expressions
- The Rust Book β Statements and Expressions β why semicolons matter
fn add_and_double(a: i32, b: i32) -> i32 {
// TODO:
// - Add a and b
// - Multiply the result by 2
// - Return the final result (no `return` needed if it's the last expression)
todo!()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add_and_double_positive() {
assert_eq!(add_and_double(2, 3), 10);
}
#[test]
fn test_add_and_double_mixed() {
assert_eq!(add_and_double(-1, 4), 6);
}
}
Topics