简体   繁体   English

Rust 多个可变自借自方法调用

[英]Rust multiple mutable self borrowing from method calls

I am learning Rust.我正在学习 Rust。 For my first program, I wrote this code to maintain data about a partial ordering:对于我的第一个程序,我编写了以下代码来维护有关偏序的数据:

use std::collections::{HashMap, HashSet};

struct Node {
    num_before: usize,
    successors: HashSet<String>,
}

impl Node {
    fn new() -> Node {
        Node {
            num_before: 0,
            successors: HashSet::new(),
        }
    }
}

pub struct PartialOrdering {
    node: HashMap<String, Node>,
}

impl PartialOrdering {
    pub fn new() -> PartialOrdering {
        PartialOrdering {
            node: HashMap::new(),
        }
    }

    pub fn get_node(&mut self, name: &String) -> &mut Node {
        self.node.entry(name.clone()).or_insert_with(Node::new)
    }

    pub fn add_order(&mut self, before: &String, after: &String) {
        let mut before_node = self.get_node(before);
        if after != before {
            let mut after_node = self.get_node(after);
            if before_node.successors.insert(after.clone()) {
                after_node.num_before += 1;
            }
        }
    }
}

Compiling this code produces this error:编译此代码会产生此错误:

error[E0499]: cannot borrow `*self` as mutable more than once at a time
  --> main.rs:35:25
   |
33 |         let before_node = self.get_node(before);
   |                           ---- first mutable borrow occurs here
34 |         if after != before {
35 |             let mut after_node = self.get_node(after);
   |                                  ^^^^ second mutable borrow occurs here
36 |             if before_node.successors.insert(after.clone()) {
   |                ---------------------- first borrow later used here

Admittedly I am new to the Rust borrowing rules, but this problem has me stumped.诚然,我是 Rust 借用规则的新手,但这个问题让我很困惑。 Please tell me what I am doing wrong, and how can I fix it?请告诉我我做错了什么,我该如何解决?

The problem is that in Rust it is forbidden to take more than one mutable reference ( &mut ) to an object at a time (see here for details).问题在于,在 Rust 中,禁止一次对 object 使用多个可变引用( &mut )(有关详细信息,请参见此处)。 Your get_node() takes &mut self and uses it to obtain an &mut Node contained in self (where self is a PartialOrdering ).您的get_node()接受&mut self并使用它来获取包含在self中的&mut Node (其中selfPartialOrdering )。 This causes the mutable borrow of self to exist for as long as the value returned by get_node() exists, preventing other calls to get_node() .只要get_node()返回的值存在,这就会导致self的可变借用存在,从而阻止对get_node()的其他调用。 This means that you can't have before_node: &mut Node and after_node: &mut Node in the same scope, unfortunately.这意味着你不能在同一个 scope 中拥有before_node: &mut Nodeafter_node: &mut Node ,不幸的是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM