Function Return Values
Level: intro (score: 1)
🚀 These intro exercises are prep for our
Rust Intro Cohort Program.
🎯 In Python, defining functions is straightforward — you write def
and return values as needed.
In Rust, functions are defined with fn
, have typed parameters, and declare a return type.
A few key points for Pythonistas:
- Rust functions must specify parameter and return types.
- If the last expression in the function body does not end with a semicolon, it is returned.
- You can also use the
return
keyword, but it’s more idiomatic to just return the last expression.
✅ Your task:
Implement the add_and_double
function which:
- Takes two
i32
integersa
andb
- Returns an
i32
equal to(a + b) * 2
This exercise introduces:
- Function parameters with explicit types
- Declaring return types
- Returning expressions without
return
💡 Hint: You don’t need return
here — let the final expression be the value.
Example:
assert_eq!(add_and_double(2, 3), 10);
assert_eq!(add_and_double(-1, 4), 6);
pub 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)
}
#[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);
}
}