不能在循环内借用为不可变的,因为它同时被借用为可变的。

huangapple go评论63阅读模式
英文:

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);
    }
}

playground

英文:

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: &amp;Vec&lt;Vec&lt;usize&gt;&gt;) -&gt; () {
    // some logic to print the stacks.
    // for now use just println!
    println!(&quot;{:?}&quot;, stacks);
}

fn main() {
    let mut stacks: Vec&lt;Vec&lt;usize&gt;&gt; = 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(&amp;stacks);
    }
}

playground

答案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实体编码(&lt;&amp;)还原为原始字符。

英文:

Holding on to stack1's borrow during the loop makes it impossible to grab a second reference to &amp;stacks because &amp;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&lt;Vec&lt;usize&gt;&gt; = 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(&amp;stacks);
}

huangapple
  • 本文由 发表于 2023年5月29日 00:41:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76352534.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定