Basic Arithmetic in Rust
Level: intro (score: 1)
🚀 These intro exercises are prep for our
Rust Intro Cohort Program.
In this exercise, you'll implement a function that performs basic arithmetic operations on two integers.
Your function will return a tuple containing:
- The sum of the numbers.
- The difference (first minus second).
- The product.
- The quotient as an Option<i32> (if the divisor is zero, return None).
This exercise helps you practice Rust’s arithmetic operators and simple conditional logic.
In real-world scenarios, such operations underpin everything from calculating daily expenses to computing mission-critical values in your favorite sci-fi adventure!
Hint: In Rust, the Option type is used to represent a value that may or may not be present. When a value exists, it's wrapped in Some(value).
When there is no value (for example, if dividing by zero), we return None.
Happy coding!
pub fn basic_arithmetic(a: i32, b: i32) -> (i32, i32, i32, Option<i32>) {
// Code here
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_basic_arithmetic_normal() {
// 10 + 2 = 12, 10 - 2 = 8, 10 * 2 = 20, 10 / 2 = 5
assert_eq!(basic_arithmetic(10, 2), (12, 8, 20, Some(5)));
}
#[test]
fn test_basic_arithmetic_division_by_zero() {
// When the divisor is zero, quotient should be None.
assert_eq!(basic_arithmetic(5, 0), (5, 5, 0, None));
}
#[test]
fn test_basic_arithmetic_negative() {
// For -8 and 4: -8 + 4 = -4, -8 - 4 = -12, -8 * 4 = -32, -8 / 4 = -2
assert_eq!(basic_arithmetic(-8, 4), (-4, -12, -32, Some(-2)));
}
#[test]
fn test_basic_arithmetic_mixed() {
// For 7 and -3: 7 + (-3) = 4, 7 - (-3) = 10, 7 * (-3) = -21, 7 / (-3) truncates to -2
assert_eq!(basic_arithmetic(7, -3), (4, 10, -21, Some(-2)));
}
}