相关疑难解决方法(0)

当借用发生在方法调用后面时,如何借用两个不相交的字段?

在下面的代码中,我有一个Foo带有只读字段a和一堆读写字段的结构。当直接从结构中借用单独的字段时,没有借用问题。但是,当我将借用隐藏在方法调用后面时,它表示我不再可以借用。

#![allow(unused_variables)]
#![allow(unused_mut)]
#![allow(dead_code)]

struct Foo {
    a: Vec<i32>,      // Public read-only  field.
    pub b: Vec<f32>,  // Public read-write field.
    pub c: Vec<i32>,  // Public read-write field.
    // ... maybe more fields ...
    pub z: Vec<bool>, // Public read-write field.
}

impl Foo {
    pub fn new() -> Self {
        Self {
            a: vec![1, 2, 3],
            b: vec![1.0, 2.0, 3.0],
            c: vec![-3, 0, 3],
            z: vec![false, true],
        }
    }
    pub fn borrow_a(&self) -> &Vec<i32> {
        &self.a …
Run Code Online (Sandbox Code Playgroud)

rust borrow-checker

9
推荐指数
1
解决办法
1950
查看次数

一次不能多次借用“*self”作为可变的

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

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 …
Run Code Online (Sandbox Code Playgroud)

rust

5
推荐指数
1
解决办法
3119
查看次数

标签 统计

rust ×2

borrow-checker ×1