addition: Fraction Error, Fraction and constructor
This commit is contained in:
40
src/lib.rs
40
src/lib.rs
@@ -1,14 +1,38 @@
|
||||
pub fn add(left: u64, right: u64) -> u64 {
|
||||
left + right
|
||||
pub struct Fraction {
|
||||
num: i64,
|
||||
den: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum FractionError {
|
||||
DivisionByZero,
|
||||
ZeroDenominator,
|
||||
Overflow,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for FractionError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
FractionError::DivisionByZero => write!(f, "Division by zero"),
|
||||
FractionError::ZeroDenominator => write!(f, "Denominator can't be zero"),
|
||||
FractionError::Overflow => write!(f, "Numeric overflow"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for FractionError {}
|
||||
|
||||
impl Fraction {
|
||||
pub fn new(num: i64, den: i64) -> Result<Self, FractionError> {
|
||||
if den == 0 {
|
||||
return Err(FractionError::ZeroDenominator);
|
||||
}
|
||||
|
||||
Ok(Fraction { num, den })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn it_works() {
|
||||
let result = add(2, 2);
|
||||
assert_eq!(result, 4);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user