3 ms·
use std::ops::Add; fn main() { let usd = Money { currency: String::from("USD"), amount: 10 }; let eur = Mon
by CraigJPerry 6y ago
use std::ops::Add;
fn main() {
let usd = Money {
currency: String::from("USD"),
amount: 10
};
let eur = Money {
currency: String::from("EUR"),
amount: 10
};
dbg!(usd + eur);
}
#[derive(Debug)]
struct Money {
currency: Currency,
amount: Amount
}
impl Add for Money {
type Output = Money;
fn add(self, other: Money) -> Money {
Money {
currency: self.currency,
amount: self.amount + other.amount
}
}
}
type Currency = String;
type Amount = i32; // i know :-)
This outputs 20 USD in rust, it’s a design problem not a types problem.
- joshuamorton 6y agoI'm not sure what your point is. It's glaringly obvious that this code is functionally wrong, in no small part bc of the type information.
- CraigJPerry 6y agoAhh no, the code isn’t functionally wrong, take for example: Money(“USD”, 10) + Money(“USD”, 5) This works just fine. We’d need more context about how it’s used to say whether we’ve made a bad trade off with our design. The error isn’t represented in the types, that’s why it compiles and runs. The compiler can’t see the design error here, which is fair, it’s a design problem and types don’t fix that - people are free to misunderstand the business domain and happily capture the wrong rules in types.
- danielscrubs 6y agoYou have declared the domain the function handle and then you don’t handle it, simple as that.
- CraigJPerry 6y agoHow is that possible? Remember the code is in reply to: >> fact both have support for erroring on this by default By default what i’ve done here (omitted a runtime check) doesn’t catch the error.