gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:30:48 26 4
gpt4 key购买 nike

我正在学习 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());
}
}

( playground )

这里有错误

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

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

最佳答案

A MRE您的问题可以简化为:

// This applies to the version of Rust this question
// was asked about; see below for updated examples.
fn main() {
let mut items = vec![1];
let item = items.last();
items.push(2);
}
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

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

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

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

现代 Rust 不再需要这个技巧,因为 non-lexical lifetimes已经实现,但潜在的限制仍然存在——当有其他引用指向同一事物时,你不能有一个可变引用。这是 rules of references 之一在 Rust 编程语言 中介绍。仍然不适用于 NLL 的修改示例:

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

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

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

如果您的类型不可克隆,您可以将其转换为引用计数值(例如 RcArc ),然后可以将其克隆。您可能也可能不需要使用 interior mutability :

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

this example from Programming Rust is quite similar

不,不是,因为它根本不使用引用。

另见

关于reference - 不能借用为可变的,因为它也被借用为不可变的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58403015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com