Move errors after making a field of a struct optional

Hello

I had the following struct:

#[derive(Deserialize, Serialize)]
pub struct Voucher {
...
    distributorvoucher: DistributorVoucher,
...

}

Now I had to change one of the fields to optional, like so:

#[derive(Deserialize, Serialize)]
pub struct Voucher {
...
    distributorvoucher: Option<DistributorVoucher>,
...

}

This causes a lot of errors in my code, this one being the most common:

borrow of partially moved value: `v` partial move occurs because `v.distributorvoucher` has type `std::option::Option<DistributorVoucher>`, which does not implement the `Copy` trait

This because I have to add .unwrap() after every code using the field distributorvoucher:

match voucher {
        None => "error".to_string(),
        Some(mut v) => {
            if v.distributorvoucher.unwrap().distributor.id != distributor.unwrap().id {
                return "error".to_string();
            }

            v.used = form.used;
            v.balance = form.balance;

            match data::update_voucher(&mysql, &v).await {
                true => "success".to_string(),
                false => "false".to_string(),
            }
        }
    }

How would I solve this in the most efficient way?

The smallest code change is probably

-if v.distributorvoucher.unwrap().distributor.id != distributor.unwrap().id {
+if v.distributorvoucher.as_ref().unwrap().distributor.id != distributor.as_ref().unwrap().id {

But you could also consider something like

trait HasId {
    fn has_id_of(&self, other: &Self) -> bool;
}

impl HasId for Option<DistributorVoucher> { /* ... */ }

fn foo() {
    // ...
    if v.distributorvoucher.has_id_of(&distributor) { /* ... */ }
}
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.