为什么self.f2()以下代码中的调用会使借用检查程序运行?是不是在另一个范围内的else块?这是一个相当难的问题!
use std::str::Chars;
struct A;
impl A {
fn f2(&mut self) {}
fn f1(&mut self) -> Option<Chars> {
None
}
fn f3(&mut self) {
if let Some(x) = self.f1() {
} else {
self.f2()
}
}
}
fn main() {
let mut a = A;
}
Run Code Online (Sandbox Code Playgroud)
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/main.rs:16:13
|
13 | if let Some(x) = self.f1() {
| ---- first mutable borrow occurs here
... …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用正则表达式解析文件:
extern crate regex; // 1.0.1
use regex::Regex;
fn example(
section_header_pattern: Regex,
section_name: &str,
mut line: String,
mut is_in_right_section: bool,
) {
loop {
if let Some(m) = section_header_pattern
.captures(&line)
.and_then(|c| c.get(1))
{
is_in_right_section = m.as_str().eq(section_name);
line.clear();
continue;
}
}
}
fn main() {}
Run Code Online (Sandbox Code Playgroud)
......但是编译器会抱怨,因为RegEx的captures()方法有哪些承受了本场比赛的一生借:
error[E0502]: cannot borrow `line` as mutable because it is also borrowed as immutable
--> src/main.rs:17:13
|
13 | .captures(&line)
| ---- immutable borrow occurs here
...
17 | line.clear();
| ^^^^ …Run Code Online (Sandbox Code Playgroud) 我刚刚遇到Rust的一些行为(1.12)我无法解释.我有一个结构,实现延迟加载与a RefCell<Option<i32>>和一个访问数据的函数:
struct Foo {
data: RefCell<Option<i32>>
}
impl Foo {
fn get_data(&self) -> i32 {
if self.data.borrow().is_none() { // <--- (a)
let d = 1337;
self.data.borrow_mut() = Some(d); // <--- (b)
d
} else {
self.data.borrow().unwrap()
}
}
}
Run Code Online (Sandbox Code Playgroud)
这会编译但会产生运行时错误:RefCell抱怨在尝试borrow_mut上线(b)时借用已经处于活动状态.但是,如果我将if语句更改为以下内容,则不会发生此问题:
let is_none = self.data.borrow().is_none();
if is_none {
Run Code Online (Sandbox Code Playgroud)
问题:为什么第(a)行的if条件中的借位在if语句的主体内仍然有效?不应该打电话is_none()导致借款结束,因为我只是坚持一个bool事后,而不是借来的价值?
我正在编写一个程序来计算单词出现的频率.这是我的代码的一部分.
// hm is a HashMap<&str, u32>
if let Some(val) = hm.get_mut(tt) {
*val += 1u32;
} else {
hm.insert(tt.clone(), 1u32);
}
Run Code Online (Sandbox Code Playgroud)
我得到了......
error: cannot borrow `hm` as mutable more than once at a time [E0499]
hm.insert(tt.clone(), 1u32);
^~
note: first mutable borrow occurs here
if let Some(val) = hm.get_mut(tt) {
^~
note: first borrow ends here
}
^
help: run `rustc --explain E0499` to see a detailed explanation
Run Code Online (Sandbox Code Playgroud)
我可以通过hm.insert()移出else范围来绕过这个但是它是一种"非程序化"的方式......我尝试使用match但是同样的错误(很明显)会发生.
我怎样才能解决这个问题?