简体   繁体   中英

cannot borrow `*self` as mutable more than once at a time

I don't understand this borrow checker error:

pub fn wait_for_device(&mut self) -> RoxResult<hidapi::HidDevice> {
    let mut device = self.open_device();
    let start = time::Instant::now();
    while device.is_err() {
        device = self.open_device();
        if start.elapsed().as_secs() > 30 {
            return Err("Can't reconnect to device".to_owned());
        }
    }
    Ok(device.expect("Out of while so we should have a device"))
}

pub fn open_device(&mut self) -> RoxResult<hidapi::HidDevice> {
    let device_info = &self.list[0]; 
    if let Ok(device) = self.api.open(device_info.vendor_id, device_info.product_id) {
        self.current_device = Some(device_info.clone());
        Ok(device)
    } else {
        Err(format!(
            "Error opening device vip: {:x} pid: {:x}",
            device_info.vendor_id, device_info.product_id
        ))
    }
}

error[E0499]: cannot borrow `*self` as mutable more than once at a time
  --> src\usb.rs:64:22
   |
61 |         let mut device = self.open_device();
   |                          ---- first mutable borrow occurs here
...
64 |             device = self.open_device();
   |                      ^^^^ second mutable borrow occurs here
...
70 |     }
   |     - first borrow ends here

I thought my first borrowing will end at the end of open_device but it seems I'm wrong. Why?

Variables are valid until the end of the scope in which they were declared. You created a variable device and assigned borrowed value to it in the scope of the entire function. In other words the borrow ends at the end of the function (as you can see in compiler error message).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM