首页 > 解决方案 > 一次不能多次借用 `*self` 作为 mutable

问题描述

我不明白这个借用检查器错误:

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但似乎我错了。为什么?

标签: rust

解决方案


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


推荐阅读