rust - 多次借用 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 但我该如何克服这个问题?
解决方案
推荐阅读
- vue.js - 为什么模板文字不输入新行?
- sql - PostgreSQL:查询 JSON 数组中的元素
- python - python - 如何迭代tensorflow中每个嵌套张量的第一个元素,python?
- javascript - AG Grid - 如果没有其他列被排序,则恢复默认排序
- json - Kotlin Moshi 从资产中加载 Json
- scala - 如何在 Scala 中应用重载方法 Using Picture?
- html - 下拉列表隐藏在弹出窗口后面
- python - 我应该在哪里实现烧瓶自定义命令(cli)
- xaml - Xamarin 窗体圆形按钮
- node.js - 如何使用 NODE JS 肥皂查看 ARRAY