Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rust snippets
#[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
You can’t perform that action at this time.