mirror of
https://github.com/rust-lang/rustlings.git
synced 2024-12-27 15:56:28 +00:00
64 lines
1.5 KiB
Rust
64 lines
1.5 KiB
Rust
#[derive(Debug, PartialEq, Eq)]
|
|
enum DivisionError {
|
|
DivideByZero,
|
|
NotDivisible,
|
|
}
|
|
|
|
// TODO: Calculate `a` divided by `b` if `a` is evenly divisible by `b`.
|
|
// Otherwise, return a suitable error.
|
|
fn divide(a: i32, b: i32) -> Result<i32, DivisionError> {
|
|
todo!();
|
|
}
|
|
|
|
// TODO: Add the correct return type and complete the function body.
|
|
// Desired output: `Ok([1, 11, 1426, 3])`
|
|
fn result_with_list() {
|
|
let numbers = [27, 297, 38502, 81];
|
|
let division_results = numbers.into_iter().map(|n| divide(n, 27));
|
|
}
|
|
|
|
// TODO: Add the correct return type and complete the function body.
|
|
// Desired output: `[Ok(1), Ok(11), Ok(1426), Ok(3)]`
|
|
fn list_of_results() {
|
|
let numbers = [27, 297, 38502, 81];
|
|
let division_results = numbers.into_iter().map(|n| divide(n, 27));
|
|
}
|
|
|
|
fn main() {
|
|
// You can optionally experiment here.
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn test_success() {
|
|
assert_eq!(divide(81, 9), Ok(9));
|
|
}
|
|
|
|
#[test]
|
|
fn test_divide_by_0() {
|
|
assert_eq!(divide(81, 0), Err(DivisionError::DivideByZero));
|
|
}
|
|
|
|
#[test]
|
|
fn test_not_divisible() {
|
|
assert_eq!(divide(81, 6), Err(DivisionError::NotDivisible));
|
|
}
|
|
|
|
#[test]
|
|
fn test_divide_0_by_something() {
|
|
assert_eq!(divide(0, 81), Ok(0));
|
|
}
|
|
|
|
#[test]
|
|
fn test_result_with_list() {
|
|
assert_eq!(result_with_list().unwarp(), [1, 11, 1426, 3]);
|
|
}
|
|
|
|
#[test]
|
|
fn test_list_of_results() {
|
|
assert_eq!(list_of_results(), [Ok(1), Ok(11), Ok(1426), Ok(3)]);
|
|
}
|
|
}
|