Help in fix - cannot borrow data in a `&` reference as mutable?

I already had mutable data in enum, but forgot how to handle them. The enum is defined as:

#[derive(PartialEq, Debug)]
pub enum OptVal {
    Num(i64),
    FNum(f64),
    Str(String),
    Arr(HashSet<(String,String)>),
    Empty,
    Unmatch
}

I use placing the set as:

if opt.v.is_none() {
       opt.v = Some(OptVal::Arr(HashSet::new()))
} 

However when I try to modify the set:

match &opt.v {
        &Some(OptVal::Arr(ref mut set)) => {

I get an error:

error[E0596]: cannot borrow data in a `&` reference as mutable
   --> src/cli.rs:144:47
    |
144 | ...                   &Some(OptVal::Arr(ref mut set)) => {
    |                                         ^^^^^^^^^^^ cannot borrow as mutable

How can I correct it?

// Change this:
match &opt.v {
    &Some(OptVal::Arr(ref mut set)) => {
        // your code here
    }
    _ => {}
}

// To this:
match &mut opt.v {
    Some(OptVal::Arr(set)) => {
        // your code here
    }
    _ => {}
}

// Or use if-let (cleaner):
if let Some(OptVal::Arr(set)) = &mut opt.v {
    // your code here
}

The problem: you used &opt.v (immutable) but tried to get ref mut set (mutable). You need &mut opt.v to modify the data inside.

Bingo! Thanks. Usually Rust gives a very detailed error messages, but in this case, the message was blind.

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.