Hello
I have a struct with two fields:
#[derive(Deserialize, Serialize)]
pub struct Voucher {
...
distributorvoucher: Option<DistributorVoucher>,
supervoucher_distributor: Option<Distributor>,
...
}
Either distributorvoucher
or supervoucher_distributor
has a value. Always exactly one of those field has a value, the other one is None
.
I have written the following function to easily check if the Voucher
is a 'supervoucher':
impl Voucher {
fn is_supervoucher(&self) -> bool {
self.distributorvoucher.is_none()
}
}
When inserting the Voucher
into a database I need to know which field to insert a NULL
.
I can successfully do it this way:
let distributorvoucher_id = match &voucher.is_supervoucher() {
true => Some(voucher.distributorvoucher.as_ref().unwrap().id),
false => None,
};
let supervoucher_distributor = match &voucher.is_supervoucher() {
true => Some(voucher.supervoucher_distributor.as_ref().unwrap().id),
false => None,
};
However, I was wondering if there is a shorter solution. I fabricated the following which seems to work:
let (distributorvoucher_id, supervoucher_distributor) = match &voucher.is_supervoucher() {
true => (Some(voucher.distributorvoucher.as_ref().unwrap().id), None),
false => (
None,
Some(voucher.supervoucher_distributor.as_ref().unwrap().id),
),
};
I am, however, not sure this is valid code. Is this the right way to do it? Thanks!