Slide 26
Slide 26 text
幽霊型を⽤いて Value Object の型を区別する②
//
振る舞いを持つVO
//
具体的には通貨単位が⼀致した場合に限り加算が可能
//
//
このケースでは通貨単位を型として表現している
// Money
のT
で通貨単位を表すようにする
//
ここで嬉しいのは、誤った通貨単位同⼠の加算をコンパイル時に検査できること
// T
はただのラベルとして扱いたいだけだが消費しないと怒られるので、std::marker::PhantomData
を⽤いる
//
参考: https://keens.github.io/blog/2018/12/15/rustdetsuyomenikatawotsukerupart_1__new_type_pattern/
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Money {
amount: Decimal,
currency: PhantomData,
}
impl Money {
fn new(amount: Decimal) -> Self {
Self {
amount,
currency: PhantomData::,
}
}
}
impl Add for Money {
type Output = Money;
fn add(self, other: Money) -> Self::Output {
Self::new(self.amount + other.amount)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum JPY {}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum USD {}