作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我所有的代码:
use std::collections::HashMap;
pub struct Book<'a> {
page: Vec<&'a str>,
histories: HashMap<&'a str, &'a str>,
}
impl<'a> Book<'a> {
pub fn new(page: Vec<&'a str>) -> Book<'a> {
let histories = HashMap::new();
Book {
page: page,
histories: histories
}
}
pub fn process(&mut self, line: &str, book_id: &'a str) {
let page_c = self.get_page(book_id);
println!("page_c {}", page_c);
for history in self.histories.iter() {
println!("histories...");
}
}
fn get_page(&mut self, book_id: &'a str) -> &str {
if !self.histories.contains_key(book_id) {
println!("not history found for book {}", book_id);
self.histories.insert(book_id, "history A");
}
self.histories.get(book_id).unwrap()
}
}
fn main() {
println!("Hello, world!");
let mut pages = Vec::new();
let st = "page1";
pages.push(st);
let mut biblio = Book::new(pages);
let sentence = "this is a line of page";
let book_id = "onebook";
biblio.process(sentence, book_id);
}
这不编译:
src/main.rs:22:24: 22:38 error: cannot borrow `self.histories` as immutable because `*self` is also borrowed as mutable [E0502]
src/main.rs:22 for history in self.histories.iter() {
^~~~~~~~~~~~~~
src/main.rs:19:22: 19:26 note: previous borrow of `*self` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `*self` until the borrow ends
src/main.rs:19 let page_c = self.get_page(book_id);
^~~~
src/main.rs:25:6: 25:6 note: previous borrow ends here
src/main.rs:17 pub fn process(&mut self, line: &str, book_id: &'a str) {
...
src/main.rs:25 }
^
error: aborting due to previous error
Could not compile `tempo`.
我理解错误信息,但经过研究和阅读后similar questions ,我不明白如何修复我的代码。
最佳答案
修复代码的最简单方法是不为 page_c 引入额外的变量,而是直接使用 get_page
的结果:
pub fn process(&mut self, line: &str, book_id: &'a str) {
println!("page_c {}", self.get_page(book_id));
for history in self.histories.iter() {
println!("histories...");
}
}
这样,当您进入for
循环时,self
不会被借用,因为它只是在调用println
时被借用.如果你确实想要 page_c 的变量,你可以在一个额外的范围内引入它,所以借用将在范围的末尾(因此在循环之前):
pub fn process(&mut self, line: &str, book_id: &'a str) {
{
let page_c = self.get_page(book_id);
println!("page_c {}", page_c);
} // page_c ceases to exist here, so the borrow of self ends
for history in self.histories.iter() {
println!("histories...");
}
}
关于rust - 不能借用 `*` 作为不可变的,因为 `*self` 也被借用为可变的 [E0502],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33724863/
COW 不是奶牛,是 Copy-On-Write 的缩写,这是一种是复制但也不完全是复制的技术。 一般来说复制就是创建出完全相同的两份,两份是独立的: 但是,有的时候复制这件事没多大必要
我是一名优秀的程序员,十分优秀!