首页 > 解决方案 > 多次借用 mutable

问题描述

我正在重构我用 Rust 编写的 ncurses 应用程序,并且遇到了一个我似乎不理解的问题。

这是我创建的一个最小示例:

#[derive(Clone)]
struct Entries {
    all: Vec<String>,
    sort: Vec<String>,
    fav: Vec<String>,
}

pub struct Application {
    pub all_entries: Entries,
    pub to_restore: Entries,
    pub view: u8,
    pub match_: u8,
    pub case_sensitivity: u8,
    pub search_string: String,
}

impl Application {
    pub fn new() -> Self {
        let history = vec!["spam".to_string(), "eggs".to_string()];
        let all_entries = Entries {
            all: history.clone(),
            sort: history.clone(),
            fav: history.clone(),
        };
        Self {
            all_entries: all_entries.clone(),
            to_restore: all_entries.clone(),
            view: 0,
            match_: 0,
            case_sensitivity: 0,
            search_string: String::new(),
        }
    }

    pub fn get_entries(&mut self, view: u8) -> &mut Vec<String> {
        match view {
            0 => &mut self.all_entries.sort,
            1 => &mut self.all_entries.fav,
            2 => &mut self.all_entries.all,
            _ => &mut self.all_entries.sort,
        }
    }
}

pub struct UserInterface {
    pub page: i32,
    pub selected: i32,
}

impl UserInterface {
    pub fn new() -> Self {
        Self {
            page: 1,
            selected: 0,
        }
    }

    pub fn populate_screen(&self, app: &mut Application) {
        let entries = app.get_entries(app.view);
        for (index, entry) in entries.iter().enumerate() {
            // print normal
            // check indices
            // if there are indices, color those spots
            if app.get_entries(1).contains(&entry) {
                // color white
            }
            if index == self.selected as usize {
                // color green
            }
        }
        // some more printing to screen
    }
}

fn main() {
    let mut app = Application::new();
    let user_interface = UserInterface::new();
    user_interface.populate_screen(&mut app);
}

错误:

error[E0499]: cannot borrow `*app` as mutable more than once at a time
  --> src/main.rs:64:16
   |
59 |         let entries = app.get_entries(app.view);
   |                       --- first mutable borrow occurs here
60 |         for (index, entry) in entries.iter().enumerate() {
   |                               -------------------------- first borrow later used here
...
64 |             if app.get_entries(1).contains(&entry) {
   |                ^^^ second mutable borrow occurs here

我知道你不能两次借用 mutable 但我该如何克服这个问题?

操场

标签: rust

解决方案


推荐阅读