不能借用可变性,因为它也被借用为不可变的

Shu*_*pli 10 reference rust

我正在学习Rust,我不明白为什么这不起作用.

#[derive(Debug)]
struct Node {
    value: String,
}

#[derive(Debug)]
pub struct Graph {
    nodes: Vec<Box<Node>>,
}

fn mk_node(value: String) -> Node {
    Node { value }
}

pub fn mk_graph() -> Graph {
    Graph { nodes: vec![] }
}

impl Graph {
    fn add_node(&mut self, value: String) {
        if let None = self.nodes.iter().position(|node| node.value == value) {
            let node = Box::new(mk_node(value));
            self.nodes.push(node);
        };
    }

    fn get_node_by_value(&self, value: &str) -> Option<&Node> {
        match self.nodes.iter().position(|node| node.value == *value) {
            None => None,
            Some(idx) => self.nodes.get(idx).map(|n| &**n),
        }
    }
}


#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn some_test() {
        let mut graph = mk_graph();

        graph.add_node("source".to_string());
        graph.add_node("destination".to_string());

        let source = graph.get_node_by_value("source").unwrap();
        let dest = graph.get_node_by_value("destination").unwrap();

        graph.add_node("destination".to_string());
    }
}
Run Code Online (Sandbox Code Playgroud)

(游乐场)

这有错误

error[E0502]: cannot borrow `graph` as mutable because it is also borrowed as immutable
  --> src/main.rs:50:9
   |
47 |         let source = graph.get_node_by_value("source").unwrap();
   |                      ----- immutable borrow occurs here
...
50 |         graph.add_node("destination".to_string());
   |         ^^^^^ mutable borrow occurs here
51 |     }
   |     - immutable borrow ends here
Run Code Online (Sandbox Code Playgroud)

来自Programming Rust的这个例子与我的相似,但是它有效:

pub struct Queue {
    older: Vec<char>,   // older elements, eldest last.
    younger: Vec<char>, // younger elements, youngest last.
}

impl Queue {
    /// Push a character onto the back of a queue.
    pub fn push(&mut self, c: char) {
        self.younger.push(c);
    }

    /// Pop a character off the front of a queue. Return `Some(c)` if there /// was a character to pop, or `None` if the queue was empty.
    pub fn pop(&mut self) -> Option<char> {
        if self.older.is_empty() {
            if self.younger.is_empty() {
                return None;
            }

            // Bring the elements in younger over to older, and put them in // the promised order.
            use std::mem::swap;
            swap(&mut self.older, &mut self.younger);
            self.older.reverse();
        }

        // Now older is guaranteed to have something. Vec's pop method // already returns an Option, so we're set.
        self.older.pop()
    }

    pub fn split(self) -> (Vec<char>, Vec<char>) {
        (self.older, self.younger)
    }
}

pub fn main() {
    let mut q = Queue {
        older: Vec::new(),
        younger: Vec::new(),
    };

    q.push('P');
    q.push('D');

    assert_eq!(q.pop(), Some('P'));
    q.push('X');

    let (older, younger) = q.split(); // q is now uninitialized.
    assert_eq!(older, vec!['D']);
    assert_eq!(younger, vec!['X']);
}
Run Code Online (Sandbox Code Playgroud)

She*_*ter 18

您的问题的MCVE可以简化为:

fn main() {
    let mut items = vec![1];
    let item = items.last();
    items.push(2);
}
Run Code Online (Sandbox Code Playgroud)
error[E0502]: cannot borrow `items` as mutable because it is also borrowed as immutable
 --> src/main.rs:4:5
  |
3 |     let item = items.last();
  |                ----- immutable borrow occurs here
4 |     items.push(2);
  |     ^^^^^ mutable borrow occurs here
5 | }
  | - immutable borrow ends here
Run Code Online (Sandbox Code Playgroud)

您遇到 Rust旨在防止的确切问题.你有一个指向矢量的参考,并试图插入矢量.这样做可能需要重新分配向量的内存,使任何现有引用无效.如果发生这种情况并且您使用了该值item,那么您将访问未初始化的内存,从而可能导致崩溃.

在这种特殊情况下,你实际上并没有使用item(或者source在原始版本中),所以你可以......不要调用那条线.我假设你出于某种原因这样做了,所以你可以将引用包装在一个块中,这样它们就会在你再次尝试改变值之前消失:

fn main() {
    let mut items = vec![1];
    {
        let item = items.last();
    }
    items.push(2);
}
Run Code Online (Sandbox Code Playgroud)

在Rust 2018中不再需要这个技巧,因为非词法生命周期已经实现,但是潜在的限制仍然存在 - 当存在对同一事物的其他引用时,你不能有可变引用.这是Rust编程语言中涉及的参考规则之一.一个仍然不适用于NLL的修改示例:

let mut items = vec![1];
let item = items.last();
items.push(2);
println!("{:?}", item);
Run Code Online (Sandbox Code Playgroud)

在其他情况下,您可以复制或克隆向量中的值.该项目将不再是参考,您可以根据需要修改矢量:

fn main() {
    let mut items = vec![1];
    let item = items.last().cloned();
    items.push(2);
}
Run Code Online (Sandbox Code Playgroud)

如果您的类型不可复制,则可以将其转换为引用计数值(例如RcArc),然后可以克隆该值.您可能需要也可能不需要使用内部可变性:

struct NonClone;

use std::rc::Rc;

fn main() {
    let mut items = vec![Rc::new(NonClone)];
    let item = items.last().cloned();
    items.push(Rc::new(NonClone));
}
Run Code Online (Sandbox Code Playgroud)

这个来自Programming Rust的例子非常相似

不,它不是,看到它根本不使用引用.

也可以看看

  • @SujitJoshi,你的意思不明确,但如果它是 `fn last(self) -&gt; Option&lt;T&gt;` 或 `fn last(&amp;mut self) -&gt; Option&lt;T&gt;` (又名 `pop`),那么是的,这样就可以了,因为返回的值不会因向量的进一步变异而变得无效。 (2认同)

小智 5

尝试将您的不可变借用放在块 {...} 中。这在块之后结束借用。

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn some_test() {
        let mut graph = mk_graph();

        graph.add_node("source".to_string());
        graph.add_node("destination".to_string());

        {
            let source = graph.get_node_by_value("source").unwrap();
            let dest = graph.get_node_by_value("destination").unwrap();
        }

        graph.add_node("destination".to_string());
    }
}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

11864 次

最近记录:

7 年,1 月 前