相关疑难解决方法(0)

从HashMap或Vec返回引用会导致借用超出其所在的范围?

我有一个持久的编译错误,其中Rust抱怨我在尝试可变借用时有一个不可变的借位,但是不可变借用来自另一个范围,而我并没有从中带来任何东西.

我有一些代码检查地图中的值,如果它存在,则返回它,否则它需要以各种方式改变地图.问题是我似乎无法找到让Rust同时执行的方法,即使这两个操作完全分开.

这是一些荒谬的代码,它遵循与我的代码相同的结构并展示了问题:

use std::collections::BTreeMap;

fn do_stuff(map: &mut BTreeMap<i32, i32>, key: i32) -> Option<&i32> {
    // extra scope in vain attempt to contain the borrow
    {
        // borrow immutably
        if let Some(key) = map.get(&key) {
            return Some(key);
        }
    }

    // now I'm DONE with the immutable borrow, but rustc still thinks it's borrowed

    map.insert(0, 0); // borrow mutably, which errors
    None
}
Run Code Online (Sandbox Code Playgroud)

这出错了:

error[E0502]: cannot borrow `*map` as mutable because it is also borrowed as immutable
  --> src/lib.rs:14:5
   |
3 …
Run Code Online (Sandbox Code Playgroud)

rust borrow-checker

16
推荐指数
1
解决办法
1836
查看次数

什么时候需要绕过 Rust 的借用检查器?

我正在实施康威的生活游戏来自学 Rust。思路是先实现单线程版本,尽量优化,然后多线程版本也一样。

我想实现一个我认为可能对缓存更友好的替代数据布局。这个想法是将板上每个点的两个单元的状态存储在一个向量中,一个单元用于读取当前一代的状态,另一个用于写入下一代状态,交替访问模式每一代的计算(可以在编译时确定)。

基本数据结构如下:

#[repr(u8)]
pub enum CellStatus {
    DEAD,
    ALIVE,
}

/** 2 bytes */
pub struct CellRW(CellStatus, CellStatus);

pub struct TupleBoard {
    width: usize,
    height: usize,
    cells: Vec<CellRW>,
}

/** used to keep track of current pos with iterator e.g. */
pub struct BoardPos {
    x_pos: usize,
    y_pos: usize,
    offset: usize,
}

pub struct BoardEvo {
    board: TupleBoard,
}
Run Code Online (Sandbox Code Playgroud)

给我带来麻烦的功能:

impl BoardEvo {
    fn evolve_step<T: RWSelector>(&mut self) {
        for (pos, cell) in self.board.iter_mut() {
            //pos: BoardPos, cell: &mut …
Run Code Online (Sandbox Code Playgroud)

rust

4
推荐指数
1
解决办法
731
查看次数

标签 统计

rust ×2

borrow-checker ×1