I'm using structs like the below in my Rust app:
pub struct Invoice {
pub id: Uuid,
pub amount: i64,
pub rows: Vec<InvoiceRow>,
pub company_id: Uuid,
pub company: Option<Box<Company>>,
pub customer_id: Uuid,
pub customer: Option<Box<Customer>>,
pub payments: Vec<Payment>,
// and many many others
}
pub struct Payment {
pub id: Uuid,
pub amount: i64,
pub invoice_id: Uuid,
pub payment_method_id: Uuid,
pub payment_method: Option<Box<PaymentMethod>>,
// and many many others
}
pub struct PaymentMethod {
pub id: Uuid,
pub name: String,
pub mode: String,
// and many many others
}
Than I have methods like this:
fn payments(invoice: &Invoice) -> String {
let payments = invoice
.payments
.iter()
.fold(String::new(), |mut output, payment| {
let _ = write!(
output,
"mode: {mode} - amount: {amount}\n",
mode = payment.payment_method.as_ref().expect("payment_method").mode(),
amount = payment.amount(),
);
output
});
payments
}
In this case Invoice
is being created from a DB call which can query payments
field (Vec<Payment>
) based on a code like this:
pub struct InvoiceFieldsToQuery {
pub rows: Option<Box<InvoiceRowFieldsToQuery>>,
pub company: Option<Box<CompanyFieldsToQuery>>,
pub customer: Option<Box<CustomerFieldsToQuery>>,
pub payments: Option<Box<PaymentFieldsToQuery>>,
// and many many others
}
let fields_to_query = InvoiceFieldsToQuery::default()
.query_company(Some(Box::new(
CompanyFieldsToQuery::default().query_address(),
)))
.query_customer(Some(Box::new(
CustomerFieldsToQuery::default().query_address(),
)))
.query_payments(Some(Box::new(
PaymentFieldsToQuery::default())
));
// and many many others
As you can see I'm using code like .expect("payment_method")
that I don't want to use.
Is there a way to avoid the usage of .expect()
using something to detect and block at compile time a struct without a field?
Or - better - a way to detect at compile time that I'll need to use payments
(or rows
etc.) and its payment_method
so I must query it with .query_payments(Some(Box::new(PaymentFieldsToQuery::default())))
?
I'm ready to change everything in my code to achieve this compile time check!