英文:
Cannot borrow as immutable (inside loop) because it is also borrowed as mutable
问题
我通过《编程之旅》学习Rust,遇到了一个我无法解决的问题。
总体上,我理解了问题,即stack1
由于pop
而被借用为可变,但我希望在print_stack
中使用它作为不可变。
如果我想在每次修改它的迭代中打印stacks
的状态,应该怎么做?
如果要克隆对象,我已经尝试过了,但没有成功。
fn print_stack(stacks: &Vec<Vec<usize>>) -> () {
// 用于打印堆栈的一些逻辑。
// 目前只使用println!
println!("{:?}", stacks);
}
fn main() {
let mut stacks: Vec<Vec<usize>> = vec![vec![], vec![1, 2, 3, 4]];
let stack1 = stacks.get_mut(1).unwrap();
while let Some(item) = stack1.pop() {
// 对item进行一些操作
// 我想在每个步骤中打印。
print_stack(&stacks);
}
}
英文:
I'm studying rust through the advent of code, and I came across an issue that I can't really work around.
In general I understand the issue that stack1
has being borrowed as mutable (because of the pop) and I want to use as immutable in the print_stack
.
How should I go about it, if I want to print the status of stacks
for every iteration that mutates it?
Sorry if it's just stupid question but I'm really stuck. I've tried to clone the object without luck.
fn print_stack(stacks: &Vec<Vec<usize>>) -> () {
// some logic to print the stacks.
// for now use just println!
println!("{:?}", stacks);
}
fn main() {
let mut stacks: Vec<Vec<usize>> = vec![vec![], vec![1,2,3,4]];
let stack1 = stacks.get_mut(1).unwrap();
while let Some(item) = stack1.pop() {
// something with item
// i would like to print every step.
print_stack(&stacks);
}
}
答案1
得分: 3
在循环期间保持对stack1
的借用会使得无法获得对&stacks
的第二个引用,因为&mut
引用是唯一的。修复的一种方法是在每次迭代中获取stacks[1]
的新引用,以便在print_stack
调用期间不保持借用。
let mut stacks: Vec<Vec<usize>> = vec![vec![], vec![1, 2, 3, 4]];
while let Some(item) = stacks[1].pop() {
// 处理item
// 我想在每一步打印。
print_stack(&stacks);
}
请注意,我已将代码中的HTML实体编码(<
和&
)还原为原始字符。
英文:
Holding on to stack1
's borrow during the loop makes it impossible to grab a second reference to &stacks
because &mut
references are unique. One way to fix it is to grab stacks[1]
fresh each iteration so the borrow isn't live during the print_stack
call.
let mut stacks: Vec<Vec<usize>> = vec![vec![], vec![1,2,3,4]];
while let Some(item) = stacks[1].pop() {
// something with item
// i would like to print every step.
print_stack(&stacks);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论