Skip to content

Instantly share code, notes, and snippets.

@jcaromiq
Created May 5, 2020 22:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcaromiq/aa4f96856354bb0760dd5b28dbd48ca1 to your computer and use it in GitHub Desktop.
Save jcaromiq/aa4f96856354bb0760dd5b28dbd48ca1 to your computer and use it in GitHub Desktop.
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