Option type problems

I've used Option a few times but not sure whats going on with this use.
I have a struct field:

pub struct UDPdata{
    pub opt_udp_writer :  option::Option<udp_writer::UDPWData>,
}

In the impl block its first initialised:

let mut opt_udp_writer: option::Option<udp_writer::UDPWData> = None;

Then if I instantiate the type it gets overwritten:

let i_udp_writer = udp_writer::UDPWData::new(arc2, arc3);
opt_udp_writer = Some(i_udp_writer);

The result is written to the structure.
``
UDPdata {
opt_udp_writer : opt_udp_writer,
}`
So far so good. When I go to use it.

match self.opt_udp_writer {
            Some(mut writer) => writer.prime(),  
            None => println!("Address invalid, hardware will not be primed!"),
        }

error[E0507]: cannot move out of self.opt_udp_writer.0 which is behind a mutable reference
--> src\udp\udp_man.rs:111:15
|
111 | match self.opt_udp_writer {
| ^^^^^^^^^^^^^^^^^^^ help: consider borrowing here: &self.opt_udp_writer
112 | Some(mut writer) => writer.prime(),
| ----------
| |
| data moved here
| move occurs because writer has type UDPWData, which does not implement the Copy trait
Usual error I know but I can't see the problem here.

Nothing wrong happened with Option. Your writer variable has been moved. Try to borrow it instead of moving.

Please post the complete code that produces the error. The snippets you posted don't, in isolation.

If you want to modify something in the match body, the usual answer is that you want to pass a mutable reference to the match:

match &mut self.opt_udp_writer {
    Some(writer) => writer.prime(),  
    None => println!("Address invalid, hardware will not be primed!"),
}

Thanks. The &mut did it and it all runs and works. I'm still at the level of keep trying until it works but I hadn't tried that variation. I'm hoping the penny will drop soon!

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.