我正在尝试 Rust 并且在理解“借用”方面存在一些问题。
fn main() {
let mut x = 10;
let mut a = 6;
let mut y = &mut x;
*y = 6;
y = &mut a;
x = 15;
println!("{}", x);
}
Run Code Online (Sandbox Code Playgroud)
我有一个错误:
fn main() {
let mut x = 10;
let mut a = 6;
let mut y = &mut x;
*y = 6;
y = &mut a;
x = 15;
println!("{}", x);
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能x摆脱“ y-borrowing”?
fn main() {
let mut x: Vec<&i32> = vec![];
let a = 1;
x.push(&a);
drop(x);
// x.len(); // error[E0382]: use of moved value: `x`
} // `a` dropped here while still borrowed
Run Code Online (Sandbox Code Playgroud)
编译器知道drop()丢弃x(从注释掉的代码中的错误可以看出),但仍然认为变量是借用的a!这不公平!
这应该被认为是众多生锈/锈病#6393之一(现在由rust-lang/rfcs#811跟踪?)但是那里的讨论似乎集中在一个块中制作&mut self和&self共存.
我还在学习Rust,在尝试将Dikjstra作为培训项目的一部分时,我遇到了这种特殊的问题.首先我定义一个HashMap:
let mut dist: HashMap<Node, usize> = HashMap::new();
Run Code Online (Sandbox Code Playgroud)
然后:
let state = State { node: next_node.clone(), cost: cost + 1 };
let current_dist = dist.get(&state.node);
if (current_dist == None) || (state.cost < *current_dist.unwrap()) {
dist.insert(state.node.clone(), state.cost);
heap.push(state);
}
Run Code Online (Sandbox Code Playgroud)
这产生了一个编译错误,因为dist.get触发了一个不可变的借位,它在if ... {...}语句之后一直保留在范围内,特别是当我dist.insert要求一个可变的借位时.
我想我错过了一个模式或关键字,允许我这种类型的过程.现在我尝试了范围drop的开头if,以及其他current_dist评估
let current_dist;
{
current_dist = dist.get(&state.node);
}
Run Code Online (Sandbox Code Playgroud)
要么
let current_dist = {|| dist.get(&state.node)}();
Run Code Online (Sandbox Code Playgroud)
但是,在if声明之后,仍然会发生不可变借款的范围.