Created
May 5, 2020 22:29
-
-
Save jcaromiq/aa4f96856354bb0760dd5b28dbd48ca1 to your computer and use it in GitHub Desktop.
Rust snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[derive(Debug, PartialEq)] | |
enum Currency {DOLLAR, EURO} | |
#[derive(Debug, PartialEq)] | |
struct Money { | |
currency: Currency, | |
amount: u8, | |
} | |
impl std::ops::Add for Money { | |
type Output = Result<Self, &'static str>; | |
fn add(self, money: Self) -> Self::Output { | |
if money.currency != self.currency { | |
return Err("Can not operate with different currencies") | |
} | |
Ok(Money { | |
currency: self.currency, | |
amount: self.amount + money.amount, | |
}) | |
} | |
} | |
#[test] | |
fn should_add_money_with_same_currency() { | |
let ten_dollars = Money { | |
currency: Currency::DOLLAR, | |
amount: 10, | |
}; | |
let five_dollars = Money { | |
currency: Currency::DOLLAR, | |
amount: 5, | |
}; | |
let fifteen = ten_dollars + five_dollars; | |
assert!(fifteen.is_ok(),true); | |
assert_eq!(fifteen.ok().unwrap().amount,15); | |
} | |
#[test] | |
fn should_not_allow_add_money_with_different_currency() { | |
let ten_dollars = Money { | |
currency: Currency::DOLLAR, | |
amount: 10, | |
}; | |
let five_euros = Money { | |
currency: Currency::EURO, | |
amount: 5, | |
}; | |
let fifteen = ten_dollars + five_euros; | |
assert!(fifteen.is_err(),true); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment