一次不能多次借用* self变量

时间:2018-07-06 11:16:10

标签: rust

我不了解此借阅检查器错误:

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

我认为我的第一次借贷将在open_device的结尾处结束,但似乎我错了。为什么?

1 个答案:

答案 0 :(得分:0)

变量在声明它们的作用域结束之前一直有效。您创建了一个变量device,并在整个函数范围内为其分配了借入值。换句话说,借用在函数的结尾处结束(如您在编译器错误消息中看到的那样)。