rust - 一次不能多次借用 `*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
但似乎我错了。为什么?
解决方案
变量在声明它们的作用域结束之前都是有效的。device
您在整个函数的范围内创建了一个变量并为其分配了借来的值。换句话说,借用在函数的末尾结束(正如您在编译器错误消息中看到的那样)。
推荐阅读
- ruby-on-rails - 如何按自定义顺序显示洗劫复选框
- c# - 使用 modbus C#
- php - PHP到telnet路由器并执行traceroute命令到目的地打印实时输出
- java - 如何使用 JOOQ 模拟聚合函数结果?
- python - Tensorboard TypeError:__init__() 得到了一个意外的关键字参数“文件”
- r - 计数非空变量并通过分组放入新列
- c - #include 与 GLSL/C 的自定义 IO?
- c# - 如何更新 ASP.NET 样板 Web 应用程序框架
- javascript - 脚本仅适用于控制台
- xamarin.forms - Xamarin.Forms Mac AuthenticationContinuationHelper