If let: passing a mutable ref option not working

Hi,

I do not understand how to pass a mutable struct reference through a "if let" statement given the example below:

struct X {
    
    data: String,
    id: usize

}


fn pass(
    a: &mut X,
    b: usize
){
    
    println!("{}",a.id);
    a.id=b;
    println!("{}",a.id);
}


fn update(
    
    a: &mut Option<X>,
    b: usize
    
     ) {
// I wanna keep this as is but what to pass into pass() so that i do not need to change it 
     if let Some(&mut a) = a.as_ref() {
        pass(&mut a,b);
     } else {
        println!("else");
     }
}


// I wanna keep this as is
fn main(){

   let xx = X{
       data: "Here".to_string(),
       id: 1
       };
 
   let cc =  &mut Some(xx);
   update(cc, 7);   
}

some help please :blush:

Change to

fn update(
    
    a: &mut Option<X>,
    b: usize
    
     ) {
// I wanna keep this as is but what to pass into pass() so that i do not need to change it 
     if let Some(a) = a.as_mut() {
        pass(a,b);
     } else {
        println!("else");
     }
}


// I wanna keep this as is
fn main(){

   let xx = X{
       data: "Here".to_string(),
       id: 1
       };
 
   let mut cc =  Some(xx);
   update(&mut cc, 7);   
}

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.